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
perf(3d): serve phones a 512x256 HDRI and stop shipping full-size coin art
nirholas5bbf0b3fc81f
diff --git a/public/hdri/outdoor-mobile.hdr b/public/hdri/outdoor-mobile.hdrnew file mode 100644index 000000000..70229228dBinary files /dev/null and b/public/hdri/outdoor-mobile.hdr differdiff --git a/public/hdri/studio-mobile.hdr b/public/hdri/studio-mobile.hdrnew file mode 100644index 000000000..67d7841e8Binary files /dev/null and b/public/hdri/studio-mobile.hdr differdiff --git a/public/hdri/sunset-mobile.hdr b/public/hdri/sunset-mobile.hdrnew file mode 100644index 000000000..7a3f57c00Binary files /dev/null and b/public/hdri/sunset-mobile.hdr differdiff --git a/scripts/build-hdri-mobile.mjs b/scripts/build-hdri-mobile.mjsnew file mode 100644index 000000000..f193ab7b7--- /dev/null+++ b/scripts/build-hdri-mobile.mjs@@ -0,0 +1,126 @@+#!/usr/bin/env node+/**+ * Generate the phone-sized copies of the curated HDRI set.+ *+ * `public/hdri/{studio,outdoor,sunset}.hdr` are 1024x512 Radiance RGBE files of+ * roughly 1.4-1.5 MB each, and they are the single largest asset any 3D page+ * downloads. Measured on a Pixel 5 over slow 4G against production on+ * 2026-09-08, `/hdri/outdoor.hdr` was 1,435 KB of `/play`'s 5,470 KB, more than+ * a quarter of the page, on a connection where that is seven seconds of radio+ * time before the world is lit.+ *+ * The environment map is PMREM-prefiltered before it lights anything, which+ * throws most of that resolution away, so the mobile tier reads a 512x256 copy+ * instead: about 370 KB, a 74% cut (src/shared/cinematic-render.js picks it).+ *+ * Two details decide whether the output is usable:+ *+ * 1. **zscale, not scale.** swscale converts float input through a 16-bit+ * fixed-point intermediate and CLAMPS to 1.0, which silently destroys+ * everything that makes the file an HDRI: a run through `-vf scale` took+ * outdoor.hdr's peak radiance from 61,408 to exactly 1.00 and halved its+ * mean. The file still loads, still looks like an image, and lights a scene+ * completely wrong. zimg keeps the float path intact.+ * 2. **bilinear, not lanczos.** Image-based lighting cares about total energy,+ * not edge crispness, and a windowed-sinc kernel rings around a sun disc+ * with 60,000:1 contrast. Measured over outdoor.hdr, mean radiance against+ * the 1024x512 original: bilinear 0.6976 vs 0.6997 (-0.3%), bicubic 0.7335+ * (+4.8%), lanczos 0.7840 (+12.0%). Bilinear is also the only kernel that+ * produced no negative undershoot, and the smallest file.+ *+ * The outputs are COMMITTED. These are three curated, never-changing assets, so+ * baking them into the repo keeps ffmpeg out of the deploy path; this script+ * exists to reproduce them, and to prove the reproduction is sound.+ *+ * node scripts/build-hdri-mobile.mjs # write the -mobile.hdr files+ * node scripts/build-hdri-mobile.mjs --check # verify without writing+ */++import { execFileSync } from 'node:child_process';+import { existsSync, readFileSync, statSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { DataUtils } from 'three';+import { HDRLoader } from 'three/examples/jsm/loaders/HDRLoader.js';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+const HDRI_DIR = join(ROOT, 'public/hdri');+const PRESETS = ['studio', 'outdoor', 'sunset'];+export const MOBILE_WIDTH = 512;+export const MOBILE_HEIGHT = 256;+// How far the downscaled copy's mean radiance may drift from the original's.+// A clamped file (the swscale failure above) misses this by a mile; a sound+// bilinear reduction lands inside a fraction of a percent.+export const MEAN_TOLERANCE = 0.02;++export function mobileNameFor(preset) {+ return `${preset}-mobile.hdr`;+}++/** Mean radiance and peak of an .hdr on disk, decoded with the loader the site uses. */+export function hdrStats(file) {+ const buf = readFileSync(file);+ const tex = new HDRLoader().parse(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));+ let sum = 0;+ let n = 0;+ let max = -Infinity;+ for (let i = 0; i < tex.data.length; i += 4) {+ for (let c = 0; c < 3; c++) {+ const v = DataUtils.fromHalfFloat(tex.data[i + c]);+ sum += v;+ n++;+ if (v > max) max = v;+ }+ }+ return { width: tex.width, height: tex.height, mean: sum / n, max, bytes: statSync(file).size };+}++function generate(preset) {+ const src = join(HDRI_DIR, `${preset}.hdr`);+ const out = join(HDRI_DIR, mobileNameFor(preset));+ execFileSync(+ 'ffmpeg',+ ['-hide_banner', '-loglevel', 'error', '-y', '-i', src,+ '-vf', `zscale=w=${MOBILE_WIDTH}:h=${MOBILE_HEIGHT}:f=bilinear`, '-c:v', 'hdr', out],+ { stdio: ['ignore', 'inherit', 'inherit'] },+ );+ return out;+}++function main() {+ const check = process.argv.includes('--check');+ let failed = 0;+ for (const preset of PRESETS) {+ const src = join(HDRI_DIR, `${preset}.hdr`);+ const out = join(HDRI_DIR, mobileNameFor(preset));+ if (!existsSync(src)) {+ console.error(`missing source: ${src}`);+ failed++;+ continue;+ }+ if (!check) generate(preset);+ if (!existsSync(out)) {+ console.error(`missing output: ${out} (run without --check to write it)`);+ failed++;+ continue;+ }+ const a = hdrStats(src);+ const b = hdrStats(out);+ const drift = Math.abs(b.mean - a.mean) / a.mean;+ const ok = b.width === MOBILE_WIDTH && b.height === MOBILE_HEIGHT && drift <= MEAN_TOLERANCE;+ if (!ok) failed++;+ console.log(+ `${ok ? 'ok ' : 'FAIL'} ${preset.padEnd(8)} ` ++ `${a.width}x${a.height} ${(a.bytes / 1024).toFixed(0)} KB -> ${b.width}x${b.height} ${(b.bytes / 1024).toFixed(0)} KB ` ++ `(${(100 - (b.bytes / a.bytes) * 100).toFixed(0)}% smaller), ` ++ `mean ${a.mean.toFixed(4)} -> ${b.mean.toFixed(4)} (${(drift * 100).toFixed(2)}% drift), ` ++ `peak ${a.max.toFixed(0)} -> ${b.max.toFixed(0)}`,+ );+ }+ if (failed) {+ console.error(`\n${failed} preset(s) failed.`);+ process.exit(1);+ }+}++if (process.argv[1] && process.argv[1].endsWith('build-hdri-mobile.mjs')) main();diff --git a/src/community/coin-lobby.js b/src/community/coin-lobby.jsindex 52a82c2ab..f669ede73 100644--- a/src/community/coin-lobby.js+++ b/src/community/coin-lobby.js@@ -163,7 +163,10 @@ export class CoinLobby {// before onerror can run. /api/img reads it server-side and answers// with open CORS; `fallback: 'none'` makes a dead pin a 204, which// still fires onerror so the card lands on its own initials tile.- const art = w.image ? proxiedImageURL(w.image, '', { fallback: 'none' }) : '';+ // The card's art box is a square that tops out around 190 CSS px in this+ // grid, so ask the proxy for a 320px WebP rather than the pinned original:+ // pump.fun art is routinely 500 KB-1 MB of full-resolution PNG.+ const art = w.image ? proxiedImageURL(w.image, '', { width: 320, fallback: 'none' }) : '';if (art) {const i = el('img');i.src = art;diff --git a/src/community/town.js b/src/community/town.jsindex 069580f3e..143a647cc 100644--- a/src/community/town.js+++ b/src/community/town.js@@ -91,7 +91,8 @@ export class Town {const badge = el('div', 'town__badge');// Same gateway CORP rule as the lobby: proxy the pinned art so the// browser is allowed to paint it (see coin-lobby.js).- const headerArt = this.meta.image ? proxiedImageURL(this.meta.image, '', { fallback: 'none' }) : '';+ // .town__coin-img paints at 38x38; 96px covers it at DPR 2.5.+ const headerArt = this.meta.image ? proxiedImageURL(this.meta.image, '', { width: 96, fallback: 'none' }) : '';if (headerArt) {const img = el('img', 'town__coin-img');img.src = headerArt;@@ -488,7 +489,7 @@ export class Town {const sym = this.root.querySelector('.town__symbol');if (sym && this.meta.symbol) sym.textContent = `$${this.meta.symbol}`;const ph = this.root.querySelector('.town__coin-img--ph');- const badgeArt = this.meta.image ? proxiedImageURL(this.meta.image, '', { fallback: 'none' }) : '';+ const badgeArt = this.meta.image ? proxiedImageURL(this.meta.image, '', { width: 96, fallback: 'none' }) : '';if (ph && badgeArt) {const img = el('img', 'town__coin-img');img.src = badgeArt;diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 6d54dc00d..a4b54c0f7 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -792,7 +792,10 @@ export class CoinCommunities {// proxiedImageURL drops anything that is not a renderable image// source (javascript:, data:text/html, an oversized URL), so a hostile// `image=` resolves to '' and the world takes its generated art path.- image: proxiedImageURL(p.get('image') || '', mint),+ // Same COIN_ART_WIDTH the feed path uses: a share link can carry a+ // raw gateway URL, and without a width the world downloads the+ // creator's full-size upload to texture a totem.+ image: proxiedImageURL(p.get('image') || '', mint, { width: COIN_ART_WIDTH }),}, { tier }).catch((err) => this._onEnterFailed(err));}diff --git a/src/game/home-town.js b/src/game/home-town.jsindex 953b5d144..9c672cb31 100644--- a/src/game/home-town.js+++ b/src/game/home-town.js@@ -18,8 +18,17 @@ export const HOME_TOWN = {symbol: 'three',// Served through the same-origin /api/img proxy (multi-gateway IPFS retry +// immutable edge cache) so the front-door art never depends on one gateway.+ //+ // `w=512` matters: the pinned original is a 567 KB PNG, and without a width+ // the proxy hands back every one of those bytes. mapCoins() asks for 512 for+ // exactly this reason (COIN_ART_WIDTH in coincommunities.js) but this literal+ // predates it, so the ONE world every first-time visitor lands in was the one+ // paying full price. Measured on a Pixel 5 over slow 4G against production on+ // 2026-09-08, that single image was 581 KB of /play's 5,470 KB, second only to+ // the HDRI. It becomes a texture a few hundred pixels tall on the totem and+ // the jumbotron, so 512 is already generous.image: '/api/img?url=' + encodeURIComponent('https://ipfs.io/ipfs/bafybeihe22b5sxr3ihnxt7pregfieyteqvubqhik3j3y4bbx243xlqjw3q')- + '&seed=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ + '&seed=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&w=512',// The signature look for the home town: Dust Gulch, an old-west frontier town —// a packed-dirt square ringed by false-front storefronts (saloon, bank,// sheriff…) under a low golden-hour sun, with a water tower on the skyline anddiff --git a/src/shared/cinematic-render.js b/src/shared/cinematic-render.jsindex a12fe650d..16e5d2237 100644--- a/src/shared/cinematic-render.js+++ b/src/shared/cinematic-render.js@@ -31,10 +31,35 @@ export const HDRI_PRESETS = {sunset: '/hdri/sunset.hdr',};+/**+ * The same three environments at 512x256, about 360 KB each instead of 1.4 MB.+ *+ * The full-size files are the largest asset any 3D page downloads: on a Pixel 5+ * over slow 4G, `/hdri/outdoor.hdr` was 1,435 KB of `/play`'s 5,470 KB, which is+ * seven seconds of radio time before the world is lit. The map is PMREM-+ * prefiltered into irradiance before it lights anything, so almost all of that+ * resolution is discarded on the way in; what has to survive the downscale is+ * the light's ENERGY, and it does, to within 0.4% of the original's mean+ * radiance (see scripts/build-hdri-mobile.mjs, which regenerates and verifies+ * these). What is genuinely lost is the peak of the sun disc, so the sharpest+ * mirror highlight on a metal is softer here. That is the right thing to trade+ * on a phone and the wrong thing to trade on a desktop, which is why this is a+ * tier choice rather than a replacement.+ */+export const HDRI_PRESETS_MOBILE = {+ studio: '/hdri/studio-mobile.hdr',+ outdoor: '/hdri/outdoor-mobile.hdr',+ sunset: '/hdri/sunset-mobile.hdr',+};+/** Render quality tiers a viewer can request. 'mobile' matches the low-end /club profile. */export const QUALITY_TIERS = {high: { pixelRatioCap: 2, shadows: true, hdri: true },- medium: { pixelRatioCap: 1.5, shadows: true, hdri: true },+ // `hdriMobile` picks the 512x256 copy. 'medium' is where a real mid-tier+ // phone lands (coarse pointer, 4 GB of RAM is not "low"), and it was pulling+ // the full 1.4 MB file; only the weakest tier opted out, and opting out+ // entirely is a worse answer than a smaller map.+ medium: { pixelRatioCap: 1.5, shadows: true, hdri: true, hdriMobile: true },mobile: { pixelRatioCap: 1, shadows: false, hdri: false },};@@ -99,14 +124,20 @@ const _envCache = new Map();* @param {import('three').WebGLRenderer} renderer* @param {import('three').Scene} scene* @param {'studio'|'outdoor'|'sunset'|null} preset+ * @param {object} [opts]+ * @param {'high'|'medium'|'mobile'} [opts.tier] - which copy of the HDRI to+ * fetch. Defaults to the same capability probe applyCinematicDefaults uses, so+ * a caller that never passed a tier still stops sending a phone 1.4 MB.*/-export async function loadEnvironment(renderer, scene, preset = 'studio') {+export async function loadEnvironment(renderer, scene, preset = 'studio', opts = {}) {+ const tier = QUALITY_TIERS[opts.tier] ? opts.tier : detectQualityTier();+ const sources = QUALITY_TIERS[tier].hdriMobile ? HDRI_PRESETS_MOBILE : HDRI_PRESETS;const pmrem = new PMREMGenerator(renderer);pmrem.compileEquirectangularShader();const roomTarget = pmrem.fromScene(new RoomEnvironment(), 0.04);scene.environment = roomTarget.texture;scene.environmentIntensity ??= 1;- if (!preset || !HDRI_PRESETS[preset]) {+ if (!preset || !sources[preset]) {// PMREMGenerator holds its own materials and LOD planes; the render target// it just handed back stays valid after the generator is disposed, so this// frees the scratch without touching the environment map itself.@@ -114,13 +145,17 @@ export async function loadEnvironment(renderer, scene, preset = 'studio') {return scene.environment;}try {- let hdrTexture = _envCache.get(preset);+ // Keyed by URL, not by preset name: the same preset resolves to a different+ // file per tier, and caching by name alone would hand a page that switched+ // tiers the wrong resolution back.+ const url = sources[preset];+ let hdrTexture = _envCache.get(url);if (!hdrTexture) {// HDRLoader is the same decoder RGBELoader wraps; RGBELoader is a// deprecated alias since three r180 and logs a warning on every use.const { HDRLoader } = await import('three/addons/loaders/HDRLoader.js');- hdrTexture = await new HDRLoader().loadAsync(HDRI_PRESETS[preset]);- _envCache.set(preset, hdrTexture);+ hdrTexture = await new HDRLoader().loadAsync(url);+ _envCache.set(url, hdrTexture);}const envTarget = pmrem.fromEquirectangular(hdrTexture);// Another loadEnvironment call (a coin switch rebuilding the world, a stagediff --git a/tests/hdri-mobile-tier.test.js b/tests/hdri-mobile-tier.test.jsnew file mode 100644index 000000000..14fc139df--- /dev/null+++ b/tests/hdri-mobile-tier.test.js@@ -0,0 +1,74 @@+/**+ * The phone-sized HDRI set: that it exists, that it is a sound reduction of the+ * full-size original, and that the tier table actually routes a phone to it.+ *+ * The HDRIs are the largest asset any 3D page downloads. Measured on a Pixel 5+ * over slow 4G against production on 2026-09-08, `/hdri/outdoor.hdr` was+ * 1,435 KB of `/play`'s 5,470 KB. Only the weakest tier opted out of them; a+ * real mid-tier phone lands on 'medium' and was paying full price.+ *+ * The soundness assertion is the one that matters. A downscale through ffmpeg's+ * default `scale` filter CLAMPS float input to 1.0, which silently destroys the+ * high dynamic range while still producing a file that loads and looks like an+ * image. Nothing about the file size or the dimensions reveals that; only the+ * radiance does.+ */++import { describe, it, expect } from 'vitest';+import { existsSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import {+ hdrStats,+ mobileNameFor,+ MOBILE_WIDTH,+ MOBILE_HEIGHT,+ MEAN_TOLERANCE,+} from '../scripts/build-hdri-mobile.mjs';+import { HDRI_PRESETS, HDRI_PRESETS_MOBILE, QUALITY_TIERS } from '../src/shared/cinematic-render.js';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+const HDRI_DIR = join(ROOT, 'public/hdri');+const PRESETS = Object.keys(HDRI_PRESETS);++describe('mobile HDRI variants', () => {+ it('offers a mobile copy of every full-size preset, at the same keys', () => {+ expect(Object.keys(HDRI_PRESETS_MOBILE).sort()).toEqual(PRESETS.slice().sort());+ });++ it.each(PRESETS)('%s ships a committed -mobile.hdr the URL table points at', (preset) => {+ const file = join(HDRI_DIR, mobileNameFor(preset));+ expect(existsSync(file)).toBe(true);+ expect(HDRI_PRESETS_MOBILE[preset]).toBe(`/hdri/${mobileNameFor(preset)}`);+ });++ it.each(PRESETS)('%s reduces to 512x256 and stays under half the bytes', (preset) => {+ const full = hdrStats(join(HDRI_DIR, `${preset}.hdr`));+ const small = hdrStats(join(HDRI_DIR, mobileNameFor(preset)));+ expect(small.width).toBe(MOBILE_WIDTH);+ expect(small.height).toBe(MOBILE_HEIGHT);+ expect(small.bytes).toBeLessThan(full.bytes * 0.5);+ });++ it.each(PRESETS)('%s keeps the light energy of the original (the clamp regression)', (preset) => {+ const full = hdrStats(join(HDRI_DIR, `${preset}.hdr`));+ const small = hdrStats(join(HDRI_DIR, mobileNameFor(preset)));+ const drift = Math.abs(small.mean - full.mean) / full.mean;+ expect(drift).toBeLessThanOrEqual(MEAN_TOLERANCE);+ // A clamped file peaks at exactly 1.0 whatever the source was. Every one of+ // these sources has values well above that, so the copy must too.+ expect(full.max).toBeGreaterThan(1);+ expect(small.max).toBeGreaterThan(1);+ });++ it('routes the mid tier to the small copy and leaves the top tier alone', () => {+ expect(QUALITY_TIERS.medium.hdri).toBe(true);+ expect(QUALITY_TIERS.medium.hdriMobile).toBe(true);+ expect(QUALITY_TIERS.high.hdri).toBe(true);+ expect(QUALITY_TIERS.high.hdriMobile).toBeUndefined();+ // The weakest tier still loads none at all; a 360 KB map is a better answer+ // than 1.4 MB, not a better answer than nothing on a device that cannot+ // afford shadows either.+ expect(QUALITY_TIERS.mobile.hdri).toBe(false);+ });+});