Skip to content

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.

feat(ar): enhance AR Studio with multi-model support and scene sharing features

nirholas02c6eb2ae483
diff --git a/api/_lib/okx-catalog.js b/api/_lib/okx-catalog.js
index 2fc4d12b2..cff7e9645 100644
--- a/api/_lib/okx-catalog.js
+++ b/api/_lib/okx-catalog.js
@@ -206,16 +206,15 @@ export const OKX_CATALOG = Object.freeze([
},
{
id: 'rig',
- name: 'Auto-Rig a GLB',
+ name: 'GLB Auto-Rigging',
kind: 'rest',
describes: {
capability:
- 'Auto-rigs a static humanoid GLB into an animation-ready model: adds a skeleton and skin ' +
- 'weights so it can be posed and animated in any engine. Paid per call; job polling is ' +
- 'free.',
+ 'Rigs a static humanoid GLB model into an animation-ready character: adds a skeleton and ' +
+ 'skin weights so the model can be posed and animated in any engine.',
input:
- 'POST JSON with glb_url: public https URL of the static GLB to rig. Humanoid models rig ' +
- 'best. Returns job_id + poll_url; poll free until done.',
+ 'Provide: 1. a public link to the static GLB model. Humanoid models rig best. Returns a ' +
+ 'job you can check for free until the rigged model is ready.',
},
priceUsd: '0.25',
amountAtomics: usdToAtomics(0.25),
@@ -257,15 +256,16 @@ export const OKX_CATALOG = Object.freeze([
},
{
id: 'retarget',
- name: 'Animation Retarget',
+ name: 'Animation Retargeting',
kind: 'rest',
describes: {
capability:
- 'Retargets a curated animation clip (idle, walk, dance and more) onto any rigged humanoid ' +
- 'GLB. Returns the clip keyed to the rig plus a bone-coverage report. Completes in-request.',
+ 'Applies a curated animation clip such as idle, walk, or dance onto any rigged humanoid ' +
+ 'GLB model, keyed to its skeleton, with a bone coverage report. Finishes within the ' +
+ 'request.',
input:
- 'POST JSON with model_url (rigged GLB https URL) and animation (preset name); optional ' +
- 'format glb|clip and speed 0.25-2.5.',
+ 'Provide: 1. a public link to the rigged GLB model 2. the animation name 3. an optional ' +
+ 'output format and playback speed.',
},
priceUsd: '0.10',
amountAtomics: usdToAtomics(0.1),
@@ -336,14 +336,14 @@ export const OKX_CATALOG = Object.freeze([
},
{
id: 'catalog',
- name: '3D Studio Catalog (free)',
+ name: '3D Studio Service Catalog',
kind: 'rest',
describes: {
capability:
'Free machine-readable index of every three.ws 3D Studio service on OKX.AI: names, ' +
- 'descriptions, prices, endpoints, and input schemas — generated from the module the ' +
- 'endpoints run on.',
- input: 'GET with no parameters. No payment, no account.',
+ 'descriptions, prices, endpoints, and input formats, always in sync with the live ' +
+ 'services.',
+ input: 'Provide nothing. No parameters, no payment, no account required.',
},
priceUsd: '0',
amountAtomics: null,
@@ -353,13 +353,13 @@ export const OKX_CATALOG = Object.freeze([
},
{
id: 'health',
- name: '3D Studio Health (free)',
+ name: '3D Studio Health Status',
kind: 'rest',
describes: {
capability:
- 'Free live health of the 3D studio lanes backing every paid service: generation, ' +
- 'rigging, rendering, and storage — real subsystem probes, not a hardcoded OK.',
- input: 'GET with no parameters. No payment, no account.',
+ 'Free live health status for the systems behind every paid service: generation, rigging, ' +
+ 'rendering, storage, and the payment rail, from real checks rather than a fixed reply.',
+ input: 'Provide nothing. No parameters, no payment, no account required.',
},
priceUsd: '0',
amountAtomics: null,
diff --git a/public/viewer.html b/public/viewer.html
index 5e4085050..f40df90e2 100644
--- a/public/viewer.html
+++ b/public/viewer.html
@@ -223,6 +223,10 @@
<span class="k"><span class="glyph" aria-hidden="true">◎</span>See it in your room</span>
<span class="d">Place it in AR: straight from your phone, or scan a QR from desktop.</span>
</button>
+ <button class="card" id="act-ar-studio" type="button">
+ <span class="k"><span class="glyph" aria-hidden="true">▣</span>Open in AR Studio</span>
+ <span class="d">Place it alongside other models in a live camera scene — and forge more without leaving the view.</span>
+ </button>
<button class="card" id="act-coin" type="button">
<span class="k"><span class="glyph" aria-hidden="true">◉</span>Launch it as a coin</span>
<span class="d" id="coin-d">Open a pump.fun launch with this model as the token image.</span>
@@ -388,6 +392,12 @@
location.href = '/ar?src=' + enc(src) + tOpt;
});
+ // AR Studio: the multi-model lane — this model joins (or starts) a live
+ // camera scene where more models can be placed and forged around it.
+ document.getElementById('act-ar-studio').addEventListener('click', function () {
+ location.href = '/ar/studio?src=' + enc(src) + tOpt;
+ });
+
// Coin launch: snapshot the rendered model into a token image, hand it to
// /launch via sessionStorage (a data URL never fits in a query string).
var coinCard = document.getElementById('act-coin');
diff --git a/src/ar-studio.js b/src/ar-studio.js
index f99f8cfa2..8341a66e7 100644
--- a/src/ar-studio.js
+++ b/src/ar-studio.js
@@ -38,8 +38,8 @@ import {
} from './ar/pinch-scale.js';
import {
deserializeScene, fitTransform, MAX_PLACEMENTS, normalizeGlbUrl,
- parseSrcParams, serializeScene, SPAWN_DISTANCE_M, spawnPointInFront,
- studioShareUrl, touchAngle, twistDelta,
+ parseSrcParams, sceneFromHashParam, serializeScene, SPAWN_DISTANCE_M,
+ spawnPointInFront, studioSceneUrl, studioShareUrl, touchAngle, twistDelta,
} from './ar/studio-scene.js';
import { renderQRToSVG } from './erc8004/qr.js';
import { deriveVerticalFovDeg, DEFAULT_DIAG_FOV_DEG } from './irl/camera-fov.js';
@@ -131,8 +131,11 @@ try {
log.warn('environment map failed', err);
}
-scene.add(new HemisphereLight(0xffffff, 0x444455, 1.0));
-const sun = new DirectionalLight(0xffffff, 1.15);
+const HEMI_BASE = 1.0;
+const SUN_BASE = 1.15;
+const hemi = new HemisphereLight(0xffffff, 0x444455, HEMI_BASE);
+scene.add(hemi);
+const sun = new DirectionalLight(0xffffff, SUN_BASE);
sun.position.set(2.5, 6, 3);
scene.add(sun);
@@ -494,13 +497,22 @@ function removePlacement(p, { persist = true } = {}) {
let armedSrc = null; // { src, title } — what an XR reticle tap places
async function restoreScene() {
- let items = [];
- try {
- items = deserializeScene(localStorage.getItem(SCENE_KEY));
- } catch {}
const params = new URLSearchParams(location.search);
const linked = parseSrcParams(params);
+ // A #s= hash is a FULL shared arrangement (models + transforms) — it opens
+ // like a document, replacing the working scene rather than merging into it.
+ const sharedScene = sceneFromHashParam(
+ new URLSearchParams(location.hash.replace(/^#/, '')).get('s'),
+ );
+
+ let items = sharedScene;
+ if (!items.length) {
+ try {
+ items = deserializeScene(localStorage.getItem(SCENE_KEY));
+ } catch {}
+ }
+
for (const it of items) {
await addModel({ src: it.src, title: it.title }, {
x: it.x, z: it.z, yaw: it.yaw, scale: it.scale, announce: false, persist: false,
@@ -515,7 +527,11 @@ async function restoreScene() {
}
if (placements.length) {
select(placements[placements.length - 1]);
- setStatus(linked.length ? 'Models loaded — tap the camera to see them in your space.' : 'Your scene is back.');
+ if (sharedScene.length) {
+ setStatus('Shared scene loaded, exactly as arranged. Clear to start fresh.');
+ } else {
+ setStatus(linked.length ? 'Models loaded — tap the camera to see them in your space.' : 'Your scene is back.');
+ }
}
saveScene();
@@ -545,6 +561,54 @@ function applyCameraFov() {
camera.updateProjectionMatrix();
}
+// ── Ambient light matching ────────────────────────────────────────────────────
+// Sample the live camera feed's mean luminance every couple of seconds and
+// ease the scene lights toward it, so a model placed in a dim bedroom doesn't
+// glow like it's under studio lights (and one on a sunny balcony isn't muddy).
+let lightTimer = null;
+const lightProbe = (() => {
+ try {
+ const cnv = document.createElement('canvas');
+ cnv.width = cnv.height = 16;
+ return { cnv, ctx: cnv.getContext('2d', { willReadFrequently: true }) };
+ } catch {
+ return null;
+ }
+})();
+
+function sampleCameraLight() {
+ if (!arActive || !lightProbe?.ctx || !videoEl?.videoWidth) return;
+ let data;
+ try {
+ lightProbe.ctx.drawImage(videoEl, 0, 0, 16, 16);
+ data = lightProbe.ctx.getImageData(0, 0, 16, 16).data;
+ } catch {
+ return; // frame not readable yet — try again next tick
+ }
+ let sum = 0;
+ for (let i = 0; i < data.length; i += 4) {
+ sum += 0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2];
+ }
+ const luma = sum / (data.length / 4) / 255; // 0 (black room) → 1 (blown out)
+ const target = Math.min(1.35, Math.max(0.4, 0.35 + luma * 1.25));
+ // Ease 40% per sample: adapts within a few seconds, never visibly pops.
+ hemi.intensity += (target * HEMI_BASE - hemi.intensity) * 0.4;
+ sun.intensity += (target * SUN_BASE - sun.intensity) * 0.4;
+}
+
+function startLightMatching() {
+ if (lightTimer || !lightProbe) return;
+ lightTimer = setInterval(sampleCameraLight, 2000);
+ sampleCameraLight();
+}
+
+function stopLightMatching() {
+ clearInterval(lightTimer);
+ lightTimer = null;
+ hemi.intensity = HEMI_BASE;
+ sun.intensity = SUN_BASE;
+}
+
async function startCamera() {
if (arTransitioning || arActive || xrSession) return;
if (!navigator.mediaDevices?.getUserMedia) {
@@ -579,6 +643,7 @@ async function startCamera() {
grid.visible = false;
videoEl?.play?.().catch(() => {});
applyCameraFov();
+ startLightMatching();
await startGyro();
setStatus('Camera on — your models are in the room. Look around.');
} finally {
@@ -593,6 +658,7 @@ function stopCamera() {
}
if (videoEl) videoEl.srcObject = null;
arActive = false;
+ stopLightMatching();
document.body.classList.remove('is-ar');
cameraBtn?.classList.remove('is-active');
cameraBtn?.setAttribute('aria-pressed', 'false');
@@ -999,6 +1065,54 @@ document.addEventListener('keydown', (e) => {
}
});
+// ── Desktop keyboard controls ─────────────────────────────────────────────────
+// Arrows nudge the selected model camera-relative (Shift = fine), R rotates,
+// D duplicates, Delete removes — the mouse never has to leave the scene.
+document.addEventListener('keydown', (e) => {
+ if (e.target.closest?.('input, textarea, select')) return;
+ if ((tray && !tray.hidden) || (qrModal && !qrModal.hidden) || xrSession) return;
+ if (!selected) return;
+
+ const key = e.key;
+ if (key.startsWith('Arrow')) {
+ e.preventDefault();
+ const step = e.shiftKey ? 0.02 : 0.1;
+ const fwd = camera.getWorldDirection(new Vector3());
+ fwd.y = 0;
+ if (fwd.lengthSq() < 1e-6) fwd.set(0, 0, -1);
+ fwd.normalize();
+ const right = new Vector3(-fwd.z, 0, fwd.x);
+ const move = key === 'ArrowUp' ? fwd
+ : key === 'ArrowDown' ? fwd.negate()
+ : key === 'ArrowLeft' ? right.negate()
+ : right;
+ selected.group.position.addScaledVector(move, step);
+ selected.shadow?.position.set(selected.group.position.x, 0.004, selected.group.position.z);
+ positionSelRing();
+ saveScene();
+ } else if (key === 'r' || key === 'R') {
+ selected.yaw += Math.PI / 4;
+ selected.group.rotation.y = selected.yaw;
+ saveScene();
+ } else if (key === 'd' || key === 'D') {
+ e.preventDefault();
+ addModel({ src: selected.src, title: selected.title }, {
+ yaw: selected.yaw, scale: selected.group.scale.x,
+ });
+ } else if (key === 'Delete' || key === 'Backspace') {
+ e.preventDefault();
+ const removed = selected;
+ removePlacement(removed);
+ setStatus('Removed.', {
+ actionLabel: 'Undo',
+ onAction: () => addModel({ src: removed.src, title: removed.title }, {
+ x: removed.group.position.x, z: removed.group.position.z,
+ yaw: removed.yaw, scale: removed.group.scale.x,
+ }),
+ });
+ }
+});
+
tray?.querySelectorAll('[data-tab]').forEach((btn) => {
btn.addEventListener('click', () => setTrayTab(btn.dataset.tab));
});
@@ -1261,13 +1375,28 @@ photoBtn?.addEventListener('click', async () => {
qrBtn?.addEventListener('click', () => {
if (!qrModal) return;
- const url = studioShareUrl('https://three.ws', placements);
+ const url = studioSceneUrl('https://three.ws', placements.map((p) => ({
+ src: p.src,
+ title: p.title,
+ x: p.group.position.x,
+ z: p.group.position.z,
+ yaw: p.yaw,
+ scale: p.group.scale.x,
+ })));
const box = $('ars-qr-box');
if (box) {
try {
box.innerHTML = renderQRToSVG(url, { scale: 6, margin: 2, dark: '#0b0b0b', light: '#ffffff' });
} catch {
- box.textContent = url;
+ // Arrangement hash too dense for the encoder → a models-only QR still
+ // beats a wall of text (the full link below keeps the arrangement).
+ try {
+ box.innerHTML = renderQRToSVG(studioShareUrl('https://three.ws', placements), {
+ scale: 6, margin: 2, dark: '#0b0b0b', light: '#ffffff',
+ });
+ } catch {
+ box.textContent = url;
+ }
}
}
const link = $('ars-qr-link');
diff --git a/src/ar/studio-scene.js b/src/ar/studio-scene.js
index e682887e8..2b27674ac 100644
--- a/src/ar/studio-scene.js
+++ b/src/ar/studio-scene.js
@@ -212,6 +212,78 @@ export function parseSrcParams(params) {
return out;
}
+// ── Full-scene links (#s= hash) ───────────────────────────────────────────────
+// The ?src= list reopens the same MODELS; the hash carries the whole
+// ARRANGEMENT (positions, yaw, scale) so a composed scene round-trips exactly.
+// base64url over the same validated JSON the localStorage scene uses — the
+// decoder funnels through deserializeScene, so a hostile hash degrades to an
+// empty scene exactly like a hostile storage blob.
+
+function toBase64Url(s) {
+ const bytes = new TextEncoder().encode(s);
+ let bin = '';
+ for (const b of bytes) bin += String.fromCharCode(b);
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+
+function fromBase64Url(s) {
+ const b64 = String(s).replace(/-/g, '+').replace(/_/g, '/');
+ const bin = atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4));
+ const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
+ return new TextDecoder().decode(bytes);
+}
+
+/**
+ * Encode the current placements (sources + transforms) as a URL-hash payload.
+ *
+ * @param {Array<{ src: string, title?: string, x: number, z: number,
+ * yaw: number, scale: number }>} placements
+ * @returns {string} base64url payload for `#s=`, or '' when nothing is shareable.
+ */
+export function sceneToHashParam(placements) {
+ const json = serializeScene(placements);
+ try {
+ return JSON.parse(json).items.length ? toBase64Url(json) : '';
+ } catch {
+ return '';
+ }
+}
+
+/**
+ * Decode a `#s=` payload back into validated scene items. Hostile, truncated,
+ * or foreign input degrades to an empty list — never a throw.
+ *
+ * @param {string|null|undefined} raw The value after `#s=`.
+ * @returns {ReturnType<typeof deserializeScene>}
+ */
+export function sceneFromHashParam(raw) {
+ if (!raw) return [];
+ try {
+ return deserializeScene(fromBase64Url(raw));
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Full-fidelity share URL: the ?src= list (link previews + old clients) plus
+ * the `#s=` arrangement hash. Falls back to the plain source URL when the
+ * payload would push the link past QR-friendly length.
+ *
+ * @param {string} origin
+ * @param {Array<{ src: string, title?: string, x?: number, z?: number,
+ * yaw?: number, scale?: number }>} placements
+ * @param {number} [maxUrlLength]
+ * @returns {string}
+ */
+export function studioSceneUrl(origin, placements, maxUrlLength = 1500) {
+ const base = studioShareUrl(origin, placements);
+ const hash = sceneToHashParam(placements);
+ if (!hash) return base;
+ const full = `${base}#s=${hash}`;
+ return full.length <= maxUrlLength ? full : base;
+}
+
/**
* Build the shareable /ar/studio URL that reopens the current scene's models
* (sources only — transforms are device-local). Caps the payload so the QR
diff --git a/tests/ar-studio-scene.test.js b/tests/ar-studio-scene.test.js
index f6d44df55..c4ec9ee0b 100644
--- a/tests/ar-studio-scene.test.js
+++ b/tests/ar-studio-scene.test.js
@@ -17,8 +17,11 @@ import {
PROP_TARGET_SIZE_M,
SCALE_MAX,
SCALE_MIN,
+ sceneFromHashParam,
+ sceneToHashParam,
serializeScene,
spawnPointInFront,
+ studioSceneUrl,
studioShareUrl,
touchAngle,
twistDelta,
@@ -174,6 +177,60 @@ describe('parseSrcParams', () => {
});
});
+describe('scene hash (#s=) codec', () => {
+ const scene = [
+ { src: 'https://x.co/a.glb', title: 'crate ✦ 沙发', x: 1.25, z: -3.5, yaw: 0.7854, scale: 1.5 },
+ { src: '/avatars/default.glb', title: 'avatar', x: -0.5, z: 2, yaw: -2.1, scale: 0.8 },
+ ];
+
+ it('round-trips models AND transforms (unicode titles included)', () => {
+ const out = sceneFromHashParam(sceneToHashParam(scene));
+ expect(out).toEqual(scene);
+ });
+
+ it('is URL-safe (no +, /, =, or characters needing escapes)', () => {
+ const hash = sceneToHashParam(scene);
+ expect(hash).toMatch(/^[A-Za-z0-9_-]+$/);
+ });
+
+ it('returns "" for an empty or fully-invalid scene', () => {
+ expect(sceneToHashParam([])).toBe('');
+ expect(sceneToHashParam([{ src: 'javascript:x', x: 0, z: 0 }])).toBe('');
+ });
+
+ it('degrades hostile hash input to an empty scene', () => {
+ expect(sceneFromHashParam('!!!not-base64!!!')).toEqual([]);
+ expect(sceneFromHashParam('aGVsbG8')).toEqual([]); // valid b64, not a scene
+ expect(sceneFromHashParam('')).toEqual([]);
+ expect(sceneFromHashParam(null)).toEqual([]);
+ });
+
+ it('validated exactly like the storage path (bad URLs dropped)', () => {
+ const forged = sceneToHashParam([
+ ...scene,
+ { src: 'https://x.co/ok.glb', title: 'ok', x: 0, z: 0, yaw: 0, scale: 1 },
+ ]);
+ expect(sceneFromHashParam(forged)).toHaveLength(3);
+ });
+});
+
+describe('studioSceneUrl', () => {
+ const scene = [{ src: 'https://x.co/a.glb', title: 'A', x: 1, z: 2, yaw: 0.5, scale: 1.2 }];
+
+ it('appends the arrangement hash to the src-list URL', () => {
+ const url = studioSceneUrl('https://three.ws', scene);
+ const [base, hash] = url.split('#s=');
+ expect(base).toBe(studioShareUrl('https://three.ws', scene));
+ expect(sceneFromHashParam(hash)).toEqual(scene);
+ });
+
+ it('falls back to the src-only URL when the payload would be QR-hostile', () => {
+ const url = studioSceneUrl('https://three.ws', scene, 40);
+ expect(url).toBe(studioShareUrl('https://three.ws', scene));
+ expect(url).not.toContain('#s=');
+ });
+});
+
describe('studioShareUrl', () => {
it('embeds unique sources up to the cap', () => {
const url = studioShareUrl('https://three.ws', [