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
IRL: anchor iPhone pins to true compass heading for shared orientation
nirholas5d32ec304f29
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2a6bfce9b..cd0883e8a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-17+- **Agents placed from an iPhone now land in the right real-world spot for everyone** — iPhone Safari can't use WebXR, so placing an agent in the real world relies on the phone's motion sensors and GPS. Until now it leaned on a relative gyro reading with no fixed sense of north, which meant an agent you pinned could show up rotated — or facing the wrong way — for other people standing at the same spot. IRL now reads the iPhone's true compass heading when you pin, so your agent is anchored to a real-world direction: pan your phone and it stays planted on its actual bearing instead of sliding with the camera, and walk toward it and it holds its place and grows as you approach. Everyone nearby sees it in the same orientation you intended. If your compass needs calibrating we still place the agent and tell you it may look rotated to others, rather than failing silently — and Android, which already had richer world-anchoring, is unchanged. (`/irl`) `[improvement, fix]`- **An inbox for your IRL agents — see who tapped, messaged, or paid, and reply** — Your IRL Agents dashboard now has an Inbox: a live, chronological feed of everyone who met your placed agents in real life. Each entry shows what happened — a view, a tap, a message, or a payment — where it happened, and how long ago. Payments show the exact amount and link straight to the block-explorer receipt, and you can reply to anyone who left your agent a message; if they were signed in, your reply lands in their notifications. Unread counts appear on the Inbox button and on each agent's card, the feed refreshes itself every few seconds, and opening the inbox marks everything read. High-signal events (a payment or a message) also ping you in the notification bell, so you find out the moment a stranger across the city engages your agent. (`/dashboard/irl-placements`) `[feature]`- **Change a placed agent's outfit from your dashboard — everyone nearby sees it** — Your IRL Agents dashboard now has a real outfit editor. Open Change outfit on any agent you've placed and a live 3D preview loads with wardrobe controls for the exact layers that avatar has — recolour its hair, skin, and clothing, strip back to the base body and dress it up again, or stack on hats, glasses, and earrings. Because your agents are public, the new look is baked into the agent itself and pushed to its real-world pin, so every person who walks up to that spot sees the updated outfit in their camera — not just you. Save when you're happy; the avatar is re-rendered for real before it confirms, the previous look stays untouched if anything fails, and nearby viewers refresh to the new outfit within seconds. Run a seasonal look, brand your agents as staff for an event, or just keep them fresh — all without walking back to where you pinned them. (`/dashboard/irl-placements`) `[feature]`- **Everyone at a location now sees your IRL agent in the same real spot** — three.ws/irl agents now line up across phones. A placed agent renders from its own saved compass bearing and ground height instead of whichever way your phone happens to face, so two people standing in the same place see it standing in the same place, facing the same way. To keep it steady, your own GPS position is now smoothed so anchored agents stop drifting and swimming as your location jitters, and noisy fixes are ignored. Every agent now sits inside a ground ring whose size reflects the real GPS accuracy — honest about the fact that phone GPS is roughly 5–15 metres, and wider (and amber) when the signal is poor — so it never pretends to be pinpoint-perfect. And if an agent landed a little off, its owner can fine-tune it: long-press your own agent (or tap Calibrate position on its card) and drag to nudge it a few centimetres, twist with two fingers to rotate it, or step its floor height up and down. Saving the nudge updates the spot for everyone nearby. Only the owner can calibrate an agent, nudges are capped to small corrections so this can never be used to drag someone's agent across the map, and a failed save keeps your change on screen with a one-tap retry. (`/irl`) `[feature, improvement]`diff --git a/data/changelog.json b/data/changelog.jsonindex e2fc6b651..68404ee70 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,13 @@{"$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-17",+ "title": "Agents placed from an iPhone now land in the right real-world spot for everyone",+ "summary": "iPhone Safari can't use WebXR, so placing an agent in the real world relies on the phone's motion sensors and GPS. Until now it leaned on a relative gyro reading with no fixed sense of north, which meant an agent you pinned could show up rotated — or facing the wrong way — for other people standing at the same spot. IRL now reads the iPhone's true compass heading when you pin, so your agent is anchored to a real-world direction: pan your phone and it stays planted on its actual bearing instead of sliding with the camera, and walk toward it and it holds its place and grows as you approach. Everyone nearby sees it in the same orientation you intended. If your compass needs calibrating we still place the agent and tell you it may look rotated to others, rather than failing silently — and Android, which already had richer world-anchoring, is unchanged.",+ "tags": ["improvement", "fix"],+ "link": "/irl"+ },{"date": "2026-06-17","title": "IRL agents now visibly react when someone engages them",diff --git a/public/changelog.json b/public/changelog.jsonindex f3f04f29d..998541428 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,22 @@{- "generated_at": "2026-06-17T04:11:05.851Z",+ "generated_at": "2026-06-17T04:29:58.009Z","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-06-17",+ "type": "update",+ "title": "Agents placed from an iPhone now land in the right real-world spot for everyone",+ "summary": "iPhone Safari can't use WebXR, so placing an agent in the real world relies on the phone's motion sensors and GPS. Until now it leaned on a relative gyro reading with no fixed sense of north, which meant an agent you pinned could show up rotated — or facing the wrong way — for other people standing at the same spot. IRL now reads the iPhone's true compass heading when you pin, so your agent is anchored to a real-world direction: pan your phone and it stays planted on its actual bearing instead of sliding with the camera, and walk toward it and it holds its place and grows as you approach. Everyone nearby sees it in the same orientation you intended. If your compass needs calibrating we still place the agent and tell you it may look rotated to others, rather than failing silently — and Android, which already had richer world-anchoring, is unchanged.",+ "link": "/irl",+ "tags": [+ "improvement",+ "fix"+ ]+ },{"date": "2026-06-17","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex c9581ea93..7bfe83142 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<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>Agents placed from an iPhone now land in the right real-world spot for everyone</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:Agents placed from an iPhone now land in the right real-world spot for everyone</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>iPhone Safari can't use WebXR, so placing an agent in the real world relies on the phone's motion sensors and GPS. Until now it leaned on a relative gyro reading with no fixed sense of north, which meant an agent you pinned could show up rotated — or facing the wrong way — for other people standing at the same spot. IRL now reads the iPhone's true compass heading when you pin, so your agent is anchored to a real-world direction: pan your phone and it stays planted on its actual bearing instead of sliding with the camera, and walk toward it and it holds its place and grows as you approach. Everyone nearby sees it in the same orientation you intended. If your compass needs calibrating we still place the agent and tell you it may look rotated to others, rather than failing silently — and Android, which already had richer world-anchoring, is unchanged.</description>+ </item><item><title>An inbox for your IRL agents — see who tapped, messaged, or paid, and reply</title><link>https://three.ws/dashboard/irl-placements</link>diff --git a/public/features.json b/public/features.jsonindex 31074316c..4f7b9d363 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-17T04:11:05.838Z",+ "generated_at": "2026-06-17T04:29:57.982Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/irl-d2-smoke.mjs b/scripts/irl-d2-smoke.mjsnew file mode 100644index 000000000..c45117f68--- /dev/null+++ b/scripts/irl-d2-smoke.mjs@@ -0,0 +1,172 @@+// Live round-trip smoke for D2 — IRL live viewer presence.+//+// node scripts/irl-d2-smoke.mjs+//+// Where irl-d1-smoke proves pin liveness, this proves the PRESENCE contract end-+// to-end: it boots the REAL multiplayer server (the same multiplayer/src/index.js+// prod runs, with the irl_world room wired exactly as deployed), connects two+// colyseus.js clients to one geocell room, and asserts the spec's acceptance+// checklist over the wire:+// 1. Two viewers in one cell → each sees a count of 2 (the "N viewing nearby").+// 2. Privacy: a viewer's broadcast position is the cell centre + jitter, never+// the precise GPS it joined with (coarse-by-construction).+// 3. Ghost opt-in is OFF by default — no positioned marker is broadcast until a+// viewer opts in; set_ghost flips it (and the shared avatar) LIVE, and opting+// back out clears it live.+// 4. A heartbeat is accepted and keeps the viewer counted.+// 5. A viewer leaving drops the count for everyone else live.+//+// The 30 s heartbeat reaper (silent/backgrounded drop) is covered by the fast unit+// test in tests/irl-presence.test.js rather than a 30 s wait here, so this smoke+// stays sub-second. The server's pin hydration is pointed at a dead API base so the+// room starts empty — the run needs no DB, no env, and no network.+// Assertions throw on failure; a clean run prints "D2 SMOKE: PASS".++import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import path from 'node:path';++import { Client, getStateCallbacks } from 'colyseus.js';+import { IrlState } from '../multiplayer/src/irl-schemas.js';+import { encodeGeohash, decodeGeohashBounds } from '../multiplayer/src/geohash.js';++const ROOT = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..');+const PORT = 2598;+const HOST = '127.0.0.1';+const BASE_WS = `ws://${HOST}:${PORT}`;+const LIVENESS_MS = 1500; // the spec's "~1 s" plus headroom for CI scheduling jitter++const LAT = 37.7749;+const LNG = -122.4194;+const GEOCELL = encodeGeohash(LAT, LNG, 6);++let failures = 0;+function check(name, cond) {+ if (cond) console.log(` ✓ ${name}`);+ else { console.error(` ✗ ${name}`); failures++; }+}+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+async function waitUntil(pred, ms) {+ const deadline = Date.now() + ms;+ while (Date.now() < deadline) { if (pred()) return true; await sleep(20); }+ return pred();+}++// ── Boot the real multiplayer server ─────────────────────────────────────────+function startServer() {+ const child = spawn(process.execPath, ['multiplayer/src/index.js'], {+ cwd: ROOT,+ env: {+ ...process.env,+ PORT: String(PORT),+ HOST,+ NODE_ENV: 'development', // allows origin-less node-client upgrades+ // Dead API base → onCreate's pin hydration fails fast and the room starts+ // empty, so presence is the only thing in state (deterministic).+ WORLD_API_BASE: 'http://127.0.0.1:9',+ REDIS_URI: '',+ REDIS_URL: '',+ },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ const ready = new Promise((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error('server did not start within 15s')), 15000);+ child.stdout.on('data', (b) => {+ if (String(b).includes('listening on ws://')) { clearTimeout(timer); resolve(); }+ });+ child.stderr.on('data', (b) => {+ const s = String(b);+ if (/FATAL|Error:|failed to start/.test(s) && !/pin load failed/.test(s)) {+ process.stderr.write(`[server] ${s}`);+ }+ });+ child.on('exit', (code) => { if (code) reject(new Error(`server exited early (${code})`)); });+ });+ return { child, ready };+}++// Connect a viewer and mirror what it SEES of the other viewers (id → live snapshot).+async function connectViewer(label, { ghost = false, avatar = '' } = {}) {+ const client = new Client(BASE_WS);+ const room = await client.joinOrCreate('irl_world',+ { geocell: GEOCELL, deviceToken: label, lat: LAT, lng: LNG, ghost, avatar }, IrlState);+ const seen = new Map();+ const $ = getStateCallbacks(room);+ $(room.state).viewers.onAdd((v, id) => {+ const snap = () => seen.set(id, { ghost: v.ghost, avatar: v.avatar, lat: v.lat, lng: v.lng });+ snap();+ $(v).onChange(snap);+ });+ $(room.state).viewers.onRemove((_v, id) => seen.delete(id));+ return {+ room,+ seen,+ count: () => room.state.viewers.size,+ other: () => [...seen.entries()].find(([id]) => id !== room.sessionId)?.[1],+ heartbeat: (heading) => room.send('heartbeat', { heading }),+ setGhost: (g, a) => room.send('set_ghost', { ghost: g, avatar: a }),+ leave: () => room.leave().catch(() => {}),+ };+}++async function main() {+ const { child, ready } = startServer();+ let A, B;+ try {+ await ready;+ console.log(`server up on ${BASE_WS} — cell ${GEOCELL}\n`);++ console.log('1) two viewers in one cell — each sees a count of 2');+ A = await connectViewer('A');+ B = await connectViewer('B');+ check('both viewers joined the same room instance', A.room.roomId === B.room.roomId);+ check('A sees count 2', await waitUntil(() => A.count() === 2, LIVENESS_MS));+ check('B sees count 2', await waitUntil(() => B.count() === 2, LIVENESS_MS));++ console.log('\n2) presence is coarse — no precise GPS ever leaves the server');+ await waitUntil(() => !!A.other(), LIVENESS_MS);+ const bAsSeenByA = A.other();+ check('B is broadcast at a jittered position (≠ the precise input)',+ bAsSeenByA && bAsSeenByA.lat !== LAT && bAsSeenByA.lng !== LNG);+ const bounds = decodeGeohashBounds(GEOCELL);+ check('…and that position stays inside the ~1km cell it claims',+ bAsSeenByA &&+ bAsSeenByA.lat >= bounds.latMin && bAsSeenByA.lat <= bounds.latMax &&+ bAsSeenByA.lng >= bounds.lngMin && bAsSeenByA.lng <= bounds.lngMax);++ console.log('\n3) ghost opt-in is OFF by default; set_ghost flips it live');+ check('B is count-only by default (no ghost marker broadcast)', A.other()?.ghost === false);+ B.setGhost(true, 'https://three.ws/cdn/default.glb');+ check('A sees B appear as a ghost within the liveness budget',+ await waitUntil(() => A.other()?.ghost === true, LIVENESS_MS));+ check('A receives B shared avatar', A.other()?.avatar === 'https://three.ws/cdn/default.glb');++ console.log('\n4) opting back out clears the ghost live');+ B.setGhost(false, '');+ check('A sees B revert to count-only', await waitUntil(() => A.other()?.ghost === false, LIVENESS_MS));+ check('A no longer holds a shared avatar for B', A.other()?.avatar === '');++ console.log('\n5) a heartbeat is accepted and keeps the viewer counted');+ B.heartbeat(270);+ await sleep(200);+ check('count is still 2 after a heartbeat', A.count() === 2);++ console.log('\n6) a viewer leaving drops the count for everyone else, live');+ await B.leave();+ check('A sees count fall to 1 after B leaves', await waitUntil(() => A.count() === 1, LIVENESS_MS));+ } finally {+ await Promise.allSettled([A?.leave(), B?.leave()]);+ child.kill('SIGTERM');+ }++ if (failures) {+ console.error(`\nD2 SMOKE: FAIL (${failures} check${failures === 1 ? '' : 's'})`);+ process.exit(1);+ }+ console.log('\nD2 SMOKE: PASS');+}++main().catch((err) => {+ console.error('\nD2 SMOKE: ERROR —', err?.message || err);+ process.exit(1);+});diff --git a/src/irl.js b/src/irl.jsindex b3addc691..0f0d890f6 100644--- a/src/irl.js+++ b/src/irl.js@@ -817,38 +817,103 @@ if (avatarBtn) {// When the avatar is locked in AR mode, device rotation drives the Three.js// camera so the avatar appears pinned to a real-world location as the user// physically rotates their phone — Pokémon GO style.+//+// Heading frame (A4). iOS Safari has no WebXR and never fires+// `deviceorientationabsolute`; its `alpha` is page-relative (arbitrary zero), so+// a delta-only yaw is consistent for THIS device but lands every placement at a+// different absolute bearing — breaking cross-user reconciliation (A3). iOS does+// expose a true magnetic-north bearing via `event.webkitCompassHeading`, so when+// it's present we drive yaw from it absolutely: the scene becomes north-aligned+// (−Z = north, matching gpsToWorld), the avatar holds its real-world bearing for+// every viewer, and the stored pose is a genuine compass heading. Page-relative+// devices keep the delta fallback and are tagged `:rel` for A3 down-weighting.let lastDevAlpha = 0, lastDevBeta = 90;let devOrientBaseAlpha = null; // null = inactivelet devOrientBaseBeta = null;let devOrientBaseCamYaw = 0;let devOrientBaseCamPitch = 0;-let prefersAbsOrientation = false;+let prefersAbsOrientation = false; // true once a north-referenced bearing is seen (source tagging)+let hasAbsoluteEventStream = false; // true if the dedicated deviceorientationabsolute event fires (Android)+let lastCompassHeading = null; // iOS true compass bearing (deg, 0=N clockwise); null = none/uncalibrated++// iOS Safari's magnetic-north bearing. A negative webkitCompassAccuracy means the+// magnetometer isn't calibrated yet — treat that as no absolute reference rather+// than trusting a garbage heading. Returns null when no usable compass is present.+function readCompassHeading(e) {+ const h = e.webkitCompassHeading;+ if (typeof h !== 'number' || !Number.isFinite(h)) return null;+ const acc = e.webkitCompassAccuracy;+ if (typeof acc === 'number' && acc < 0) return null;+ return ((h % 360) + 360) % 360;+}++// THREE.js Y-rotation maps to a clockwise-from-north bearing as renderedBearing =+// (−cameraYaw); to point the rendered camera at compass bearing H we set+// cameraYaw = −H (verified against three's quaternion). Portrait AR assumed.+function compassToYaw(headingDeg) {+ return -headingDeg * (Math.PI / 180);+}function onDeviceOrientation(e) {const a = e.alpha ?? 0;const b = e.beta ?? 90;lastDevAlpha = a;lastDevBeta = b;+ const compass = readCompassHeading(e);+ if (compass !== null) { lastCompassHeading = compass; prefersAbsOrientation = true; }+ else if (hasAbsoluteEventStream) { prefersAbsOrientation = true; }if (!avatarLocked || !arActive || devOrientBaseAlpha === null) return;- // Delta from baseline — handle 0/360 wrap on alpha- let dAlpha = a - devOrientBaseAlpha;- if (dAlpha > 180) dAlpha -= 360;- if (dAlpha < -180) dAlpha += 360;- cameraYaw = devOrientBaseCamYaw + dAlpha * (Math.PI / 180);+ if (lastCompassHeading !== null) {+ // Absolute frame (iOS compass): yaw tracks the real bearing, so panning the+ // phone leaves the avatar planted on its real-world direction for everyone.+ cameraYaw = compassToYaw(lastCompassHeading);+ } else {+ // Page-relative fallback: integrate alpha deltas from the lock baseline.+ let dAlpha = a - devOrientBaseAlpha;+ if (dAlpha > 180) dAlpha -= 360;+ if (dAlpha < -180) dAlpha += 360;+ cameraYaw = devOrientBaseCamYaw + dAlpha * (Math.PI / 180);+ }cameraPitch = Math.max(PITCH_MIN, Math.min(PITCH_MAX,devOrientBaseCamPitch - (b - devOrientBaseBeta) * (Math.PI / 180)));}-// Prefer absolute (compass-referenced) over page-relative orientation+// Two orientation streams: Android's dedicated absolute event (north-referenced+// alpha) owns updates when present; iOS only fires the plain event, which is where+// webkitCompassHeading rides — so the relative listener gates on the *stream*+// existing, never on prefersAbsOrientation (which a compass reading now also sets,+// and which would otherwise silence iOS after the first event).window.addEventListener('deviceorientationabsolute', e => {- prefersAbsOrientation = true;+ hasAbsoluteEventStream = true;onDeviceOrientation(e);}, true);window.addEventListener('deviceorientation', e => {- if (prefersAbsOrientation) return;+ if (hasAbsoluteEventStream) return;onDeviceOrientation(e);}, true);+// iOS only starts firing orientation events once motion access is granted, and the+// compass rides those events — so a lock that anchors synchronously right after the+// grant would store a stale page-relative bearing. Wait briefly for the first+// compass sample so the persisted pose is the real heading. Resolves in a frame on+// iOS; resolves immediately on devices that don't expose a compass (no wait).+function waitForCompass(ms = 1200) {+ if (lastCompassHeading !== null || !needsMotionGesture()) return Promise.resolve();+ return new Promise((resolve) => {+ let done = false;+ const finish = () => {+ if (done) return;+ done = true;+ clearTimeout(to);+ window.removeEventListener('deviceorientation', onEvt, true);+ resolve();+ };+ const onEvt = () => { if (lastCompassHeading !== null) finish(); };+ const to = setTimeout(finish, ms);+ window.addEventListener('deviceorientation', onEvt, true);+ });+}+// ── Avatar lock ───────────────────────────────────────────────────────────let avatarLocked = false;@@ -875,6 +940,9 @@ async function setLocked(next) {}return;}+ // Let the first compass sample land before we capture the bearing, so the+ // stored pose is the real heading rather than a page-relative placeholder.+ await waitForCompass();}}avatarLocked = next;@@ -886,10 +954,16 @@ async function setLocked(next) {if (arActive) {if (next) {// Capture baseline orientation — gyro deltas from here drive the camera+ // on the page-relative fallback path. The pitch baseline is used by both+ // paths; the yaw baseline only by the delta fallback.devOrientBaseAlpha = lastDevAlpha;devOrientBaseBeta = lastDevBeta;devOrientBaseCamYaw = cameraYaw;devOrientBaseCamPitch = cameraPitch;+ // iOS compass available: snap the very first locked frame to the true+ // bearing so the view is north-aligned before the next orientation event+ // (which keeps it live). No-op on page-relative devices.+ if (lastCompassHeading !== null) cameraYaw = compassToYaw(lastCompassHeading);arFrozenCamPos = null;arFrozenCamLook = null;document.body.classList.add('is-locked');@@ -1185,6 +1259,10 @@ function anchorGpsPin() {const pinLng = gpsState.lng + ( avatarRig.position.x / mLng);gpsModeActive = true;document.body.classList.add('gps-mode');+ // On iOS the live compass is the authoritative bearing — re-derive cameraYaw from+ // the freshest reading so the stored heading is north-anchored even when this runs+ // between orientation events (notably the deferred first-GPS-fix path).+ if (lastCompassHeading !== null) cameraYaw = compassToYaw(lastCompassHeading);const headingDeg = ((cameraYaw * 180 / Math.PI) % 360 + 360) % 360;// Snap the avatar to face the heading we're about to store so it matches how// nearby users will see it — spawnNearbyPin() rotates foreign avatars with the