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.

IRL presence + token endpoints, diorama page/api, sensor-fusion + camera-fov, changelog regen

nirholas38cdeb566643
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a2d036732..f5bf0d5be 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **AR & half-body avatar export fixed for compressed models** — View-in-AR (USDZ for iOS Quick Look) and the half-body VR-seat export now work for avatars that ship with meshopt or Draco geometry compression. Previously these exports silently failed on compressed GLBs because the loader had no decoder registered; the pipeline now loads the meshopt and Draco decoders before parsing, so every avatar — including the compressed ones produced by the server-side bake — converts cleanly. (`/gallery`) `[fix]`
- **Creator royalty payouts protected against double-settlement** — Royalty payouts to skill authors now claim each pending amount atomically before sending funds on-chain, so two overlapping settlement runs can never pay the same balance twice. Creators are paid exactly once for what they've earned. `[fix]`
- **Discovery now shows only real creator avatars** — The Explore / discovery feed previously padded itself with a set of built-in sample avatars and counted them in the totals. The feed and its counts now reflect only real avatars created by the community — no filler. (`/explore`) `[improvement]`
+- **Every page now shares with its own social card** — Share any three.ws page on X, Discord, Slack, iMessage, or LinkedIn and the link now previews with a branded card built for that exact page — its title, its one-line description, and a colour that matches the section it belongs to — instead of one generic image for the whole site. The cards render as real PNGs so they show up everywhere (not just the apps that handle SVG), and they're generated on the fly from the same page catalog that feeds the sitemap, so the preview always matches what's actually on the page. We also tightened the behind-the-scenes SEO on every page: cleaner canonical links, richer structured data with breadcrumbs, and crawler hints that let search engines show large image previews. `[improvement, infra]`
- **Fixed broken links and added retry on failed loads across the app** — Several navigation links pointed at pages that no longer exist — "View plans" on the agent deploy flow, the Classic viewer menu item, and the API-key links on the AWS welcome and selfie pages — and now go to the right place. List pages that could get stuck showing a blank grid or endless skeletons on a network hiccup (your collection, a coin's community profile, the bounty board, the agents directory) now show a clear, retryable error instead. The $THREE dashboard also replaced a non-working "claim" button with a plain explanation that revenue share is distributed to holders automatically. `[fix, improvement]`
- **Fund any agent wallet by scanning a QR or copying the address — with live confirmation** — The agent wallet's Deposit tab is now a complete, public funding panel: a crisp QR code (generated on-device, no third-party service) that your phone wallet can scan, a one-tap copyable Solana address, an optional preset amount, and a Solana deep-link that opens Phantom, Solflare or Backpack on mobile. The panel watches the agent's real on-chain balance and confirms the moment your SOL lands — "◎0.5 SOL received" — instead of leaving you guessing. Anyone can fund an agent, not just its owner, and the new "Fund agent wallet" button on the create-agent success screen leads new users straight into it. `[feature]`
- **Funds and payments hardened: wallet-key isolation, spend-cap races, recipient checks** — Following the security audit, we strengthened everything that touches money. Custodial agent-wallet private keys now encrypt with a dedicated key — separate from the session secret — and a unique salt per wallet, so the secret guarding your funds no longer shares fate with anything else (existing wallets keep working; they re-key on next use). Per-agent daily spend limits, x402 payment de-duplication, and on-chain permission caps are now enforced atomically, closing races where a burst of concurrent requests could slip past a budget or run paid work twice for one payment. Pay-by-name sends re-check that the name still resolves to the exact address you approved before the agent signs, and reject look-alike or invalid targets; withdrawals now only ever pay out to a wallet you've already saved. We also removed a stored cross-site-scripting vector in uploaded 3D-model metadata and the admin panel, added clickjacking and permissions-policy protections site-wide, and moved IPFS pinning fully server-side so no upload credential ever ships to the browser. No action needed on your end. `[security]`
diff --git a/api/_lib/irl-presence.js b/api/_lib/irl-presence.js
new file mode 100644
index 000000000..83a81b5bb
--- /dev/null
+++ b/api/_lib/irl-presence.js
@@ -0,0 +1,144 @@
+// IRL proof-of-presence (epic IRL-Hardening H3).
+//
+// The nearby read (`GET /api/irl/pins`) is the ONLY surface that returns another
+// user's pin coordinates, and it does so only within a tight radius of the
+// caller. But it has trusted CALLER-SUPPLIED lat/lng: anyone could query any
+// point on earth they aren't standing at and harvest the pins there (the radius
+// cap + IP rate-limit slow a sweep but don't bind the read to a genuine fix).
+//
+// A proof-of-presence token closes that hole. The client mints a short-lived,
+// HMAC-signed token from its real geolocation fix; the read then only answers for
+// the coarse area that token was minted in. "Query anywhere" becomes "query where
+// you are" — the actual product contract ("you stumble on an agent by walking up
+// to it"), made structural rather than merely rate-limited.
+//
+// Token shape (compact, URL-safe, stateless — no DB):
+// token = base64url(JSON payload) + '.' + base64url(HMAC_SHA256(payload))
+// payload = { a: anchorLat, o: anchorLng, c: cell7, iat: issuedAtSec }
+// where anchorLat/Lng are the mint fix COARSENED to ANCHOR_DP (~110 m) so the
+// token itself never carries a fine coordinate, and cell7 is the geocell-7 the
+// fix fell in (handy for the client's "re-mint on cell change" trigger).
+//
+// Enforcement: a read is allowed when its claimed point is within
+// FIX_TOLERANCE_M of the token anchor and the token is unexpired and unforged.
+// The tolerance generously covers a cell + its edges (so a viewer near a cell
+// boundary keeps polling seamlessly) while staying far too tight to read a city.
+
+import { hmacSha256, constantTimeEquals } from './crypto.js';
+import { encodeGeohash } from './geohash.js';
+
+export const FIX_TTL_SEC = 180; // 3 min — long enough to keep polling as you
+ // walk a block, short enough to defeat banking.
+export const ANCHOR_DP = 3; // ~110 m coarsening of the mint fix in the token.
+export const FIX_TOLERANCE_M = 250; // a read's claimed point must be within this of
+ // the token anchor (~1 cell + edge slack).
+export const FIX_CELL_PRECISION = 7; // ~153 m geocell, the client's re-mint trigger.
+
+const SECRET_ENV = 'IRL_FIX_SECRET';
+
+// Whether proof-of-presence is enforced. Unset secret ⇒ dev/preview bypass: the
+// read works unchanged so local/sandbox testing isn't gated. Production MUST set
+// IRL_FIX_SECRET. Callers log the active mode once at cold start.
+export function fixEnforced() {
+ const s = process.env[SECRET_ENV];
+ return typeof s === 'string' && s.length >= 16;
+}
+
+function secret() {
+ return process.env[SECRET_ENV] || '';
+}
+
+function b64urlEncode(str) {
+ return Buffer.from(str, 'utf8').toString('base64')
+ .replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
+}
+
+function b64urlDecode(str) {
+ const pad = str.length % 4 === 0 ? '' : '='.repeat(4 - (str.length % 4));
+ return Buffer.from(str.replaceAll('-', '+').replaceAll('_', '/') + pad, 'base64').toString('utf8');
+}
+
+function roundAnchor(v) {
+ const f = 10 ** ANCHOR_DP;
+ return Math.round(v * f) / f;
+}
+
+// Great-circle distance in metres (haversine). Kept local so this module has no
+// dependency on the pins handler.
+function haversineM(lat1, lng1, lat2, lng2) {
+ const R = 6371000;
+ const toRad = (d) => (d * Math.PI) / 180;
+ const dLat = toRad(lat2 - lat1);
+ const dLng = toRad(lng2 - lng1);
+ const a = Math.sin(dLat / 2) ** 2
+ + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) ** 2;
+ return 2 * R * Math.asin(Math.min(1, Math.sqrt(a)));
+}
+
+// Mint a token from a real fix. Returns { token, expires_in, cell } or null when
+// the fix is non-finite (unplaceable) — the caller turns null into a 400.
+export async function mintFixToken(lat, lng, nowSec = Math.floor(Date.now() / 1000)) {
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
+ if (lat < -90 || lat > 90 || lng < -180 || lng > 180) return null;
+ const payload = {
+ a: roundAnchor(lat),
+ o: roundAnchor(lng),
+ c: encodeGeohash(lat, lng, FIX_CELL_PRECISION),
+ iat: nowSec,
+ };
+ const json = JSON.stringify(payload);
+ const sig = await hmacSha256(secret(), json);
+ return {
+ token: `${b64urlEncode(json)}.${sig}`,
+ expires_in: FIX_TTL_SEC,
+ cell: payload.c,
+ };
+}
+
+// Verify a token authorises a read at the claimed point. Returns
+// { ok: true, cell } or { ok: false, reason } — never throws on bad input.
+// reason: 'missing' | 'malformed' | 'forged' | 'expired' | 'out_of_area'
+export async function verifyFixToken(token, claimLat, claimLng, nowSec = Math.floor(Date.now() / 1000)) {
+ if (typeof token !== 'string' || !token.length) return { ok: false, reason: 'missing' };
+ const dot = token.indexOf('.');
+ if (dot <= 0 || dot === token.length - 1) return { ok: false, reason: 'malformed' };
+
+ const encPayload = token.slice(0, dot);
+ const sig = token.slice(dot + 1);
+
+ let json;
+ try {
+ json = b64urlDecode(encPayload);
+ } catch {
+ return { ok: false, reason: 'malformed' };
+ }
+
+ // Recompute the signature over the EXACT decoded JSON and compare in constant
+ // time — a forged or tampered payload won't reproduce the HMAC.
+ const expected = await hmacSha256(secret(), json);
+ if (!constantTimeEquals(sig, expected)) return { ok: false, reason: 'forged' };
+
+ let payload;
+ try {
+ payload = JSON.parse(json);
+ } catch {
+ return { ok: false, reason: 'malformed' };
+ }
+ const { a, o, c, iat } = payload || {};
+ if (!Number.isFinite(a) || !Number.isFinite(o) || !Number.isFinite(iat)) {
+ return { ok: false, reason: 'malformed' };
+ }
+ if (nowSec - iat > FIX_TTL_SEC || iat - nowSec > 60) {
+ // Past TTL, or issued implausibly in the future (clock-skew slack 60 s).
+ return { ok: false, reason: 'expired' };
+ }
+ if (!Number.isFinite(claimLat) || !Number.isFinite(claimLng)) {
+ return { ok: false, reason: 'out_of_area' };
+ }
+ // The read's claimed point must sit within tolerance of the token anchor — i.e.
+ // the caller is reading roughly where they minted, not a distant cell.
+ if (haversineM(a, o, claimLat, claimLng) > FIX_TOLERANCE_M) {
+ return { ok: false, reason: 'out_of_area' };
+ }
+ return { ok: true, cell: typeof c === 'string' ? c : encodeGeohash(a, o, FIX_CELL_PRECISION) };
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index b6de4cdce..2120ae0f7 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -204,6 +204,11 @@ export const limits = {
// · irlInteractIp — log a tap/view/message (lighter; legit viewing fans out)
irlPinIp: (ip) => getLimiter('irl:pin:ip', { limit: 20, window: '10 m' }).limit(ip),
irlInteractIp: (ip) => getLimiter('irl:interact:ip', { limit: 60, window: '1 m' }).limit(ip),
+ // IRL proof-of-presence mint (H3) — a walking viewer re-mints a fix token only
+ // when their coarse cell changes (every ~150 m of travel), so a generous 30/min
+ // covers a brisk walk + a few re-tries while a token-banking sweep (mint many
+ // distinct cells to scrape) trips fast. Keyed per IP.
+ irlFixIp: (ip) => getLimiter('irl:fix:ip', { limit: 30, window: '1 m' }).limit(ip),
// IRL placement token bucket (D4) — keyed per (device_token + IP), tighter than
// the coarse per-IP `irlPinIp` so one device can't script a rapid placement flood
// even from a rotating IP. Two windows: a 5/min burst guard and a 30/hour ceiling.
diff --git a/api/diorama.js b/api/diorama.js
new file mode 100644
index 000000000..f07f305fd
--- /dev/null
+++ b/api/diorama.js
@@ -0,0 +1,246 @@
+/**
+ * Diorama — speak a little world into being.
+ *
+ * POST /api/diorama { action:'compose', prompt } → a diorama PLAN
+ * Decomposes one sentence into a placed set of single-object forge prompts
+ * plus a mood/palette/ground, using the platform's free-first LLM chain.
+ * Returns objects with status:'pending' and no meshes — the browser then
+ * forges each one on /api/forge and watches the world assemble.
+ *
+ * POST /api/diorama { action:'save', diorama, clientKey? } → { id, url }
+ * Persists a fully-forged world so it gets a permalink + gallery slot.
+ *
+ * GET /api/diorama?id=<uuid> → { diorama }
+ * GET /api/diorama?list=recent|featured&limit=<n> → { dioramas:[card] }
+ *
+ * No mocks: when the LLM chain is unreachable the compose route returns a clean
+ * 503 and the page renders a designed retry state — it never fabricates a world.
+ */
+
+import { cors, json, method, readJson, wrap } from './_lib/http.js';
+import { llmComplete, llmConfigured } from './_lib/llm.js';
+import { saveDiorama, getDiorama, listDioramas, bumpViews, dioramaStoreEnabled } from './_lib/diorama-store.js';
+import {
+ normalizeDiorama,
+ MIN_OBJECTS,
+ MAX_OBJECTS,
+ MAX_PROMPT_LEN,
+ ISLAND_RADIUS,
+} from '../src/diorama/schema.js';
+
+const SITE = process.env.PUBLIC_BASE_URL || 'https://three.ws';
+
+const COMPOSE_SYSTEM = `You are a 3D set designer. You turn ONE short sentence into a tiny diorama — a miniature scene that sits on a small floating island a viewer can orbit.
+
+Return ONLY a JSON object (no prose, no markdown fence) with exactly this shape:
+{
+ "title": "2-4 word evocative title",
+ "mood": one of "dawn" | "day" | "dusk" | "night",
+ "ground": one of "grass" | "sand" | "snow" | "stone" | "water" | "meadow" | "void",
+ "island": one of "round" | "craggy" | "plateau",
+ "palette": { "sky": ["#RRGGBB","#RRGGBB"], "ground": "#RRGGBB", "fog": "#RRGGBB", "accent": "#RRGGBB" },
+ "objects": [ { "label": "short", "prompt": "ONE physical object: subject + key material + color", "position": [x, 0, z], "scale": 0.5-2.5, "rotationY": radians } ]
+}
+
+Rules:
+- ${MIN_OBJECTS} to ${MAX_OBJECTS} objects. Each "prompt" describes exactly ONE isolated physical object (a single tree, a single tent) — never a scene, never "and", never people unless one figure is the whole subject. Lead with the subject, then its dominant material and color, ≤ 12 words.
+- Spread objects across the island: x and z each between -${ISLAND_RADIUS - 1} and ${ISLAND_RADIUS - 1}, keep at least 1.5 between any two, never stack them. y is always 0. One object may sit near the center as a focal point.
+- "palette" sky is a 2-stop vertical gradient (top, horizon). Pick colors that match the mood and the scene. "accent" is the warm/cool glow color.
+- Choose mood + ground that fit the sentence (a beach → sand/day, a haunted forest → night/grass).
+- Output MUST be valid JSON. No trailing commas. No comments.`;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ if (req.method === 'GET') return handleGet(req, res);
+ if (method(req, res, ['POST'])) return;
+
+ const body = await readJson(req).catch(() => null);
+ if (!body || typeof body !== 'object') {
+ return json(res, 400, { error: 'invalid_body', message: 'Send a JSON body.' });
+ }
+
+ if (body.action === 'compose') return handleCompose(req, res, body);
+ if (body.action === 'save') return handleSave(req, res, body);
+ return json(res, 400, { error: 'unknown_action', message: 'action must be "compose" or "save".' });
+});
+
+async function handleGet(req, res) {
+ const url = new URL(req.url, 'http://x');
+ const id = url.searchParams.get('id');
+ const list = url.searchParams.get('list');
+
+ if (id) {
+ const diorama = await getDiorama(id);
+ if (!diorama) {
+ return json(res, 404, { error: 'not_found', message: 'No diorama with that id.' });
+ }
+ bumpViews(id); // fire and forget
+ return json(res, 200, { diorama }, { 'cache-control': 'public, max-age=30, s-maxage=300' });
+ }
+
+ if (list !== null) {
+ const scope = list === 'featured' ? 'featured' : 'recent';
+ const limit = Number(url.searchParams.get('limit')) || 24;
+ const dioramas = await listDioramas({ scope, limit });
+ return json(
+ res,
+ 200,
+ { dioramas, storage: dioramaStoreEnabled() },
+ { 'cache-control': 'public, max-age=30, s-maxage=120' },
+ );
+ }
+
+ return json(res, 400, { error: 'bad_request', message: 'Pass ?id= or ?list=.' });
+}
+
+async function handleCompose(req, res, body) {
+ const prompt = String(body.prompt ?? '').slice(0, MAX_PROMPT_LEN).trim();
+ if (prompt.length < 3) {
+ return json(res, 400, { error: 'prompt_required', message: 'Describe your world in a sentence.' });
+ }
+ if (!llmConfigured()) {
+ return json(res, 503, {
+ error: 'composer_unavailable',
+ message: 'The world composer is warming up. Try again in a moment.',
+ });
+ }
+
+ let completion;
+ try {
+ completion = await llmComplete({
+ system: COMPOSE_SYSTEM,
+ user: `Sentence: "${prompt}"\nReturn the diorama JSON.`,
+ maxTokens: 900,
+ timeoutMs: 30_000,
+ track: { tool: 'diorama-compose' },
+ });
+ } catch (err) {
+ console.error('[diorama] compose llm failed:', err?.message);
+ return json(res, 503, {
+ error: 'composer_unavailable',
+ message: 'The world composer is busy. Try again in a moment.',
+ });
+ }
+
+ const plan = parseJsonObject(completion?.text);
+ if (!plan) {
+ return json(res, 502, {
+ error: 'compose_unparseable',
+ message: 'The composer returned an unexpected shape. Try rephrasing your world.',
+ });
+ }
+
+ plan.prompt = prompt;
+ plan.objects = declump(Array.isArray(plan.objects) ? plan.objects : []);
+ const { ok, diorama, errors } = normalizeDiorama(plan);
+ if (!ok || diorama.objects.length < 1) {
+ return json(res, 502, {
+ error: 'compose_invalid',
+ message: 'The composer could not place that world. Try a more concrete sentence.',
+ detail: errors,
+ });
+ }
+ // Force a clean pending plan: never trust model-supplied ids/meshes here.
+ diorama.objects = diorama.objects.map((o, i) => ({
+ ...o,
+ id: `obj-${i}`,
+ status: 'pending',
+ glbUrl: null,
+ }));
+
+ return json(res, 200, { diorama });
+}
+
+async function handleSave(req, res, body) {
+ if (!dioramaStoreEnabled()) {
+ return json(res, 503, {
+ error: 'sharing_unavailable',
+ message: 'Sharing is not configured on this deployment.',
+ });
+ }
+ let saved;
+ try {
+ saved = await saveDiorama({
+ diorama: body.diorama,
+ clientKey: typeof body.clientKey === 'string' ? body.clientKey.slice(0, 128) : null,
+ });
+ } catch (err) {
+ if (err?.code === 'invalid_diorama') {
+ return json(res, 400, { error: 'invalid_diorama', message: err.message });
+ }
+ throw err;
+ }
+ if (!saved) {
+ return json(res, 500, { error: 'save_failed', message: 'Could not save this world. Try again.' });
+ }
+ return json(res, 200, {
+ id: saved.id,
+ createdAt: saved.createdAt,
+ url: `${SITE}/diorama?id=${saved.id}`,
+ });
+}
+
+// Extract the first balanced top-level JSON object from a model response that
+// may be wrapped in prose or a ```json fence. Returns the parsed object or null.
+function parseJsonObject(text) {
+ if (typeof text !== 'string') return null;
+ const fence = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
+ const candidate = fence ? fence[1] : text;
+ const start = candidate.indexOf('{');
+ if (start < 0) return null;
+ let depth = 0;
+ let inStr = false;
+ let esc = false;
+ for (let i = start; i < candidate.length; i++) {
+ const c = candidate[i];
+ if (inStr) {
+ if (esc) esc = false;
+ else if (c === '\\') esc = true;
+ else if (c === '"') inStr = false;
+ continue;
+ }
+ if (c === '"') inStr = true;
+ else if (c === '{') depth++;
+ else if (c === '}') {
+ depth--;
+ if (depth === 0) {
+ try {
+ return JSON.parse(candidate.slice(start, i + 1));
+ } catch {
+ return null;
+ }
+ }
+ }
+ }
+ return null;
+}
+
+// Guard against the model stacking objects at the origin (a common failure):
+// if any two objects are closer than MIN_SPACING, re-seat everything on a tidy
+// spiral so the world always reads as a composed scene, never a pile.
+const MIN_SPACING = 1.4;
+function declump(objects) {
+ if (objects.length < 2) return objects;
+ let clumped = false;
+ for (let i = 0; i < objects.length && !clumped; i++) {
+ for (let j = i + 1; j < objects.length; j++) {
+ const a = objects[i]?.position || [0, 0, 0];
+ const b = objects[j]?.position || [0, 0, 0];
+ if (Math.hypot((a[0] || 0) - (b[0] || 0), (a[2] || 0) - (b[2] || 0)) < MIN_SPACING) {
+ clumped = true;
+ break;
+ }
+ }
+ }
+ if (!clumped) return objects;
+ const n = objects.length;
+ const golden = Math.PI * (3 - Math.sqrt(5));
+ return objects.map((o, i) => {
+ // Phyllotaxis: even, non-overlapping spread filling the island disc.
+ const t = (i + 0.5) / n;
+ const r = (ISLAND_RADIUS - 1.2) * Math.sqrt(t);
+ const a = i * golden;
+ return { ...o, position: [Math.cos(a) * r, 0, Math.sin(a) * r] };
+ });
+}
diff --git a/api/irl/fix-token.js b/api/irl/fix-token.js
new file mode 100644
index 000000000..d42b36f7b
--- /dev/null
+++ b/api/irl/fix-token.js
@@ -0,0 +1,62 @@
+/**
+ * IRL proof-of-presence mint — POST /api/irl/fix-token (epic IRL-Hardening H3)
+ *
+ * Body: { lat, lng, accuracy? } — the caller's CURRENT geolocation fix.
+ * Returns: { token, expires_in, cell }
+ *
+ * The returned token is a short-lived, HMAC-signed proof that the caller had a
+ * real fix in a coarse (~150 m) cell. The nearby read (GET /api/irl/pins) then
+ * only answers for that area, so a viewer can't browse pins at a location they
+ * aren't standing near. Stateless: no DB row, no stored coordinate (the token
+ * anchor is coarsened to ~110 m inside api/_lib/irl-presence.js).
+ *
+ * Privacy: the fix never reaches a log line — this handler reads lat/lng only to
+ * mint, never persists or prints them, and the response is no-store. A 5xx here
+ * routes through the same redactUrl scrub as every other geolocated path.
+ *
+ * Rate-limited per IP (irlFixIp): a walking viewer re-mints only on a cell change
+ * (~every 150 m), so the budget is generous for real use and tight for a sweep
+ * that would need to mint many distinct cells.
+ */
+
+import { cors, json, wrap, error, rateLimited, readJson } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { mintFixToken, fixEnforced } from '../_lib/irl-presence.js';
+
+// Log the active enforcement mode exactly once per cold start so a prod misconfig
+// (secret unset ⇒ bypass) is visible without spamming every request.
+let _modeLogged = false;
+function logModeOnce() {
+ if (_modeLogged) return;
+ _modeLogged = true;
+ console.log(`[irl] proof-of-presence ${fixEnforced() ? 'ENFORCED' : 'BYPASS (IRL_FIX_SECRET unset — dev/preview)'}`);
+}
+
+export default wrap(async (req, res) => {
+ cors(req, res, { methods: ['POST', 'OPTIONS'] });
+ if (req.method === 'OPTIONS') return res.end();
+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'method not allowed');
+
+ logModeOnce();
+
+ const rl = await limits.irlFixIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (err) {
+ return error(res, err.status || 400, 'bad_request', err.message || 'invalid body');
+ }
+
+ const lat = parseFloat(body?.lat);
+ const lng = parseFloat(body?.lng);
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
+ return error(res, 400, 'fix_invalid', 'a live latitude and longitude are required');
+ }
+
+ const minted = await mintFixToken(lat, lng);
+ if (!minted) return error(res, 400, 'fix_invalid', 'latitude/longitude out of range');
+
+ return json(res, 200, minted);
+});
diff --git a/api/irl/pins.js b/api/irl/pins.js
index f30d7b119..161978fbc 100644
--- a/api/irl/pins.js
+++ b/api/irl/pins.js
@@ -25,7 +25,7 @@ import { cacheGet, cacheSet } from '../_lib/cache.js';
import { sendOpsAlert } from '../_lib/alerts.js';
import { sha256 } from '../_lib/crypto.js';
import { readDeviceToken } from '../_lib/irl-auth.js';
-import { verifyFixToken } from '../_lib/irl-presence.js';
+import { verifyFixToken, fixEnforced } from '../_lib/irl-presence.js';
// ── Moderation, safety & density caps (D4) ──────────────────────────────────
// Everything below makes the public, shared IRL world safe to launch: content
@@ -736,6 +736,27 @@ export default wrap(async (req, res) => {
return json(res, 400, { error: 'lat and lng are required' });
}
+ // Proof-of-presence (H3): bind the read to a genuine fix. The caller mints a
+ // short-lived, HMAC-signed token from their real GPS via POST /fix-token; this
+ // read only answers for the coarse area that token was minted in, so a viewer
+ // can't browse pins at a location they aren't standing near (the actual product
+ // contract). Enforced only when IRL_FIX_SECRET is set — dev/preview without it
+ // works unchanged so local testing isn't gated (the mode is logged once at the
+ // mint endpoint's cold start). Failure → 401 fix_required, which the client
+ // turns into the "Getting your location…" designed state, never a blank screen.
+ if (fixEnforced()) {
+ const fixHeader = req.headers['x-irl-fix'];
+ const fixToken = Array.isArray(fixHeader) ? fixHeader[0] : fixHeader;
+ const v = await verifyFixToken(fixToken, lat, lng);
+ if (!v.ok) {
+ return json(res, 401, {
+ error: 'fix_required',
+ reason: v.reason,
+ error_description: 'a fresh location fix is required to read nearby agents',
+ });
+ }
+ }
+
// Bounding-box pre-filter (fast index scan), then haversine in app
const latDelta = radius / 110540;
const lngDelta = radius / (111320 * Math.cos(lat * Math.PI / 180));
diff --git a/data/changelog.json b/data/changelog.json
index 310f37678..de994e020 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-19",
+ "title": "Every page now shares with its own social card",
+ "summary": "Share any three.ws page on X, Discord, Slack, iMessage, or LinkedIn and the link now previews with a branded card built for that exact page — its title, its one-line description, and a colour that matches the section it belongs to — instead of one generic image for the whole site. The cards render as real PNGs so they show up everywhere (not just the apps that handle SVG), and they're generated on the fly from the same page catalog that feeds the sitemap, so the preview always matches what's actually on the page. We also tightened the behind-the-scenes SEO on every page: cleaner canonical links, richer structured data with breadcrumbs, and crawler hints that let search engines show large image previews.",
+ "tags": [
+ "improvement",
+ "infra"
+ ]
+ },
{
"date": "2026-06-19",
"title": "Funds and payments hardened: wallet-key isolation, spend-cap races, recipient checks",
diff --git a/pages/diorama.html b/pages/diorama.html
new file mode 100644
index 000000000..6f7f32179
--- /dev/null
+++ b/pages/diorama.html
@@ -0,0 +1,224 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>
+ /* three.ws theme boot — no-flash; runtime in /theme-switcher.js */ (function () {
+ try {
+ var m = localStorage.getItem('twx_theme');
+ var l =
+ m === 'auto'
+ ? window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches
+ : m === 'light';
+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');
+ } catch (e) {
+ document.documentElement.setAttribute('data-theme', 'dark');
+ }
+ })();
+ </script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />
+ <title>Diorama — Speak a little world into being · three.ws</title>
+ <meta
+ name="description"
+ content="Type one sentence and watch it become a tiny explorable 3D world. Claude composes the scene, each object is forged into a real 3D model, and your world assembles before your eyes — then share it as a live 3D postcard."
+ />
+ <link rel="canonical" href="https://three.ws/diorama" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Diorama — Speak a little world into being" />
+ <meta
+ property="og:description"
+ content="One sentence → a tiny explorable 3D world. Each object forged into a real model, assembled live, shareable as a 3D postcard."
+ />
+ <meta property="og:url" content="https://three.ws/diorama" />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Diorama — Speak a little world into being" />
+ <meta
+ name="twitter:description"
+ content="One sentence → a tiny explorable 3D world, forged live and shareable."
+ />
+ <meta name="twitter:image" content="https://three.ws/og-image.png" />
+
+ <!-- model-viewer powers the optional "view in your room" (AR) handoff, mirroring /forge. -->
+ <script
+ type="module"
+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
+ integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw"
+ crossorigin="anonymous"
+ ></script>
+
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/src/diorama/diorama.css" />
+ </head>
+ <body>
+ <!--
+ ────────────────────────────────────────────────────────────────────────
+ DOM CONTRACT — the single integration surface for the diorama modules.
+ Every dynamic module (main.js controller, renderer.js, gallery.js,
+ share.js) targets the ids/classes below. Do not rename without updating
+ the modules. main.js is the only script entry; it imports the rest.
+ ────────────────────────────────────────────────────────────────────────
+ #diorama-stage → renderer mounts its <canvas> here (fills the box)
+ #stage-loader → skeleton/idle overlay shown before a world exists
+ #stage-hud → in-canvas overlay (title + mood + author)
+ #compose-form → the sentence form
+ #compose-input the <input> / <textarea>
+ #compose-submit the "Build my world" button
+ #compose-examples clickable example sentences (data-prompt)
+ #world-status → live forge progress (text + bar)
+ #world-progress the <progress>/bar element
+ #world-objects → per-object chips with status (forging/ready/failed)
+ #world-actions → Remix · Save & share · View in room · Download
+ #share-panel → revealed after save (hidden by default)
+ #share-link the permalink <input>
+ #share-copy copy-link button
+ #share-x share-to-X button
+ #share-embed embed-snippet button
+ #gallery-list → public gallery cards (gallery.js fills this)
+ #empty-state → first-run guidance (no world yet)
+ #error-state → designed, actionable error surface
+ ────────────────────────────────────────────────────────────────────────
+ -->
+ <div id="nav-container"></div>
+
+ <main class="dio" id="dio-root">
+ <!-- ░░ Composer / hero ░░ -->
+ <section class="dio-hero" aria-labelledby="dio-title">
+ <div class="dio-hero__copy">
+ <p class="dio-eyebrow">three.ws · Diorama</p>
+ <h1 id="dio-title" class="dio-h1">Speak a little world into being.</h1>
+ <p class="dio-lede">
+ Write one sentence. Claude composes the scene, each piece is forged into a
+ real 3D model, and your world assembles in front of you — then share it as a
+ live 3D postcard anyone can explore.
+ </p>
+
+ <form id="compose-form" class="dio-compose" autocomplete="off">
+ <label class="dio-compose__field">
+ <span class="sr-only">Describe your world</span>
+ <input
+ id="compose-input"
+ name="prompt"
+ type="text"
+ maxlength="240"
+ class="dio-compose__input"
+ placeholder="a cozy autumn campsite by a lake at dusk"
+ aria-describedby="compose-help"
+ />
+ </label>
+ <button id="compose-submit" type="submit" class="btn primary btn--primary dio-compose__go">
+ <span class="dio-compose__go-label">Build my world</span>
+ </button>
+ </form>
+ <p id="compose-help" class="dio-compose__help">
+ One concrete scene works best — a place, a mood, a few things in it.
+ </p>
+
+ <ul id="compose-examples" class="dio-examples" aria-label="Example worlds">
+ <li><button type="button" class="dio-chip" data-prompt="a cozy autumn campsite by a lake at dusk">🏕️ autumn campsite</button></li>
+ <li><button type="button" class="dio-chip" data-prompt="a tiny Japanese zen garden with a stone lantern and a maple tree">🍁 zen garden</button></li>
+ <li><button type="button" class="dio-chip" data-prompt="a sunny tropical beach with a palm tree, a surfboard, and a beach umbrella">🏖️ tropical beach</button></li>
+ <li><button type="button" class="dio-chip" data-prompt="a snowy alpine cabin at night under the northern lights">❄️ alpine cabin</button></li>
+ <li><button type="button" class="dio-chip" data-prompt="a desert oasis at noon with a camel, palm trees, and a small pool">🐪 desert oasis</button></li>
+ <li><button type="button" class="dio-chip" data-prompt="a spooky graveyard at midnight with crooked tombstones and a dead tree">🎃 haunted graveyard</button></li>
+ </ul>
+ </div>
+ </section>
+
+ <!-- ░░ The world stage ░░ -->
+ <section class="dio-stage-wrap" aria-label="Your 3D world">
+ <div id="diorama-stage" class="dio-stage" role="img" aria-label="A live 3D diorama you can orbit with click-drag">
+ <!-- Idle / skeleton overlay until a world exists -->
+ <div id="stage-loader" class="dio-stage__loader">
+ <div class="dio-orb" aria-hidden="true">
+ <span class="dio-orb__ring"></span>
+ <span class="dio-orb__ring"></span>
+ <span class="dio-orb__core"></span>
+ </div>
+ <p class="dio-stage__hint">Describe a world above to begin.</p>
+ </div>
+ <!-- In-canvas overlay: title + mood, filled by the controller -->
+ <div id="stage-hud" class="dio-hud" hidden>
+ <span class="dio-hud__title"></span>
+ <span class="dio-hud__meta"></span>
+ </div>
+ </div>
+
+ <!-- Live forge progress + per-object status -->
+ <aside class="dio-side">
+ <div id="world-status" class="dio-status" hidden>
+ <div class="dio-status__row">
+ <span class="dio-status__label">Forging your world…</span>
+ <span class="dio-status__count" data-count></span>
+ </div>
+ <div class="dio-progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
+ <div id="world-progress" class="dio-progress__fill"></div>
+ </div>
+ </div>
+
+ <ul id="world-objects" class="dio-objects" aria-label="Objects in your world"></ul>
+
+ <div id="world-actions" class="dio-actions" hidden>
+ <button type="button" class="btn dio-act" data-act="remix">↻ Remix</button>
+ <button type="button" class="btn primary btn--primary dio-act" data-act="save">Save &amp; share</button>
+ <button type="button" class="btn dio-act" data-act="ar" hidden>View in your room</button>
+ <button type="button" class="btn dio-act" data-act="download" hidden>Download</button>
+ </div>
+
+ <!-- Share panel: revealed after a successful save -->
+ <div id="share-panel" class="dio-share" hidden>
+ <p class="dio-share__title">Your world is live ✨</p>
+ <div class="dio-share__link">
+ <input id="share-link" class="dio-share__input" readonly aria-label="Shareable link" />
+ <button id="share-copy" type="button" class="btn dio-share__copy">Copy</button>
+ </div>
+ <div class="dio-share__row">
+ <button id="share-x" type="button" class="btn dio-share__x">Share on X</button>
+ <button id="share-embed" type="button" class="btn">Embed</button>
+ </div>
+ </div>
+ </aside>
+ </section>
+
+ <!-- ░░ Designed error state (hidden until needed) ░░ -->
+ <section id="error-state" class="dio-error" hidden role="alert">
+ <h2 class="dio-error__title">That world didn’t come together.</h2>
+ <p class="dio-error__body"></p>
+ <button type="button" class="btn primary btn--primary" data-act="retry">Try again</button>
+ </section>
+
+ <!-- ░░ Public gallery ░░ -->
+ <section class="dio-gallery" aria-labelledby="gallery-title">
+ <div class="dio-gallery__head">
+ <h2 id="gallery-title" class="dio-h2">Worlds people spoke into being</h2>
+ <p class="dio-gallery__sub">Every world is real geometry, forged from a sentence. Open one to explore it.</p>
+ </div>
+ <div id="empty-state" class="dio-gallery__empty" hidden>
+ <p>No worlds yet — yours could be the first. Describe one above.</p>
+ </div>
+ <div id="gallery-list" class="dio-gallery__grid" aria-busy="true"></div>
+ </section>
+ </main>
+
+ <!-- Single module entry; it imports renderer, compose, gallery, and share. -->
+ <script type="module" src="/src/diorama/main.js"></script>
+ <script type="module" src="/nav.js"></script>
+
+ <script type="application/ld+json">
+ {
+ "@context": "https://schema.org",
+ "@type": "WebApplication",
+ "name": "Diorama — three.ws",
+ "applicationCategory": "DesignApplication",
+ "operatingSystem": "Web",
+ "description": "Type one sentence and watch it become a tiny explorable 3D world. Each object is forged into a real 3D model and the scene assembles live, then can be shared as an interactive 3D postcard.",
+ "url": "https://three.ws/diorama",
+ "offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" },
+ "isPartOf": { "@type": "WebSite", "name": "three.ws", "url": "https://three.ws" }
+ }
+ </script>
+ </body>
+</html>
diff --git a/public/changelog.json b/public/changelog.json
index 6ea774fdd..c46ea53fe 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T01:24:30.158Z",
+ "generated_at": "2026-06-19T01:33:56.909Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -46,6 +46,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "Every page now shares with its own social card",
+ "summary": "Share any three.ws page on X, Discord, Slack, iMessage, or LinkedIn and the link now previews with a branded card built for that exact page — its title, its one-line description, and a colour that matches the section it belongs to — instead of one generic image for the whole site. The cards render as real PNGs so they show up everywhere (not just the apps that handle SVG), and they're generated on the fly from the same page catalog that feeds the sitemap, so the preview always matches what's actually on the page. We also tightened the behind-the-scenes SEO on every page: cleaner canonical links, richer structured data with breadcrumbs, and crawler hints that let search engines show large image previews.",
+ "link": null,
+ "tags": [
+ "improvement",
+ "infra"
+ ]
+ },
{
"date": "2026-06-19",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index f5e09333a..c6afa0739 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -38,6 +38,14 @@
<category>improvement</category>
<description>The Explore / discovery feed previously padded itself with a set of built-in sample avatars and counted them in the totals. The feed and its counts now reflect only real avatars created by the community — no filler.</description>
</item>
+ <item>
+ <title>Every page now shares with its own social card</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-19:Every page now shares with its own social card</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Share any three.ws page on X, Discord, Slack, iMessage, or LinkedIn and the link now previews with a branded card built for that exact page — its title, its one-line description, and a colour that matches the section it belongs to — instead of one generic image for the whole site. The cards render as real PNGs so they show up everywhere (not just the apps that handle SVG), and they're generated on the fly from the same page catalog that feeds the sitemap, so the preview always matches what's actually on the page. We also tightened the behind-the-scenes SEO on every page: cleaner canonical links, richer structured data with breadcrumbs, and crawler hints that let search engines show large image previews.</description>
+ </item>
<item>
<title>Fixed broken links and added retry on failed loads across the app</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index e7ab580ac..56ae7df00 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T01:24:30.057Z",
+ "generated_at": "2026-06-19T01:33:56.767Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/irl.js b/src/irl.js
index e9e48d42f..1b95cbf5a 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -58,7 +58,8 @@ import { sharedGLTFLoader, createLoadQueue } from './irl/load-queue.js';
import { roomOriginWorld, agentWorldPosition } from './irl/room-anchor.js';
import { anchorPoseToPin, yawDegFromQuat } from './irl/floor-anchor.js';
import { initRoomMode } from './irl/room-mode.js';
-import { isFiniteReading, isCompassFresh, shouldUseAbsoluteYaw, resolveLockYaw, clampPitch } from './irl/sensor-fusion.js';
+import { isFiniteReading, isCompassFresh, shouldUseAbsoluteYaw, resolveLockYaw, clampPitch, screenPitchDeg } from './irl/sensor-fusion.js';
+import { deriveVerticalFovDeg, DEFAULT_DIAG_FOV_DEG } from './irl/camera-fov.js';
import { pinBandAction } from './irl/proximity-band.js';
import {
shouldCueArrival,
@@ -298,6 +299,32 @@ let arFrozenCamLook = null;
// fixed point and only rotates with the phone, so a pinned avatar stays anchored
// in the room and is only visible when the camera points at it. null = inactive.
let gyroLockCamPos = null;
+// Last rear-camera sensor dimensions (from the video track) — captured when AR
+// starts and refreshed on viewport change so the FOV can be re-derived against the
+// current viewport aspect rather than frozen at the orientation AR opened in.
+let arTrackW = 0;
+let arTrackH = 0;
+
+// Re-derive and apply the camera vertical FOV from the live video track + current
+// viewport. Safe to call any time: a no-op (just the projection-matrix refresh)
+// when AR is off / no track, so the resize path can call it unconditionally.
+function applyCameraFov() {
+ const track = mediaStream?.getVideoTracks?.()[0];
+ if (track) {
+ const s = track.getSettings?.() ?? {};
+ if (Number.isFinite(s.width) && s.width > 0) arTrackW = s.width;
+ if (Number.isFinite(s.height) && s.height > 0) arTrackH = s.height;
+ }
+ if (!arActive || !(arTrackW > 0) || !(arTrackH > 0)) return;
+ camera.fov = deriveVerticalFovDeg({
+ trackWidth: arTrackW,
+ trackHeight: arTrackH,
+ viewWidth: window.innerWidth,
+ viewHeight: window.innerHeight,
+ diagFovDeg: DEFAULT_DIAG_FOV_DEG,
+ });
+ camera.updateProjectionMatrix();
+}
async function enableAR() {
if (!navigator.mediaDevices?.getUserMedia) {
@@ -362,19 +389,11 @@ async function enableAR() {
videoEl.play().catch(() => {/* autoplay policies — frames still arrive via the stream */});
- // Match Three.js FOV to device rear camera so the avatar's scale agrees
- // with real-world objects (typically 70–75° diagonal for rear cameras).
- const track = mediaStream.getVideoTracks()[0];
- const s = track?.getSettings?.() ?? {};
- const vw = s.width ?? window.innerWidth;
- const vh = s.height ?? window.innerHeight;
- const diagFov = 72;
- const diagPx = Math.hypot(vw, vh);
- const hFovRad = 2 * Math.atan((vw / diagPx) * Math.tan((diagFov * Math.PI / 180) / 2));
- const aspect = window.innerWidth / window.innerHeight;
- const vFovDeg = (2 * Math.atan(Math.tan(hFovRad / 2) / aspect)) * (180 / Math.PI);
- camera.fov = Math.max(50, Math.min(90, vFovDeg));
- camera.updateProjectionMatrix();
+ // Match Three.js FOV to device rear camera so the avatar's scale agrees with
+ // real-world objects. The sensor dimensions are captured so the resize /
+ // orientation path can re-derive the FOV when the viewport rotates — the
+ // derivation is no longer a one-shot frozen at portrait (task-02).
+ applyCameraFov();
// Freeze camera so the avatar walks through the real room instead of the
// follow-camera chasing it (which would shift the real-world background).
@@ -404,6 +423,8 @@ function disableAR() {
arFrozenCamPos = null;
arFrozenCamLook = null;
gyroLockCamPos = null;
+ arTrackW = 0;
+ arTrackH = 0;
setStatus('Camera off');
}
@@ -3756,7 +3777,7 @@ function postInteraction(body) {
return fetch('/api/irl/interactions', {
method: 'POST',
credentials: 'include',
- headers: { 'Content-Type': 'application/json' },
+ headers: deviceHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ deviceToken: _deviceToken, ...body }),
});
}
@@ -4042,7 +4063,7 @@ function openPinSheet(pin) {
if (pin.id) {
fetch('/api/irl/interactions', {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: deviceHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({
pinId: pin.id,
type: 'view',
@@ -4103,7 +4124,7 @@ document.getElementById('irl-sheet-msg')?.addEventListener('submit', async (e) =
try {
const r = await fetch('/api/irl/interactions', {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: deviceHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({
pinId,
type: 'message',
@@ -4175,7 +4196,7 @@ document.querySelectorAll('.irl-report-reason').forEach((btn) => {
try {
const r = await fetch('/api/irl/report', {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: deviceHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ pinId, reason, deviceToken: _deviceToken }),
});
if (!r.ok) throw new Error(`HTTP ${r.status}`);
@@ -5272,7 +5293,7 @@ async function saveCalibrate() {
try {
const r = await fetch('/api/irl/pins', {
method: 'PATCH', credentials: 'include',
- headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
+ headers: deviceHeaders({ 'Content-Type': 'application/json' }), body: JSON.stringify(body),
});
if (!r.ok) {
const m = r.status === 403 ? 'Only the owner can calibrate this agent.'
diff --git a/src/irl/camera-fov.js b/src/irl/camera-fov.js
new file mode 100644
index 000000000..2ee6dea45
--- /dev/null
+++ b/src/irl/camera-fov.js
@@ -0,0 +1,83 @@
+// Pure camera-FOV math for the /irl AR passthrough.
+//
+// Why this exists
+// ───────────────
+// In AR the Three.js camera must share the REAL rear camera's field of view, or
+// the avatar renders at the wrong scale: too small and it looks like a toy on the
+// floor, too large and it clips through real objects. The phone exposes the video
+// track's pixel dimensions (`track.getSettings()`), and rear cameras run at a
+// roughly fixed ~72° DIAGONAL FOV, so we can recover the horizontal FOV from the
+// sensor aspect and then the vertical FOV (what Three.js wants) from the VIEWPORT
+// aspect — which is what actually fills the screen.
+//
+// This was inlined in enableAR() and only ran ONCE, so rotating portrait↔landscape
+// left the avatar at the portrait scale. Extracted here as a pure function the
+// resize/orientation path can re-run every time the viewport changes, and the test
+// suite verifies the optics directly (mirrors src/irl/sensor-fusion.js).
+//
+// No DOM, no Three.js — plain numbers in, a clamped vertical-FOV in degrees out.
+
+// Typical rear-camera diagonal field of view in degrees. iOS/Android rear cameras
+// cluster tightly around this; it is the one constant the device does not report.
+export const DEFAULT_DIAG_FOV_DEG = 72;
+
+// Three.js PerspectiveCamera.fov is sane between these. We clamp so a degenerate
+// track dimension (0×0, 1×1) or an extreme aspect can never produce a NaN/∞ or a
+// fish-eye/pinhole projection that detaches the avatar from the floor.
+export const VFOV_MIN_DEG = 50;
+export const VFOV_MAX_DEG = 90;
+
+const DEG = Math.PI / 180;
+const RAD = 180 / Math.PI;
+
+/**
+ * Vertical FOV (degrees) for the Three.js camera, derived from the rear-camera
+ * sensor and the on-screen viewport.
+ *
+ * Steps: the sensor's diagonal FOV → its HORIZONTAL FOV (via the sensor aspect)
+ * → the VERTICAL FOV that fills a viewport of `viewAspect`. Using the sensor
+ * aspect for the first step and the viewport aspect for the second is what keeps
+ * the scale correct as the viewport rotates while the camera sensor does not.
+ *
+ * Every input is defended: a non-finite or non-positive dimension/aspect falls
+ * back to a sensible value, and the result is clamped to [VFOV_MIN, VFOV_MAX], so
+ * this is always safe to call straight from a resize handler.
+ *
+ * @param {object} p
+ * @param {number} p.trackWidth video track pixel width (sensor)
+ * @param {number} p.trackHeight video track pixel height (sensor)
+ * @param {number} p.viewWidth viewport CSS pixel width
+ * @param {number} p.viewHeight viewport CSS pixel height
+ * @param {number} [p.diagFovDeg] sensor diagonal FOV (default ~72°)
+ * @returns {number} vertical FOV in degrees, clamped
+ */
+export function deriveVerticalFovDeg({
+ trackWidth,
+ trackHeight,
+ viewWidth,
+ viewHeight,
+ diagFovDeg = DEFAULT_DIAG_FOV_DEG,
+}) {
+ const tw = posOr(trackWidth, viewWidth);
+ const th = posOr(trackHeight, viewHeight);
+ const vw = posOr(viewWidth, tw);
+ const vh = posOr(viewHeight, th);
+ const diag = posOr(diagFovDeg, DEFAULT_DIAG_FOV_DEG);
+
+ // Sensor diagonal → sensor horizontal FOV.
+ const diagPx = Math.hypot(tw, th) || 1;
+ const hFovRad = 2 * Math.atan((tw / diagPx) * Math.tan((diag * DEG) / 2));
+
+ // Sensor horizontal FOV → viewport vertical FOV (viewport aspect drives this).
+ const viewAspect = vw / vh;
+ const vFovRad = 2 * Math.atan(Math.tan(hFovRad / 2) / (viewAspect || 1));
+ const vFovDeg = vFovRad * RAD;
+
+ if (!Number.isFinite(vFovDeg)) return VFOV_MIN_DEG;
+ return Math.max(VFOV_MIN_DEG, Math.min(VFOV_MAX_DEG, vFovDeg));
+}
+
+function posOr(v, fallback) {
+ const n = Number(v);
+ return Number.isFinite(n) && n > 0 ? n : (Number(fallback) > 0 ? Number(fallback) : 1);
+}
diff --git a/src/irl/sensor-fusion.js b/src/irl/sensor-fusion.js
index 2730e5b60..9316a16bd 100644
--- a/src/irl/sensor-fusion.js
+++ b/src/irl/sensor-fusion.js
@@ -101,3 +101,35 @@ export function clampPitch(pitch, min, max) {
const p = Number.isFinite(pitch) ? pitch : 0;
return p < min ? min : p > max ? max : p;
}
+
+// ── Screen-orientation frame correction (task-02) ───────────────────────────
+// The pitch path integrates `beta` (front↔back tilt) on the assumption the phone
+// is held PORTRAIT. Rotate to landscape and the physical "look up / look down" the
+// user does no longer moves `beta` — it moves `gamma` (left↔right tilt), and the
+// sign flips between the two landscape directions. Left uncorrected, tilting the
+// phone up in landscape slides the avatar sideways instead of raising the view.
+//
+// `screen.orientation.angle` (0 | 90 | 180 | 270) tells us how the screen is
+// rotated relative to its natural (portrait) frame. We fold it in to recover the
+// PORTRAIT-EQUIVALENT pitch angle, so every downstream baseline/delta computation
+// keeps working unchanged regardless of how the device is held.
+//
+// angle 0 (portrait) → +beta
+// angle 90 (landscape, ⟲ 90°) → +gamma
+// angle 180 (portrait, upside-down)→ −beta
+// angle 270 (landscape, ⟳ 90°) → −gamma
+//
+// Returns a finite number by contract when given finite beta/gamma; a non-finite
+// component for the active axis collapses to 0 (horizon) rather than poisoning the
+// camera.
+export function screenPitchDeg(beta, gamma, screenAngle = 0) {
+ const a = ((Math.round(Number(screenAngle) / 90) * 90) % 360 + 360) % 360;
+ let v;
+ switch (a) {
+ case 90: v = gamma; break;
+ case 180: v = -beta; break;
+ case 270: v = -gamma; break;
+ default: v = beta; break; // 0 / unknown → portrait
+ }
+ return Number.isFinite(v) ? v : 0;
+}