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.

Add avatar fork endpoint and club entrance audio/venue

nirholasefb88f73e4bd
diff --git a/.gitignore b/.gitignore
index aa3d3337a..6297674b3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -232,3 +232,5 @@ scripts/test-corr.mjs
*_tweets_*.json
scripts/.corr-*
space_smugglers_club_house_-_dark_version.glb
+
+im-in-love-wit-a-stripper-fast.mp3
diff --git a/api/_lib/agent-wallet.js b/api/_lib/agent-wallet.js
index a65dbc7c7..54f206079 100644
--- a/api/_lib/agent-wallet.js
+++ b/api/_lib/agent-wallet.js
@@ -82,6 +82,54 @@ export async function recoverAgentKey(encryptedKey) {
return decrypt(encryptedKey);
}
+/**
+ * Idempotently provision a custodial EVM wallet for an agent.
+ *
+ * Mirrors getOrCreateAgentSolanaWallet(): generate a keypair via
+ * generateAgentWallet(), store the address in agent_identities.wallet_address
+ * and the encrypted key in meta.encrypted_wallet_key, and never re-create if one
+ * already exists. Returns { address, created }.
+ */
+export async function getOrCreateAgentEvmWallet(agentId, { chainId = 8453 } = {}) {
+ const { sql } = await import('./db.js');
+ const [row] = await sql`
+ select id, wallet_address, meta from agent_identities
+ where id = ${agentId} and deleted_at is null
+ limit 1
+ `;
+ if (!row) throw new Error('agent not found');
+ if (row.wallet_address && row.meta?.encrypted_wallet_key) {
+ return { address: row.wallet_address, created: false };
+ }
+
+ const wallet = await generateAgentWallet();
+ const meta = {
+ ...(row.meta || {}),
+ encrypted_wallet_key: wallet.encrypted_key,
+ evm_wallet_source: 'generated',
+ };
+ await sql`
+ update agent_identities
+ set wallet_address = ${wallet.address},
+ chain_id = coalesce(chain_id, ${chainId}),
+ meta = ${JSON.stringify(meta)}::jsonb
+ where id = ${agentId}
+ `;
+ return { address: wallet.address, created: true };
+}
+
+/**
+ * Idempotently provision BOTH the EVM and Solana custodial wallets for an agent.
+ * Used by the "create wallet" action on every avatar surface and by the
+ * auto-provision on first avatar save. Returns the live addresses.
+ * @returns {Promise<{ evm: string, solana: string, created: boolean }>}
+ */
+export async function provisionAgentWallets(agentId, { chainId = 8453 } = {}) {
+ const evm = await getOrCreateAgentEvmWallet(agentId, { chainId });
+ const sol = await getOrCreateAgentSolanaWallet(agentId);
+ return { evm: evm.address, solana: sol.address, created: evm.created || sol.created };
+}
+
// ── EVM on-chain balance + spend helpers ────────────────────────────────────
let _ethUsdPrice = null;
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.js
index 7c148385c..3dd982c1a 100644
--- a/api/_lib/avatars.js
+++ b/api/_lib/avatars.js
@@ -35,7 +35,7 @@ export async function listAvatars({
`select a.id, a.owner_id, a.slug, a.name, a.description, a.storage_key, a.thumbnail_key,
a.alt_text,
a.appearance, a.appearance_hash, a.baked_storage_key, a.baked_at,
- a.size_bytes, a.content_type, a.source, a.visibility, a.tags, a.version,
+ a.size_bytes, a.content_type, a.source, a.source_meta, a.fork_count, a.visibility, a.tags, a.version,
a.model_category,
a.created_at, a.updated_at, a.parent_avatar_id,
ai.id as agent_id, ai.wallet_address as agent_wallet_address
@@ -242,7 +242,7 @@ export async function searchPublicAvatars({ q, tag, limit = 24, cursor, withTota
av.alt_text,
av.appearance, av.appearance_hash, av.baked_storage_key, av.baked_at,
av.size_bytes,
- av.content_type, av.source, av.visibility, av.tags, av.view_count, av.created_at,
+ av.content_type, av.source, av.source_meta, av.fork_count, av.visibility, av.tags, av.view_count, av.created_at,
ai.id as agent_id, ai.onchain as agent_onchain
from avatars av
left join lateral (
@@ -346,6 +346,12 @@ function decorate(row) {
content_type: row.content_type,
source: row.source,
source_meta: row.source_meta || {},
+ // GitHub-style fork lineage. `forked_from` (captured at fork time in
+ // source_meta) names the original avatar + owner so the UI can render a
+ // "Forked from @owner" link without a join. `fork_count` is how many
+ // times THIS avatar has itself been forked by others.
+ forked_from: (row.source_meta && row.source_meta.forked_from) || null,
+ fork_count: row.fork_count == null ? 0 : Number(row.fork_count),
model_category: row.model_category || 'avatar',
visibility: row.visibility,
tags: row.tags || [],
diff --git a/api/_lib/migrations/20260615040000_avatars_fork.sql b/api/_lib/migrations/20260615040000_avatars_fork.sql
new file mode 100644
index 000000000..6feca6448
--- /dev/null
+++ b/api/_lib/migrations/20260615040000_avatars_fork.sql
@@ -0,0 +1,26 @@
+-- GitHub-style avatar forks.
+--
+-- When one user "saves" another user's avatar it becomes a NEW avatar in the
+-- saver's namespace (new owner_id, copied GLB), linked back to the original via
+-- parent_avatar_id with full attribution in source_meta.forked_from. Neither
+-- user can mutate or delete the other's row — they are independent objects.
+--
+-- 1. 'fork' joins the allowed source set so forked avatars carry clear provenance.
+-- 2. fork_count caches how many times an avatar has been forked (for the
+-- "Forked NN times" badge), maintained by api/avatars/fork.js.
+-- 3. An index on parent_avatar_id makes "list forks of X" / fork-count backfill
+-- cheap.
+
+ALTER TABLE avatars
+DROP CONSTRAINT avatars_source_check,
+ADD CONSTRAINT avatars_source_check
+ CHECK (source = ANY (ARRAY[
+ 'upload', 'avaturn', 'readyplayer', 'import',
+ 'direct-upload', 'reconstruct', 'studio', 'forge', 'fork'
+ ]));
+
+ALTER TABLE avatars
+ ADD COLUMN IF NOT EXISTS fork_count integer NOT NULL DEFAULT 0;
+
+CREATE INDEX IF NOT EXISTS idx_avatars_parent ON avatars (parent_avatar_id)
+ WHERE parent_avatar_id IS NOT NULL;
diff --git a/api/_lib/r2.js b/api/_lib/r2.js
index e9a72d78e..951763890 100644
--- a/api/_lib/r2.js
+++ b/api/_lib/r2.js
@@ -6,6 +6,7 @@ import {
GetObjectCommand,
DeleteObjectCommand,
HeadObjectCommand,
+ CopyObjectCommand,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { env } from './env.js';
@@ -90,6 +91,24 @@ export async function putObject({ key, body, contentType, metadata = {} }) {
);
}
+// Server-side object copy (no download/re-upload). Used by avatar forks to
+// duplicate a source GLB/thumbnail into the new owner's `u/{ownerId}/` namespace
+// so the fork is a fully independent object. Returns false (and the caller can
+// fall back to referencing the source URL) when the source is an absolute URL
+// rather than a bucket object — those live outside our bucket and nothing needs
+// copying.
+export async function copyObject({ fromKey, toKey }) {
+ if (isAbsoluteUrl(fromKey)) return false;
+ await r2.send(
+ new CopyObjectCommand({
+ Bucket: env.S3_BUCKET,
+ CopySource: `${env.S3_BUCKET}/${encodeR2Key(fromKey)}`,
+ Key: toKey,
+ }),
+ );
+ return true;
+}
+
export async function getObjectBuffer(key) {
const { Body } = await r2.send(new GetObjectCommand({ Bucket: env.S3_BUCKET, Key: key }));
const chunks = [];
diff --git a/api/agents.js b/api/agents.js
index bd86e4d4a..c0dee13f7 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -477,7 +477,7 @@ async function handleDelete(req, res, id, auth) {
// ── Wallet ────────────────────────────────────────────────────────────────
-export async function handleWallet(req, res, id) {
+export async function handleWallet(req, res, id, action = null) {
if (cors(req, res, { methods: 'POST,DELETE,OPTIONS', credentials: true })) return;
const auth = await resolveAuth(req);
@@ -485,11 +485,30 @@ export async function handleWallet(req, res, id) {
if (!(await requireCsrf(req, res, auth.userId))) return;
const [existing] = await sql`
- SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ SELECT id, user_id, wallet_address FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
`;
if (!existing) return error(res, 404, 'not_found', 'agent not found');
if (existing.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+ // POST /api/agents/:id/wallet/provision — idempotently generate the agent's
+ // custodial EVM + Solana wallets. This is the "Create wallet" action surfaced
+ // on every avatar surface; safe to call repeatedly (returns existing addresses).
+ if (action === 'provision') {
+ if (!method(req, res, ['POST'])) return;
+ const { provisionAgentWallets } = await import('./_lib/agent-wallet.js');
+ try {
+ const wallets = await provisionAgentWallets(id);
+ return json(res, 200, {
+ ok: true,
+ created: wallets.created,
+ wallet_address: wallets.evm,
+ solana_address: wallets.solana,
+ });
+ } catch (e) {
+ return error(res, 500, 'provision_failed', e?.message || 'wallet provisioning failed');
+ }
+ }
+
if (req.method === 'DELETE') {
await sql`
UPDATE agent_identities
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 3d596a4e3..4d6360519 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -45,7 +45,7 @@ export default wrap(async function handler(req, res) {
return error(res, 404, 'not_found', 'agent not found');
}
- if (sub === 'wallet') return handleWallet(req, res, id);
+ if (sub === 'wallet') return handleWallet(req, res, id, action);
if (sub === 'solana') {
const mod = await import('./solana-wallet.js');
diff --git a/api/avatars/fork.js b/api/avatars/fork.js
new file mode 100644
index 000000000..67996d992
--- /dev/null
+++ b/api/avatars/fork.js
@@ -0,0 +1,167 @@
+// POST /api/avatars/fork — GitHub-style "save someone else's avatar".
+//
+// Saving another user's avatar never produces shared ownership of one row.
+// It creates a NEW avatar in the caller's namespace: the source GLB (and
+// thumbnail) are server-side copied into `u/{callerId}/…`, a fresh avatar row
+// is inserted with owner_id = caller, source = 'fork', parent_avatar_id = source,
+// and full attribution captured in source_meta.forked_from. The new avatar gets
+// its own agent + freshly provisioned custodial wallet — the caller controls it
+// alone; the original owner's avatar, agent, and wallet are untouched.
+
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { createAvatar, storageKeyFor } from '../_lib/avatars.js';
+import { copyObject, headObject } from '../_lib/r2.js';
+import { provisionAgentWallets } from '../_lib/agent-wallet.js';
+import { sql } from '../_lib/db.js';
+import { withDbRetry } from '../_lib/db-retry.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { isUuid } from '../_lib/validate.js';
+import { recordEvent } from '../_lib/usage.js';
+import { dispatchWebhooks } from '../_lib/webhook-dispatch.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req, 'avatars:write');
+ if (!auth) return error(res, 401, 'unauthorized', 'avatars:write scope required');
+
+ const body = await readJson(req);
+ const sourceId = String(body.source_avatar_id || body.avatar_id || '').trim();
+ if (!isUuid(sourceId)) return error(res, 400, 'validation_error', 'source_avatar_id required');
+
+ // Load the raw source row (need storage_key/thumbnail_key, which decorate hides).
+ const [src] = await sql`
+ select a.id, a.owner_id, a.name, a.description, a.storage_key, a.thumbnail_key,
+ a.content_type, a.size_bytes, a.visibility, a.tags, a.appearance,
+ a.model_category, a.slug, u.display_name as owner_name
+ from avatars a
+ join users u on u.id = a.owner_id
+ where a.id = ${sourceId} and a.deleted_at is null
+ limit 1
+ `;
+ if (!src) return error(res, 404, 'not_found', 'avatar not found');
+
+ // Only public / unlisted avatars (or your own) can be forked. A private
+ // avatar you don't own must not even be discoverable as forkable.
+ if (src.visibility === 'private' && src.owner_id !== auth.userId) {
+ return error(res, 404, 'not_found', 'avatar not found');
+ }
+
+ // Copy the model object into the caller's namespace so the fork is fully
+ // independent. Absolute-URL ("first-party hosted") sources live outside the
+ // bucket — reference the URL directly rather than copying.
+ const slugBase =
+ (src.slug || src.name || 'avatar')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 40) || 'avatar';
+ let newStorageKey = storageKeyFor({ userId: auth.userId, slug: slugBase });
+ const copiedGlb = await copyObject({ fromKey: src.storage_key, toKey: newStorageKey });
+ if (!copiedGlb) newStorageKey = src.storage_key; // hosted URL — pass through
+
+ // Best-effort thumbnail copy. Never fatal — the gallery falls back to the name.
+ let newThumbKey = null;
+ if (src.thumbnail_key) {
+ try {
+ const candidate = `u/${auth.userId}/${slugBase}/${Date.now().toString(36)}-thumb.png`;
+ const copiedThumb = await copyObject({ fromKey: src.thumbnail_key, toKey: candidate });
+ newThumbKey = copiedThumb ? candidate : src.thumbnail_key;
+ } catch (e) {
+ console.warn('[fork] thumbnail copy failed', e?.message);
+ }
+ }
+
+ // Confirm the copied object is real before we register a row pointing at it.
+ if (copiedGlb) {
+ const head = await headObject(newStorageKey);
+ if (!head) return error(res, 502, 'copy_failed', 'failed to copy source model');
+ }
+
+ const forked_from = {
+ avatar_id: src.id,
+ owner_id: src.owner_id,
+ owner_name: src.owner_name || null,
+ name: src.name,
+ slug: src.slug,
+ };
+
+ const avatar = await createAvatar({
+ userId: auth.userId,
+ input: {
+ name: src.name,
+ description: src.description ?? null,
+ size_bytes: Number(src.size_bytes),
+ content_type: src.content_type || 'model/gltf-binary',
+ source: 'fork',
+ source_meta: { forked_from },
+ // Default a fork to unlisted: usable + shareable by the new owner, but
+ // not injected into the public gallery until they choose to publish.
+ visibility: 'unlisted',
+ tags: src.tags || [],
+ checksum_sha256: null,
+ parent_avatar_id: src.id,
+ appearance: src.appearance || null,
+ },
+ storageKey: newStorageKey,
+ });
+
+ if (newThumbKey) {
+ await sql`update avatars set thumbnail_key = ${newThumbKey} where id = ${avatar.id}`.catch(
+ () => {},
+ );
+ }
+
+ // Bump the source's fork counter (best-effort; never blocks the fork).
+ sql`update avatars set fork_count = fork_count + 1 where id = ${src.id}`.catch(() => {});
+
+ // Create the fork's own agent and provision its custodial wallet synchronously
+ // so the response can hand back the new wallet address. Owned by the caller.
+ let agent = null;
+ try {
+ agent = await withDbRetry(async () => {
+ const [row] = await sql`
+ insert into agent_identities (user_id, name, avatar_id, is_public, created_at, updated_at)
+ values (${auth.userId}, ${avatar.name || 'My Agent'}, ${avatar.id}, false, now(), now())
+ returning id
+ `;
+ return row;
+ });
+ if (agent?.id) {
+ const wallets = await provisionAgentWallets(agent.id);
+ agent = { id: agent.id, wallet_address: wallets.evm, solana_address: wallets.solana };
+ }
+ } catch (e) {
+ // A wallet provisioning hiccup must not fail the fork — the avatar + agent
+ // still exist and the wallet can be (re)provisioned from any avatar surface.
+ console.error('[fork] agent/wallet provision failed', { avatarId: avatar.id, error: e?.message });
+ }
+
+ dispatchWebhooks({
+ userId: auth.userId,
+ eventType: 'avatar.created',
+ data: { id: avatar.id, name: avatar.name, slug: avatar.slug, source: 'fork', forked_from: src.id },
+ }).catch(() => {});
+
+ recordEvent({
+ userId: auth.userId,
+ apiKeyId: auth.apiKeyId,
+ clientId: auth.clientId,
+ avatarId: avatar.id,
+ kind: 'fork',
+ bytes: avatar.size_bytes,
+ meta: { source_avatar_id: src.id },
+ });
+
+ return json(res, 201, { avatar, agent });
+});
+
+async function resolveAuth(req, requiredScope) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id, source: 'session' };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (!bearer) return null;
+ if (!hasScope(bearer.scope, requiredScope)) return null;
+ return bearer;
+}
diff --git a/api/avatars/index.js b/api/avatars/index.js
index 43daaad01..b6da635db 100644
--- a/api/avatars/index.js
+++ b/api/avatars/index.js
@@ -127,7 +127,7 @@ async function handleCreate(req, res) {
// without its agent. The claim is naturally idempotent and the
// insert is guarded by NOT EXISTS below, so the whole sequence is
// safe to retry on a connection-level failure.
- await withDbRetry(async () => {
+ const agentId = await withDbRetry(async () => {
// First try to claim an existing agent that has no avatar yet.
const linked = await sql`
WITH agent_to_update AS (
@@ -144,26 +144,37 @@ async function handleCreate(req, res) {
WHERE agent_identities.id = agent_to_update.id
RETURNING agent_identities.id
`;
+ if (linked.length) return linked[0].id;
// No existing agent to claim — create a default one. The NOT EXISTS
// guard keeps a retried insert (after a lost response) from
// creating a second agent for the same avatar.
- if (!linked.length) {
- await sql`
- INSERT INTO agent_identities (user_id, name, avatar_id, is_public, created_at, updated_at)
- SELECT
- ${auth.userId},
- ${avatar.name || 'My Agent'},
- ${avatar.id},
- false,
- NOW(),
- NOW()
- WHERE NOT EXISTS (
- SELECT 1 FROM agent_identities
- WHERE user_id = ${auth.userId} AND avatar_id = ${avatar.id}
- )
- `;
- }
+ const [created] = await sql`
+ INSERT INTO agent_identities (user_id, name, avatar_id, is_public, created_at, updated_at)
+ SELECT
+ ${auth.userId},
+ ${avatar.name || 'My Agent'},
+ ${avatar.id},
+ false,
+ NOW(),
+ NOW()
+ WHERE NOT EXISTS (
+ SELECT 1 FROM agent_identities
+ WHERE user_id = ${auth.userId} AND avatar_id = ${avatar.id}
+ )
+ RETURNING id
+ `;
+ return created?.id ?? null;
});
+
+ // Every avatar's agent gets a custodial wallet on first save so it
+ // can transact immediately. Idempotent — a claimed agent that already
+ // has a wallet is left untouched.
+ if (agentId) {
+ const { provisionAgentWallets } = await import('../_lib/agent-wallet.js');
+ await provisionAgentWallets(agentId).catch((e) =>
+ console.warn('[avatars] wallet provision failed', agentId, e?.message),
+ );
+ }
} catch (err) {
console.error('[avatars] auto-agent failed', {
avatarId: avatar.id,
diff --git a/public/club/audio/LICENSES.md b/public/club/audio/LICENSES.md
index 856b73e94..3b2be8d69 100644
--- a/public/club/audio/LICENSES.md
+++ b/public/club/audio/LICENSES.md
@@ -8,11 +8,14 @@ and re-running `node scripts/build-club-audio.mjs` regenerates these
files byte-for-byte.
Because no external sample material was used, three.ws holds full
-copyright on these audio files and dedicates them to the public domain
+copyright on these loops and dedicates them to the public domain
under **Creative Commons CC0 1.0 Universal**
(https://creativecommons.org/publicdomain/zero/1.0/). You can use them
for any purpose, with or without attribution.
+The one exception is `entrance.mp3` (the walk-in anthem) — a supplied
+third-party track that is **not** CC0. See its row in the table below.
+
| File | Source | License | Length | Notes |
| -------------------- | ------------------------------------------------------------- | ------- | --------------------- | --------------------------------------------------------------------- |
| `ambience.{ogg,mp3}` | Authored — pink noise bed + slow LFO + low rumble | CC0 1.0 | ~60 s loop | Crowd / room ambience. Constant level, no rhythmic content. |
@@ -22,6 +25,7 @@ for any purpose, with or without attribution.
| `capoeira.{ogg,mp3}` | Authored — 110 BPM berimbau ostinato + atabaque approximation | CC0 1.0 | ~8.7 s loop (4 bars) | Brazilian roda rhythm for the Capoeira clip. |
| `silly.{ogg,mp3}` | Authored — 130 BPM major-key bounce + woodblock + cartoon arp | CC0 1.0 | ~7.4 s loop (4 bars) | Playful bed for the Silly clip. |
| `pole.{ogg,mp3}` | Authored — 105 BPM neutral groove + sine pad | CC0 1.0 | ~9.1 s loop (4 bars) | Generic backing track for pole choreography clips (spin/climb/combo). |
+| `entrance.mp3` | Supplied third-party track | © original artist — **not** CC0 | full track, one-shot | Walk-in anthem played once on `club:admitted` via `ClubAudio.playEntrance()`. Not synthesised — confirm the artist's license before any redistribution beyond three.ws. |
## Mastering notes
diff --git a/public/club/audio/entrance.mp3 b/public/club/audio/entrance.mp3
new file mode 100644
index 000000000..1ad4f7a9c
Binary files /dev/null and b/public/club/audio/entrance.mp3 differ
diff --git a/public/club/venue/LICENSES.md b/public/club/venue/LICENSES.md
index de1451576..099f50758 100644
--- a/public/club/venue/LICENSES.md
+++ b/public/club/venue/LICENSES.md
@@ -47,3 +47,21 @@ npm run build:club-assets # → both props + venue (in one shot)
Output is deterministic — same input code produces byte-identical files —
so committed files only change when a builder script changes.
+
+## Third-party entrance asset
+
+`space-smugglers-clubhouse.glb` is **not** authored by three.ws. It is the
+interior rendered live behind the cover-charge door (the backdrop in
+[src/club-entrance.js](../../../src/club-entrance.js)), compressed from a
+supplied "Space Smugglers Club House (dark version)" GLB export.
+
+| File | Source | License | Modifications |
+| ------------------------------- | --------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `space-smugglers-clubhouse.glb` | Supplied third-party export | © original author — see source | weld + prune + dedup, textures resized ≤2048 → WebP q82, position/normal/UV quantization, Meshopt compression (~20 MB → ~1.6 MB) via [scripts/build-club-entrance-venue.mjs](../../../scripts/build-club-entrance-venue.mjs) |
+
+This file is **not** CC0 — confirm the original model's license before any
+redistribution beyond three.ws. Regenerate from the source export with:
+
+```sh
+npm run build:club-entrance-venue # → space-smugglers-clubhouse.glb
+```
diff --git a/public/club/venue/space-smugglers-clubhouse.glb b/public/club/venue/space-smugglers-clubhouse.glb
new file mode 100644
index 000000000..99f635857
Binary files /dev/null and b/public/club/venue/space-smugglers-clubhouse.glb differ
diff --git a/scripts/build-club-entrance-venue.mjs b/scripts/build-club-entrance-venue.mjs
new file mode 100644
index 000000000..19a8e6759
--- /dev/null
+++ b/scripts/build-club-entrance-venue.mjs
@@ -0,0 +1,85 @@
+#!/usr/bin/env node
+/**
+ * Compresses the authored "space smugglers club house" GLB into the runtime
+ * asset the /club entrance scene loads (src/club-entrance.js). The raw export
+ * is ~21 MB — far too heavy to stream behind the cover-charge door while a
+ * visitor waits in line — so we run the same GLB → Meshopt + WebP pipeline the
+ * rest of the venue assets use:
+ *
+ * weld → prune → dedup → resize+WebP textures → quantize → Meshopt
+ *
+ * The runtime GLTFLoader (src/loaders/gltf.js) already wires the Meshopt
+ * decoder + EXT_texture_webp, so the output drops straight in with no loader
+ * changes. Re-run after re-exporting the source model:
+ *
+ * npm run build:club-entrance-venue
+ */
+
+import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import {
+ weld,
+ prune,
+ dedup,
+ quantize,
+ textureCompress,
+ meshopt,
+} from '@gltf-transform/functions';
+import { MeshoptEncoder } from 'meshoptimizer';
+import sharp from 'sharp';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, '..');
+
+const SRC = resolve(ROOT, 'space_smugglers_club_house_-_dark_version.glb');
+const OUT_DIR = resolve(ROOT, 'public/club/venue');
+const OUT = resolve(OUT_DIR, 'space-smugglers-clubhouse.glb');
+
+const MAX_TEXTURE = 2048;
+
+async function main() {
+ if (!existsSync(SRC)) {
+ throw new Error(`source GLB not found: ${SRC}`);
+ }
+
+ await MeshoptEncoder.ready;
+
+ const io = new NodeIO()
+ .registerExtensions(ALL_EXTENSIONS)
+ .registerDependencies({ 'meshopt.encoder': MeshoptEncoder });
+
+ const before = statSync(SRC).size;
+ const doc = await io.read(SRC);
+
+ await doc.transform(
+ weld(),
+ prune(),
+ dedup(),
+ textureCompress({
+ encoder: sharp,
+ targetFormat: 'webp',
+ resize: [MAX_TEXTURE, MAX_TEXTURE],
+ quality: 82,
+ }),
+ quantize({ pattern: /.*/, quantizePosition: 14, quantizeNormal: 10, quantizeTexcoord: 12 }),
+ meshopt({ encoder: MeshoptEncoder, level: 'high' }),
+ );
+
+ mkdirSync(OUT_DIR, { recursive: true });
+ const glb = await io.writeBinary(doc);
+ writeFileSync(OUT, glb);
+
+ const after = statSync(OUT).size;
+ const mb = (n) => (n / 1024 / 1024).toFixed(2);
+ console.log(`club entrance venue: ${mb(before)} MB → ${mb(after)} MB`);
+ console.log(`wrote ${OUT}`);
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/src/club-audio.js b/src/club-audio.js
index 1448f8825..6b680f955 100644
--- a/src/club-audio.js
+++ b/src/club-audio.js
@@ -22,6 +22,8 @@ const AMBIENCE_GAIN = 0.35;
const STYLE_GAIN = 0.75;
const AMBIENCE_DUCK_GAIN = 0.1;
const MASTER_GAIN = 0.75;
+// Walk-in anthem — plays once, full-volume, the moment the rope drops.
+const ENTRANCE_GAIN = 0.9;
export class ClubAudio {
constructor() {
@@ -29,6 +31,8 @@ export class ClubAudio {
this.master = null;
this.ambience = null; // { source, gain }
this.style = null; // { name, source, gain }
+ this.entrance = null; // { source, gain } — one-shot walk-in anthem
+ this._entrancePlayed = false;
this.analyser = null;
this._buffers = new Map(); // styleName → AudioBuffer
this._loading = new Map(); // styleName → Promise<AudioBuffer>
@@ -184,6 +188,70 @@ export class ClubAudio {
}
}
+ // One-shot walk-in anthem: the moment the bouncer admits the wallet we
+ // play `entrance.{ogg,mp3}` straight through (no loop), ducking any crowd
+ // ambience under it and restoring it when the track ends. Routed through
+ // the master bus, so the mute pill silences it like everything else.
+ //
+ // Throws if the AudioContext can't be unlocked (no user gesture yet) so
+ // the caller can retry on the next interaction — and leaves
+ // `_entrancePlayed` false in that case so the retry still fires.
+ async playEntrance(name = 'entrance', { gain = ENTRANCE_GAIN } = {}) {
+ if (this._entrancePlayed) return null;
+ await this.ensureContext();
+ if (this.ctx.state === 'suspended') {
+ try {
+ await this.ctx.resume();
+ } catch {}
+ }
+ if (this.ctx.state === 'suspended') {
+ throw new Error('AudioContext locked — needs a user gesture');
+ }
+
+ const buf = await this.loadBuffer(name);
+ // A second caller may have won the race while we awaited the buffer.
+ if (this._entrancePlayed) return null;
+ this._entrancePlayed = true;
+
+ const source = this.ctx.createBufferSource();
+ source.buffer = buf;
+ source.loop = false;
+ const g = this.ctx.createGain();
+ g.gain.value = gain;
+ source.connect(g).connect(this.master);
+
+ const now = this.ctx.currentTime;
+ // Duck ambience under the anthem if it's already running.
+ if (this.ambience) {
+ this.ambience.gain.gain.cancelScheduledValues(now);
+ this.ambience.gain.gain.setValueAtTime(this.ambience.gain.gain.value, now);
+ this.ambience.gain.gain.linearRampToValueAtTime(AMBIENCE_DUCK_GAIN, now + 0.4);
+ }
+
+ source.onended = () => {
+ try {
+ source.disconnect();
+ } catch {}
+ // Bring ambience back up if it's still around when the anthem ends.
+ if (this.ambience && this.ctx) {
+ const t = this.ctx.currentTime;
+ this.ambience.gain.gain.cancelScheduledValues(t);
+ this.ambience.gain.gain.setValueAtTime(this.ambience.gain.gain.value, t);
+ this.ambience.gain.gain.linearRampToValueAtTime(AMBIENCE_GAIN, t + 1.2);
+ }
+ this.entrance = null;
+ };
+ source.start();
+ this.entrance = { source, gain: g };
+
+ if (this._onStatus) {
+ try {
+ this._onStatus(name);
+ } catch {}
+ }
+ return this.entrance;
+ }
+
_fadeOutLayer(layer, durationMs) {
const now = this.ctx.currentTime;
const end = now + Math.max(0.05, durationMs / 1000);
@@ -259,6 +327,7 @@ export function styleAudioFor(dance) {
// Display labels for screen-reader announcements.
export const TRACK_LABELS = Object.freeze({
ambience: 'Crowd ambience',
+ entrance: 'Walk-in anthem',
rumba: 'Rumba mix',
silly: 'Silly mix',
thriller: 'Thriller mix',
diff --git a/src/club-entrance.js b/src/club-entrance.js
new file mode 100644
index 000000000..328ca2399
--- /dev/null
+++ b/src/club-entrance.js
@@ -0,0 +1,221 @@
+// /club entrance — a real 3D scene behind the cover-charge door.
+//
+// Our avatar stands in the Space Smugglers club house while you wait in line.
+// It renders into its own canvas (#club-door-canvas) layered under the door
+// card, so the door (src/club-gate.js) is a panel floating over a live scene
+// rather than a flat screen. When the bouncer admits you (`club:admitted`),
+// the camera dollies in toward the avatar as the rope drops, then the scene
+// disposes and the pole stage (src/club.js) takes over.
+//
+// Kept deliberately light: one model (~1.6 MB Meshopt+WebP clubhouse, built by
+// scripts/build-club-entrance-venue.mjs), the shared avatar GLB (already
+// cached for the stage), a few accent lights, no postprocessing. If a wallet
+// already holds a pass for the night the door is gone on load, so we skip the
+// scene entirely.
+
+import {
+ AmbientLight,
+ Box3,
+ Fog,
+ Group,
+ HemisphereLight,
+ PerspectiveCamera,
+ PointLight,
+ Scene,
+ SpotLight,
+ SRGBColorSpace,
+ Vector3,
+ WebGLRenderer,
+ ACESFilmicToneMapping,
+} from 'three';
+import { gltfLoader } from './loaders/gltf.js';
+import { AnimationManager } from './animation-manager.js';
+import { log } from './shared/log.js';
+
+const CLUBHOUSE_URL = '/club/venue/space-smugglers-clubhouse.glb';
+const AVATAR_URL = '/avatars/default.glb';
+const MANIFEST_URL = '/animations/manifest.json';
+const PASS_KEY = 'club:pass:v1';
+const IDLE_CLIPS = new Set(['idle', 'walk']);
+
+const canvas = document.getElementById('club-door-canvas');
+const door = document.getElementById('club-door');
+
+// No canvas, or the wallet already paid cover tonight (door auto-dismissed) —
+// nothing to render.
+if (canvas && door && !hasValidPass()) {
+ start(canvas).catch((err) => {
+ // A scene failure must never block entry — the cover door still works
+ // on its own. Just leave the canvas dark.
+ log.warn('[club-entrance] scene failed', err);
+ });
+}
+
+function hasValidPass() {
+ try {
+ const raw = localStorage.getItem(PASS_KEY);
+ if (!raw) return false;
+ const p = JSON.parse(raw);
+ return p?.expiresAt && Date.parse(p.expiresAt) > Date.now();
+ } catch {
+ return false;
+ }
+}
+
+async function start(canvasEl) {
+ const renderer = new WebGLRenderer({ canvas: canvasEl, antialias: true, alpha: true });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+ renderer.setSize(window.innerWidth, window.innerHeight, false);
+ renderer.outputColorSpace = SRGBColorSpace;
+ renderer.toneMapping = ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.15;
+
+ const scene = new Scene();
+ scene.background = null; // canvas alpha — the CSS gradient shows through edges
+ scene.fog = new Fog(0x05030a, 8, 26);
+
+ const camera = new PerspectiveCamera(42, window.innerWidth / window.innerHeight, 0.05, 100);
+ const camStart = new Vector3(1.7, 1.65, 4.0);
+ const camLook = new Vector3(0, 1.0, 0);
+ camera.position.copy(camStart);
+ camera.lookAt(camLook);
+
+ // ── Lighting — moody club palette, keyed on the avatar ──────────────────
+ scene.add(new AmbientLight(0x241433, 0.7));
+ const hemi = new HemisphereLight(0xff6abf, 0x0a0512, 0.4);
+ hemi.position.set(0, 6, 0);
+ scene.add(hemi);
+
+ // Warm key spot from the doorway side, raking across the avatar.
+ const key = new SpotLight(0xffd6a0, 18, 16, Math.PI / 6, 0.5, 1.4);
+ key.position.set(2.4, 4.2, 3.2);
+ key.target.position.set(0, 1.0, 0);
+ scene.add(key, key.target);
+
+ // Neon rim accents — pink behind, cyan side — the club signature.
+ const pink = new PointLight(0xff3bd6, 6, 14, 1.5);
+ pink.position.set(-2.2, 2.4, -2.0);
+ scene.add(pink);
+ const cyan = new PointLight(0x4ad6ff, 4, 12, 1.6);
+ cyan.position.set(2.6, 1.6, -1.2);
+ scene.add(cyan);
+
+ const loader = gltfLoader(renderer);
+
+ // Load the clubhouse + avatar + animation manifest together.
+ const [houseGltf, avatarGltf, manifest] = await Promise.all([
+ loader.loadAsync(CLUBHOUSE_URL),
+ loader.loadAsync(AVATAR_URL),
+ fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => (r.ok ? r.json() : [])).catch(() => []),
+ ]);
+
+ // ── Clubhouse: normalize the authored export to a room-sized backdrop and
+ // drop it to the floor, pushed back so the avatar reads clearly in front.
+ // normalizeToHeight scales the largest dimension, so the source units are
+ // irrelevant. ─────────────────────────────────────────────────────────────
+ const house = houseGltf.scene;
+ normalizeToHeight(house, 8.5);
+ const houseBox = new Box3().setFromObject(house);
+ house.position.y -= houseBox.min.y; // feet of the room on the floor
+ house.position.z -= 2.0; // set the avatar forward of the interior
+ house.traverse((n) => {
+ if (n.isMesh && n.material && 'envMapIntensity' in n.material) n.material.envMapIntensity = 0.8;
+ });
+ scene.add(house);
+
+ // ── Avatar: our default, standing front-and-center, idling ──────────────
+ const avatar = avatarGltf.scene;
+ const aBox = new Box3().setFromObject(avatar);
+ avatar.position.y -= aBox.min.y;
+ const rig = new Group();
+ rig.add(avatar);
+ rig.rotation.y = Math.PI * 0.04; // a hair off-axis so it's not flat-on
+ scene.add(rig);
+
+ const anim = new AnimationManager();
+ anim.attach(avatar);
+ anim.setAnimationDefs((Array.isArray(manifest) ? manifest : []).filter((d) => IDLE_CLIPS.has(d.name)));
+ anim.play('idle').catch(() => {});
+
+ // ── Render loop ─────────────────────────────────────────────────────────
+ let raf = 0;
+ let last = performance.now();
+ let t = 0;
+ let admitted = false;
+ let admitT = 0;
+
+ function frame(now) {
+ const dt = Math.min((now - last) / 1000, 0.05);
+ last = now;
+ t += dt;
+ anim.update(dt);
+
+ if (!admitted) {
+ // Slow idle orbit drift around the avatar.
+ const a = Math.sin(t * 0.18) * 0.18;
+ camera.position.x = Math.sin(a) * 4.0 + Math.cos(a) * 1.7;
+ camera.position.z = Math.cos(a) * 4.0;
+ camera.position.y = 1.62 + Math.sin(t * 0.5) * 0.04;
+ camera.lookAt(camLook);
+ } else {
+ // Dolly in toward the avatar / doorway, then fade the canvas out.
+ admitT = Math.min(1, admitT + dt / 1.2);
+ const e = easeInOut(admitT);
+ camera.position.lerpVectors(camStart, new Vector3(0.2, 1.2, 1.5), e);
+ camera.lookAt(0, 1.15, 0);
+ canvasEl.style.opacity = String(1 - e);
+ if (admitT >= 1) return dispose();
+ }
+
+ renderer.render(scene, camera);
+ raf = requestAnimationFrame(frame);
+ }
+ raf = requestAnimationFrame(frame);
+
+ function onResize() {
+ renderer.setSize(window.innerWidth, window.innerHeight, false);
+ camera.aspect = window.innerWidth / window.innerHeight;
+ camera.updateProjectionMatrix();
+ }
+ window.addEventListener('resize', onResize);
+
+ // Bouncer admitted the wallet — start the push-in.
+ window.addEventListener('club:admitted', () => { admitted = true; admitT = 0; }, { once: true });
+
+ function dispose() {
+ cancelAnimationFrame(raf);
+ window.removeEventListener('resize', onResize);
+ try { anim.dispose?.(); } catch {}
+ scene.traverse((n) => {
+ if (n.isMesh) {
+ n.geometry?.dispose?.();
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ mats.forEach((m) => {
+ if (!m) return;
+ for (const k in m) { if (m[k]?.isTexture) m[k].dispose(); }
+ m.dispose?.();
+ });
+ }
+ });
+ renderer.dispose();
+ canvasEl.remove();
+ }
+}
+
+// Scale an object uniformly so its largest dimension equals `target` units.
+function normalizeToHeight(obj, target) {
+ const box = new Box3().setFromObject(obj);
+ const size = box.getSize(new Vector3());
+ const largest = Math.max(size.x, size.y, size.z) || 1;
+ const s = target / largest;
+ obj.scale.setScalar(s);
+ // Recenter on X/Z around the origin after scaling.
+ const box2 = new Box3().setFromObject(obj);
+ const center = box2.getCenter(new Vector3());
+ obj.position.x -= center.x;
+ obj.position.z -= center.z;
+}
+
+function easeInOut(x) {
+ return x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2;
+}