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.

fix(play): stop phones being killed seconds after joining a world

nirholas891cf8a327b7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f81d7740a..07369f2e5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **A transaction guard now stands between the chat agent and your wallet**: Every fund-moving tool the chat agent can call (SOL and token transfers, Jupiter and 1inch swaps, pump.fun buys and sells, token launches) is now preflighted through a seven-layer policy engine before the tool even runs: a security blacklist, approval policy, dollar caps with live SOL pricing, a spend envelope with a token and destination firewall, an MEV slippage clamp that automatically tightens risky swap parameters, and an hourly budget for paid agent calls. A blocked call never reaches your wallet, and the approval popup now shows the verdict: what was checked, what was flagged, and what could not be verified. The engine ships as an open building block, @three-ws/agent-runtime, with an agent decision loop and a tamper-evident action ledger, plus a public preflight endpoint at /api/agent/guard for your own agents. (`/docs/agent-runtime`) `[feature, security, sdk]`
- **Agent payments: fresher signatures and a health readout that names the real cause**: Two reliability fixes for the x402 agent economy on Solana. First, autonomous payments are now signed against a fresh blockhash instead of one fetched at the start of a long batch, which eliminates the class of settlement failures where a payment expired before it could reach the chain; a refused payment also retries with a brand-new blockhash. Second, the platform health readout at /api/healthz now cross-checks failed settlements against the settlement engine's own records, so a deliberate spending pause (the daily fee budget protecting the treasury) is reported as exactly that instead of masquerading as a payment-rail outage. Operators and holders watching platform status now see the true cause and the true rail health at a glance. `[fix, infra]`
- **Avatars now save in a clean, neutral stance instead of a frozen animation frame**: Saving an avatar in the Studio used to capture whatever the idle animation happened to be doing at that exact instant, and freeze it into the model permanently. Because the saved file carries no animation of its own, that one arbitrary frame became the avatar's pose everywhere it appeared: arms tucked in at odd angles, one side sitting differently from the other, and a different result each time you saved the same avatar. Avatars are now saved in their proper neutral pose, which is symmetric and identical on every save, so downloads, animation retargeting and clothing all start from the stance the body was actually built around. Your gallery thumbnail still shows the relaxed idle pose it always did. `[fix, improvement]`
+- **Chat gets an agent that does its own research: pick a model that uses real tools**: There is a new option in the chat model picker: three.ws Agent (server tools). Ask it a question and instead of answering from memory, it works the problem with live platform tools on the server: real token prices and market caps, trending coins, web search, SOL balances for any wallet, the trade-firewall rug and honeypot verdict on any mint, smart-money activity, and .sol name resolution. It loops through the tools it needs, then streams back one grounded answer. Every tool it can touch is read-only and every call passes the platform guard first; it cannot transfer, swap, or sign anything. Developers get the same loop as an OpenAI-compatible endpoint at /api/agent/run, so any existing OpenAI client can point at it unchanged. (`/docs/agent-runtime`) `[feature, improvement]`
+- **Game-Ready export stops charging $THREE holders who connected a wallet**: Exporting a model for Unity or Unreal is free if you hold $THREE, but the export panel only recognised holders who had signed in with a wallet linked to their account. If you had simply connected your wallet to the site, the way most people browse the Forge, the panel could not see what you hold and asked you to pay the per-export fee your holding already covered. It now proves your holding from whichever identity you actually have: a linked account signs silently, and a connected wallet proves ownership with one free signature that never moves funds. That signature is only ever requested when your wallet genuinely clears the tier, so a non-holder is never prompted for something that could not unlock anything. The panel also now tells you your real price before you export: holders read 'free for you', everyone else reads the exact per-export price. (`/forge`) `[fix, improvement]`
+- **Play: phones stop getting dropped out of the world seconds after joining**: Players on phones were being thrown out of /play within seconds of entering a world, seemingly at random. The cause was memory: the decorative crowd drew random models from the public avatar gallery with no size limit, no reuse and no cleanup, and community models there run as large as 24 MB. A phone that happened to draw a few heavy ones pulled tens of megabytes of 3D geometry within seconds of entering, and the browser killed the tab. The crowd now works to a memory budget sized for the device, downloads each model once and reuses it, and releases everything when you leave a world. The lobby's avatar picker also stops downloading full models on phones when it already has a real picture of them. And if a phone does reclaim graphics memory mid-session, the world now pauses rendering and recovers instead of freezing on a dead frame. (`/play`) `[fix, improvement]`
- **The chat no longer refuses questions it was never asked to refuse**: Every message sent to a three.ws chat surface used to pass through a small safety classifier of ours before the actual model saw it, and when that classifier said "unsafe" you got a canned brush-off instead of an answer. It was wrong often enough to be a real problem: it judged one message at a time with no memory of the conversation, so an ordinary follow-up in a security, trading, or fiction discussion could read as alarming on its own and get blocked, and you were left staring at a refusal no model had actually made. That layer is gone from all of it: the main chat, the /chat app, the embeddable concierge, the widget chat on customer sites, and the agent-idea box on /create. Your question now goes to the model as written. If a model declines something, that is the model exercising its own judgment in its own words, and you can switch models or bring your own key. Nothing else changed: the same rate limits still apply, and the separate confirmation step before any wallet action is untouched. The one place a content check still runs is outbound: what our own official Sketchfab account publishes under the three.ws name. (`/chat`) `[improvement, fix]`
- **The embedded avatar brain is now scoped to the sites it was meant for**: Every agent and avatar embed can chat for free because the platform pays for the model behind it, and the agent owner decides which sites may run that embed and which model it uses. Both of those controls only really applied to browsers: a request that simply left out the header a browser always sends slipped past the site allowlist entirely, and any caller could ask for a pricier model than the owner had chosen. Both are closed. A request with no site header now has to sign in (a session or an API key) instead of riding on an agent id anyone could read off our public sitemap, and a model that bills our own provider keys runs only when the owner selected it in the dashboard. There is also a new platform-wide ceiling across all of this traffic combined, so no amount of spreading requests around can drain the shared budget. Nothing changes for a normal embed on an allowlisted site. (`/docs/api-reference`) `[security, fix]`
diff --git a/data/changelog.json b/data/changelog.json
index 969edcd2b..30226ebb7 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,26 @@
{
"$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-08-07",
+ "title": "Game-Ready export stops charging $THREE holders who connected a wallet",
+ "summary": "Exporting a model for Unity or Unreal is free if you hold $THREE, but the export panel only recognised holders who had signed in with a wallet linked to their account. If you had simply connected your wallet to the site, the way most people browse the Forge, the panel could not see what you hold and asked you to pay the per-export fee your holding already covered. It now proves your holding from whichever identity you actually have: a linked account signs silently, and a connected wallet proves ownership with one free signature that never moves funds. That signature is only ever requested when your wallet genuinely clears the tier, so a non-holder is never prompted for something that could not unlock anything. The panel also now tells you your real price before you export: holders read 'free for you', everyone else reads the exact per-export price.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/forge"
+ },
+ {
+ "date": "2026-08-07",
+ "title": "Play: phones stop getting dropped out of the world seconds after joining",
+ "summary": "Players on phones were being thrown out of /play within seconds of entering a world, seemingly at random. The cause was memory: the decorative crowd drew random models from the public avatar gallery with no size limit, no reuse and no cleanup, and community models there run as large as 24 MB. A phone that happened to draw a few heavy ones pulled tens of megabytes of 3D geometry within seconds of entering, and the browser killed the tab. The crowd now works to a memory budget sized for the device, downloads each model once and reuses it, and releases everything when you leave a world. The lobby's avatar picker also stops downloading full models on phones when it already has a real picture of them. And if a phone does reclaim graphics memory mid-session, the world now pauses rendering and recovers instead of freezing on a dead frame.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/play"
+ },
{
"date": "2026-08-07",
"title": "Agent payments: fresher signatures and a health readout that names the real cause",
@@ -18463,6 +18483,16 @@
"sdk"
],
"link": "/docs/agent-runtime"
+ },
+ {
+ "date": "2026-08-07",
+ "title": "Chat gets an agent that does its own research: pick a model that uses real tools",
+ "summary": "There is a new option in the chat model picker: three.ws Agent (server tools). Ask it a question and instead of answering from memory, it works the problem with live platform tools on the server: real token prices and market caps, trending coins, web search, SOL balances for any wallet, the trade-firewall rug and honeypot verdict on any mint, smart-money activity, and .sol name resolution. It loops through the tools it needs, then streams back one grounded answer. Every tool it can touch is read-only and every call passes the platform guard first; it cannot transfer, swap, or sign anything. Developers get the same loop as an OpenAI-compatible endpoint at /api/agent/run, so any existing OpenAI client can point at it unchanged.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/docs/agent-runtime"
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index 6ae6204c1..2c317c7f4 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-07T08:35:30.152Z",
+ "generated_at": "2026-08-07T09:01:37.039Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -50,6 +50,39 @@
"improvement"
]
},
+ {
+ "date": "2026-08-07",
+ "type": "update",
+ "title": "Chat gets an agent that does its own research: pick a model that uses real tools",
+ "summary": "There is a new option in the chat model picker: three.ws Agent (server tools). Ask it a question and instead of answering from memory, it works the problem with live platform tools on the server: real token prices and market caps, trending coins, web search, SOL balances for any wallet, the trade-firewall rug and honeypot verdict on any mint, smart-money activity, and .sol name resolution. It loops through the tools it needs, then streams back one grounded answer. Every tool it can touch is read-only and every call passes the platform guard first; it cannot transfer, swap, or sign anything. Developers get the same loop as an OpenAI-compatible endpoint at /api/agent/run, so any existing OpenAI client can point at it unchanged.",
+ "link": "/docs/agent-runtime",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-08-07",
+ "type": "update",
+ "title": "Game-Ready export stops charging $THREE holders who connected a wallet",
+ "summary": "Exporting a model for Unity or Unreal is free if you hold $THREE, but the export panel only recognised holders who had signed in with a wallet linked to their account. If you had simply connected your wallet to the site, the way most people browse the Forge, the panel could not see what you hold and asked you to pay the per-export fee your holding already covered. It now proves your holding from whichever identity you actually have: a linked account signs silently, and a connected wallet proves ownership with one free signature that never moves funds. That signature is only ever requested when your wallet genuinely clears the tier, so a non-holder is never prompted for something that could not unlock anything. The panel also now tells you your real price before you export: holders read 'free for you', everyone else reads the exact per-export price.",
+ "link": "/forge",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-08-07",
+ "type": "update",
+ "title": "Play: phones stop getting dropped out of the world seconds after joining",
+ "summary": "Players on phones were being thrown out of /play within seconds of entering a world, seemingly at random. The cause was memory: the decorative crowd drew random models from the public avatar gallery with no size limit, no reuse and no cleanup, and community models there run as large as 24 MB. A phone that happened to draw a few heavy ones pulled tens of megabytes of 3D geometry within seconds of entering, and the browser killed the tab. The crowd now works to a memory budget sized for the device, downloads each model once and reuses it, and releases everything when you leave a world. The lobby's avatar picker also stops downloading full models on phones when it already has a real picture of them. And if a phone does reclaim graphics memory mid-session, the world now pauses rendering and recovers instead of freezing on a dead frame.",
+ "link": "/play",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-08-07",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index a409282d7..f39f3deb0 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -38,6 +38,30 @@
<category>fix</category>
<description>Saving an avatar in the Studio used to capture whatever the idle animation happened to be doing at that exact instant, and freeze it into the model permanently. Because the saved file carries no animation of its own, that one arbitrary frame became the avatar's pose everywhere it appeared: arms tucked in at odd angles, one side sitting differently from the other, and a different result each time you saved the same avatar. Avatars are now saved in their proper neutral pose, which is symmetric and identical on every save, so downloads, animation retargeting and clothing all start from the stance the body was actually built around. Your gallery thumbnail still shows the relaxed idle pose it always did.</description>
</item>
+ <item>
+ <title>Chat gets an agent that does its own research: pick a model that uses real tools</title>
+ <link>https://three.ws/docs/agent-runtime</link>
+ <guid isPermaLink="false">2026-08-07:Chat gets an agent that does its own research: pick a model that uses real tools</guid>
+ <pubDate>Fri, 07 Aug 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>There is a new option in the chat model picker: three.ws Agent (server tools). Ask it a question and instead of answering from memory, it works the problem with live platform tools on the server: real token prices and market caps, trending coins, web search, SOL balances for any wallet, the trade-firewall rug and honeypot verdict on any mint, smart-money activity, and .sol name resolution. It loops through the tools it needs, then streams back one grounded answer. Every tool it can touch is read-only and every call passes the platform guard first; it cannot transfer, swap, or sign anything. Developers get the same loop as an OpenAI-compatible endpoint at /api/agent/run, so any existing OpenAI client can point at it unchanged.</description>
+ </item>
+ <item>
+ <title>Game-Ready export stops charging $THREE holders who connected a wallet</title>
+ <link>https://three.ws/forge</link>
+ <guid isPermaLink="false">2026-08-07:Game-Ready export stops charging $THREE holders who connected a wallet</guid>
+ <pubDate>Fri, 07 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Exporting a model for Unity or Unreal is free if you hold $THREE, but the export panel only recognised holders who had signed in with a wallet linked to their account. If you had simply connected your wallet to the site, the way most people browse the Forge, the panel could not see what you hold and asked you to pay the per-export fee your holding already covered. It now proves your holding from whichever identity you actually have: a linked account signs silently, and a connected wallet proves ownership with one free signature that never moves funds. That signature is only ever requested when your wallet genuinely clears the tier, so a non-holder is never prompted for something that could not unlock anything. The panel also now tells you your real price before you export: holders read 'free for you', everyone else reads the exact per-export price.</description>
+ </item>
+ <item>
+ <title>Play: phones stop getting dropped out of the world seconds after joining</title>
+ <link>https://three.ws/play</link>
+ <guid isPermaLink="false">2026-08-07:Play: phones stop getting dropped out of the world seconds after joining</guid>
+ <pubDate>Fri, 07 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Players on phones were being thrown out of /play within seconds of entering a world, seemingly at random. The cause was memory: the decorative crowd drew random models from the public avatar gallery with no size limit, no reuse and no cleanup, and community models there run as large as 24 MB. A phone that happened to draw a few heavy ones pulled tens of megabytes of 3D geometry within seconds of entering, and the browser killed the tab. The crowd now works to a memory budget sized for the device, downloads each model once and reuses it, and releases everything when you leave a world. The lobby's avatar picker also stops downloading full models on phones when it already has a real picture of them. And if a phone does reclaim graphics memory mid-session, the world now pauses rendering and recovers instead of freezing on a dead frame.</description>
+ </item>
<item>
<title>The chat no longer refuses questions it was never asked to refuse</title>
<link>https://three.ws/chat</link>
diff --git a/public/features.json b/public/features.json
index 44bd639fe..e92d34d1b 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-07T08:35:30.128Z",
+ "generated_at": "2026-08-07T09:01:36.996Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/game/ambient-crowd.js b/src/game/ambient-crowd.js
index 0204dca54..4b8fb70f8 100644
--- a/src/game/ambient-crowd.js
+++ b/src/game/ambient-crowd.js
@@ -13,9 +13,11 @@
import { Group, Vector3 } from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
import { getMeshoptDecoder } from '../viewer/internal.js';
import { Box3, Mesh, CapsuleGeometry, SphereGeometry, MeshStandardMaterial } from 'three';
import { AnimationManager } from '../animation-manager.js';
+import { detectProfile } from '../club-perf.js';
const AVATAR_DEFAULT = '/avatars/default.glb';
const MANIFEST_URL = '/animations/manifest.json';
@@ -24,7 +26,45 @@ const CLIP_IDLE = 'idle';
const CLIP_WALK = 'av-walk-feminine';
const WORLD_RADIUS = 54; // a touch inside the plaza edge
const AMBIENT_SPEED = 1.7; // gentle stroll, slower than the player
-const AMBIENT_TARGET = 5; // strollers to keep around when you're alone
+
+const MB = 1024 * 1024;
+
+// Memory budget for the decorative crowd, per render tier.
+//
+// The public gallery is user-uploaded and uncapped: live models in it run from
+// ~700 KB to 24 MB. The crowd used to draw a fresh random model per wanderer,
+// per re-sync, with no size filter, no reuse and no disposal, so a phone that
+// happened to draw a few heavy avatars pulled tens of megabytes of GLB into
+// memory within seconds of world entry, and iOS Safari killed the tab. That is
+// what made /play "randomly" kick mobile players: the draw is random, so the
+// crash was too.
+//
+// Three limits keep it bounded. `maxModelBytes` filters the pool down to models
+// the device can afford at all, `sessionBytes` caps what one visit may download
+// in total (past it, the crowd re-clones models already resident rather than
+// fetching more), and `count` sizes the crowd itself. Shadow casting is dropped
+// on the low tier, where five shadow-casting skinned meshes cost more than the
+// crowd is worth.
+const CROWD_BUDGET = {
+ high: { count: 5, maxModelBytes: 12 * MB, sessionBytes: 80 * MB, shadows: true },
+ medium: { count: 4, maxModelBytes: 6 * MB, sessionBytes: 32 * MB, shadows: true },
+ low: { count: 2, maxModelBytes: 3 * MB, sessionBytes: 10 * MB, shadows: false },
+};
+// A phone lands in the shared 'medium' tier because Safari reports neither
+// deviceMemory nor hardwareConcurrency, so the detector defaults both to
+// "plenty". That is the right call for the renderer (a modern iPhone draws the
+// world fine) and the wrong one for a download budget: the phone still has a
+// fraction of a laptop's memory headroom and is the device that actually gets
+// killed. Step the crowd budget down one tier when the primary pointer is
+// coarse, without touching the shared render profile.
+function crowdBudget() {
+ const tiers = ['high', 'medium', 'low'];
+ let i = Math.max(0, tiers.indexOf(detectProfile()));
+ const touchPrimary = typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches;
+ if (touchPrimary) i = Math.min(tiers.length - 1, i + 1);
+ return CROWD_BUDGET[tiers[i]];
+}
+const BUDGET = crowdBudget();
const NAMES = ['satoshi', 'anon', 'gm_ser', 'degenape', 'moonboy', 'pepe', 'wagmi', 'hodlqueen', 'vibes', 'chad', 'frfr', 'fomo', 'ngmi', 'based_dev', 'gigachad', '0xshill', 'florp'];
const LINES = ['gm ☀️', 'wen moon', 'lfg 🚀', 'wagmi', 'probably nothing', 'few understand', 'based', 'diamond hands 💎', 'ser…', 'this is the way', 'bullish af', 'vibes immaculate', 'we so back', 'iykyk', 'up only 📈'];
@@ -34,7 +74,16 @@ const _gltf = new GLTFLoader();
const _meshoptReady = getMeshoptDecoder().then((d) => _gltf.setMeshoptDecoder(d));
let _defs = null; // [idle, walk] animation defs
let _emotes = null; // a handful of emote defs
-let _avatars = null; // pool of public-gallery GLB URLs ([] once the fetch settles)
+let _avatars = null; // pool of affordable gallery picks ([] once the fetch settles)
+
+// One download per distinct model, shared by every wanderer that wears it.
+// SkeletonUtils.clone() deep-copies a skinned hierarchy (bones included) while
+// sharing geometry and materials with the template, so the second wanderer in a
+// given model costs no network and almost no memory. Cloned meshes share the
+// template's buffers, so a template must outlive every clone of it. Disposal
+// happens in AmbientCrowd.clear(), once the whole crowd is gone.
+const _templates = new Map(); // url → Promise<Group>
+let _spentBytes = 0; // gallery bytes downloaded this visit
async function loadManifest() {
if (_defs) return;
@@ -49,29 +98,53 @@ async function loadManifest() {
}
// Pull a varied set of real avatars from the public gallery so the crowd reads as
-// a living mix of community models rather than one repeated default. Settles to an
-// empty array on failure — each wanderer then falls back to AVATAR_DEFAULT.
+// a living mix of community models rather than one repeated default. Only models
+// whose published size fits this device's per-model budget make the pool; an
+// entry with no size is skipped rather than gambled on, since one 24 MB draw is
+// enough to end a mobile session. Settles to an empty array on failure; each
+// wanderer then falls back to AVATAR_DEFAULT.
async function loadAvatarPool() {
if (_avatars) return;
- let urls = [];
+ let picks = [];
try {
const r = await fetch(GALLERY_URL, { headers: { accept: 'application/json' } });
if (r.ok) {
const { avatars } = await r.json();
- urls = (avatars || []).map((a) => a.model_url || a.base_model_url).filter(Boolean);
+ picks = (avatars || [])
+ .map((a) => ({ url: a.model_url || a.base_model_url, bytes: Number(a.size_bytes) || 0 }))
+ .filter((p) => p.url && p.bytes > 0 && p.bytes <= BUDGET.maxModelBytes);
}
} catch { /* default-avatar fallback below */ }
- _avatars = urls;
+ _avatars = picks;
+}
+
+// Fetch a model once and hand every later wanderer a clone of it. `bytes` is the
+// published size charged against this visit's download budget; a cache hit costs
+// nothing and is never charged twice.
+function loadTemplate(url, bytes) {
+ let pending = _templates.get(url);
+ if (!pending) {
+ _spentBytes += bytes;
+ pending = _meshoptReady.then(() => _gltf.loadAsync(url)).then((gltf) => gltf.scene);
+ _templates.set(url, pending);
+ // Evict a failed load so one bad model doesn't poison the URL for the rest
+ // of the visit, and refund its budget: nothing was actually held.
+ pending.catch(() => {
+ if (_templates.get(url) === pending) _templates.delete(url);
+ _spentBytes = Math.max(0, _spentBytes - bytes);
+ });
+ }
+ return pending;
}
// Load a gallery avatar (or the default) into a rig + animation manager. Falls
// back to a simple stand-in so a wanderer is never invisible.
-async function buildAvatar(rig, anim, url) {
+async function buildAvatar(rig, anim, pick) {
+ const url = pick?.url || AVATAR_DEFAULT;
try {
- await _meshoptReady;
- const gltf = await _gltf.loadAsync(url || AVATAR_DEFAULT);
- const model = gltf.scene;
- model.traverse((n) => { if (n.isMesh) { n.castShadow = true; n.receiveShadow = false; } });
+ const template = await loadTemplate(url, pick?.bytes || 0);
+ const model = cloneSkinnedScene(template);
+ model.traverse((n) => { if (n.isMesh) { n.castShadow = BUDGET.shadows; n.receiveShadow = false; } });
const box = new Box3().setFromObject(model);
model.position.y -= box.min.y;
rig.add(model);
@@ -81,16 +154,37 @@ async function buildAvatar(rig, anim, url) {
} catch {
// A gallery model that fails to load shouldn't strand the wanderer on a
// capsule — fall back to the bundled default once before the stand-in.
- if (url && url !== AVATAR_DEFAULT) return buildAvatar(rig, anim, AVATAR_DEFAULT);
+ if (url !== AVATAR_DEFAULT) return buildAvatar(rig, anim, null);
const body = new Mesh(new CapsuleGeometry(0.32, 0.7, 4, 10), new MeshStandardMaterial({ color: 0x9aa3ad }));
- body.position.y = 0.85; body.castShadow = true;
+ body.position.y = 0.85; body.castShadow = BUDGET.shadows;
const head = new Mesh(new SphereGeometry(0.28, 14, 10), new MeshStandardMaterial({ color: 0xc9cdd2 }));
- head.position.y = 1.55; head.castShadow = true;
+ head.position.y = 1.55; head.castShadow = BUDGET.shadows;
rig.add(body, head);
return 1.7;
}
}
+// Release every model this visit downloaded. Safe only once no wanderer is left
+// standing: clones share their template's geometry and materials, so freeing a
+// template while a clone still renders would corrupt it.
+function disposeTemplates() {
+ for (const pending of _templates.values()) {
+ pending.then((scene) => {
+ scene.traverse((n) => {
+ if (!n.isMesh) return;
+ n.geometry?.dispose?.();
+ for (const mat of Array.isArray(n.material) ? n.material : [n.material]) {
+ if (!mat) continue;
+ for (const value of Object.values(mat)) value?.isTexture && value.dispose();
+ mat.dispose?.();
+ }
+ });
+ }).catch(() => { /* never loaded, nothing to free */ });
+ }
+ _templates.clear();
+ _spentBytes = 0;
+}
+
async function playEmote(anim, motion) {
if (!_emotes?.length) return;
const def = _emotes[(Math.random() * _emotes.length) | 0];
@@ -102,7 +196,7 @@ async function playEmote(anim, motion) {
}
class Wanderer {
- constructor(scene, name, avatarUrl) {
+ constructor(scene, name, avatarPick) {
this.name = name;
this.rig = new Group();
this.anim = new AnimationManager();
@@ -125,7 +219,7 @@ class Wanderer {
this._sayIn = 5 + Math.random() * 16;
this._emoteIn = 9 + Math.random() * 22;
- buildAvatar(this.rig, this.anim, avatarUrl).then((h) => { this.height = h; });
+ buildAvatar(this.rig, this.anim, avatarPick).then((h) => { this.height = h; });
}
_setMotion(m) {
if (m === this.motion) return;
@@ -175,6 +269,10 @@ class Wanderer {
}
dispose() {
this.scene.remove(this.rig);
+ this.rig.clear();
+ // Drop the mixer + its bound clip actions. The clips themselves are shared
+ // module-wide and stay cached; only this rig's bindings go.
+ this.anim.dispose();
this.label.remove();
this.bubble?.remove();
clearTimeout(this._bubbleTimer);
@@ -200,15 +298,23 @@ class AmbientCrowd {
return this._names.splice(i, 1)[0];
}
// Hand out a distinct gallery avatar each time; refill (and reshuffle) only once
- // the bag empties, so we exhaust the pool before any model repeats.
+ // the bag empties, so we exhaust the pool before any model repeats. Once this
+ // visit's download budget is spent, keep the variety we already paid for: draw
+ // from the models still resident in memory instead of fetching another one.
+ // Wanderers churn every time a real player joins or leaves, so without this an
+ // hour in a busy world would download the whole gallery.
_takeAvatar() {
- if (!_avatars?.length) return AVATAR_DEFAULT;
+ if (!_avatars?.length) return null;
+ if (_spentBytes >= BUDGET.sessionBytes) {
+ const resident = [..._templates.keys()];
+ return resident.length ? { url: resident[(Math.random() * resident.length) | 0], bytes: 0 } : null;
+ }
if (!this._avatarBag.length) this._avatarBag = [..._avatars];
const i = (Math.random() * this._avatarBag.length) | 0;
return this._avatarBag.splice(i, 1)[0];
}
sync(realCount) {
- const want = Math.max(0, AMBIENT_TARGET - (realCount | 0));
+ const want = Math.max(0, BUDGET.count - (realCount | 0));
while (this.list.length < want) this.list.push(new Wanderer(this.cc.scene, this._takeName(), this._takeAvatar()));
while (this.list.length > want) this.list.pop().dispose();
// The HUD's online count reports REAL players only (self + live peers).
@@ -234,6 +340,11 @@ class AmbientCrowd {
clear() {
for (const w of this.list) w.dispose();
this.list = [];
+ this._avatarBag = [];
+ // Every clone is gone, so the shared templates can go too. Leaving a world
+ // used to keep every model the crowd had ever worn resident for the rest of
+ // the page's life; on a phone that alone could outlive the tab.
+ disposeTemplates();
}
}
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index 3394fcbb2..d0aa4df31 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -691,9 +691,11 @@ export class CommunityUI {
? el('img', {
src: a.thumbnail_url, alt: a.name || 'Avatar', loading: 'lazy',
// A stale thumbnail (e.g. a legacy OG key that 404s before the
- // avatar self-heals) shouldn't leave a broken-image icon — drop
- // it; _renderChipPreview paints the live model over this anyway.
- onerror: (e) => e.target.remove(),
+ // avatar self-heals) shouldn't leave a broken-image icon: drop it
+ // and let _renderChipPreview's live model render stand in. Removing
+ // the node is also what makes the mobile skip-the-render path fall
+ // back to a real render when the thumbnail turns out to be dead.
+ onerror: (e) => { e.target.remove(); this._renderChipPreview(chip, { url: a.model_url || value, label: a.name || 'Your avatar' }); },
})
: el('span', { class: 'cc-avatar-glyph', text: '🧑' }),
]);
@@ -701,7 +703,7 @@ export class CommunityUI {
chip._avatarId = a.id || '';
this._galleryChip = chip;
this.presetRow.insertBefore(chip, this.presetRow.firstChild);
- this._renderChipPreview(chip, { url: a.model_url || value, label: a.name || 'Your avatar' });
+ this._renderChipPreview(chip, { url: a.model_url || value, label: a.name || 'Your avatar', thumb: a.thumbnail_url });
this._setAvatar(value, false);
}
@@ -726,7 +728,10 @@ export class CommunityUI {
const fallback = p.thumb
? el('img', {
src: p.thumb, alt: p.label, loading: 'lazy',
- onerror: (e) => e.target.remove(), // broken thumb → let the model preview stand in
+ // Broken thumb: drop it and render the real model instead, so the
+ // chip is never left empty (on mobile a live thumbnail is what lets
+ // us skip that render in the first place).
+ onerror: (e) => { e.target.remove(); this._renderChipPreview(chip, { ...p, thumb: null }); },
})
: el('span', { class: 'cc-avatar-glyph', text: p.icon || '🙂' });
const chip = el('button', {
@@ -745,6 +750,16 @@ export class CommunityUI {
// replacing the placeholder. Leaves the fallback in place if rendering fails
// (no WebGL, model load error) so the chip stays meaningful.
async _renderChipPreview(chip, p) {
+ // Rendering a chip means downloading the whole model: community avatars run
+ // to 24 MB, and the row holds seven of them. On a phone that is up to a few
+ // hundred megabytes of geometry bought for seven 160px portraits, on the
+ // lobby screen, before the world has even loaded. When the API already gave
+ // us a real portrait of the same avatar, the chip is already correct, so
+ // keep it and skip the download. Desktop still gets the live render.
+ if (p.thumb && this._touchPrimary()) {
+ chip.classList.remove('cc-avatar-loading');
+ return;
+ }
let dataUrl = null;
try {
dataUrl = await renderAvatarThumb(await resolveAvatarUrl(p.url));
@@ -756,6 +771,12 @@ export class CommunityUI {
chip.appendChild(el('img', { class: 'cc-avatar-render', src: dataUrl, alt: p.label }));
}
+ // True on phones and tablets: a coarse pointer is the primary input. Used to
+ // spend the memory and bandwidth budget differently, never to hide a feature.
+ _touchPrimary() {
+ return typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches;
+ }
+
_setAvatar(url, fromCustom) {
this.avatar = url || DEFAULT_AVATAR;
lsSet('cc-avatar', this.avatar);
@@ -932,7 +953,8 @@ export class CommunityUI {
// (default $8) of the coin. This overlay is a thin view over the scene's gate
// state machine (coincommunities.js _passHolderGate) — the scene drives us
// through setHolderGate(state, data) and we report the player's choice back via
- // onHolderAction(action): 'signin' | 'wallet' | 'switch' | 'buy' | 'recheck' | 'cancel'.
+ // onHolderAction(action): 'signin' | 'wallet' | 'switch' | 'buy' | 'recheck' |
+ // 'general' (continue this entry into the open world) | 'cancel'.
openHolderGate(coin) {
if (this._gate) return; // already open — the scene re-uses it across states
this._gateBody = el('div', { class: 'cc-gate-body' });
@@ -1146,7 +1168,22 @@ export class CommunityUI {
btn(`Buy ${sym}`, 'buy', 'cc-gate-primary'),
btn('I bought — re-check', 'recheck'),
btn('Use a different wallet', 'switch'),
- btn('Enter the open world instead', 'cancel', 'cc-gate-ghost'),
+ btn('Enter the open world instead', 'general', 'cc-gate-ghost'),
+ ),
+ ];
+ break;
+ case 'unavailable':
+ // Holder verification is down deployment-wide (cc_unconfigured).
+ // Retrying or switching wallets cannot succeed, so lead with the
+ // open world; keep one retry for when the service comes back.
+ nodes = [
+ el('div', { class: 'cc-gate-lock', text: '🛠' }),
+ title('Holder check is offline'),
+ msg(`We can’t verify ${sym} holdings right now. That’s on our side, not yours, and your tokens are unaffected. The open world is live for everyone.`),
+ actions(
+ btn('Enter the open world', 'general', 'cc-gate-primary'),
+ btn('Try again', 'recheck'),
+ btn('Back to the lobby', 'cancel', 'cc-gate-ghost'),
),
];
break;
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 1feb87f29..2058fcdfc 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -475,6 +475,8 @@ export class CoinCommunities {
// and the normal seeded look is used, so default play is unaffected.
this._biomePin = new URLSearchParams(location.search).get('biome') || null;
+ // True between webglcontextlost and webglcontextrestored (see _bindContextLoss).
+ this._contextLost = false;
this._initRenderer();
this._initScene();
@@ -709,6 +711,34 @@ export class CoinCommunities {
this._applyPerfTier();
window.addEventListener('resize', () => this._onResize());
this._watchDevicePixelRatio();
+ this._bindContextLoss();
+ }
+
+ // A browser may take the WebGL context away at any time. On phones it is the
+ // usual response to memory pressure, and it arrives with no warning and no JS
+ // error. Unhandled, the default action cancels restoration for good: the canvas
+ // freezes on its last frame, three.js logs a flood of GL warnings, and the
+ // player is left in a world that renders nothing while the socket, chat and
+ // economy carry on underneath. Calling preventDefault() is what asks the
+ // browser to give the context back; until it does, we stop drawing and say so.
+ _bindContextLoss() {
+ this.canvas.addEventListener('webglcontextlost', (e) => {
+ e.preventDefault();
+ this._contextLost = true;
+ log.warn('[coincommunities] WebGL context lost, pausing rendering until it is restored');
+ this.ui?.toast('Graphics paused: your device reclaimed 3D memory. Restoring…', 'warn');
+ });
+ this.canvas.addEventListener('webglcontextrestored', () => {
+ this._contextLost = false;
+ // The GPU-side objects three.js held are gone; it rebuilds them lazily
+ // from the scene graph on the next render. Re-apply the tier so pixel
+ // ratio and shadow state land on the fresh context, and resize so the
+ // new drawing buffer matches the viewport.
+ this._applyPerfTier();
+ this._onResize();
+ log.info('[coincommunities] WebGL context restored');
+ this.ui?.toast('Graphics restored.', 'info');
+ });
}
// devicePixelRatio changes when the window moves to a display with a
@@ -994,7 +1024,7 @@ export class CoinCommunities {
// when /play is open (no token pinned) or when we already hold a fresh pass.
if (this._playReady) { try { await this._playReady; } catch { /* gate self-heals */ } }
if (this.phase !== 'loading') return; // torn down while the gate was up
- const tier = opts.tier === 'holders' ? 'holders' : 'general';
+ let tier = opts.tier === 'holders' ? 'holders' : 'general';
// Entry does several awaits (gate, manifest, avatar GLB, room connect) and
// the Leave button goes live the moment the HUD shows — well before connect
// resolves. Stamp this attempt so a continuation that resumes after the
@@ -1012,10 +1042,18 @@ export class CoinCommunities {
if (tier === 'holders') {
const pass = await this._passHolderGate(coin);
if (!pass) { if (this.phase === 'loading') this.phase = 'lobby'; return; }
- holderPass = pass.holderPass;
- holderMinUsd = pass.minUsd;
- holderMinTokens = pass.minTokens || 0;
if (this.phase !== 'loading') return; // torn down while the gate was up
+ if (pass === 'general') {
+ // The player picked the open world from inside the gate (short
+ // balance, or holder verification unavailable): keep this same
+ // entry going as a General-world entry instead of bouncing them
+ // back to the lobby to click again.
+ tier = 'general';
+ } else {
+ holderPass = pass.holderPass;
+ holderMinUsd = pass.minUsd;
+ holderMinTokens = pass.minTokens || 0;
+ }
}
// A bare deep link (/play?coin=<home mint>) carries no name/art; backfill the
@@ -1629,6 +1667,14 @@ export class CoinCommunities {
} catch (err) {
if (err?.code === 'auth_required') { state = 'auth'; data = { symbol, error: carryError }; }
else if (err?.code === 'wallet_required') { state = 'wallet'; data = { symbol, error: carryError }; }
+ else if (err?.code === 'cc_unconfigured') {
+ // Holder verification depends on the CoinCommunities API
+ // key, which this deployment does not have yet. Nothing the
+ // player does (retry, switch wallet) can succeed, so route
+ // to the designed "verification offline" state that leads
+ // them into the open world instead.
+ state = 'unavailable'; data = { symbol };
+ }
else { state = 'error'; data = { symbol, error: err?.message || 'Could not verify your holdings.' }; }
carryError = '';
}
@@ -1637,6 +1683,13 @@ export class CoinCommunities {
const action = await this._holderGateWait(state, data);
if (action === 'cancel') return null;
+ if (action === 'general') {
+ // Continue this entry as the open General world. The caller
+ // (enter()) downgrades the tier; close the gate ourselves since
+ // the finally below only cleans up on a return to the lobby.
+ this.ui.closeHolderGate();
+ return 'general';
+ }
if (action === 'signin') {
this.ui.setHolderGate('working', { symbol, msg: 'Opening X sign-in…' });
try { await signInWithX(); } catch (e) { carryError = e?.message || 'Sign-in was cancelled.'; }
@@ -3853,7 +3906,10 @@ export class CoinCommunities {
}
this._tickEnv(dt);
this._updateCamera(dt);
- this.renderer.render(this.scene, this.camera);
+ // Drawing into a lost context throws GL errors on every call and can keep
+ // the browser from handing it back. Simulation above keeps running, so the
+ // world is live and correct the instant the context returns.
+ if (!this._contextLost) this.renderer.render(this.scene, this.camera);
}
// Kick the avatar into the air. Ignored while already airborne so a held key