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.

feat(club): bring the Pole Club room to life with a crowd, floor bills, and in-room tipping

nirholas4c060a7679de
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 23c6fbbe1..2b3880b47 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@
Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).
+## 2026-09-28
+
+- **The Pole Club floor comes alive: a crowd, money on the stages, and tipping from inside the room**: Walking into the Club used to land you in an empty room. Now a crowd stands around the three stages, and every tip turns into $0.001 bills. When you tip, a clump of bills flies from where you are standing and flutters down onto her stage. When someone else tips, bills drop from the lights above her pole. The bills stay where they land, so each stage keeps a pile for the night, sized from that dancer's real tips today. You can tip without leaving the scene: every dancer has a tag over her head, and clicking her or her pole opens a picker for her routine. A tip from another visitor now puts her through the routine they paid for on your screen too, and the people at her stage cheer. Tips paid by three.ws platform agents are labelled as agent tips in the feed, drop a single violet bill, and never start a routine, and each dancer's card now says how many of today's tips came from people and how many from agents. (`/club`) `[feature, improvement]`
+
## 2026-09-25
- **Props the platform pays Forge to make now land in the /forged gallery**: Every half hour the platform pays its own Forge to make a new 3D prop for the public /forged gallery. A standard generation takes 20 to 55 seconds, but the paying side gave up after 20. Forge still finished the model and took the payment, so most of those props were paid for, never saved to the gallery, and logged as failed. The paying side now waits up to 90 seconds for a generation. Each paid prop lands in the gallery, and the payment health numbers stop counting these successful payments as failures. (`/forged`) `[fix, infra]`
diff --git a/README.md b/README.md
index faaa21e31..ae287d588 100644
--- a/README.md
+++ b/README.md
@@ -9654,8 +9654,8 @@ Launchpad templates are JSON-configured and can embed any combination of `<agent
**Economics:**
- Tips API at `/api/club/tips` — viewers tip dancers in USDC via x402 (CDP-settled, Permit2-gasless sibling available)
-- Leaderboard at `/api/club/leaderboard` with windowed top-tipper rankings, memoized for 15s so a full room costs one aggregate per window rather than one per viewer, and answering `503` with a retry hint when the database is over capacity instead of a bare failure
-- Live tip feed at `/api/club/tips-stream` (SSE); a cold stream rewinds its cursor to the moment the first viewer arrives, so a room that went quiet does not replay the banked backlog as if it were live
+- Leaderboard at `/api/club/leaderboard` with windowed top-tipper rankings, memoized for 15s so a full room costs one aggregate per window rather than one per viewer, and answering `503` with a retry hint when the database is over capacity instead of a bare failure. Each row also carries `agent_tip_count`, the share of `tip_count` paid from a registered platform wallet, so the page can split tips from people and tips from agents
+- Live tip feed at `/api/club/tips/stream` (SSE); a cold stream rewinds its cursor to the moment the first viewer arrives, so a room that went quiet does not replay the banked backlog as if it were live. Rows from the feed and from `/api/club/tips` carry `agent` (true when the payer is in `x402_ring_wallets`) and the style's choreography (`durationSec`, `track`, `pole`, `sequence`), so every viewer replays the routine that was bought
- Hourly payouts cron sweeps the tips ledger into the dancers' treasury wallets
**Detail:** performance notes, venue plan, and release checklist live in `docs/internal/` alongside other internal working docs.
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 970a19dfd..d8805dbf6 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -90,7 +90,7 @@ bottom.
| x402 Preflight (signed payability attestations) | Format core [api/_lib/x402/preflight.js](api/_lib/x402/preflight.js), server [api/x402/preflight.js](api/x402/preflight.js) `→ /.well-known/x402-preflight`, page [pages/preflight.html](pages/preflight.html) `→ /preflight` + [src/preflight-page.js](src/preflight-page.js), client SDK + CLI [packages/x402-preflight](packages/x402-preflight), MCP tool [api/_mcp3d/tools/preflight.js](api/_mcp3d/tools/preflight.js), spec [specs/x402-preflight.md](specs/x402-preflight.md), docs [docs/x402-preflight.md](docs/x402-preflight.md) | Live | The reliability layer x402 is missing. x402 says what a resource costs; nothing says whether the seller can still SETTLE it, so a buyer discovers an empty seller fee wallet only after signing. Born from the 2026-08-28 incident where three.ws was that seller: sponsor at 0.000899107 SOL against a 0.02 floor, 95 payment attempts, 0 settled, 3 hours. A seller publishes a signed, time-bounded ed25519 attestation of per-network payability, built from the same `gatherX402SettleHealth()` sensor healthz uses plus the live sponsor floor guard, so every field is measured rather than declared. `payable` is three-valued (a seller that cannot measure must say `unknown`, never `true`), every rate ships with its window and sample, `alternates` names the rails that DO work so a client re-routes in the same round trip, and `retry_after` stops a fleet synchronising into a retry storm. Verification enforces expiry, so a healthy attestation cannot be replayed through an outage. The open format is unencumbered: any x402 seller can serve one, any client can verify one, nothing routes through three.ws. Tests: [tests/x402-preflight.test.js](tests/x402-preflight.test.js) (38, including a cross-implementation digest check that the browser SDK and the node server sign byte-identical bytes). |
| Paid Market Data API (x402, 17 endpoints) | Registry [api/_lib/market-data/registry.js](api/_lib/market-data/registry.js), fetchers [api/_lib/market-data/fetch.js](api/_lib/market-data/fetch.js), factory [api/_lib/market-data/endpoint.js](api/_lib/market-data/endpoint.js), routes `api/x402/market-*.js` `→ /api/x402/market-<category>`, free index [api/x402/market.js](api/x402/market.js) `→ /api/x402/market`, catalog projection [api/_lib/service-catalog/services/market-data.js](api/_lib/service-catalog/services/market-data.js), docs [docs/market-data-api.md](docs/market-data-api.md) `→ /docs/market-data-api` | Live | Every free /markets feed (coins, coin profile, price history, categories, exchanges, derivatives, global+Fear&Greed, ETH gas, trending, DeFi TVL, chains, ~15k yield pools, stablecoins, fees/revenue, DEX volumes, hacks) wrapped as pay-per-call x402 endpoints at $0.001 USDC (Solana/Base), plus the $0.005 one-call `market-pulse` bundle. One registry drives the live 402s, the discovery-doc listings, and the free index — zero drift by construction; the fetchers delegate to the SAME exported builders the free pages use (`api/coin/*`, `api/defi/*`), so paid data always matches the site. Params rejected pre-settle (422) and upstream outages (503) never charge the buyer. Tests: [tests/market-data-api.test.js](tests/market-data-api.test.js). |
| Datapoint fabric (x402, 480k+ endpoints) | Registry [api/_lib/market-data/datapoints.js](api/_lib/market-data/datapoints.js), dynamic route [api/x402/d/[...path].js](api/x402/d/%5B...path%5D.js) `→ /api/x402/d/<family>/<id>/<metric>`, free catalog [api/x402/d/index.js](api/x402/d/index.js) `→ /api/x402/d`, discovery slice `buildDatapointItems` in [api/wk.js](api/wk.js), docs § in [docs/market-data-api.md](docs/market-data-api.md#the-datapoint-fabric--480000-standalone-endpoints) | Live | Every individual market datapoint as its OWN standalone paid endpoint — one URL = one value = one $0.0005 USDC x402 micro-payment (override `X402_PRICE_DATAPOINT_<FAMILY>`). 9 families × 68 metrics × live id spaces ≈ 484k addressable endpoints (~17.5k coins × 20, ~15.5k pools × 7, ~6k protocols × 6, chains, stablecoins, exchanges, global/gas/fear-greed) served by ONE dynamic route reading the registry; ids are runtime values, nothing hardcodes a third-party asset. Path that cannot exist → 404/422 with NO 402 issued; unknown id/outage rejects pre-settle. Free catalog enumerates families, metrics, prices, and pages each family's full live id space (200/page) so crawlers can walk the universe; the .well-known discovery doc carries a curated runtime-derived slice (~83 concrete resources). Tests: [tests/market-datapoints.test.js](tests/market-datapoints.test.js). |
-| Pole Club (x402 micro-tips drive a live 3D room) | Page [pages/club.html](pages/club.html) `→ /club` and `→ /stripclub` (same page, the path picks the walk-in via [src/club-variant.js](src/club-variant.js)), stage app [src/club.js](src/club.js) with [src/club-camera.js](src/club-camera.js), [src/club-crowd.js](src/club-crowd.js), [src/club-dances.js](src/club-dances.js), [src/club-audio.js](src/club-audio.js), [src/club-venue.js](src/club-venue.js), [src/club-perf.js](src/club-perf.js), [src/club-sequence.js](src/club-sequence.js); walk-in [src/club-entrance.js](src/club-entrance.js) + cover gate [src/club-gate.js](src/club-gate.js) (shared express flag [src/shared/club-express.js](src/shared/club-express.js)), the 3D doorman [src/club-bouncer.js](src/club-bouncer.js) and the line outside [src/club-queue.js](src/club-queue.js); paid endpoints [api/x402/club-cover.js](api/x402/club-cover.js) `→ /api/x402/club-cover` and [api/x402/dance-tip.js](api/x402/dance-tip.js) `→ /api/x402/dance-tip`; free reads [api/club/leaderboard.js](api/club/leaderboard.js), [api/club/tips.js](api/club/tips.js), [api/club/tips-stream.js](api/club/tips-stream.js) `→ /api/club/tips/stream` (SSE), [api/club/presence.js](api/club/presence.js); payouts [api/\_lib/club/payouts.js](api/_lib/club/payouts.js) via the `/api/cron/club-payouts` job; assets [public/club/](public/club) | Live | The platform's showcase of x402 as a live interaction loop rather than a billing detail: a $0.01 USDC cover charge at the door (with an on-chain bouncer that reads the paying wallet's ban list and prior visits, and a device-cached pass so one cover lasts the night). That bouncer is also a character in the alley: a rigged avatar posted beside the door who tracks you as you walk up, quotes the cover, and acts out each step of the payment (reads the list while the wallet is checked, nods you through by tier, shakes his head on a refusal), driven by the `club:door-state` event the cover gate emits on every state change; tap him and he explains how the club works. A roped line of waiting avatars talks among itself beside him, then $0.001 USDC per routine at three poles. A settled tip is what puts a dancer on the pole, so the payment IS the interaction. Third-person walk-in through alley → gallery → clubhouse → stage before the room opens; dancers are ordinary gallery avatars retargeted onto the shared clip library, swappable per pole. Tips land live over SSE with REST backfill on reconnect, and per-dancer earnings accrue to `club_dancer_wallets` for the payout sweep. `/club?demo` is the express entry that skips the cover for QA and recordings. `/stripclub` is a second entrance to the same room: it opens on a brick back alley (CC BY 4.0 model, credited on screen and in [public/club/venue/LICENSES.md](public/club/venue/LICENSES.md)) instead of the neon alley, shares the cover pass, and falls back to the neon alley if its model cannot load. |
+| Pole Club (x402 micro-tips drive a live 3D room) | Page [pages/club.html](pages/club.html) `→ /club` and `→ /stripclub` (same page, the path picks the walk-in via [src/club-variant.js](src/club-variant.js)), stage app [src/club.js](src/club.js) with [src/club-camera.js](src/club-camera.js), [src/club-crowd.js](src/club-crowd.js), [src/club-dances.js](src/club-dances.js), [src/club-audio.js](src/club-audio.js), [src/club-venue.js](src/club-venue.js), [src/club-perf.js](src/club-perf.js), [src/club-sequence.js](src/club-sequence.js), in-room life [src/club-money.js](src/club-money.js) (the $0.001 bills), [src/club-floor-crowd.js](src/club-floor-crowd.js) (the people around the stages) and [src/club-tip-hud.js](src/club-tip-hud.js) (the tip tags over each dancer); walk-in [src/club-entrance.js](src/club-entrance.js) + cover gate [src/club-gate.js](src/club-gate.js) (shared express flag [src/shared/club-express.js](src/shared/club-express.js)), the 3D doorman [src/club-bouncer.js](src/club-bouncer.js) and the line outside [src/club-queue.js](src/club-queue.js); paid endpoints [api/x402/club-cover.js](api/x402/club-cover.js) `→ /api/x402/club-cover` and [api/x402/dance-tip.js](api/x402/dance-tip.js) `→ /api/x402/dance-tip`; style table [api/\_lib/club/styles.js](api/_lib/club/styles.js) and feed row shaper [api/\_lib/club/tip-rows.js](api/_lib/club/tip-rows.js); free reads [api/club/leaderboard.js](api/club/leaderboard.js), [api/club/tips.js](api/club/tips.js), [api/club/tips-stream.js](api/club/tips-stream.js) `→ /api/club/tips/stream` (SSE), [api/club/presence.js](api/club/presence.js); payouts [api/\_lib/club/payouts.js](api/_lib/club/payouts.js) via the `/api/cron/club-payouts` job; assets [public/club/](public/club) | Live | The platform's showcase of x402 as a live interaction loop rather than a billing detail: a $0.01 USDC cover charge at the door (with an on-chain bouncer that reads the paying wallet's ban list and prior visits, and a device-cached pass so one cover lasts the night). That bouncer is also a character in the alley: a rigged avatar posted beside the door who tracks you as you walk up, quotes the cover, and acts out each step of the payment (reads the list while the wallet is checked, nods you through by tier, shakes his head on a refusal), driven by the `club:door-state` event the cover gate emits on every state change; tap him and he explains how the club works. A roped line of waiting avatars talks among itself beside him, then $0.001 USDC per routine at three poles. A settled tip is what puts a dancer on the pole, so the payment IS the interaction. Inside, the room is alive: a crowd stands around the stages (never in the camera's sightlines), each dancer carries a floating tag you tip her from (click her or her pole to pick a style), and every settled tip turns into $0.001 bills: thrown from the camera for your own tip, dropped from the rig for anyone else's, left lying on that stage so each pile is the dancer's night so far. Tips paid from a platform wallet (`x402_ring_wallets`) arrive flagged `agent`: they drop one violet bill and never start a routine or pass for a person, and each pole card splits tips today into people and agents. Third-person walk-in through alley → gallery → clubhouse → stage before the room opens; dancers are ordinary gallery avatars retargeted onto the shared clip library, swappable per pole. Tips land live over SSE with REST backfill on reconnect, and per-dancer earnings accrue to `club_dancer_wallets` for the payout sweep. `/club?demo` is the express entry that skips the cover for QA and recordings. `/stripclub` is a second entrance to the same room: it opens on a brick back alley (CC BY 4.0 model, credited on screen and in [public/club/venue/LICENSES.md](public/club/venue/LICENSES.md)) instead of the neon alley, shares the cover pass, and falls back to the neon alley if its model cannot load. |
| Living Stages (an AI host performs live, tipped in $THREE) | Page [pages/stage.html](pages/stage.html) `→ /stage` (the marquee) and `→ /stage?id=<stage>` (the venue), runtime [src/stage.js](src/stage.js), realtime client [src/stage-net.js](src/stage-net.js) → `stage_world` in [multiplayer/src/rooms/StageRoom.js](multiplayer/src/rooms/StageRoom.js) with the show logic in [multiplayer/src/stage-show.js](multiplayer/src/stage-show.js); API [api/stage/index.js](api/stage/index.js) `→ /api/stage`, tips [api/stage/tip.js](api/stage/tip.js) `→ /api/stage/tip`, host brain [api/stage/host.js](api/stage/host.js) `→ /api/stage/host` (HMAC, multiplayer server only) | Live | An embodied agent hosts a show in a 3D venue. Each beat is a timed `utterance` broadcast every client renders identically: TTS through a `PositionalAudio` whose analyser drives lip-sync, plus live captions, so a late joiner or a no-WebGL browser still reads the show. The crowd is co-present on a server-assigned ring, questions queue for the host, and a $THREE tip that settles on-chain to the host wallet is verified by the API and pushed into the room so the host reacts within a beat. The page resolves the realtime server through the same chain as `/play` ([src/shared/game-server-url.js](src/shared/game-server-url.js)) from the `game-server` meta it carries; localhost talks to `:2567`. The client subscribes to the host frame with `listen` (the join resolves before the first state patch, so `onChange` on the not-yet-decoded child throws) and registers message handlers before any state work, because the room opens the show the instant the first person arrives. With no feed the pill reads offline and reconnects on tap. Docs: [docs/stage.md](docs/stage.md). Tests: [tests/multiplayer-server-boot.test.js](tests/multiplayer-server-boot.test.js) (a real `stage_world` join wired the way the page does it), [tests/stage-show.test.js](tests/stage-show.test.js) |
| Fits: the public cosmetics economy | [pages/fits.html](pages/fits.html) `→ /fits`, page module [src/fits.js](src/fits.js) + pure helpers [src/fits-lib.js](src/fits-lib.js), backends [api/cosmetics/leaderboard.js](api/cosmetics/leaderboard.js) + [api/cosmetics/earnings.js](api/cosmetics/earnings.js), engine [api/_lib/cosmetics-economy.js](api/_lib/cosmetics-economy.js) | Live | The settled-sale cosmetics ledger, promoted out of a panel inside `/play` into a public surface. Rarest premium fits ranked by how few wallets own them (owner count first, rarity as the tie-break, so a legendary never sorts under an equally-scarce rare), top collectors by rarity-weighted flex score, top creators by **actually settled** USDC, and a live sales drip; each fit deep-links to its coin world at `/play?coin=<mint>`. Plus a creator-earnings lookup any wallet can run without an account (lifetime + 30-day, paid vs pending, per-cosmetic and per-coin-world breakdowns), reachable in one click from each creator row rather than by copy-pasting an address. Coin mints are runtime ledger values, never hardcoded. Headline numbers are derived from the same rows rendered beneath them, so they cannot disagree; the volume tile is labelled as the returned sales window, not as an all-time total. Sub-cent sales keep their precision instead of collapsing to $0.00. Tests: [tests/fits-lib.test.js](tests/fits-lib.test.js) |
| Receipt Vault: buyer-side proof of purchase | [pages/receipts.html](pages/receipts.html) `→ /receipts`, page module [src/receipts.js](src/receipts.js) + pure helpers [src/receipts-lib.js](src/receipts-lib.js), backend [api/x402/my-receipts.js](api/x402/my-receipts.js), storage [api/_lib/x402/receipt-storage.js](api/_lib/x402/receipt-storage.js), issuer [api/_lib/x402/offer-receipt-issuer.js](api/_lib/x402/offer-receipt-issuer.js), key publication [api/x402/did.js](api/x402/did.js) `→ /.well-known/did.json` | Live | What a given wallet **spent** on the platform's paid endpoints. Every settled x402 call issues a signed Offer & Receipt artifact (USE-17) and durably logs it; a buyer connects a Solana or EVM wallet, signs one read-only message (5-minute window, no transaction, no fee) and gets every receipt ever issued to that wallet: endpoint, settled amount, network, explorer-linked tx, the full signed artifact as JSON, plus search and CSV export. The signing message is a fixed four-line string that must stay byte-identical between `buildReceiptsMessage()` (client) and `buildExpectedMessage()` (server); [tests/receipts-lib.test.js](tests/receipts-lib.test.js) pins that contract against a verbatim copy of the server's function. The signed artifact carries no amount and omits the tx hash under the spec §5.2 privacy default, so the row records both separately as our own audit trail (migration [api/_lib/migrations/2026-07-28-x402-receipt-settlement.sql](api/_lib/migrations/2026-07-28-x402-receipt-settlement.sql)); receipts predating that capture report as "N of M priced" rather than under-reporting a total. Issuance requires `OFFER_RECEIPT_JWK` (jws) or `OFFER_RECEIPT_SIGNING_PRIVATE_KEY` (eip712); unset means no receipts are issued at all. Docs: [docs/x402-endpoints.md](docs/x402-endpoints.md) |
diff --git a/api/_lib/club/styles.js b/api/_lib/club/styles.js
new file mode 100644
index 000000000..72831fe56
--- /dev/null
+++ b/api/_lib/club/styles.js
@@ -0,0 +1,80 @@
+// The dance styles the /club stage sells, shared by the paid endpoint
+// (api/x402/dance-tip.js) and the free tip feeds (api/club/tips*.js), which
+// attach each row's choreography so a spectator replays the routine the payer
+// bought. src/club-dances.js mirrors the menu order and labels for the browser;
+// tests/club-dances.test.js keeps the two in step.
+
+// `track` names map to /public/club/audio/<track>.{ogg,mp3} loops the /club
+// page crossfades to when the dance starts. The client picks whichever format
+// the browser supports: see src/club-audio.js loadBuffer().
+export const STYLES = Object.freeze({
+ // Free-floor (existing): single clip looped for the full duration.
+ hiphop: { clip: 'dance', label: 'Hip Hop', loop: true, durationSec: 12, track: 'hiphop' },
+ rumba: { clip: 'rumba', label: 'Rumba', loop: true, durationSec: 14, track: 'rumba' },
+ silly: { clip: 'silly', label: 'Silly', loop: true, durationSec: 10, track: 'silly' },
+ thriller: { clip: 'thriller', label: 'Thriller', loop: true, durationSec: 14, track: 'thriller' },
+ capoeira: { clip: 'capoeira', label: 'Capoeira', loop: true, durationSec: 12, track: 'capoeira' },
+ // 16.1s of choreography, the longest single-clip style on the stage: booked
+ // for one full pass rather than cut mid-routine.
+ offabean: { clip: 'av-offabean-dance', label: 'Offabean', loop: true, durationSec: 16, track: 'hiphop' },
+
+ // Pole work: `pole: true` tells the /club stage to turn the dancer into the
+ // pole and dance against it (back to the crowd) rather than facing out like
+ // the free-floor styles. The twerk loops on the pole for the full duration.
+ twerk: {
+ clip: 'twerk', label: 'Pole Twerk', loop: true, durationSec: 12,
+ track: 'im-in-love-wit-a-stripper-fast', pole: true,
+ },
+
+ // Choreographed routines: sequences chain multiple clips back-to-back at
+ // PoleStation playback time (the feature free-floor styles lack). Every clip
+ // here is a real, deployed entry in /animations/manifest.json so the routine
+ // always performs; durationSec is the sum of the steps. The audio loop
+ // crossfades to the dedicated `pole` track (/public/club/audio/pole.*).
+ spin: {
+ label: 'Spin',
+ durationSec: 10,
+ track: 'pole',
+ sequence: [
+ { clip: 'capoeira', durationSec: 6 },
+ { clip: 'dance', durationSec: 4 },
+ ],
+ },
+ climb: {
+ label: 'Slow Burn',
+ durationSec: 14,
+ track: 'pole',
+ sequence: [
+ { clip: 'thriller', durationSec: 7 },
+ { clip: 'capoeira', durationSec: 4 },
+ { clip: 'dance', durationSec: 3 },
+ ],
+ },
+ combo: {
+ label: 'Full Combo',
+ durationSec: 18,
+ track: 'pole',
+ sequence: [
+ { clip: 'rumba', durationSec: 4 },
+ { clip: 'capoeira', durationSec: 4 },
+ { clip: 'thriller', durationSec: 4 },
+ { clip: 'silly', durationSec: 3 },
+ { clip: 'dance', durationSec: 3 },
+ ],
+ },
+});
+
+/**
+ * The choreography a spectator needs to replay a tip row: the style's booked
+ * duration, audio loop, pole flag and clip sequence. Null for a style this
+ * build no longer sells (an old row), so the caller keeps the row's own clip.
+ * @param {string} key
+ */
+export function styleChoreography(key) {
+ const style = Object.hasOwn(STYLES, key) ? STYLES[key] : null;
+ if (!style) return null;
+ const out = { durationSec: style.durationSec, track: style.track };
+ if (style.pole) out.pole = true;
+ if (style.sequence) out.sequence = style.sequence;
+ return out;
+}
diff --git a/api/_lib/club/tip-rows.js b/api/_lib/club/tip-rows.js
new file mode 100644
index 000000000..a77ce1dfa
--- /dev/null
+++ b/api/_lib/club/tip-rows.js
@@ -0,0 +1,27 @@
+// Shape a club_tips row for the free tip feeds (/api/club/tips and its SSE
+// stream).
+//
+// Two things are added to the stored row:
+//
+// agent true when the payer is a registered platform wallet
+// (x402_ring_wallets: the ring payer and the roster agents).
+// The queries compute it as `is_agent`; the /club page draws
+// those tips as agent tips and never as a person in the room,
+// and only a person's tip puts a dancer through a routine.
+// choreography the style's duration, audio loop, pole flag and clip sequence
+// (api/_lib/club/styles.js), so a spectator's screen replays
+// exactly the routine the payer bought rather than guessing
+// from the single `clip` column.
+
+import { styleChoreography } from './styles.js';
+
+/**
+ * @param {Record<string, any>} row a club_tips row plus the `is_agent` column
+ */
+export function shapeTipRow(row) {
+ const { is_agent: isAgent, ...rest } = row;
+ const out = { ...rest, agent: isAgent === true };
+ const chor = styleChoreography(row.dance);
+ if (chor) Object.assign(out, chor);
+ return out;
+}
diff --git a/api/club/leaderboard.js b/api/club/leaderboard.js
index a1b461c2b..934f3e134 100644
--- a/api/club/leaderboard.js
+++ b/api/club/leaderboard.js
@@ -7,6 +7,10 @@
// `window` is a strict whitelist, never user-injected SQL. Each entry in
// QUERIES is its own tagged template so the underlying Neon HTTP client
// parameterizes the interval literal safely.
+//
+// `agent_tip_count` is the share of `tip_count` paid from a registered platform
+// wallet (x402_ring_wallets: the ring payer and the roster agents), so the page
+// can say how much of a dancer's night came from people and how much from agents.
import { sql, isDbUnavailableError, isDbCapacityError } from '../_lib/db.js';
import { cacheWrap } from '../_lib/cache.js';
@@ -26,10 +30,12 @@ const QUERIES = {
d.display_name,
coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
count(t.*)::int as tip_count,
+ count(t.*) filter (where w.pubkey is not null)::int as agent_tip_count,
coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
from club_dancer_wallets d
left join club_tips t
on t.dancer = d.dancer and t.created_at >= now() - interval '1 hour'
+ left join x402_ring_wallets w on w.pubkey = t.payer
group by d.dancer, d.display_name
order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
`,
@@ -39,10 +45,12 @@ const QUERIES = {
d.display_name,
coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
count(t.*)::int as tip_count,
+ count(t.*) filter (where w.pubkey is not null)::int as agent_tip_count,
coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
from club_dancer_wallets d
left join club_tips t
on t.dancer = d.dancer and t.created_at >= now() - interval '24 hours'
+ left join x402_ring_wallets w on w.pubkey = t.payer
group by d.dancer, d.display_name
order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
`,
@@ -52,10 +60,12 @@ const QUERIES = {
d.display_name,
coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
count(t.*)::int as tip_count,
+ count(t.*) filter (where w.pubkey is not null)::int as agent_tip_count,
coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
from club_dancer_wallets d
left join club_tips t
on t.dancer = d.dancer and t.created_at >= now() - interval '7 days'
+ left join x402_ring_wallets w on w.pubkey = t.payer
group by d.dancer, d.display_name
order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
`,
@@ -65,9 +75,11 @@ const QUERIES = {
d.display_name,
coalesce(sum(t.amount_atomics), 0)::text as total_atomics,
count(t.*)::int as tip_count,
+ count(t.*) filter (where w.pubkey is not null)::int as agent_tip_count,
coalesce(sum(case when t.paid_at is null then t.amount_atomics else 0 end), 0)::text as unpaid_atomics
from club_dancer_wallets d
left join club_tips t on t.dancer = d.dancer
+ left join x402_ring_wallets w on w.pubkey = t.payer
group by d.dancer, d.display_name
order by coalesce(sum(t.amount_atomics), 0) desc, d.dancer asc
`,
diff --git a/api/club/tips-stream.js b/api/club/tips-stream.js
index 2f268f89b..b02f9962e 100644
--- a/api/club/tips-stream.js
+++ b/api/club/tips-stream.js
@@ -22,6 +22,7 @@
import { sql } from '../_lib/db.js';
import { cors, method } from '../_lib/http.js';
+import { shapeTipRow } from '../_lib/club/tip-rows.js';
// ── Per-instance shared poll state ───────────────────────────────────────────
// Each registered listener is a function: (event, data) => void.
@@ -55,7 +56,8 @@ async function runSharedPoll() {
try {
const rows = await sql`
select ticket_id, dancer, dance, clip, label, payer, network,
- amount_atomics, asset, started_at, ends_at, created_at
+ amount_atomics, asset, started_at, ends_at, created_at,
+ exists (select 1 from x402_ring_wallets w where w.pubkey = club_tips.payer) as is_agent
from club_tips
where (created_at, ticket_id) > (${sharedCursor.toISOString()}::timestamptz, ${sharedCursorId})
order by created_at asc, ticket_id asc
@@ -68,9 +70,10 @@ async function runSharedPoll() {
const last = rows[rows.length - 1];
sharedCursor = last.created_at instanceof Date ? last.created_at : new Date(last.created_at);
sharedCursorId = last.ticket_id;
- // Fan out to all connected clients.
+ // Fan out to all connected clients. Shape once, not once per listener.
+ const events = rows.map(shapeTipRow);
for (const send of clients) {
- for (const row of rows) {
+ for (const row of events) {
send('tip', row);
}
}
diff --git a/api/club/tips.js b/api/club/tips.js
index cd6babebd..0bfd8006d 100644
--- a/api/club/tips.js
+++ b/api/club/tips.js
@@ -2,10 +2,13 @@
//
// Returns the most-recent tip events written by /api/x402/dance-tip. Powers
// the initial render of the /club "Live tips" widget on page boot; the SSE
-// channel at /api/club/tips/stream takes over for live updates.
+// channel at /api/club/tips/stream takes over for live updates. Rows carry
+// `agent` (platform-wallet payer) and the style's choreography; see
+// api/_lib/club/tip-rows.js.
import { sql } from '../_lib/db.js';
import { cors, json, method, wrap } from '../_lib/http.js';
+import { shapeTipRow } from '../_lib/club/tip-rows.js';
const MAX_LIMIT = 100;
const DEFAULT_LIMIT = 20;
@@ -25,7 +28,8 @@ export default wrap(async (req, res) => {
const rows = await (dancer
? sql`
select ticket_id, dancer, dance, clip, label, payer, network,
- amount_atomics, asset, started_at, ends_at, created_at
+ amount_atomics, asset, started_at, ends_at, created_at,
+ exists (select 1 from x402_ring_wallets w where w.pubkey = club_tips.payer) as is_agent
from club_tips
where dancer = ${dancer}
order by created_at desc
@@ -33,11 +37,12 @@ export default wrap(async (req, res) => {
`
: sql`
select ticket_id, dancer, dance, clip, label, payer, network,
- amount_atomics, asset, started_at, ends_at, created_at
+ amount_atomics, asset, started_at, ends_at, created_at,
+ exists (select 1 from x402_ring_wallets w where w.pubkey = club_tips.payer) as is_agent
from club_tips
order by created_at desc
limit ${limit}
`);
- return json(res, 200, { tips: rows });
+ return json(res, 200, { tips: rows.map(shapeTipRow) });
});
diff --git a/api/x402/dance-tip.js b/api/x402/dance-tip.js
index 2f61f802e..97d6c15e2 100644
--- a/api/x402/dance-tip.js
+++ b/api/x402/dance-tip.js
@@ -24,6 +24,7 @@ import { installAccessControl } from '../_lib/x402/access-control.js';
import { withService } from '../_lib/x402/bazaar-helpers.js';
import { sql } from '../_lib/db.js';
import { priceFor } from '../_lib/x402-prices.js';
+import { STYLES } from '../_lib/club/styles.js';
const ROUTE = '/api/x402/dance-tip';
@@ -36,65 +37,7 @@ const DESCRIPTION =
'dancer and play the routine — sequence styles chain multiple clips ' +
'back-to-back, and pole styles turn her into the pole.';
-// `track` names map to /public/club/audio/<track>.{ogg,mp3} loops the /club
-// page crossfades to when the dance starts. The client picks whichever format
-// the browser supports — see src/club-audio.js loadBuffer().
-export const STYLES = Object.freeze({
- // Free-floor (existing) — single clip looped for the full duration.
- hiphop: { clip: 'dance', label: 'Hip Hop', loop: true, durationSec: 12, track: 'hiphop' },
- rumba: { clip: 'rumba', label: 'Rumba', loop: true, durationSec: 14, track: 'rumba' },
- silly: { clip: 'silly', label: 'Silly', loop: true, durationSec: 10, track: 'silly' },
- thriller: { clip: 'thriller', label: 'Thriller', loop: true, durationSec: 14, track: 'thriller' },
- capoeira: { clip: 'capoeira', label: 'Capoeira', loop: true, durationSec: 12, track: 'capoeira' },
- // 16.1s of choreography, the longest single-clip style on the stage: booked
- // for one full pass rather than cut mid-routine.
- offabean: { clip: 'av-offabean-dance', label: 'Offabean', loop: true, durationSec: 16, track: 'hiphop' },
-
- // Pole work — `pole: true` tells the /club stage to turn the dancer into the
- // pole and dance against it (back to the crowd) rather than facing out like
- // the free-floor styles. The twerk loops on the pole for the full duration.
- twerk: {
- clip: 'twerk', label: 'Pole Twerk', loop: true, durationSec: 12,
- track: 'im-in-love-wit-a-stripper-fast', pole: true,
- },
-
- // Choreographed routines — sequences chain multiple clips back-to-back at
- // PoleStation playback time (the feature free-floor styles lack). Every clip
- // here is a real, deployed entry in /animations/manifest.json so the routine
- // always performs; durationSec is the sum of the steps. The audio loop
- // crossfades to the dedicated `pole` track (/public/club/audio/pole.*).
- spin: {
- label: 'Spin',
- durationSec: 10,
- track: 'pole',
- sequence: [
- { clip: 'capoeira', durationSec: 6 },
- { clip: 'dance', durationSec: 4 },
- ],
- },
- climb: {
- label: 'Slow Burn',
- durationSec: 14,
- track: 'pole',
- sequence: [
- { clip: 'thriller', durationSec: 7 },
- { clip: 'capoeira', durationSec: 4 },
- { clip: 'dance', durationSec: 3 },
- ],
- },
- combo: {
- label: 'Full Combo',
- durationSec: 18,
- track: 'pole',
- sequence: [
- { clip: 'rumba', durationSec: 4 },
- { clip: 'capoeira', durationSec: 4 },
- { clip: 'thriller', durationSec: 4 },
- { clip: 'silly', durationSec: 3 },
- { clip: 'dance', durationSec: 3 },
- ],
- },
-});
+export { STYLES };
const VALID_DANCERS = new Set(['1', '2', '3', '4']);
diff --git a/data/changelog.json b/data/changelog.json
index 2835d62a8..3b75e72e8 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -28746,6 +28746,16 @@
"feature"
],
"link": "/docs/trade-receipts"
+ },
+ {
+ "date": "2026-09-28",
+ "title": "The Pole Club floor comes alive: a crowd, money on the stages, and tipping from inside the room",
+ "summary": "Walking into the Club used to land you in an empty room. Now a crowd stands around the three stages, and every tip turns into $0.001 bills. When you tip, a clump of bills flies from where you are standing and flutters down onto her stage. When someone else tips, bills drop from the lights above her pole. The bills stay where they land, so each stage keeps a pile for the night, sized from that dancer's real tips today. You can tip without leaving the scene: every dancer has a tag over her head, and clicking her or her pole opens a picker for her routine. A tip from another visitor now puts her through the routine they paid for on your screen too, and the people at her stage cheer. Tips paid by three.ws platform agents are labelled as agent tips in the feed, drop a single violet bill, and never start a routine, and each dancer's card now says how many of today's tips came from people and how many from agents.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/club"
}
]
}
diff --git a/pages/club.html b/pages/club.html
index 2b04ed508..71ecc0349 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -1606,6 +1606,20 @@
color: var(--text-3);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
+ .club-pole-stats.is-loading {
+ border-radius: 4px;
+ color: transparent;
+ background: linear-gradient(90deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.04));
+ background-size: 200% 100%;
+ animation: clubStatsShimmer 1.2s linear infinite;
+ }
+ @keyframes clubStatsShimmer {
+ from { background-position: 200% 0; }
+ to { background-position: -200% 0; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .club-pole-stats.is-loading { animation: none; }
+ }
.club-tip-btn {
appearance: none;
border: none;
@@ -1754,6 +1768,215 @@
font-size: 10.5px;
}
.club-tip-mid { color: var(--text); font-size: 11px; }
+ /* A tip paid from a platform wallet (x402 ring / roster agent). */
+ .club-tip-agent {
+ display: inline-block;
+ margin-left: 5px;
+ padding: 0 5px;
+ border-radius: 4px;
+ border: 1px solid rgba(180, 150, 255, 0.45);
+ color: #c9b6ff;
+ font-size: 9px;
+ font-weight: 700;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ vertical-align: 1px;
+ }
+
+ /* ── Tip tags over the dancers ───────────────────── */
+ .club-tags {
+ position: fixed;
+ z-index: 9;
+ overflow: hidden;
+ pointer-events: none;
+ }
+ .club-tags.is-hidden { display: none; }
+ .club-tag {
+ --tag-accent: var(--accent);
+ position: absolute;
+ left: 0;
+ top: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 6px;
+ padding-bottom: 9px; /* room for the pointer nub */
+ pointer-events: auto;
+ opacity: 1;
+ visibility: visible;
+ will-change: transform, opacity;
+ transition: opacity var(--duration-base) var(--ease-standard), visibility 0s linear 0s;
+ }
+ .club-tag.is-offscreen {
+ opacity: 0;
+ visibility: hidden;
+ pointer-events: none;
+ transition: opacity var(--duration-base) var(--ease-standard), visibility 0s linear var(--duration-base);
+ }
+ /* Pointer nub under the tag, aimed at her head. */
+ .club-tag::after {
+ content: '';
+ position: absolute;
+ bottom: 3px;
+ left: 50%;
+ width: 8px;
+ height: 8px;
+ transform: translateX(-50%) rotate(45deg);
+ background: rgba(8, 6, 16, 0.86);
+ border-right: 1px solid color-mix(in srgb, var(--tag-accent) 55%, transparent);
+ border-bottom: 1px solid color-mix(in srgb, var(--tag-accent) 55%, transparent);
+ }
+ .club-tag-bar {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px;
+ border-radius: 999px;
+ border: 1px solid color-mix(in srgb, var(--tag-accent) 45%, transparent);
+ background: rgba(8, 6, 16, 0.86);
+ box-shadow: 0 0 22px -8px var(--tag-accent), 0 8px 20px -12px rgba(0, 0, 0, 0.9);
+ backdrop-filter: blur(8px);
+ -webkit-backdrop-filter: blur(8px);
+ transition: border-color var(--duration-fast) var(--ease-standard), box-shadow var(--duration-fast) var(--ease-standard);
+ }
+ .club-tag.is-hover .club-tag-bar,
+ .club-tag.is-open .club-tag-bar {
+ border-color: var(--tag-accent);
+ box-shadow: 0 0 30px -6px var(--tag-accent), 0 8px 20px -12px rgba(0, 0, 0, 0.9);
+ }
+ .club-tag-name {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 6px;
+ min-height: 30px;
+ padding: 0 8px 0 10px;
+ border: 0;
+ border-radius: 999px;
+ background: transparent;
+ color: var(--text);
+ font: inherit;
+ cursor: pointer;
+ white-space: nowrap;
+ align-items: center;
+ transition: background var(--duration-fast) var(--ease-standard);
+ }
+ .club-tag-name:hover { background: rgba(255, 255, 255, 0.06); }
+ .club-tag-name:active { background: rgba(255, 255, 255, 0.1); }
+ .club-tag-who { font-size: 12.5px; font-weight: 700; }
+ .club-tag-style {
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--tag-accent);
+ }
+ .club-tag-caret {
+ width: 10px;
+ height: 6px;
+ color: var(--text-2);
+ transition: transform var(--duration-fast) var(--ease-standard);
+ }
+ .club-tag.is-open .club-tag-caret { transform: rotate(180deg); }
+ .club-tag-tip {
+ min-height: 30px;
+ padding: 0 12px;
+ border: 0;
+ border-radius: 999px;
+ background: var(--tag-accent);
+ color: #0a0610;
+ font: inherit;
+ font-size: 12px;
+ font-weight: 800;
+ white-space: nowrap;
+ cursor: pointer;
+ transition: filter var(--duration-fast) var(--ease-standard), transform var(--duration-instant) var(--ease-standard), opacity var(--duration-fast) var(--ease-standard);
+ }
+ .club-tag-tip:hover:not(:disabled) { filter: brightness(1.12); }
+ .club-tag-tip:active:not(:disabled) { transform: translateY(1px); }
+ .club-tag-tip:disabled { opacity: 0.55; cursor: default; }
+ .club-tag-tip.is-pending { opacity: 0.75; }
+ .club-tag-name:focus-visible,
+ .club-tag-tip:focus-visible,
+ .club-tag-chip:focus-visible {
+ outline: 2px solid #fff;
+ outline-offset: 2px;
+ }
+ .club-tag-live {
+ display: none;
+ padding: 3px 9px;
+ border-radius: 999px;
+ background: rgba(8, 6, 16, 0.8);
+ color: var(--text);
+ font-size: 10.5px;
+ font-weight: 600;
+ white-space: nowrap;
+ }
+ .club-tag.is-live .club-tag-live { display: inline-flex; align-items: center; gap: 6px; }
+ .club-tag.is-live .club-tag-live::before {
+ content: '';
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--tag-accent);
+ box-shadow: 0 0 8px var(--tag-accent);
+ animation: clubTagPulse 1.1s ease-in-out infinite;
+ }
+ @keyframes clubTagPulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.35; }
+ }
+ .club-tag-tray {
+ order: -1; /* opens above the bar, away from her head */
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 4px;
+ width: 244px;
+ padding: 6px;
+ border-radius: 14px;
+ border: 1px solid color-mix(in srgb, var(--tag-accent) 45%, transparent);
+ background: rgba(8, 6, 16, 0.92);
+ box-shadow: 0 12px 30px -12px rgba(0, 0, 0, 0.9);
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ animation: clubTrayIn var(--duration-base) var(--ease-standard);
+ }
+ .club-tag-tray[hidden] { display: none; }
+ @keyframes clubTrayIn {
+ from { opacity: 0; transform: translateY(4px); }
+ to { opacity: 1; transform: none; }
+ }
+ .club-tag-chip {
+ min-height: 30px;
+ padding: 0 8px;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 9px;
+ background: rgba(255, 255, 255, 0.03);
+ color: var(--text-2);
+ font: inherit;
+ font-size: 11.5px;
+ font-weight: 600;
+ text-align: left;
+ cursor: pointer;
+ transition: background var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard);
+ }
+ .club-tag-chip:hover { background: rgba(255, 255, 255, 0.08); color: var(--text); }
+ .club-tag-chip:active { background: rgba(255, 255, 255, 0.12); }
+ .club-tag-chip[aria-pressed='true'] {
+ border-color: var(--tag-accent);
+ color: var(--text);
+ background: color-mix(in srgb, var(--tag-accent) 18%, transparent);
+ }
+ @media (max-width: 800px) {
+ .club-tag-who { font-size: 11.5px; }
+ .club-tag-style { display: none; }
+ .club-tag-tip { padding: 0 10px; font-size: 11px; }
+ .club-tag-tray { width: 212px; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .club-tag, .club-tag.is-offscreen { transition: none; }
+ .club-tag-tray { animation: none; }
+ .club-tag.is-live .club-tag-live::before { animation: none; }
+ }
/* ── Status bar (bottom) ─────────────────────────── */
.club-status-bar {
@@ -2380,6 +2603,9 @@
</div>
</div>
<div id="club-reaction-canvas" class="club-reaction-canvas" aria-hidden="true"></div>
+ <!-- Tip tags: one over each dancer, pinned by src/club-tip-hud.js. The
+ layer is laid over the canvas box and clips to it. -->
+ <div id="club-tags" class="club-tags is-hidden" role="group" aria-label="Dancers on stage"></div>
<!-- RIGHT PANEL -->
<aside id="club-right" role="complementary" aria-label="Club controls and information">
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index 9bd8964ac..5fedd3e82 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,14 +1,25 @@
{
- "generated_at": "2026-09-25T19:21:51.999Z",
+ "generated_at": "2026-09-28T03:03:43.032Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3757,
+ "total": 3758,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
+ {
+ "date": "2026-09-28",
+ "type": "update",
+ "title": "The Pole Club floor comes alive: a crowd, money on the stages, and tipping from inside the room",
+ "summary": "Walking into the Club used to land you in an empty room. Now a crowd stands around the three stages, and every tip turns into $0.001 bills. When you tip, a clump of bills flies from where you are standing and flutters down onto her stage. When someone else tips, bills drop from the lights above her pole. The bills stay where they land, so each stage keeps a pile for the night, sized from that dancer's real tips today. You can tip without leaving the scene: every dancer has a tag over her head, and clicking her or her pole opens a picker for her routine. A tip from another visitor now puts her through the routine they paid for on your screen too, and the people at her stage cheer. Tips paid by three.ws platform agents are labelled as agent tips in the feed, drop a single violet bill, and never start a routine, and each dancer's card now says how many of today's tips came from people and how many from agents.",
+ "link": "/club",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-09-25",
"type": "update",
@@ -1597,16 +1608,6 @@
"fix",
"improvement"
]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The homepage stops calling its Community strip live when no new models are arriving",
- "summary": "The Community strip on the homepage is headed \"Made with Forge. Right now.\" and carries a pulsing live chip. That chip was switched on by the Fresh tab alone, so it asserted liveness no matter how old the newest model on the strip actually was. When our object storage started rejecting the platform's credential on 2026-09-07, finished generations could no longer be recorded, the strip froze on the last model stored before that, and the chip went on pulsing live over two-day-old work with nothing on the page to say otherwise. The chip is now earned by the data: it appears only when the newest model on the strip is from the last six hours, and it reads the newest timestamp in the list rather than trusting the order it arrives in. Older models still show exactly as before, because a quiet stretch is worth showing; it just is not live.",
- "link": "/",
- "tags": [
- "fix"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index 11f80f449..f50d828f2 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,22 @@
{
- "generated_at": "2026-09-25T19:21:51.979Z",
+ "generated_at": "2026-09-28T03:03:43.010Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-09-28",
+ "type": "update",
+ "title": "The Pole Club floor comes alive: a crowd, money on the stages, and tipping from inside the room",
+ "summary": "Walking into the Club used to land you in an empty room. Now a crowd stands around the three stages, and every tip turns into $0.001 bills. When you tip, a clump of bills flies from where you are standing and flutters down onto her stage. When someone else tips, bills drop from the lights above her pole. The bills stay where they land, so each stage keeps a pile for the night, sized from that dancer's real tips today. You can tip without leaving the scene: every dancer has a tag over her head, and clicking her or her pole opens a picker for her routine. A tip from another visitor now puts her through the routine they paid for on your screen too, and the people at her stage cheer. Tips paid by three.ws platform agents are labelled as agent tips in the feed, drop a single violet bill, and never start a routine, and each dancer's card now says how many of today's tips came from people and how many from agents.",
+ "link": "/club",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-09-25",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index d728e9cc8..a4975d2f4 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws: features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>The Pole Club floor comes alive: a crowd, money on the stages, and tipping from inside the room</title>
+ <link>https://three.ws/club</link>
+ <guid isPermaLink="false">2026-09-28:The Pole Club floor comes alive: a crowd, money on the stages, and tipping from inside the room</guid>
+ <pubDate>Mon, 28 Sep 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Walking into the Club used to land you in an empty room. Now a crowd stands around the three stages, and every tip turns into $0.001 bills. When you tip, a clump of bills flies from where you are standing and flutters down onto her stage. When someone else tips, bills drop from the lights above her pole. The bills stay where they land, so each stage keeps a pile for the night, sized from that dancer's real tips today. You can tip without leaving the scene: every dancer has a tag over her head, and clicking her or her pole opens a picker for her routine. A tip from another visitor now puts her through the routine they paid for on your screen too, and the people at her stage cheer. Tips paid by three.ws platform agents are labelled as agent tips in the feed, drop a single violet bill, and never start a routine, and each dancer's card now says how many of today's tips came from people and how many from agents.</description>
+ </item>
<item>
<title>Props the platform pays Forge to make now land in the /forged gallery</title>
<link>https://three.ws/forged</link>
diff --git a/public/features.json b/public/features.json
index ce0c28d30..017c0f4ce 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-25T19:21:51.968Z",
+ "generated_at": "2026-09-28T03:03:42.998Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/club-floor-crowd.js b/src/club-floor-crowd.js
new file mode 100644
index 000000000..c1d596604
--- /dev/null
+++ b/src/club-floor-crowd.js
@@ -0,0 +1,145 @@
+// /club floor crowd: the people standing around the stages.
+//
+// The walk-in hands you off to a room that used to be empty: three stages and
+// nobody watching them. This module plans where a crowd stands inside the club
+// (a loose ring around each stage, facing the pole) and drives it: when a
+// person's tip puts a dancer on her pole, the people at that stage cheer.
+//
+// The bodies themselves come from ClubCrowd (src/club-crowd.js), the same
+// roster, retarget cache and clip pools that fill the alley line, fed through
+// its directed-lineup path so every member lands on an exact planned spot.
+// Nobody is placed in the wedge between a stage and the default camera, or in
+// any other sightline a stage declares (its close-up camera), so the crowd
+// frames the dancer instead of blocking her.
+
+import { ClubCrowd } from './club-crowd.js';
+import { log } from './shared/log.js';
+
+// Mood pools for a standing audience. Names must exist in the animation
+// manifest; ClubCrowd drops any a rig cannot play and falls back to idle.
+const WATCH_CLIPS = ['av-listening-music', 'av-idle-breath', 'idle', 'av-waiting'];
+const HYPE_CLIPS = ['av-cheering', 'av-banging-tunes', 'av-headbang', 'av-dance-shuffle', 'dance'];
+const CHEER_GESTURE = ['av-cheering'];
+
+const RING_GAP_MIN = 0.75; // metres past the stage rim
+const RING_GAP_MAX = 1.45;
+const CAMERA_WEDGE = 0.95; // half-angle (rad) kept clear toward the camera
+const MIN_SPACING = 0.78;
+const HYPE_SHARE = 0.4; // fraction of the audience already moving to the music
+
+/** Signed smallest difference between two angles. */
+function angleDiff(a, b) {
+ let d = (a - b) % (Math.PI * 2);
+ if (d > Math.PI) d -= Math.PI * 2;
+ if (d < -Math.PI) d += Math.PI * 2;
+ return d;
+}
+
+/**
+ * Plan crowd spots around the stages. Pure and seedable, so the layout is
+ * unit-testable without a renderer.
+ *
+ * @param {object} opts
+ * @param {Array<{id:string,x:number,z:number,radius:number,clearDirs?:number[]}>} opts.stages
+ * `clearDirs` are extra headings (atan2(dx, dz) from the stage centre) whose
+ * wedge is kept empty, e.g. where that stage's close-up camera sits
+ * @param {{x:number,z:number}} opts.camera default viewpoint to keep clear
+ * @param {number} opts.count total audience size
+ * @param {() => number} [opts.rng]
+ * @returns {Array<{stageId:string,x:number,y:number,z:number,yaw:number,clips:string[]}>}
+ */
+export function planFloorCrowd({ stages, camera, count, rng = Math.random }) {
+ const slots = [];
+ if (!stages.length || count <= 0) return slots;
+ const clear = (x, z) => {
+ for (const s of stages) {
+ if (Math.hypot(x - s.x, z - s.z) < s.radius + RING_GAP_MIN - 0.05) return false;
+ }
+ for (const p of slots) {
+ if (Math.hypot(x - p.x, z - p.z) < MIN_SPACING) return false;
+ }
+ return true;
+ };
+ const perStage = Math.ceil(count / stages.length);
+ for (const stage of stages) {
+ const keepClear = [Math.atan2(camera.x - stage.x, camera.z - stage.z), ...(stage.clearDirs || [])];
+ let placed = 0;
+ for (let tries = 0; tries < perStage * 30 && placed < perStage && slots.length < count; tries++) {
+ const a = rng() * Math.PI * 2;
+ if (keepClear.some((dir) => Math.abs(angleDiff(a, dir)) < CAMERA_WEDGE)) continue;
+ const r = stage.radius + RING_GAP_MIN + rng() * (RING_GAP_MAX - RING_GAP_MIN);
+ const x = stage.x + Math.sin(a) * r;
+ const z = stage.z + Math.cos(a) * r;
+ if (!clear(x, z)) continue;
+ // Face the pole, with a little head-turn so the ring isn't robotic.
+ const yaw = Math.atan2(stage.x - x, stage.z - z) + (rng() - 0.5) * 0.35;
+ const clips = rng() < HYPE_SHARE ? HYPE_CLIPS : WATCH_CLIPS;
+ slots.push({ stageId: stage.id, x, y: 0, z, yaw, clips });
+ placed++;
+ }
+ }
+ return slots;
+}
+
+export class ClubFloorCrowd {
+ /**
+ * @param {object} opts
+ * @param {import('three').WebGLRenderer} opts.renderer
+ * @param {import('three').Scene} opts.scene
+ * @param {Array} opts.manifest animation manifest
+ * @param {Array<{name:string,url:string}>} opts.bundled offline-safe rigs
+ */
+ constructor({ renderer, scene, manifest, bundled }) {
+ this.crowd = new ClubCrowd({ renderer, scene, manifest, max: 64, bundled });
+ /** @type {Map<string, object[]>} stage id -> members standing at it */
+ this.byStage = new Map();
+ }
+
+ /**
+ * Fill the floor. Safe to call once; members stream in without stalling a
+ * frame, and any load failure leaves a smaller (or empty) crowd.
+ * @param {object} opts
+ * @param {import('three').Object3D} opts.envRoot
+ * @param {Array<{id:string,x:number,z:number,radius:number}>} opts.stages
+ * @param {{x:number,z:number}} opts.camera
+ * @param {number} opts.count
+ */
+ mount({ envRoot, stages, camera, count }) {
+ const slots = planFloorCrowd({ stages, camera, count });
+ if (!slots.length) return;
+ this.byStage.clear();
+ const origin = { x: camera.x, y: 0, z: camera.z };
+ this.crowd.mount({
+ envRoot,
+ bounds: { minX: -1, maxX: 1, minZ: -1, maxZ: 1 },
+ path: { spawn: origin, door: origin },
+ max: slots.length,
+ lineup: {
+ slots,
+ onMember: (inst, slot) => {
+ const list = this.byStage.get(slot.stageId) || [];
+ list.push(inst);
+ this.byStage.set(slot.stageId, list);
+ },
+ },
+ });
+ log.info(`[club-floor-crowd] planned ${slots.length} around ${stages.length} stages`);
+ }
+
+ /** The people at one stage cheer (a person's tip just landed there). */
+ cheer(stageId) {
+ for (const inst of this.byStage.get(stageId) || []) {
+ // Stagger so the ring erupts rather than moving as one body.
+ setTimeout(() => this.crowd.gesture(inst, CHEER_GESTURE), Math.random() * 450);
+ }
+ }
+
+ update(dt) {
+ this.crowd.update(dt);
+ }
+
+ dispose() {
+ this.crowd.dispose();
+ this.byStage.clear();
+ }
+}
diff --git a/src/club-money.js b/src/club-money.js
new file mode 100644
index 000000000..ca84a26bb
--- /dev/null
+++ b/src/club-money.js
@@ -0,0 +1,434 @@
+// /club money: the $0.001 bills that land on the stages.
+//
+// Every tip is real USDC, so the room should show money moving. A tip you pay
+// is thrown: a clump of bills leaves the camera, arcs over the floor and
+// flutters down onto that dancer's stage. Someone else's tip, arriving live
+// over the tips stream, drops out of the rig above the pole instead. Bills
+// that land stay where they fell, so each stage keeps a pile for the night,
+// seeded on boot from that dancer's real tip count.
+//
+// One InstancedMesh draws every bill (one draw call however many are in the
+// air). Slots are recycled oldest-resting-first once the device's budget is
+// full, so a busy night never grows the scene. The bill face is drawn once to
+// a canvas texture: no image asset, no network fetch.
+//
+// Tips paid from a platform wallet (the x402 ring and roster agents, flagged
+// `agent` by /api/club/tips) print on a violet bill, so agent money is never
+// passed off as a person's.
+
+import {
+ CanvasTexture,
+ Color,
+ DoubleSide,
+ DynamicDrawUsage,
+ Euler,
+ InstancedBufferAttribute,
+ InstancedMesh,
+ Matrix4,
+ MeshStandardMaterial,
+ PlaneGeometry,
+ Quaternion,
+ SRGBColorSpace,
+ Vector3,
+} from 'three';
+
+// A real banknote is ~156 x 66 mm; the bill keeps that proportion.
+const BILL_W = 0.16;
+const BILL_H = 0.068;
+
+const GRAVITY = -9.8;
+const TERMINAL_FALL = -0.75; // m/s once a bill is fluttering, paper-slow
+const FLUTTER_BELOW_VY = -0.6; // a thrown bill starts to flutter once it is falling this fast
+const THROW_FLIGHT_SEC = 0.9;
+const DROP_HEIGHT = 3.4; // how far above the stage a dropped bill starts
+const REST_LIFT = 0.0015; // clears the stage top so a flat bill never z-fights
+const STACK_STEP = 0.0007; // each landed bill sits a hair above the last
+const STACK_MAX = 0.035;
+
+const STATE_FREE = 0;
+const STATE_THROWN = 1;
+const STATE_FLUTTER = 2;
+const STATE_REST = 3;
+
+const HUMAN_TINT = new Color(1, 1, 1);
+const AGENT_TINT = new Color(0.78, 0.66, 1.0);
+
+const _m = new Matrix4();
+const _q = new Quaternion();
+const _e = new Euler();
+const _p = new Vector3();
+const _s = new Vector3(1, 1, 1);
+const ZERO_SCALE = new Matrix4().makeScale(0, 0, 0);
+
+/**
+ * Initial velocity that carries a body from `from` to `to` in `t` seconds under
+ * gravity alone. Pure, so the throw arc is unit-testable.
+ * @param {{x:number,y:number,z:number}} from
+ * @param {{x:number,y:number,z:number}} to
+ * @param {number} t
+ */
+export function ballisticVelocity(from, to, t) {
+ return {
+ x: (to.x - from.x) / t,
+ y: (to.y - from.y) / t - 0.5 * GRAVITY * t,
+ z: (to.z - from.z) / t,
+ };
+}
+
+/**
+ * A random point on a stage disc, kept off the pole in the middle and inside
+ * the rim so a landed bill reads as lying on the stage.
+ * @param {{x:number,z:number,radius:number}} stage
+ * @param {() => number} rng
+ */
+export function pointOnStage(stage, rng) {
+ const inner = 0.16;
+ const outer = Math.max(inner + 0.05, stage.radius - 0.12);
+ // sqrt keeps the scatter even across the disc instead of bunching at the pole
+ const r = Math.sqrt(inner * inner + rng() * (outer * outer - inner * inner));
+ const a = rng() * Math.PI * 2;
+ return { x: stage.x + Math.cos(a) * r, z: stage.z + Math.sin(a) * r };
+}
+
+/** Draw the bill face once. Big denomination, USDC blue, three.ws mark. */
+function drawBillTexture() {
+ const c = document.createElement('canvas');
+ c.width = 512;
+ c.height = 218;
+ const g = c.getContext('2d');
+ const grad = g.createLinearGradient(0, 0, c.width, c.height);
+ grad.addColorStop(0, '#2d7fd6');
+ grad.addColorStop(0.55, '#2263ad');
+ grad.addColorStop(1, '#173f78');
+ g.fillStyle = grad;
+ g.fillRect(0, 0, c.width, c.height);
+
+ // Guilloche-style fine lines, the texture that makes it read as money.
+ g.strokeStyle = 'rgba(255,255,255,0.08)';
+ g.lineWidth = 1;
+ for (let i = -c.height; i < c.width; i += 9) {
+ g.beginPath();
+ g.moveTo(i, 0);
+ g.lineTo(i + c.height, c.height);
+ g.stroke();
+ }
+ g.strokeStyle = 'rgba(255,255,255,0.75)';
+ g.lineWidth = 5;
+ g.strokeRect(10, 10, c.width - 20, c.height - 20);
+ g.lineWidth = 1.5;
+ g.strokeRect(20, 20, c.width - 40, c.height - 40);
+
+ // Emblem: the USDC ring on the left.
+ g.beginPath();
+ g.arc(110, c.height / 2, 58, 0, Math.PI * 2);
+ g.fillStyle = 'rgba(255,255,255,0.14)';
+ g.fill();
+ g.lineWidth = 6;
+ g.strokeStyle = '#ffffff';
+ g.stroke();
+ g.fillStyle = '#ffffff';
+ g.font = '700 58px system-ui, -apple-system, Segoe UI, sans-serif';
+ g.textAlign = 'center';
+ g.textBaseline = 'middle';
+ g.fillText('$', 110, c.height / 2 + 3);
+
+ g.textAlign = 'right';
+ g.font = '800 84px system-ui, -apple-system, Segoe UI, sans-serif';
+ g.fillText('0.001', c.width - 36, 96);
+ g.font = '700 22px system-ui, -apple-system, Segoe UI, sans-serif';
+ g.fillStyle = 'rgba(255,255,255,0.9)';
+ g.fillText('ONE TENTH OF A CENT', c.width - 38, 150);
+ g.font = '600 17px system-ui, -apple-system, Segoe UI, sans-serif';
+ g.fillStyle = 'rgba(255,255,255,0.7)';
+ g.fillText('USDC · SETTLED ON-CHAIN · THREE.WS', c.width - 38, 180);
+
+ const tex = new CanvasTexture(c);
+ tex.colorSpace = SRGBColorSpace;
+ tex.anisotropy = 4;
+ return tex;
+}
+
+export class ClubMoney {
+ /**
+ * @param {object} opts
+ * @param {import('three').Scene} opts.scene
+ * @param {number} opts.capacity bills alive at once (device budget)
+ * @param {boolean} [opts.reducedMotion] land bills straight on the pile
+ * @param {() => number} [opts.rng]
+ * @param {import('three').Texture} [opts.texture] injected in tests (no canvas)
+ */
+ constructor({ scene, capacity, reducedMotion = false, rng = Math.random, texture = null }) {
+ this.capacity = Math.max(1, Math.floor(capacity));
+ this.reducedMotion = reducedMotion;
+ this.rng = rng;
+ /** @type {Map<string, {x:number,z:number,topY:number,radius:number,stack:number}>} */
+ this.stages = new Map();
+
+ const n = this.capacity;
+ this.state = new Uint8Array(n);
+ this.pos = new Float32Array(n * 3);
+ this.vel = new Float32Array(n * 3);
+ this.rot = new Float32Array(n * 3);
+ this.spin = new Float32Array(n * 3);
+ this.phase = new Float32Array(n);
+ this.target = new Float32Array(n * 2);
+ this.restY = new Float32Array(n);
+ this.stageOf = new Array(n).fill(null);
+ this.restOrder = []; // slot indices in landing order: the recycle queue
+ this.airborne = 0;
+ this.dirty = false;
+ this.clock = 0;
+
+ const geo = new PlaneGeometry(BILL_W, BILL_H);
+ geo.rotateX(-Math.PI / 2); // identity rotation = lying flat on the floor
+ const map = texture || drawBillTexture();
+ this.material = new MeshStandardMaterial({
+ map,
+ emissive: 0xffffff,
+ emissiveMap: map,
+ emissiveIntensity: 0.22, // readable in a dark room without a spotlight on it
+ roughness: 0.78,
+ metalness: 0,
+ side: DoubleSide,
+ });
+ this.mesh = new InstancedMesh(geo, this.material, n);
+ this.mesh.name = 'club-money';
+ this.mesh.instanceMatrix.setUsage(DynamicDrawUsage);
+ this.mesh.instanceColor = new InstancedBufferAttribute(new Float32Array(n * 3), 3);
+ this.mesh.frustumCulled = false; // instances span the whole room
+ this.mesh.castShadow = false;
+ this.mesh.receiveShadow = false;
+ for (let i = 0; i < n; i++) {
+ this.mesh.setMatrixAt(i, ZERO_SCALE);
+ this.mesh.setColorAt(i, HUMAN_TINT);
+ }
+ scene.add(this.mesh);
+ this.scene = scene;
+ }
+
+ /**
+ * Register (or move) a stage disc bills can land on.
+ * @param {string} id
+ * @param {{x:number,z:number,topY:number,radius:number}} disc
+ */
+ setStage(id, { x, z, topY, radius }) {
+ const prev = this.stages.get(id);
+ this.stages.set(id, { x, z, topY, radius, stack: prev?.stack ?? 0 });
+ }
+
+ /** Bills currently resting on a stage (the visible pile). */
+ pileSize(id) {
+ let n = 0;
+ for (let i = 0; i < this.capacity; i++) {
+ if (this.state[i] === STATE_REST && this.stageOf[i] === id) n++;
+ }
+ return n;
+ }
+
+ /**
+ * Lay `count` bills straight onto a stage's pile (boot, from real tip counts).
+ * @param {string} id
+ * @param {number} count
+ * @param {{agent?:boolean}} [opts]
+ */
+ seed(id, count, { agent = false } = {}) {
+ const stage = this.stages.get(id);
+ if (!stage) return;
+ for (let k = 0; k < count; k++) {
+ const i = this._claim();
+ const pt = pointOnStage(stage, this.rng);
+ this._tint(i, agent);
+ this._land(i, id, pt.x, pt.z);
+ }
+ }
+
+ /**
+ * Throw a clump of bills from `from` (the camera) onto a stage: your own tip.
+ * @param {string} id
+ * @param {{x:number,y:number,z:number}} from
+ * @param {number} [count]
+ */
+ throwTo(id, from, count = 8) {
+ const stage = this.stages.get(id);
+ if (!stage) return;
+ for (let k = 0; k < count; k++) {
+ const i = this._claim();
+ const pt = pointOnStage(stage, this.rng);
+ this._tint(i, false);
+ if (this.reducedMotion) { this._land(i, id, pt.x, pt.z); continue; }
+ const jitter = () => (this.rng() - 0.5) * 0.25;
+ const start = { x: from.x + jitter(), y: from.y - 0.35 + jitter() * 0.5, z: from.z + jitter() };
+ // Aim a touch above the stage so the bill flutters the last stretch down.
+ const aim = { x: pt.x, y: stage.topY + 0.9 + this.rng() * 0.5, z: pt.z };
+ const v = ballisticVelocity(start, aim, THROW_FLIGHT_SEC * (0.85 + this.rng() * 0.3));
+ this._launch(i, id, start, v, pt, STATE_THROWN);
+ }
+ }
+
+ /**
+ * Drop bills out of the rig above a stage: someone else's tip.
+ * @param {string} id
+ * @param {number} [count]
+ * @param {{agent?:boolean}} [opts]
+ */
+ dropOn(id, count = 1, { agent = false } = {}) {
+ const stage = this.stages.get(id);
+ if (!stage) return;
+ for (let k = 0; k < count; k++) {
+ const i = this._claim();
+ const pt = pointOnStage(stage, this.rng);
+ this._tint(i, agent);
+ if (this.reducedMotion) { this._land(i, id, pt.x, pt.z); continue; }
+ const start = {
+ x: pt.x + (this.rng() - 0.5) * 0.6,
+ y: stage.topY + DROP_HEIGHT + this.rng() * 0.8,
+ z: pt.z + (this.rng() - 0.5) * 0.6,
+ };
+ this._launch(i, id, start, { x: 0, y: TERMINAL_FALL, z: 0 }, pt, STATE_FLUTTER);
+ }
+ }
+
+ /** Advance every airborne bill. Resting bills cost nothing per frame. */
+ update(dt) {
+ this.clock += dt;
+ if (this.airborne > 0) {
+ for (let i = 0; i < this.capacity; i++) {
+ const st = this.state[i];
+ if (st === STATE_THROWN) this._stepThrown(i, dt);
+ else if (st === STATE_FLUTTER) this._stepFlutter(i, dt);
+ }
+ }
+ if (this.dirty) {
+ this.mesh.instanceMatrix.needsUpdate = true;
+ if (this.mesh.instanceColor) this.mesh.instanceColor.needsUpdate = true;
+ this.dirty = false;
+ }
+ }
+
+ dispose() {
+ this.scene.remove(this.mesh);
+ this.mesh.geometry.dispose();
+ this.material.map?.dispose();
+ this.material.dispose();
+ this.mesh.dispose?.();
+ }
+
+ // ── internals ────────────────────────────────────────────────────────
+
+ /** A free slot, or the oldest resting bill when the budget is full. */
+ _claim() {
+ for (let i = 0; i < this.capacity; i++) {
+ if (this.state[i] === STATE_FREE) return i;
+ }
+ if (this.restOrder.length) {
+ const i = this.restOrder.shift();
+ this.state[i] = STATE_FREE;
+ return i;
+ }
+ // Every slot is airborne: reuse the first one; it is mid-air anyway.
+ this.airborne = Math.max(0, this.airborne - 1);
+ return 0;
+ }
+
+ _tint(i, agent) {
+ this.mesh.setColorAt(i, agent ? AGENT_TINT : HUMAN_TINT);
+ this.dirty = true;
+ }
+
+ _launch(i, id, start, v, pt, state) {
+ const o = i * 3;
+ this.pos[o] = start.x; this.pos[o + 1] = start.y; this.pos[o + 2] = start.z;
+ this.vel[o] = v.x; this.vel[o + 1] = v.y; this.vel[o + 2] = v.z;
+ this.rot[o] = this.rng() * Math.PI * 2;
+ this.rot[o + 1] = this.rng() * Math.PI * 2;
+ this.rot[o + 2] = this.rng() * Math.PI * 2;
+ this.spin[o] = (this.rng() - 0.5) * 9;
+ this.spin[o + 1] = (this.rng() - 0.5) * 5;
+ this.spin[o + 2] = (this.rng() - 0.5) * 9;
+ this.phase[i] = this.rng() * Math.PI * 2;
+ this.target[i * 2] = pt.x;
+ this.target[i * 2 + 1] = pt.z;
+ this.stageOf[i] = id;
+ this.state[i] = state;
+ this.airborne++;
+ this._write(i);
+ }
+
+ _stepThrown(i, dt) {
+ const o = i * 3;
+ this.vel[o + 1] += GRAVITY * dt;
+ this.pos[o] += this.vel[o] * dt;
+ this.pos[o + 1] += this.vel[o + 1] * dt;
+ this.pos[o + 2] += this.vel[o + 2] * dt;
+ this.rot[o] += this.spin[o] * dt * 1.6;
+ this.rot[o + 1] += this.spin[o + 1] * dt;
+ this.rot[o + 2] += this.spin[o + 2] * dt * 1.6;
+ // Paper catches the air once it starts to fall: hand over to the flutter.
+ if (this.vel[o + 1] < FLUTTER_BELOW_VY) this.state[i] = STATE_FLUTTER;
+ this._write(i);
+ }
+
+ _stepFlutter(i, dt) {
+ const o = i * 3;
+ const stage = this.stages.get(this.stageOf[i]);
+ const floorY = this._restHeight(stage);
+ // Ease toward terminal fall speed, and drift toward the landing point
+ // while swaying side to side like paper does.
+ this.vel[o + 1] += (TERMINAL_FALL - this.vel[o + 1]) * Math.min(1, dt * 3.5);
+ const tx = this.target[i * 2];
+ const tz = this.target[i * 2 + 1];
+ const t = this.clock * 3.1 + this.phase[i];
+ this.vel[o] += ((tx - this.pos[o]) * 1.2 - this.vel[o]) * Math.min(1, dt * 2.5);
+ this.vel[o + 2] += ((tz - this.pos[o + 2]) * 1.2 - this.vel[o + 2]) * Math.min(1, dt * 2.5);
+ this.pos[o] += (this.vel[o] + Math.sin(t) * 0.55) * dt;
+ this.pos[o + 1] += this.vel[o + 1] * dt;
+ this.pos[o + 2] += (this.vel[o + 2] + Math.cos(t * 0.8) * 0.4) * dt;
+ // Rock around the flat pose rather than tumbling end over end: a
+ // fluttering bill mostly faces the floor.
+ const h = Math.max(0, this.pos[o + 1] - floorY);
+ const settle = Math.min(1, h / 0.6);
+ this.rot[o] = Math.sin(t * 1.3) * 0.7 * settle;
+ this.rot[o + 1] += this.spin[o + 1] * dt * 0.6;
+ this.rot[o + 2] = Math.cos(t) * 0.55 * settle;
+ if (this.pos[o + 1] <= floorY) {
+ this.airborne = Math.max(0, this.airborne - 1);
+ this._land(i, this.stageOf[i], this.pos[o], this.pos[o + 2]);
+ return;
+ }
+ this._write(i);
+ }
+
+ _restHeight(stage) {
+ return stage ? stage.topY + REST_LIFT + stage.stack : REST_LIFT;
+ }
+
+ _land(i, id, x, z) {
+ const stage = this.stages.get(id);
+ const o = i * 3;
+ // On the disc the bill lies on the stage top; a stray that drifted past the
+ // rim lies on the club floor at its feet.
+ const onDisc = stage && Math.hypot(x - stage.x, z - stage.z) <= stage.radius - 0.02;
+ const y = onDisc ? this._restHeight(stage) : REST_LIFT;
+ if (onDisc) stage.stack = Math.min(STACK_MAX, stage.stack + STACK_STEP);
+ this.pos[o] = x; this.pos[o + 1] = y; this.pos[o + 2] = z;
+ this.rot[o] = (this.rng() - 0.5) * 0.06;
+ this.rot[o + 1] = this.rng() * Math.PI * 2;
+ this.rot[o + 2] = (this.rng() - 0.5) * 0.06;
+ this.restY[i] = y;
+ this.stageOf[i] = id;
+ this.state[i] = STATE_REST;
+ const at = this.restOrder.indexOf(i);
+ if (at >= 0) this.restOrder.splice(at, 1);
+ this.restOrder.push(i);
+ this._write(i);
+ }
+
+ _write(i) {
+ const o = i * 3;
+ _p.set(this.pos[o], this.pos[o + 1], this.pos[o + 2]);
+ _q.setFromEuler(_e.set(this.rot[o], this.rot[o + 1], this.rot[o + 2]));
+ _m.compose(_p, _q, _s);
+ this.mesh.setMatrixAt(i, _m);
+ this.dirty = true;
+ }
+}
diff --git a/src/club-tip-hud.js b/src/club-tip-hud.js
new file mode 100644
index 000000000..594ff553e
--- /dev/null
+++ b/src/club-tip-hud.js
@@ -0,0 +1,399 @@
+// /club tip tags: tip a dancer from inside the room.
+//
+// Each dancer carries a floating tag over her head (name, the style she will
+// dance, a Tip button) pinned to her in screen space every frame. Click the
+// dancer herself, her pole, or her name and a tray of style chips opens on
+// the tag. Pick a style, hit Tip, and the wallet opens. The sidebar pole cards
+// stay as the full controls; the tag writes its style pick straight into the
+// sidebar select, so the two surfaces never disagree about what she'll dance.
+//
+// While a dancer performs, her tag shows who she is dancing for and how long
+// is left, read from the station each frame (no timers of its own).
+
+import { Raycaster, Vector2, Vector3 } from 'three';
+
+const TAG_LIFT = 0.42; // metres above the dancer's head
+const PICK_RADIUS = 0.62; // how close to the pole axis a click must land
+const PICK_TOP = 2.4; // the clickable column: stage floor to just over her head
+const CLICK_SLOP_PX = 6; // more movement than this is an orbit drag, not a click
+const CLICK_MAX_MS = 450;
+
+const _v = new Vector3();
+const _ray = new Raycaster();
+const _ndc = new Vector2();
+
+/**
+ * Distance between a ray and a vertical segment (the pole column), plus the
+ * ray parameter at the closest point. Pure, so picking is unit-testable.
+ * @param {{origin:{x:number,y:number,z:number}, direction:{x:number,y:number,z:number}}} ray
+ * @param {{x:number,z:number,y0:number,y1:number}} col
+ * @returns {{dist:number, t:number}}
+ */
+export function rayToColumn(ray, col) {
+ const o = ray.origin;
+ const d = ray.direction;
+ // Closest points between the ray o + t d and the segment p + s u, u = +Y.
+ const wx = o.x - col.x;
+ const wy = o.y - col.y0;
+ const wz = o.z - col.z;
+ const len = col.y1 - col.y0;
+ const b = d.y; // d . u
+ const dd = d.x * wx + d.y * wy + d.z * wz;
+ const e = wy; // u . w
+ const denom = 1 - b * b; // |d| = |u| = 1
+ let t = denom > 1e-6 ? (b * e - dd) / denom : 0;
+ if (t < 0) t = 0;
+ let s = e + b * t;
+ if (s < 0) s = 0;
+ else if (s > len) s = len;
+ // Re-project t onto the clamped segment point.
+ t = Math.max(0, (col.x - o.x) * d.x + (col.y0 + s - o.y) * d.y + (col.z - o.z) * d.z);
+ const px = o.x + d.x * t - col.x;
+ const py = o.y + d.y * t - (col.y0 + s);
+ const pz = o.z + d.z * t - col.z;
+ return { dist: Math.hypot(px, py, pz), t };
+}
+
+function escapeHtml(s) {
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+function shortWallet(addr) {
+ return addr ? `${addr.slice(0, 4)}…${addr.slice(-4)}` : 'someone';
+}
+
+export class ClubTipHud {
+ /**
+ * @param {object} opts
+ * @param {HTMLElement} opts.layer fixed overlay the tags live in
+ * @param {HTMLCanvasElement} opts.canvas
+ * @param {import('three').Camera} opts.camera
+ * @param {Array<{id:string,name:string,accent:string,station:object}>} opts.dancers
+ * @param {Array<{key:string,label:string}>} opts.dances
+ * @param {(id:string) => string} opts.getStyle
+ * @param {(id:string, key:string) => void} opts.setStyle
+ * @param {(id:string, key:string, button:HTMLButtonElement) => void} opts.onTip
+ * @param {(id:string) => void} [opts.onFocus] a dancer was picked in the scene
+ */
+ constructor({ layer, canvas, camera, dancers, dances, getStyle, setStyle, onTip, onFocus }) {
+ this.layer = layer;
+ this.canvas = canvas;
+ this.camera = camera;
+ this.dances = dances;
+ this.getStyle = getStyle;
+ this.setStyle = setStyle;
+ this.onTip = onTip;
+ this.onFocus = onFocus;
+ this.enabled = false;
+ this.hidden = false;
+ this.openId = null;
+ this.hoverId = null;
+ /** @type {Map<string, {el:HTMLElement, tip:HTMLButtonElement, nameBtn:HTMLButtonElement, styleEl:HTMLElement, tray:HTMLElement, live:HTMLElement, station:object, x:number, y:number, shown:boolean, liveText:string, tipState:string}>} */
+ this.tags = new Map();
+ this.rect = null;
+ // The canvas box moves when the window resizes or the side panel reflows;
+ // every tag is placed relative to it.
+ this._ro = typeof ResizeObserver === 'function' ? new ResizeObserver(() => this.measure()) : null;
+ this._ro?.observe(canvas);
+ this._onResize = () => this.measure();
+ window.addEventListener('resize', this._onResize);
+
+ for (const d of dancers) this._build(d);
+ this.measure();
+ this._bindScenePicking();
+ this._onDocPointer = (e) => {
+ if (!this.openId) return;
+ const tag = this.tags.get(this.openId);
+ if (tag && !tag.el.contains(e.target) && e.target !== this.canvas) this.close();
+ };
+ this._onKey = (e) => { if (e.key === 'Escape' && this.openId) this.close({ refocus: true }); };
+ document.addEventListener('pointerdown', this._onDocPointer, true);
+ document.addEventListener('keydown', this._onKey);
+ }
+
+ /** Tip buttons stay disabled until the payment widget is live. */
+ setEnabled(on) {
+ this.enabled = on;
+ for (const tag of this.tags.values()) this._syncTip(tag, true);
+ }
+
+ /** Hide every tag (the alley still covers the stage, or a modal is up). */
+ setHidden(hidden) {
+ if (this.hidden === hidden) return;
+ this.hidden = hidden;
+ this.layer.classList.toggle('is-hidden', hidden);
+ if (hidden) this.close();
+ // A hidden layer measures every tag as zero wide; re-read them now that
+ // they can be laid out, so edge clamping uses their real size.
+ else this.measure();
+ }
+
+ /**
+ * Re-read the canvas box after a resize or layout change. The tag layer is
+ * laid exactly over the canvas and clips to it, so a tag can never slide
+ * over the side panel.
+ */
+ measure() {
+ const r = this.canvas.getBoundingClientRect();
+ this.rect = r;
+ const st = this.layer.style;
+ st.left = `${r.left}px`;
+ st.top = `${r.top}px`;
+ st.width = `${r.width}px`;
+ st.height = `${r.height}px`;
+ for (const tag of this.tags.values()) this._measureTag(tag);
+ }
+
+ /** Keep a tag's style label in step when the sidebar select changes. */
+ refreshStyle(id) {
+ const tag = this.tags.get(id);
+ if (!tag) return;
+ const key = this.getStyle(id);
+ tag.styleEl.textContent = this.dances.find((d) => d.key === key)?.label || key;
+ for (const chip of tag.tray.querySelectorAll('.club-tag-chip')) {
+ chip.setAttribute('aria-pressed', chip.dataset.dance === key ? 'true' : 'false');
+ }
+ }
+
+ open(id) {
+ if (this.openId && this.openId !== id) this.close();
+ const tag = this.tags.get(id);
+ if (!tag) return;
+ this.openId = id;
+ tag.el.classList.add('is-open');
+ tag.tray.hidden = false;
+ tag.nameBtn.setAttribute('aria-expanded', 'true');
+ this.refreshStyle(id);
+ this._measureTag(tag);
+ }
+
+ close({ refocus = false } = {}) {
+ const tag = this.openId && this.tags.get(this.openId);
+ this.openId = null;
+ if (!tag) return;
+ tag.el.classList.remove('is-open');
+ tag.tray.hidden = true;
+ tag.nameBtn.setAttribute('aria-expanded', 'false');
+ this._measureTag(tag);
+ if (refocus) tag.nameBtn.focus({ preventScroll: true });
+ }
+
+ /** Pin every tag over its dancer. Called once per rendered frame. */
+ update() {
+ if (this.hidden) return;
+ const { rect } = this;
+ for (const tag of this.tags.values()) {
+ const rig = tag.station.rig;
+ if (!rig) continue;
+ rig.getWorldPosition(_v);
+ _v.y += (tag.station.headHeight || 1.75) + TAG_LIFT;
+ _v.project(this.camera);
+ const onScreen = _v.z > -1 && _v.z < 1 && Math.abs(_v.x) < 1.02 && _v.y < 1.1 && _v.y > -1.02;
+ if (onScreen !== tag.shown) {
+ tag.shown = onScreen;
+ tag.el.classList.toggle('is-offscreen', !onScreen);
+ if (!onScreen && this.openId === tag.id) this.close();
+ }
+ if (onScreen) {
+ // Layer-local coordinates, kept inside the canvas box so the whole
+ // tag (open tray included) stays readable at the edges.
+ const half = tag.w / 2 + 8;
+ const x = Math.min(Math.max((_v.x * 0.5 + 0.5) * rect.width, half), rect.width - half);
+ const y = Math.max((-_v.y * 0.5 + 0.5) * rect.height, tag.h + 8);
+ // Sub-pixel jitter is invisible; skipping it spares a style write.
+ if (Math.abs(x - tag.x) > 0.5 || Math.abs(y - tag.y) > 0.5) {
+ tag.x = x;
+ tag.y = y;
+ tag.el.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) translate(-50%, -100%)`;
+ }
+ }
+ this._syncTip(tag);
+ }
+ }
+
+ dispose() {
+ document.removeEventListener('pointerdown', this._onDocPointer, true);
+ document.removeEventListener('keydown', this._onKey);
+ window.removeEventListener('resize', this._onResize);
+ this._ro?.disconnect();
+ this._unbindScene?.();
+ for (const tag of this.tags.values()) tag.el.remove();
+ this.tags.clear();
+ }
+
+ // ── internals ────────────────────────────────────────────────────────
+
+ _build({ id, name, accent, station }) {
+ const el = document.createElement('div');
+ el.className = 'club-tag is-offscreen';
+ el.dataset.pole = id;
+ el.style.setProperty('--tag-accent', accent);
+ const trayId = `club-tag-tray-${id}`;
+ el.innerHTML = `
+ <div class="club-tag-bar">
+ <button type="button" class="club-tag-name" aria-expanded="false" aria-controls="${trayId}"
+ aria-label="Choose ${escapeHtml(name)}'s dance">
+ <span class="club-tag-who">${escapeHtml(name)}</span>
+ <span class="club-tag-style"></span>
+ <svg class="club-tag-caret" viewBox="0 0 10 6" aria-hidden="true"><path d="M1 1l4 4 4-4" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ </button>
+ <button type="button" class="club-tag-tip" disabled aria-disabled="true">Tip $0.001</button>
+ </div>
+ <div class="club-tag-live" aria-live="polite"></div>
+ <div class="club-tag-tray" id="${trayId}" role="group" aria-label="Dance style for ${escapeHtml(name)}" hidden>
+ ${this.dances.map((d) => `<button type="button" class="club-tag-chip" data-dance="${escapeHtml(d.key)}" aria-pressed="false">${escapeHtml(d.label)}</button>`).join('')}
+ </div>
+ `;
+ this.layer.appendChild(el);
+ const tag = {
+ id,
+ el,
+ station,
+ nameBtn: el.querySelector('.club-tag-name'),
+ tip: el.querySelector('.club-tag-tip'),
+ styleEl: el.querySelector('.club-tag-style'),
+ tray: el.querySelector('.club-tag-tray'),
+ live: el.querySelector('.club-tag-live'),
+ // Far off-canvas, so the first on-screen frame always writes a position.
+ x: -1e4,
+ y: -1e4,
+ shown: false,
+ w: 160,
+ h: 40,
+ liveText: '',
+ tipState: '',
+ };
+ this.tags.set(id, tag);
+ this.refreshStyle(id);
+ this._measureTag(tag);
+
+ tag.nameBtn.addEventListener('click', () => {
+ if (this.openId === id) this.close();
+ else this.open(id);
+ });
+ tag.tray.addEventListener('click', (e) => {
+ const chip = e.target.closest('.club-tag-chip');
+ if (!chip) return;
+ this.setStyle(id, chip.dataset.dance);
+ this.refreshStyle(id);
+ tag.tip.focus({ preventScroll: true });
+ });
+ tag.tip.addEventListener('click', () => {
+ if (tag.tip.disabled) return;
+ this.close();
+ this.onTip(id, this.getStyle(id), tag.tip);
+ });
+ el.addEventListener('pointerenter', () => el.classList.add('is-hover'));
+ el.addEventListener('pointerleave', () => el.classList.remove('is-hover'));
+ }
+
+ /** Cache a tag's box; read only when its content changes, never per frame. */
+ _measureTag(tag) {
+ const wasOff = tag.el.classList.contains('is-offscreen');
+ if (wasOff) tag.el.classList.remove('is-offscreen');
+ tag.w = tag.el.offsetWidth || tag.w;
+ tag.h = tag.el.offsetHeight || tag.h;
+ if (wasOff) tag.el.classList.add('is-offscreen');
+ }
+
+ /** Mirror the station's performance state onto the tag's button and caption. */
+ _syncTip(tag, force = false) {
+ const st = tag.station;
+ const local = st.performing && st.activeTicket?.local;
+ const pending = tag.tip.classList.contains('is-pending');
+ let state;
+ if (pending) state = 'pending';
+ else if (!this.enabled) state = 'off';
+ else if (local) state = 'local';
+ else state = 'ready';
+ if (force || state !== tag.tipState) {
+ tag.tipState = state;
+ const off = state === 'off' || state === 'local' || state === 'pending';
+ tag.tip.disabled = off;
+ tag.tip.setAttribute('aria-disabled', off ? 'true' : 'false');
+ if (state === 'ready' || state === 'off') tag.tip.textContent = 'Tip $0.001';
+ else if (state === 'local') tag.tip.textContent = 'Your dance';
+ }
+ let live = '';
+ if (st.performing && st.activeTicket) {
+ const left = Math.max(0, Math.ceil((st.activeUntil - Date.now()) / 1000));
+ const who = st.activeTicket.local ? 'you' : shortWallet(st.activeTicket.payer);
+ live = `${st.activeTicket.label || 'Dancing'} for ${who} · ${left}s`;
+ }
+ if (live !== tag.liveText) {
+ tag.liveText = live;
+ tag.live.textContent = live;
+ const wasLive = tag.el.classList.contains('is-live');
+ tag.el.classList.toggle('is-live', Boolean(live));
+ if (wasLive !== Boolean(live)) this._measureTag(tag);
+ }
+ }
+
+ /** Nearest dancer column under a screen point, or null. */
+ _pick(clientX, clientY) {
+ const { rect } = this;
+ _ndc.set(((clientX - rect.left) / rect.width) * 2 - 1, -((clientY - rect.top) / rect.height) * 2 + 1);
+ _ray.setFromCamera(_ndc, this.camera);
+ let best = null;
+ let bestT = Infinity;
+ for (const tag of this.tags.values()) {
+ const rig = tag.station.rig;
+ if (!rig) continue;
+ rig.getWorldPosition(_v);
+ const hit = rayToColumn(_ray.ray, { x: _v.x, z: _v.z, y0: 0, y1: PICK_TOP });
+ if (hit.dist < PICK_RADIUS && hit.t < bestT) {
+ bestT = hit.t;
+ best = tag.id;
+ }
+ }
+ return best;
+ }
+
+ _bindScenePicking() {
+ const canvas = this.canvas;
+ let down = null;
+ let hoverRaf = 0;
+ let lastMove = null;
+ const onDown = (e) => {
+ down = { x: e.clientX, y: e.clientY, t: performance.now(), id: e.pointerId };
+ };
+ const onUp = (e) => {
+ if (!down || down.id !== e.pointerId) return;
+ const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y);
+ const quick = performance.now() - down.t < CLICK_MAX_MS;
+ down = null;
+ if (moved > CLICK_SLOP_PX || !quick || this.hidden) return;
+ const id = this._pick(e.clientX, e.clientY);
+ if (id) {
+ this.open(id);
+ this.onFocus?.(id);
+ } else {
+ this.close();
+ }
+ };
+ const onMove = (e) => {
+ if (e.buttons || e.pointerType !== 'mouse') return;
+ lastMove = e;
+ if (hoverRaf) return;
+ hoverRaf = requestAnimationFrame(() => {
+ hoverRaf = 0;
+ if (!lastMove || this.hidden) return;
+ const id = this._pick(lastMove.clientX, lastMove.clientY);
+ if (id === this.hoverId) return;
+ if (this.hoverId) this.tags.get(this.hoverId)?.el.classList.remove('is-hover');
+ this.hoverId = id;
+ if (id) this.tags.get(id)?.el.classList.add('is-hover');
+ canvas.style.cursor = id ? 'pointer' : '';
+ });
+ };
+ canvas.addEventListener('pointerdown', onDown);
+ canvas.addEventListener('pointerup', onUp);
+ canvas.addEventListener('pointermove', onMove);
+ this._unbindScene = () => {
+ canvas.removeEventListener('pointerdown', onDown);
+ canvas.removeEventListener('pointerup', onUp);
+ canvas.removeEventListener('pointermove', onMove);
+ cancelAnimationFrame(hoverRaf);
+ };
+ }
+}
diff --git a/src/club.js b/src/club.js
index ad4a70c1e..3e818f674 100644
--- a/src/club.js
+++ b/src/club.js
@@ -54,6 +54,9 @@ import { ClubCamera } from './club-camera.js';
import { ClubAudio, styleAudioFor, TRACK_LABELS } from './club-audio.js';
import { DANCES } from './club-dances.js';
import { playSequence, ticketSteps } from './club-sequence.js';
+import { ClubMoney } from './club-money.js';
+import { ClubFloorCrowd } from './club-floor-crowd.js';
+import { ClubTipHud } from './club-tip-hud.js';
import { detectProfile, PROFILES, createFrameWatchdog, isMobileLayout } from './club-perf.js';
import {
createFrameGovernor, trackWindowFocus, getPowerSaver, setPowerSaver, onPowerSaverChange,
@@ -103,6 +106,26 @@ const PERFORMANCE_FADE = 0.45; // seconds for clip crossfade
// Top of the stage GLB. Authored in scripts/build-club-props.mjs at y=0.18.
// Mirrored here so the dancer rig + pole base sit on the disc face.
const STAGE_TOP_Y = 0.18;
+// Stage disc radius, mirrored from STAGE_RADIUS in scripts/build-club-props.mjs.
+// Bills land inside it and the floor crowd stands outside it.
+const STAGE_DISC_RADIUS = 1.1;
+// How many $0.001 bills can be alive in the room at once, per device tier. Past
+// that the oldest bill on a pile is recycled, so a busy night never grows the scene.
+const MONEY_CAPACITY = { high: 360, medium: 220, low: 90 };
+// Bills laid on a stage's pile at boot from that dancer's tips today.
+const PILE_SEED_MAX = 70;
+// A tip you pay throws a clump from the camera; a person's live tip drops a
+// smaller clump from the rig; an agent tip drops a single violet bill.
+const BILLS_THROWN = 9;
+const BILLS_REMOTE_HUMAN = 6;
+// People standing around the stages, per device tier (each is a skinned rig).
+const FLOOR_CROWD = { high: 12, medium: 8, low: 4 };
+const FLOOR_CROWD_RIGS = [
+ { name: 'Aria', url: '/avatars/default.glb' },
+ { name: 'Michelle', url: '/avatars/michelle.glb' },
+ { name: 'Realistic', url: '/avatars/realistic-female.glb' },
+ { name: 'Studio', url: '/avatars/studio.glb' },
+];
const POLES = Array.from({ length: POLE_COUNT }, (_, i) => {
// Spread across an arc from -55° to +55° at the front of the room.
@@ -207,11 +230,14 @@ function renderTipRow(rowLike, { live = false, prepend = true } = {}) {
row.className = 'club-tip-row';
if (live) row.classList.add('is-live');
const who = payer ? `${payer.slice(0, 4)}...${payer.slice(-4)}` : 'someone';
+ // A platform wallet (x402 ring or roster agent) is labeled as an agent, never
+ // passed off as a person in the room.
+ const agentBadge = rowLike.agent ? '<span class="club-tip-agent" title="Paid by a three.ws platform agent wallet">agent</span>' : '';
const safeLabel = String(label).replace(/[<>&]/g, '');
const time = formatTimestamp(timestamp);
row.innerHTML = `
<span class="club-tip-time">${time}</span>
- <span class="club-tip-mid"><span class="club-tip-who">${who}</span> tipped ${dancerName} &rarr; ${safeLabel}</span>
+ <span class="club-tip-mid"><span class="club-tip-who">${who}</span>${agentBadge} tipped ${dancerName} &rarr; ${safeLabel}</span>
<span class="club-tip-amt">${fmtUsd(amountAtomics)}</span>
`;
if (prepend) {
@@ -349,12 +375,18 @@ function subscribeTipStream() {
}
});
es.addEventListener('tip', (e) => {
+ let row;
try {
- const row = JSON.parse(e.data);
- renderTipRow(row, { live: true });
+ row = JSON.parse(e.data);
} catch (err) {
log.warn('[club] tip event parse failed', err);
+ return;
}
+ // Only a tip this tab has not already shown reaches the stage: our own
+ // tip's echo is dropped here, exactly as the feed drops it.
+ const fresh = !renderedTicketIds.has(row?.ticket_id);
+ renderTipRow(row, { live: true });
+ if (fresh) stageRemoteTip(row);
});
es.onerror = () => {
// EventSource auto-reconnects in some browsers but keeps the
@@ -629,6 +661,12 @@ class PoleStation {
this.performing = false;
this.walkPhase = 'idle'; // 'idle' | 'to-pole' | 'dancing' | 'returning'
this._phaseTarget = this.rig.position.clone();
+ // Bumped whenever a routine starts or is cut off, so a routine that was
+ // taken over mid-sequence stops at its next step and never walks the
+ // dancer off the stage under the routine that replaced it.
+ this._perfGen = 0;
+ // Standing height the tip tag floats above.
+ this.headHeight = DANCER_HEIGHT_M;
// Render-loop coupled sleepers (sleep() resolves them in tick()).
// Wall-clock setTimeout would drift if the tab is throttled or paused;
@@ -880,6 +918,7 @@ class PoleStation {
// (its isCancelled sees performing === false), and re-home the rig.
const wasPerforming = this.performing;
this.performing = false;
+ this._perfGen += 1;
this.walkPhase = 'idle';
while (this._sleepers.length) this._sleepers.pop().resolve();
this.activeTicket = null;
@@ -927,16 +966,39 @@ class PoleStation {
return new Vector3(this.layout.x, 0, this.layout.z + 0.02);
}
+ /**
+ * Put the dancer through a paid routine. `ticket.local` marks a tip this
+ * visitor paid; anything else came in over the tips stream. A routine that
+ * is already playing is cut off and replaced: the new one starts from its
+ * first step, straight at the pole if she is already on it.
+ */
async startPerformance(ticket) {
+ const takeover = this.performing;
+ const onPole = this.walkPhase === 'dancing';
+ if (takeover) {
+ // Wake the old routine's pending step so its loop sees it was replaced.
+ while (this._sleepers.length) this._sleepers.pop().resolve();
+ }
+ this._perfGen += 1;
this.activeTicket = ticket;
this.performing = true;
this.activeUntil = Date.now() + (ticket.durationSec || 12) * 1000;
- this.walkPhase = 'to-pole';
- this._phaseTarget = this.poleBasePos;
// Spotlight ramps up while the dancer walks on stage.
this._spotTarget = this.spotActiveIntensity;
this._accentTarget = 2.4;
+ updatePoleCardStatus(this.id, 'performing', { local: ticket.local === true });
+
+ if (onPole) {
+ this._arriveAtPole().catch((err) => log.warn(`[club] dancer ${this.id} takeover failed`, err));
+ return;
+ }
+ this.walkPhase = 'to-pole';
+ this._phaseTarget = this.poleBasePos;
+ if (takeover) {
+ // She was mid-walk for the old routine; the walk clip is already playing.
+ return;
+ }
// Auto-cam: if the user opted in and no manual VIP/house shot is active,
// switch to an orbiting auto-cam for the duration. We remember that the
@@ -948,9 +1010,6 @@ class PoleStation {
this._autoCammed = false;
}
- // Update pole card status.
- updatePoleCardStatus(this.id, 'performing');
-
// Crossfade idle → walking → dance once the dancer reaches the pole.
await this.anim?.crossfadeTo(WALK_CLIP, PERFORMANCE_FADE);
}
@@ -974,6 +1033,7 @@ class PoleStation {
async _arriveAtPole() {
this.walkPhase = 'dancing';
+ const gen = this._perfGen;
const requested = ticketSteps(this.activeTicket).length
? ticketSteps(this.activeTicket)
: [{ clip: this.activeTicket?.clip || FALLBACK_CLIP, durationSec: this.activeTicket?.durationSec || 12 }];
@@ -994,7 +1054,7 @@ class PoleStation {
anim: this.anim,
steps,
fadeSec: PERFORMANCE_FADE,
- isCancelled: () => !this.performing,
+ isCancelled: () => !this.performing || gen !== this._perfGen,
sleep: (ms) => this.sleep(ms),
});
} catch (err) {
@@ -1007,6 +1067,8 @@ class PoleStation {
// pole to her idle home. Cancellation is a fast-path: performing is
// already false, so _endPerformance won't toggle it back, but the
// walking + audio cleanup still runs.
+ // A routine that was taken over leaves the stage to its replacement.
+ if (gen !== this._perfGen) return;
if (this.walkPhase === 'dancing') await this._endPerformance();
}
@@ -1122,6 +1184,199 @@ function angleDelta(from, to) {
const stations = POLES.map((layout, i) => new PoleStation(i, layout));
if (typeof window !== 'undefined') window.__clubStations = stations;
+// ── Money on the stages ──────────────────────────────────────────────────
+// Every settled tip becomes $0.001 bills: thrown from the camera for a tip you
+// pay, dropped from the rig for anyone else's (violet for a platform agent).
+// Landed bills stay on the stage, so each pile is that dancer's night so far.
+const money = new ClubMoney({
+ scene,
+ capacity: MONEY_CAPACITY[activeProfile.tier] ?? MONEY_CAPACITY.medium,
+ reducedMotion: prefersReducedMotion,
+});
+
+// The floating tip tags over each dancer (built right after the pole cards, so
+// declared here where the render loop and the x402 gate can both reach it).
+let tipHud = null;
+// True once the x402 widget is live; a tag built after that point starts enabled.
+let tipButtonsLive = false;
+
+// People standing around the stages. Built once the visitor is inside (see
+// mountFloorCrowd) so its downloads never compete with the alley walk-in.
+let floorCrowd = null;
+let venueRootRef = null;
+let manifestRef = null;
+// The default viewpoint the crowd keeps clear (camera.position at boot).
+const CROWD_CLEAR_VIEW = { x: 0, z: 6 };
+
+function mountFloorCrowd() {
+ if (floorCrowd || !venueRootRef || !manifestRef) return;
+ const count = FLOOR_CROWD[activeProfile.tier] ?? FLOOR_CROWD.medium;
+ if (!count) return;
+ try {
+ floorCrowd = new ClubFloorCrowd({ renderer, scene, manifest: manifestRef, bundled: FLOOR_CROWD_RIGS });
+ floorCrowd.mount({
+ envRoot: venueRootRef,
+ // Also keep each pole's close-up (VIP) sightline clear: ClubCamera.setVip
+ // looks from yaw + PI, the side of the pole she faces.
+ stages: stations.map((st) => ({
+ id: st.id,
+ x: st.layout.x,
+ z: st.layout.z,
+ radius: STAGE_DISC_RADIUS,
+ clearDirs: [st.layout.yaw + Math.PI],
+ })),
+ camera: CROWD_CLEAR_VIEW,
+ count,
+ });
+ } catch (err) {
+ // The room still works empty; a crowd failure never blocks tipping.
+ log.warn('[club] floor crowd failed', err);
+ floorCrowd = null;
+ }
+}
+
+/**
+ * Rebuild a performance ticket from a tips-stream row. The row carries the
+ * style's choreography (api/_lib/club/tip-rows.js), so a spectator sees the
+ * same routine the payer bought.
+ */
+function ticketFromRow(row) {
+ const booked = (Date.parse(row.ends_at) - Date.parse(row.started_at)) / 1000;
+ return {
+ ticketId: row.ticket_id,
+ dancer: String(row.dancer),
+ dance: row.dance,
+ clip: row.clip,
+ label: row.label || row.dance,
+ durationSec: row.durationSec || (Number.isFinite(booked) && booked > 0 ? booked : 12),
+ sequence: row.sequence,
+ pole: row.pole === true,
+ track: row.track,
+ payer: row.payer,
+ local: false,
+ };
+}
+
+/**
+ * Put a tip that arrived over the stream onto the stage. An agent's tip drops
+ * one violet bill and nothing more: only a person's tip puts a dancer through a
+ * routine, so the platform's own traffic never passes for a crowd. A person's
+ * tip drops a clump, gets the people at that stage cheering, and she dances
+ * unless she is mid-routine for this visitor.
+ */
+function stageRemoteTip(row) {
+ const dancer = String(row?.dancer ?? '');
+ const agent = row?.agent === true;
+ bumpPoleStats(dancer, { agent });
+ const station = stations.find((st) => st.id === dancer);
+ if (!station) return;
+ if (agent) {
+ money.dropOn(station.id, 1, { agent: true });
+ return;
+ }
+ money.dropOn(station.id, BILLS_REMOTE_HUMAN);
+ floorCrowd?.cheer(station.id);
+ if (station.performing && station.activeTicket?.local) return;
+ const ticket = ticketFromRow(row);
+ station.startPerformance(ticket).catch((err) => log.warn('[club] remote performance failed', err));
+ // Only follow the music if this tab already has sound running; a spectator
+ // who never clicked anything keeps their silence.
+ const track = ticket.track || styleAudioFor(ticket.dance);
+ if (track && audio.ctx?.state === 'running') {
+ audio.fadeToStyle(track).catch((err) => log.warn('[club] fadeToStyle', err));
+ }
+}
+
+// ── Tips today, per dancer ───────────────────────────────────────────────
+// Each pole card says how many tips she took in the last 24 hours and splits
+// people from platform agents, read from /api/club/leaderboard (which flags a
+// payer in x402_ring_wallets). The stream bumps the counts live between polls.
+const POLE_STATS_URL = '/api/club/leaderboard?window=day';
+const POLE_STATS_REFRESH_MS = 60_000;
+/** @type {Map<string, {people:number, agents:number}>} */
+const poleStats = new Map();
+let poleStatsSeeded = false;
+const compactNumber = new Intl.NumberFormat(undefined, { notation: 'compact', maximumFractionDigits: 1 });
+
+function renderPoleStats(id) {
+ const el = document.getElementById(`club-pole-stats-${id}`);
+ const stat = poleStats.get(id);
+ if (!el || !stat) return;
+ const { people, agents } = stat;
+ let text;
+ let label;
+ if (!people && !agents) {
+ text = 'No tips yet today';
+ label = 'No tips in the last 24 hours';
+ } else {
+ text = `${compactNumber.format(people)} from people · ${compactNumber.format(agents)} from agents`;
+ label = `Last 24 hours: ${people} tips from people, ${agents} from platform agents`;
+ }
+ el.textContent = text;
+ el.setAttribute('aria-label', label);
+ el.classList.remove('is-loading');
+}
+
+function bumpPoleStats(id, { agent }) {
+ const stat = poleStats.get(id);
+ if (!stat) return;
+ if (agent) stat.agents += 1;
+ else stat.people += 1;
+ renderPoleStats(id);
+}
+
+async function refreshPoleStats() {
+ if (document.hidden && poleStatsSeeded) return;
+ let rows;
+ try {
+ const res = await fetch(POLE_STATS_URL, { headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ rows = (await res.json())?.rows;
+ } catch (err) {
+ log.warn('[club] tips-today fetch failed', err);
+ for (const st of stations) {
+ const el = document.getElementById(`club-pole-stats-${st.id}`);
+ if (el && !poleStats.has(st.id)) {
+ el.textContent = 'Tip count unavailable';
+ el.classList.remove('is-loading');
+ }
+ }
+ return;
+ }
+ if (!Array.isArray(rows)) return;
+ for (const row of rows) {
+ const id = String(row.dancer);
+ const total = Number(row.tip_count) || 0;
+ const agents = Math.min(total, Number(row.agent_tip_count) || 0);
+ const people = total - agents;
+ const prev = poleStats.get(id);
+ // The server caches for 15s, so never let a poll undo a tip the stream
+ // already counted.
+ poleStats.set(id, {
+ people: Math.max(people, prev?.people ?? 0),
+ agents: Math.max(agents, prev?.agents ?? 0),
+ });
+ renderPoleStats(id);
+ }
+ if (!poleStatsSeeded) {
+ poleStatsSeeded = true;
+ seedPiles();
+ }
+}
+
+// Lay each stage's pile from that dancer's real tips today: people's bills
+// first, the rest violet for agents, capped so the pile reads as a pile.
+function seedPiles() {
+ for (const st of stations) {
+ const stat = poleStats.get(st.id);
+ if (!stat) continue;
+ const total = Math.min(PILE_SEED_MAX, stat.people + stat.agents);
+ const human = Math.min(stat.people, total);
+ money.seed(st.id, human, { agent: false });
+ money.seed(st.id, total - human, { agent: true });
+ }
+}
+
// ── Disco / strobe light cycling ─────────────────────────────────────────
// A slowly rotating set of fill lights to keep the room feeling alive even
// when no dancers are out. Kept low-intensity so spotlights still dominate.
@@ -1420,8 +1675,26 @@ async function bootstrap() {
const wanted = dancerUrls[station.idx] || AVATAR_URL;
const template = avatarTemplates.get(wanted) || fallbackTemplate;
station.attachAvatar(template, animationDefs, fallbackTemplate);
+ money.setStage(station.id, {
+ x: station.layout.x,
+ z: station.layout.z,
+ topY: STAGE_TOP_Y,
+ radius: STAGE_DISC_RADIUS,
+ });
}
+ // Tips today per dancer (pole cards) and the piles they seed, then a slow
+ // poll; the stream keeps both live in between.
+ refreshPoleStats();
+ setInterval(refreshPoleStats, POLE_STATS_REFRESH_MS);
+
+ // The crowd fills the floor once the visitor is inside. A cached pass or the
+ // express entry has already dropped the door by now; otherwise wait for it.
+ venueRootRef = venueGltf.scene;
+ manifestRef = manifest;
+ if (!document.getElementById('club-door')) mountFloorCrowd();
+ else window.addEventListener('club:admitted', mountFloorCrowd, { once: true });
+
// Ambient dust particles — skip on low-perf devices.
if (activeProfile.tier !== 'low') {
const particleCount = activeProfile.tier === 'high' ? 50 : 30;
@@ -1548,6 +1821,8 @@ window.addEventListener('pagehide', () => {
});
function enableTipButtons() {
+ tipButtonsLive = true;
+ tipHud?.setEnabled(true);
for (const card of poleCardEls.values()) {
const btn = card.querySelector('.club-tip-btn');
if (!btn) continue;
@@ -1577,8 +1852,10 @@ async function tipDancer({ dancer, dance, button }) {
setStatus(`No dancer ${dancer} on stage.`, { kind: 'error' });
return;
}
- if (station.performing) {
- setStatus(`Dancer ${dancer} is already performing — tip another pole.`, { kind: 'warn' });
+ // Your own routine still playing on this pole blocks a second tip there.
+ // Anyone else's routine does not: your tip takes the pole over.
+ if (station.performing && station.activeTicket?.local) {
+ setStatus(`${dancerNameFor(station.id)} is still dancing for you. Tip another pole.`, { kind: 'warn' });
return;
}
@@ -1627,7 +1904,12 @@ async function tipDancer({ dancer, dance, button }) {
// A short triple buzz on phones the moment USDC settles — the tip lands
// in your hand the way it lands on stage.
try { navigator.vibrate?.([18, 40, 60]); } catch { /* unsupported */ }
- station.startPerformance(ticket).catch((err) => {
+ // Make it rain: the bills leave from where you're watching and land on
+ // her stage, and the people at that stage cheer.
+ money?.throwTo(station.id, camera.position, BILLS_THROWN);
+ floorCrowd?.cheer(station.id);
+ bumpPoleStats(station.id, { agent: false });
+ station.startPerformance({ ...ticket, local: true }).catch((err) => {
log.warn('[club] startPerformance failed', err);
setStatus('Performance hit a snag — tip again to retry.', { kind: 'warn' });
});
@@ -1663,7 +1945,10 @@ async function tipDancer({ dancer, dance, button }) {
}
} finally {
button?.classList.remove('is-pending');
- if (button && originalLabel) button.textContent = originalLabel;
+ // A settled tip leaves the button showing her routine for you; only a
+ // failed or cancelled one goes back to its Tip label.
+ const dancingForYou = station.performing && station.activeTicket?.local;
+ if (button && originalLabel && !dancingForYou) button.textContent = originalLabel;
}
}
@@ -1777,7 +2062,9 @@ const poleCardEls = new Map();
// loop never queries the DOM and only writes styles on a visible change.
const poleProgressEls = new Map();
-function updatePoleCardStatus(poleId, status) {
+// `local` marks a routine this visitor paid for. Only that one locks the Tip
+// button: anyone else's routine can be taken over by a tip from here.
+function updatePoleCardStatus(poleId, status, { local = false } = {}) {
const cardEl = poleCardEls.get(poleId);
if (!cardEl) return;
const dotEl = cardEl.querySelector('.club-status-dot');
@@ -1793,11 +2080,12 @@ function updatePoleCardStatus(poleId, status) {
labelEl.textContent = status === 'performing' ? 'Performing' : status === 'backstage' ? 'Backstage' : 'Idle';
}
if (btnEl) {
- if (status === 'performing') {
+ if (status === 'performing' && local) {
btnEl.disabled = true;
- btnEl.textContent = 'Performing...';
+ btnEl.textContent = 'Dancing for you';
} else {
- btnEl.disabled = false;
+ // Never enable ahead of the payment widget.
+ btnEl.disabled = !tipButtonsLive;
btnEl.textContent = 'Tip $0.001';
}
}
@@ -2135,7 +2423,7 @@ function renderPoles() {
<div class="club-pole-status" aria-label="Status: Idle">
<span class="club-status-dot is-idle" aria-hidden="true"></span>
<span class="club-pole-status-label">Idle</span>
- <span class="club-pole-stats" id="club-pole-stats-${pole.id}" aria-label="Tips today: 0">0 tips today</span>
+ <span class="club-pole-stats is-loading" id="club-pole-stats-${pole.id}" aria-label="Loading tips today">Counting tonight's tips…</span>
</div>
<div class="club-pole-progress" style="display:none" role="progressbar" aria-label="Performance progress" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
<div class="club-pole-progress-bar" style="width:0%"></div>
@@ -2443,16 +2731,57 @@ function animate(frameNow) {
// Camera state machine — orbit / VIP / house / auto.
clubCam.tick(dt);
+ // Bills in the air, and the people around the stages. The crowd is not
+ // drawn while the alley still covers the room, so it is not stepped either.
+ money.update(dt);
+ if (!covered) floorCrowd?.update(dt);
+ tipHud?.setHidden(covered || !stageWarmed);
+
// Audio-reactive bloom — pulse intensity with the beat (skip under reduced motion).
if (!prefersReducedMotion) bloomEffect.intensity = 1.0 + peak * 1.5;
if (covered) return;
composer.render(dt);
stageWarmed = true;
+ // Pin the tip tags after the render, when the camera matrices are this frame's.
+ tipHud?.update();
}
renderPoles();
+// Tip from inside the room: a tag over each dancer, and clicking her (or her
+// pole) opens the style picker on it. The sidebar select stays the one record
+// of which style each pole will dance, so the two surfaces always agree.
+{
+ const layer = document.getElementById('club-tags');
+ const selectFor = (id) => polesPanel?.querySelector(`.club-pole-select[data-dancer="${id}"]`);
+ if (layer && canvas) {
+ tipHud = new ClubTipHud({
+ layer,
+ canvas,
+ camera,
+ dances: DANCES,
+ dancers: stations.map((st) => ({
+ id: st.id,
+ name: dancerNameFor(st.id),
+ accent: `#${POLE_COLORS[st.idx % POLE_COLORS.length].toString(16).padStart(6, '0')}`,
+ station: st,
+ })),
+ getStyle: (id) => selectFor(id)?.value || DANCES[0].key,
+ setStyle: (id, key) => {
+ const sel = selectFor(id);
+ if (sel) sel.value = key;
+ },
+ onTip: (id, key, button) => tipDancer({ dancer: id, dance: key, button }),
+ });
+ tipHud.setEnabled(tipButtonsLive);
+ polesPanel?.addEventListener('change', (e) => {
+ const sel = e.target.closest?.('.club-pole-select');
+ if (sel) tipHud.refreshStyle(sel.dataset.dancer);
+ });
+ }
+}
+
// Bind the auto-follow checkbox to persisted state.
{
const cb = document.getElementById('club-auto-follow');
diff --git a/tests/api/club-tips.test.js b/tests/api/club-tips.test.js
index 33e24edda..60e982375 100644
--- a/tests/api/club-tips.test.js
+++ b/tests/api/club-tips.test.js
@@ -95,17 +95,49 @@ describe('GET /api/club/tips', () => {
expect(status).toBe(200);
// Dates round-trip through JSON.stringify as ISO strings; rebuild the
// expectation accordingly so the deep-equal compares apples to apples.
+ // Each row also carries `agent` (payer is a platform wallet) and the
+ // style's choreography, so a spectator replays the routine that was bought.
expect(body).toEqual({
tips: [{
...sampleRow,
started_at: sampleRow.started_at.toISOString(),
ends_at: sampleRow.ends_at.toISOString(),
created_at: sampleRow.created_at.toISOString(),
+ agent: false,
+ durationSec: 14,
+ track: 'rumba',
}],
});
expect(sqlState.calls).toHaveLength(1);
});
+ it('flags a platform-wallet payer as an agent and drops the raw column', async () => {
+ sqlState.queue.push([{ ...sampleRow, is_agent: true }]);
+ const { body } = await invoke();
+ expect(body.tips[0].agent).toBe(true);
+ expect(body.tips[0]).not.toHaveProperty('is_agent');
+ expect(sqlState.calls[0].query).toContain('x402_ring_wallets');
+ });
+
+ it('attaches the clip sequence and pole flag a routine was sold with', async () => {
+ sqlState.queue.push([
+ { ...sampleRow, ticket_id: 't-2', dance: 'combo', clip: 'rumba', label: 'Full Combo' },
+ { ...sampleRow, ticket_id: 't-3', dance: 'twerk', clip: 'twerk', label: 'Pole Twerk' },
+ ]);
+ const { body } = await invoke();
+ const [combo, twerk] = body.tips;
+ expect(combo.sequence.map((s) => s.clip)).toEqual(['rumba', 'capoeira', 'thriller', 'silly', 'dance']);
+ expect(combo.durationSec).toBe(18);
+ expect(twerk.pole).toBe(true);
+ });
+
+ it('keeps a row whose style is no longer sold as-is', async () => {
+ sqlState.queue.push([{ ...sampleRow, dance: 'retired-style' }]);
+ const { body } = await invoke();
+ expect(body.tips[0]).not.toHaveProperty('durationSec');
+ expect(body.tips[0].clip).toBe('rumba');
+ });
+
it('defaults to limit=20 when not provided', async () => {
sqlState.queue.push([]);
await invoke();
diff --git a/tests/club-stage-life.test.js b/tests/club-stage-life.test.js
new file mode 100644
index 000000000..66a00c029
--- /dev/null
+++ b/tests/club-stage-life.test.js
@@ -0,0 +1,171 @@
+// The /club stage: money on the piles, the floor crowd's layout, and picking a
+// dancer by clicking her in the scene. Pure pieces only, no renderer.
+
+import { describe, it, expect } from 'vitest';
+import { Scene, Texture, Ray, Vector3 } from 'three';
+
+import { ClubMoney, ballisticVelocity, pointOnStage } from '../src/club-money.js';
+import { planFloorCrowd } from '../src/club-floor-crowd.js';
+import { rayToColumn } from '../src/club-tip-hud.js';
+
+function seeded(seed = 7) {
+ let s = seed >>> 0;
+ return () => {
+ s = (s * 1664525 + 1013904223) >>> 0;
+ return s / 2 ** 32;
+ };
+}
+
+const STAGE = { x: 2, z: -1, topY: 0.18, radius: 1.1 };
+
+describe('club money', () => {
+ it('throw arc lands on the aim point after the flight time', () => {
+ const from = { x: 0, y: 1.8, z: 6 };
+ const to = { x: 2, y: 1.2, z: -1 };
+ const t = 0.9;
+ const v = ballisticVelocity(from, to, t);
+ const y = from.y + v.y * t + 0.5 * -9.8 * t * t;
+ expect(from.x + v.x * t).toBeCloseTo(to.x, 6);
+ expect(from.z + v.z * t).toBeCloseTo(to.z, 6);
+ expect(y).toBeCloseTo(to.y, 6);
+ });
+
+ it('scatters landing points on the disc, clear of the pole', () => {
+ const rng = seeded(3);
+ for (let i = 0; i < 500; i++) {
+ const p = pointOnStage(STAGE, rng);
+ const r = Math.hypot(p.x - STAGE.x, p.z - STAGE.z);
+ expect(r).toBeGreaterThanOrEqual(0.16 - 1e-9);
+ expect(r).toBeLessThanOrEqual(STAGE.radius - 0.12 + 1e-9);
+ }
+ });
+
+ function makeMoney(capacity, opts = {}) {
+ const money = new ClubMoney({ scene: new Scene(), capacity, rng: seeded(11), texture: new Texture(), ...opts });
+ money.setStage('1', STAGE);
+ money.setStage('2', { ...STAGE, x: -2 });
+ return money;
+ }
+
+ it('seeds a pile that rests on the stage top', () => {
+ const money = makeMoney(50);
+ money.seed('1', 12);
+ expect(money.pileSize('1')).toBe(12);
+ for (let i = 0; i < 12; i++) {
+ expect(money.pos[i * 3 + 1]).toBeGreaterThan(STAGE.topY);
+ expect(money.pos[i * 3 + 1]).toBeLessThan(STAGE.topY + 0.05);
+ }
+ });
+
+ it('recycles the oldest resting bill once the budget is full', () => {
+ const money = makeMoney(10);
+ money.seed('1', 10);
+ money.seed('2', 4);
+ expect(money.pileSize('1')).toBe(6);
+ expect(money.pileSize('2')).toBe(4);
+ });
+
+ it('a dropped bill flutters down and joins the pile', () => {
+ const money = makeMoney(20);
+ money.dropOn('1', 3, { agent: true });
+ expect(money.airborne).toBe(3);
+ for (let f = 0; f < 60 * 12 && money.airborne; f++) money.update(1 / 60);
+ expect(money.airborne).toBe(0);
+ expect(money.pileSize('1') + money.pileSize('2')).toBeLessThanOrEqual(3);
+ // Stray bills that drift past the rim lie on the floor; most land on the disc.
+ expect(money.pileSize('1')).toBeGreaterThanOrEqual(2);
+ });
+
+ it('a thrown clump crosses the room and comes to rest', () => {
+ const money = makeMoney(20);
+ money.throwTo('1', { x: 0, y: 1.8, z: 6 }, 8);
+ for (let f = 0; f < 60 * 15 && money.airborne; f++) money.update(1 / 60);
+ expect(money.airborne).toBe(0);
+ expect(money.pileSize('1')).toBeGreaterThanOrEqual(6);
+ });
+
+ it('lands bills straight on the pile under reduced motion', () => {
+ const money = makeMoney(20, { reducedMotion: true });
+ money.throwTo('1', { x: 0, y: 1.8, z: 6 }, 5);
+ expect(money.airborne).toBe(0);
+ expect(money.pileSize('1')).toBe(5);
+ });
+});
+
+describe('floor crowd plan', () => {
+ const stages = [
+ { id: '1', x: -3.47, z: -0.97, radius: 1.1 },
+ { id: '2', x: 0, z: -2.8, radius: 1.1 },
+ { id: '3', x: 3.47, z: -0.97, radius: 1.1 },
+ ];
+ const camera = { x: 0, z: 6 };
+
+ it('places people off the stages, spaced, and facing the pole', () => {
+ const slots = planFloorCrowd({ stages, camera, count: 12, rng: seeded(5) });
+ expect(slots.length).toBeGreaterThan(8);
+ expect(slots.length).toBeLessThanOrEqual(12);
+ for (const s of slots) {
+ for (const st of stages) {
+ expect(Math.hypot(s.x - st.x, s.z - st.z)).toBeGreaterThan(st.radius + 0.6);
+ }
+ const own = stages.find((st) => st.id === s.stageId);
+ const facing = Math.atan2(own.x - s.x, own.z - s.z);
+ expect(Math.abs(Math.atan2(Math.sin(s.yaw - facing), Math.cos(s.yaw - facing)))).toBeLessThan(0.2);
+ }
+ for (let i = 0; i < slots.length; i++) {
+ for (let j = i + 1; j < slots.length; j++) {
+ expect(Math.hypot(slots[i].x - slots[j].x, slots[i].z - slots[j].z)).toBeGreaterThanOrEqual(0.78 - 1e-9);
+ }
+ }
+ });
+
+ it('keeps the wedge between each stage and the camera clear', () => {
+ const slots = planFloorCrowd({ stages, camera, count: 12, rng: seeded(9) });
+ for (const s of slots) {
+ const st = stages.find((x) => x.id === s.stageId);
+ const toCam = Math.atan2(camera.x - st.x, camera.z - st.z);
+ const toSlot = Math.atan2(s.x - st.x, s.z - st.z);
+ const diff = Math.abs(Math.atan2(Math.sin(toSlot - toCam), Math.cos(toSlot - toCam)));
+ expect(diff).toBeGreaterThanOrEqual(0.95);
+ }
+ });
+
+ it('keeps a stage\'s declared close-up sightline clear too', () => {
+ const vip = stages.map((st) => ({ ...st, clearDirs: [Math.PI / 2] }));
+ const slots = planFloorCrowd({ stages: vip, camera, count: 12, rng: seeded(21) });
+ expect(slots.length).toBeGreaterThan(0);
+ for (const s of slots) {
+ const st = vip.find((x) => x.id === s.stageId);
+ const toSlot = Math.atan2(s.x - st.x, s.z - st.z);
+ const diff = Math.abs(Math.atan2(Math.sin(toSlot - Math.PI / 2), Math.cos(toSlot - Math.PI / 2)));
+ expect(diff).toBeGreaterThanOrEqual(0.95);
+ }
+ });
+
+ it('returns nothing for an empty room or zero budget', () => {
+ expect(planFloorCrowd({ stages: [], camera, count: 10 })).toEqual([]);
+ expect(planFloorCrowd({ stages, camera, count: 0 })).toEqual([]);
+ });
+});
+
+describe('picking a dancer in the scene', () => {
+ const col = { x: 0, z: -3, y0: 0, y1: 2.4 };
+
+ it('a ray through the dancer hits her column', () => {
+ const ray = new Ray(new Vector3(0, 1.8, 6), new Vector3(0, 1.0 - 1.8, -9).normalize());
+ const hit = rayToColumn(ray, col);
+ expect(hit.dist).toBeLessThan(0.05);
+ expect(hit.t).toBeGreaterThan(8);
+ });
+
+ it('a ray well to the side misses', () => {
+ const ray = new Ray(new Vector3(0, 1.8, 6), new Vector3(2, -0.2, -9).normalize());
+ expect(rayToColumn(ray, col).dist).toBeGreaterThan(0.62);
+ });
+
+ it('a ray passing over her head measures to the top of the column', () => {
+ const ray = new Ray(new Vector3(0, 4, 6), new Vector3(0, 0, -1));
+ const hit = rayToColumn(ray, col);
+ expect(hit.dist).toBeCloseTo(4 - 2.4, 5);
+ });
+});