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: add Coin Wars clash multiplayer, body mocap, and UFO play page

nirholas2c6651d3b2f0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 93c0aa7a2..6ab5576b2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-19
- **Agent Studio** (`/agent-studio`) — Author your agent's brain, memory, body, money, and skills in one place, with a live 3D avatar that updates everywhere as you edit.
+- **Coin Clash** (`/clash`) — Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.
+- **Flappin UFO — dodge asteroids for $THREE** (`/play/ufo`) — Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.
- **Agent Studio — one place to build your whole agent, with a live avatar** — Agent Studio is the new home for authoring everything about your AI agent — its brain, memory, 3D body, money, and skills — side by side with a live avatar that updates the instant you make a change, no save button and no refresh. The same living avatar can now appear anywhere on the platform as a presence companion, reacting with real emotion to what's happening: it celebrates a filled trade, looks concerned when a position drops, and stays in sync with whatever you edit in the Studio. This release ships the Studio shell and the shared foundation the rest of the experience builds on. (`/agent-studio`) `[feature]`
- **Agent wallet's full money loop is now verified end-to-end on devnet** — A re-runnable harness now exercises the entire agent-wallet lifecycle in one pass — create a wallet, fund it, trade and snipe pump.fun tokens, pay an x402 service, exit a graduated position, and withdraw — against real Solana devnet state. It runs simulate-first and reports each step as passed or honestly blocked on funding/credentials, never a fake result, so regressions in the seams between deposit, trading, sniping, payments, and withdrawal surface before they reach holders. The agent wallet hub's Snipe tab now opens the live Sniper dashboard directly instead of a placeholder. (`/agent-wallet`) `[infra]`
- **Align a whole room of agents in one gesture** — When you place several agents around a room, their spacing is already exact for everyone — but the whole cluster can sit a few metres off where it really is, because phone GPS only knows the spot to within several metres. Now you can fix that in one move: open any of your room agents and tap “Align this room,” then drag to slide the entire group onto its true spot and twist with two fingers to rotate it — every agent moves together, keeping its layout intact, instead of nudging them one at a time. A live readout shows the move in honest metres and degrees, and the room is labelled with how tightly it's anchored so you know when it's worth aligning. Only the room's owner can move it. And if you arrive at a room someone placed without a compass that looks turned the wrong way, a one-tap “Align to your view” straightens it out for you. (`/irl`) `[improvement]`
@@ -20,6 +22,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Every IRL moment now has a designed, honest state** — IRL asks for the three most sensitive permissions a web app can — camera, motion, and location — and we made every moment around them feel deliberate instead of uncertain. While your phone is still finding your GPS fix, the top bar shows a clear "Finding your location…" shimmer so the wait never looks like an empty, nobody-here screen. If discovery ever has to slow down to catch its breath, you get a calm "catching up…" note that quietly recovers on its own — never a scary error. The live-presence indicator stays honest too: when it drops, nearby discovery keeps working and nothing implies otherwise. Every control is now reachable by keyboard with a visible focus ring, screen readers announce each state change once, and all of it respects reduced-motion settings. (`/irl`) `[improvement]`
- **Every page now shares with its own social card** — Share any three.ws page on X, Discord, Slack, iMessage, or LinkedIn and the link now previews with a branded card built for that exact page — its title, its one-line description, and a colour that matches the section it belongs to — instead of one generic image for the whole site. The cards render as real PNGs so they show up everywhere (not just the apps that handle SVG), and they're generated on the fly from the same page catalog that feeds the sitemap, so the preview always matches what's actually on the page. We also tightened the behind-the-scenes SEO on every page: cleaner canonical links, richer structured data with breadcrumbs, and crawler hints that let search engines show large image previews. `[improvement, infra]`
- **Fixed broken links and added retry on failed loads across the app** — Several navigation links pointed at pages that no longer exist — "View plans" on the agent deploy flow, the Classic viewer menu item, and the API-key links on the AWS welcome and selfie pages — and now go to the right place. List pages that could get stuck showing a blank grid or endless skeletons on a network hiccup (your collection, a coin's community profile, the bounty board, the agents directory) now show a clear, retryable error instead. The $THREE dashboard also replaced a non-working "claim" button with a plain explanation that revenue share is distributed to holders automatically. `[fix, improvement]`
+- **Flappin UFO — a $THREE arcade game is live** — You can now play Flappin UFO on three.ws at /play/ufo — a Flappy Bird-style space game where you pilot a UFO through asteroid fields. Connect your Solana wallet, copy your address as your in-game name, and submit your score to the global leaderboard. The leaderboard panel refreshes live every 15 seconds and highlights your wallet entry so you can see exactly where you rank among $THREE holders. (`/play/ufo`) `[feature]`
- **Freeze your agent wallet in one tap — plus hardened custody security** — Your agent's wallet now has a freeze switch. Open the wallet's Limits & Safety panel and tap Freeze to instantly pause every kind of automatic spending — trades, snipes and payments all stop at once — while you stay free to withdraw your funds out at any time; a freeze locks down the agent without ever trapping your money. Withdrawals also got safer: before you confirm, you'll see a clear reminder that crypto transfers are final, and if you've set a withdraw allowlist the screen now tells you whether the address you're sending to is on it. Under the hood we tightened wallet security across the board — every money-moving request is now protected against cross-site request forgery, the keys that sign for your wallet are encrypted at rest with a dedicated key separated from the login system, and a class of launch keys that were previously stored in plain text are now encrypted too. `[feature, security]`
- **Fund any agent wallet by scanning a QR or copying the address — with live confirmation** — The agent wallet's Deposit tab is now a complete, public funding panel: a crisp QR code (generated on-device, no third-party service) that your phone wallet can scan, a one-tap copyable Solana address, an optional preset amount, and a Solana deep-link that opens Phantom, Solflare or Backpack on mobile. The panel watches the agent's real on-chain balance and confirms the moment your SOL lands — "◎0.5 SOL received" — instead of leaving you guessing. Anyone can fund an agent, not just its owner, and the new "Fund agent wallet" button on the create-agent success screen leads new users straight into it. `[feature]`
- **Funds and payments hardened: wallet-key isolation, spend-cap races, recipient checks** — Following the security audit, we strengthened everything that touches money. Custodial agent-wallet private keys now encrypt with a dedicated key — separate from the session secret — and a unique salt per wallet, so the secret guarding your funds no longer shares fate with anything else (existing wallets keep working; they re-key on next use). Per-agent daily spend limits, x402 payment de-duplication, and on-chain permission caps are now enforced atomically, closing races where a burst of concurrent requests could slip past a budget or run paid work twice for one payment. Pay-by-name sends re-check that the name still resolves to the exact address you approved before the agent signs, and reject look-alike or invalid targets; withdrawals now only ever pay out to a wallet you've already saved. We also removed a stored cross-site-scripting vector in uploaded 3D-model metadata and the admin panel, added clickjacking and permissions-policy protections site-wide, and moved IPFS pinning fully server-side so no upload credential ever ships to the browser. No action needed on your end. `[security]`
diff --git a/api/_lib/migrations/20260619160000_coin_wars.sql b/api/_lib/migrations/20260619160000_coin_wars.sql
new file mode 100644
index 000000000..db618fb27
--- /dev/null
+++ b/api/_lib/migrations/20260619160000_coin_wars.sql
@@ -0,0 +1,54 @@
+-- Migration: Coin Wars — the battle ledger behind community-vs-community clashes.
+-- Each row is one finished clash between two coin communities, written by the
+-- multiplayer game server (ClashRoom) over an HMAC-signed POST to /api/wars?action=
+-- report. The /wars War Standings are RECOMPUTED from this ledger with the pure Elo
+-- league math in multiplayer/src/war-standings.js, so the ledger is the single source
+-- of truth and ratings can be re-derived deterministically from it at any time.
+--
+-- We store both the indexable outcome columns (for the recent-battles feed and
+-- head-to-head queries) and the per-faction kill/death tallies the standings fold
+-- needs, so a standings rebuild never has to reach back into game-server memory.
+
+begin;
+
+create table if not exists clash_battles (
+ id uuid primary key default gen_random_uuid(),
+ -- The arena instance this battle was fought in (network + the two mints). Unique
+ -- so a re-reported result (game server retry) updates rather than double-counts.
+ match_key text not null,
+ network text not null default 'mainnet',
+ -- Outcome. winner_mint is NULL for a draw; reason is how it ended
+ -- (score_cap | timeout | sudden_death | forfeit).
+ winner_mint text,
+ reason text not null default 'score_cap',
+ duration_ms integer not null default 0,
+ -- Faction A.
+ a_mint text not null,
+ a_name text not null default '',
+ a_symbol text not null default '',
+ a_score integer not null default 0,
+ a_kills integer not null default 0,
+ a_deaths integer not null default 0,
+ -- Faction B.
+ b_mint text not null,
+ b_name text not null default '',
+ b_symbol text not null default '',
+ b_score integer not null default 0,
+ b_kills integer not null default 0,
+ b_deaths integer not null default 0,
+ -- Match MVP { id, faction, kills, deaths, damage } as reported by the engine.
+ mvp jsonb,
+ ended_at timestamptz not null default now(),
+ created_at timestamptz not null default now(),
+ constraint clash_battles_distinct_factions check (a_mint <> b_mint)
+);
+
+-- One canonical row per arena instance — a retry of the same battle's report upserts.
+create unique index if not exists clash_battles_match_key_uniq on clash_battles (match_key);
+-- The recent-battles feed reads newest-first per network.
+create index if not exists clash_battles_network_ended_idx on clash_battles (network, ended_at desc);
+-- Per-community history (a coin's battle log + head-to-head) hits either faction column.
+create index if not exists clash_battles_a_mint_idx on clash_battles (a_mint, ended_at desc);
+create index if not exists clash_battles_b_mint_idx on clash_battles (b_mint, ended_at desc);
+
+commit;
diff --git a/api/config.js b/api/config.js
index 04c6f592a..b6f203f4a 100644
--- a/api/config.js
+++ b/api/config.js
@@ -20,6 +20,12 @@ export default wrap(async (req, res) => {
const videoAvatarEnabled = !!(process.env.LONGCAT_WORKER_URL || '').trim();
+ // Live webcam body motion capture (Pose Landmarker → humanoid bones). Ships
+ // dark: the capture module and solver are bundled but no surface wires them in
+ // until this flag is flipped on via env, so it can be validated in production
+ // before being bridged into /mocap-studio.
+ const liveBodyMocapEnabled = /^(1|true|on)$/i.test((process.env.LIVE_BODY_MOCAP || '').trim());
+
// Enterprise SAML SSO — true when an IdP is wired (explicit cert + SSO URL,
// or a metadata URL to fetch them from). Drives the SSO button on /login.
// Cheap env-only check so this hot endpoint doesn't pull in the SAML lib.
@@ -49,6 +55,9 @@ export default wrap(async (req, res) => {
// /create/video uses the LongCat GPU worker on Cloud Run; only
// available once LONGCAT_WORKER_URL is set in Vercel env.
videoAvatar: videoAvatarEnabled,
+ // Live webcam body capture. Off until LIVE_BODY_MOCAP is set; the
+ // frontend gates the "go live (body)" affordance on this.
+ liveBodyMocap: liveBodyMocapEnabled,
},
});
});
diff --git a/data/changelog.json b/data/changelog.json
index dd52839d3..d1e2acbdf 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-19",
+ "title": "Flappin UFO — a $THREE arcade game is live",
+ "summary": "You can now play Flappin UFO on three.ws at /play/ufo — a Flappy Bird-style space game where you pilot a UFO through asteroid fields. Connect your Solana wallet, copy your address as your in-game name, and submit your score to the global leaderboard. The leaderboard panel refreshes live every 15 seconds and highlights your wallet entry so you can see exactly where you rank among $THREE holders.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/play/ufo"
+ },
{
"date": "2026-06-19",
"title": "Homepage “Create” card now shows its 3D agent",
diff --git a/data/pages.json b/data/pages.json
index 64d2e43f5..81aa2b065 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -497,6 +497,14 @@
"changefreq": "daily",
"added": "2026-06-12"
},
+ {
+ "path": "/clash",
+ "title": "Coin Clash",
+ "description": "Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.",
+ "priority": 0.7,
+ "changefreq": "daily",
+ "added": "2026-06-19"
+ },
{
"path": "/leaderboard",
"title": "Trader Leaderboard",
@@ -553,6 +561,14 @@
"changefreq": "daily",
"added": "2026-06-15"
},
+ {
+ "path": "/play/ufo",
+ "title": "Flappin UFO \u2014 dodge asteroids for $THREE",
+ "description": "Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.",
+ "priority": 0.7,
+ "changefreq": "weekly",
+ "added": "2026-06-19"
+ },
{
"path": "/smart-money",
"title": "Smart Money Radar \u2014 follow the wallets that win on pump.fun",
diff --git a/multiplayer/src/clash-schemas.js b/multiplayer/src/clash-schemas.js
new file mode 100644
index 000000000..ce9d45ce4
--- /dev/null
+++ b/multiplayer/src/clash-schemas.js
@@ -0,0 +1,107 @@
+// Wire schema for the Coin Wars clash arena (ClashRoom). Kept separate from the
+// shared WalkState in schemas.js: that schema is append-only and frozen by every
+// deployed walk/play client, whereas the clash arena is its own room with its own
+// clients, so it gets its own clean, minimal schema. Only what peers must SEE rides
+// here — a fighter's exact HP stays private on the engine (see clash.js), exactly as
+// WalkRoom keeps vitals off the wire.
+
+import { Schema, MapSchema, defineTypes } from '@colyseus/schema';
+
+// One fighter in the arena. Mirrors the relevant slice of the walk Player (so the
+// same avatar/animation client renders them) plus the two clash-only states peers
+// must see: which community they fight for, whether they're downed, and their score.
+export class ClashFighter extends Schema {
+ constructor() {
+ super();
+ this.id = '';
+ this.name = 'guest';
+ this.color = 0xffffff;
+ this.x = 0;
+ this.y = 0;
+ this.z = 0;
+ this.yaw = 0;
+ this.motion = 'idle'; // 'idle' | 'walk' | 'run'
+ this.emote = '';
+ this.emoteTs = 0;
+ this.avatar = ''; // GLB/VRM URL so peers render the real avatar
+ this.agent = ''; // optional three.ws agent id (cross-links)
+ this.account = ''; // verified wallet bound in onAuth
+ this.faction = ''; // coin mint this fighter battles for (which team)
+ this.dead = false; // downed → peers render the ragdoll + skip as a target
+ this.kills = 0; // this fighter's confirmed kills (scoreboard)
+ this.deaths = 0;
+ this.cosmetics = ''; // equipped loadout wire string (same format as walk)
+ this.tsServer = 0; // last authoritative update (epoch ms) for interpolation
+ }
+}
+defineTypes(ClashFighter, {
+ id: 'string',
+ name: 'string',
+ color: 'uint32',
+ x: 'float32',
+ y: 'float32',
+ z: 'float32',
+ yaw: 'float32',
+ motion: 'string',
+ emote: 'string',
+ emoteTs: 'float64',
+ avatar: 'string',
+ agent: 'string',
+ account: 'string',
+ faction: 'string',
+ dead: 'boolean',
+ kills: 'uint16',
+ deaths: 'uint16',
+ cosmetics: 'string',
+ tsServer: 'float64',
+});
+
+// The arena state every client renders. The two factions are flat fields (always
+// exactly two communities) rather than a collection, so the HUD reads scoreA/scoreB
+// directly. `phase` and the clock mirror the authoritative ClashMatch engine.
+export class ClashState extends Schema {
+ constructor() {
+ super();
+ this.fighters = new MapSchema();
+ // Match identity + lifecycle (mirrored from the ClashMatch engine each tick).
+ this.phase = 'lobby'; // lobby | countdown | live | sudden_death | ended
+ this.scoreCap = 0;
+ this.startedAt = 0; // epoch ms LIVE began
+ this.endsAt = 0; // epoch ms round clock expires
+ this.countdownEndsAt = 0; // epoch ms countdown flips to live
+ this.winner = ''; // mint of the winning community, or 'draw' (set at end)
+ this.mvpId = ''; // session id of the match MVP (set at end)
+ // Faction A.
+ this.aMint = '';
+ this.aName = '';
+ this.aSymbol = '';
+ this.aImage = '';
+ this.aScore = 0;
+ // Faction B.
+ this.bMint = '';
+ this.bName = '';
+ this.bSymbol = '';
+ this.bImage = '';
+ this.bScore = 0;
+ }
+}
+defineTypes(ClashState, {
+ fighters: { map: ClashFighter },
+ phase: 'string',
+ scoreCap: 'uint16',
+ startedAt: 'float64',
+ endsAt: 'float64',
+ countdownEndsAt: 'float64',
+ winner: 'string',
+ mvpId: 'string',
+ aMint: 'string',
+ aName: 'string',
+ aSymbol: 'string',
+ aImage: 'string',
+ aScore: 'uint16',
+ bMint: 'string',
+ bName: 'string',
+ bSymbol: 'string',
+ bImage: 'string',
+ bScore: 'uint16',
+});
diff --git a/multiplayer/src/clash.js b/multiplayer/src/clash.js
new file mode 100644
index 000000000..ab8d1af0d
--- /dev/null
+++ b/multiplayer/src/clash.js
@@ -0,0 +1,364 @@
+// Clash — the pure, server-authoritative core of Coin Wars (community-vs-community
+// battles). Where combat.js owns a single swing's geometry and damage, clash.js
+// owns the *match*: two coin communities as opposing factions, the kill score that
+// decides which community wins, respawns, the round clock, sudden death, and the
+// final result a war league is built from.
+//
+// Like combat.js this file touches NOTHING external — no network, no @colyseus
+// schema, no world geometry. The ClashRoom feeds it validated hits (it already
+// holds authoritative positions, so it runs combat.selectTarget itself) and ticks
+// it with a clock; clash.js resolves damage through combat.js, keeps score, and
+// reports phase transitions. Keeping it dependency-light (only combat.js, which is
+// itself dependency-free) is deliberate: the whole match lifecycle is unit-testable
+// in isolation, and the box's corrupted @colyseus/schema never enters the picture.
+//
+// A match is always exactly TWO factions, each a coin community keyed by its mint.
+// Players fight FOR the coin they joined under; same-faction hits never land
+// (friendly fire is off — you don't grief your own community). First faction to the
+// score cap wins; if the clock runs out level, the match goes to sudden death where
+// the next kill takes it.
+
+import { rollDamage, applyDamage } from './combat.js';
+
+// Match phases. A match walks lobby → countdown → live → (sudden_death) → ended.
+// 'lobby' waits for both communities to field at least MIN_PER_TEAM fighters;
+// 'countdown' is the brief lock-in before the gates open; 'live' is the fight;
+// 'sudden_death' is overtime on a level clock; 'ended' is terminal.
+export const ClashPhase = Object.freeze({
+ LOBBY: 'lobby',
+ COUNTDOWN: 'countdown',
+ LIVE: 'live',
+ SUDDEN_DEATH: 'sudden_death',
+ ENDED: 'ended',
+});
+
+// Tunables. These are the defaults a ClashRoom seeds a match with; every one can be
+// overridden per match (e.g. a quick 1-min skirmish vs a 5-min war) via the config.
+export const CLASH_DEFAULTS = Object.freeze({
+ scoreCap: 25, // kills for a community to win outright
+ durationMs: 5 * 60_000, // round clock; level score at expiry → sudden death
+ countdownMs: 5_000, // lock-in before the gates open
+ respawnMs: 6_000, // downed fighter returns after this long
+ minPerTeam: 1, // fighters each side needs before a match can start
+ maxPerTeam: 16, // roster cap per community (mirrors the room client cap)
+ maxHp: 100, // every fighter spawns at this
+ startArmor: 0, // armor is earned from loadout/cosmetics, not granted
+});
+
+// A single fighter in the match. Vitals live HERE (not on the wire-visible schema)
+// for the same reason combat.js keeps them private: peers see `dead` and the
+// scoreboard, never your exact HP. `combatLevel` gently scales the damage you deal
+// (see combat.rollDamage). Plain mutable object — the engine owns it.
+function makeFighter(id, faction, combatLevel, maxHp, startArmor) {
+ return {
+ id,
+ faction, // coin mint this fighter battles for
+ combatLevel: Math.max(1, combatLevel | 0),
+ hp: maxHp,
+ maxHp,
+ armor: Math.max(0, startArmor | 0),
+ dead: false,
+ respawnAt: 0, // epoch ms the engine will revive them (0 = alive)
+ kills: 0,
+ deaths: 0,
+ damage: 0, // total damage dealt to enemy fighters (MVP tiebreak)
+ joinedAt: 0,
+ };
+}
+
+export class ClashMatch {
+ // `config` overrides any CLASH_DEFAULTS. `factions` is the two competing coins:
+ // [{ mint, name, symbol, image }, { mint, ... }]. Both are required up front so
+ // the match always knows the two sides it is scoring, even before either fields
+ // a fighter (the lobby renders the matchup card from these).
+ constructor({ factions, config = {} } = {}) {
+ if (!Array.isArray(factions) || factions.length !== 2) {
+ throw new Error('ClashMatch requires exactly two factions');
+ }
+ const [a, b] = factions;
+ if (!a?.mint || !b?.mint || a.mint === b.mint) {
+ throw new Error('ClashMatch factions must be two distinct coin mints');
+ }
+ this.cfg = { ...CLASH_DEFAULTS, ...config };
+ // Faction state keyed by mint: identity (for the scoreboard/result) + live score.
+ this.factions = new Map();
+ for (const f of factions) {
+ this.factions.set(f.mint, {
+ mint: f.mint,
+ name: f.name || f.symbol || 'Community',
+ symbol: f.symbol || '',
+ image: f.image || '',
+ score: 0,
+ });
+ }
+ this.fighters = new Map(); // id → fighter
+ this.phase = ClashPhase.LOBBY;
+ this.startedAt = 0; // epoch ms the LIVE phase began (0 until started)
+ this.endsAt = 0; // epoch ms the round clock expires (0 until live)
+ this.countdownEndsAt = 0; // epoch ms COUNTDOWN flips to LIVE
+ this.endedAt = 0; // epoch ms the match ended
+ this.winner = null; // mint of the winning faction, or 'draw'
+ this.endReason = null; // 'score_cap' | 'timeout' | 'sudden_death' | 'forfeit'
+ }
+
+ // --- roster -------------------------------------------------------------
+
+ // Seat a fighter on a faction. Rejected (returns null) if the mint isn't one of
+ // the two competitors, the side is full, or they're already seated. The room
+ // gates *eligibility* (you hold the coin) before calling this; the engine only
+ // owns capacity + identity so the rules stay testable.
+ addFighter(id, factionMint, { combatLevel = 1, now = 0 } = {}) {
+ if (!id || !this.factions.has(factionMint)) return null;
+ if (this.fighters.has(id)) return this.fighters.get(id);
+ const onTeam = this.countFaction(factionMint);
+ if (onTeam >= this.cfg.maxPerTeam) return null;
+ const f = makeFighter(id, factionMint, combatLevel, this.cfg.maxHp, this.cfg.startArmor);
+ f.joinedAt = now;
+ this.fighters.set(id, f);
+ return f;
+ }
+
+ removeFighter(id) {
+ return this.fighters.delete(id);
+ }
+
+ countFaction(mint) {
+ let n = 0;
+ for (const f of this.fighters.values()) if (f.faction === mint) n++;
+ return n;
+ }
+
+ // Both communities have fielded enough fighters to start a fair match.
+ canStart() {
+ for (const mint of this.factions.keys()) {
+ if (this.countFaction(mint) < this.cfg.minPerTeam) return false;
+ }
+ return true;
+ }
+
+ // --- lifecycle ----------------------------------------------------------
+
+ // Begin the lock-in countdown. Idempotent and only valid from the lobby once
+ // both sides are staffed; returns true if it actually armed the countdown.
+ beginCountdown(now) {
+ if (this.phase !== ClashPhase.LOBBY || !this.canStart()) return false;
+ this.phase = ClashPhase.COUNTDOWN;
+ this.countdownEndsAt = now + this.cfg.countdownMs;
+ return true;
+ }
+
+ // Open the gates: COUNTDOWN → LIVE. Resets every fighter to full and starts the
+ // round clock. Callable directly (skipping countdown) for tests/instant matches.
+ start(now) {
+ if (this.phase === ClashPhase.LIVE) return false;
+ this.phase = ClashPhase.LIVE;
+ this.startedAt = now;
+ this.endsAt = now + this.cfg.durationMs;
+ for (const f of this.fighters.values()) this._revive(f);
+ return true;
+ }
+
+ // Resolve one attack the room has already targeted (it owns positions, so it runs
+ // combat.selectTarget and hands us the chosen victim). We enforce the match rules
+ // the geometry can't know: no hits before LIVE, none on the dead, and never on a
+ // teammate. On a kill we move the score, the meter the whole league is built on.
+ //
+ // Returns a result the room broadcasts as hit feedback, or null when the attack
+ // is a no-op (wrong phase, dead actor, friendly, self).
+ resolveAttack(attackerId, targetId, weapon, { rng = Math.random, now = 0 } = {}) {
+ if (this.phase !== ClashPhase.LIVE && this.phase !== ClashPhase.SUDDEN_DEATH) return null;
+ if (!attackerId || !targetId || attackerId === targetId) return null;
+ const attacker = this.fighters.get(attackerId);
+ const target = this.fighters.get(targetId);
+ if (!attacker || !target) return null;
+ if (attacker.dead || target.dead) return null;
+ if (attacker.faction === target.faction) return null; // friendly fire off
+
+ const dmg = rollDamage(weapon, attacker.combatLevel, rng);
+ const res = applyDamage(target, dmg);
+ attacker.damage += res.hpLost + res.armorAbsorbed;
+
+ let scored = false;
+ if (res.killed) {
+ target.dead = true;
+ target.respawnAt = now + this.cfg.respawnMs;
+ target.deaths += 1;
+ attacker.kills += 1;
+ const fac = this.factions.get(attacker.faction);
+ fac.score += 1;
+ scored = true;
+ // Sudden death: the first blood in overtime ends it immediately.
+ if (this.phase === ClashPhase.SUDDEN_DEATH) {
+ this._end(attacker.faction, 'sudden_death', now);
+ } else if (fac.score >= this.cfg.scoreCap) {
+ this._end(attacker.faction, 'score_cap', now);
+ }
+ }
+
+ return {
+ attacker: attackerId,
+ target: targetId,
+ faction: attacker.faction,
+ dealt: res.dealt,
+ armorAbsorbed: res.armorAbsorbed,
+ hpLost: res.hpLost,
+ targetHp: target.hp,
+ killed: res.killed,
+ scored,
+ scoreA: this._scoreOf(0),
+ scoreB: this._scoreOf(1),
+ };
+ }
+
+ // Advance time: revive anyone whose respawn has come due, run the countdown→live
+ // flip, and check the round clock. Returns the frame's events so the room can
+ // broadcast respawns and the phase change without re-reading internal state.
+ tick(now) {
+ const events = { phase: this.phase, respawns: [], ended: false, winner: null, started: false };
+
+ if (this.phase === ClashPhase.COUNTDOWN && now >= this.countdownEndsAt) {
+ this.start(now);
+ events.started = true;
+ events.phase = this.phase;
+ }
+
+ if (this.phase === ClashPhase.LIVE || this.phase === ClashPhase.SUDDEN_DEATH) {
+ for (const f of this.fighters.values()) {
+ if (f.dead && f.respawnAt && now >= f.respawnAt) {
+ this._revive(f);
+ events.respawns.push(f.id);
+ }
+ }
+ }
+
+ // Round clock. On expiry, the leader wins; a level score goes to sudden death
+ // (and only flips to a draw if a sudden-death round itself somehow expires,
+ // which a real match avoids by ending on first blood — see resolveAttack).
+ if (this.phase === ClashPhase.LIVE && now >= this.endsAt) {
+ const [fa, fb] = this._orderedFactions();
+ if (fa.score === fb.score) {
+ this.phase = ClashPhase.SUDDEN_DEATH;
+ } else {
+ this._end(fa.score > fb.score ? fa.mint : fb.mint, 'timeout', now);
+ }
+ }
+
+ if (this.phase === ClashPhase.ENDED) {
+ events.ended = true;
+ events.winner = this.winner;
+ }
+ events.phase = this.phase;
+ return events;
+ }
+
+ // Concede on behalf of a community — used when a side empties out mid-match (every
+ // fighter disconnected). The other community takes the win; if both are empty the
+ // match is a draw. Terminal.
+ forfeit(losingMint, now) {
+ if (this.phase === ClashPhase.ENDED) return;
+ const other = [...this.factions.keys()].find((m) => m !== losingMint);
+ this._end(other || 'draw', 'forfeit', now);
+ }
+
+ // --- snapshots ----------------------------------------------------------
+
+ // Live scoreboard for the HUD: each side's score + identity, the clock, and the
+ // per-fighter kill/death/damage lines. Cheap to call every tick.
+ scoreboard(now = 0) {
+ const [fa, fb] = this._orderedFactions();
+ const remainingMs = this.phase === ClashPhase.LIVE
+ ? Math.max(0, this.endsAt - now)
+ : (this.phase === ClashPhase.SUDDEN_DEATH ? 0 : this.cfg.durationMs);
+ return {
+ phase: this.phase,
+ remainingMs,
+ factions: [this._facLine(fa), this._facLine(fb)],
+ fighters: [...this.fighters.values()].map((f) => ({
+ id: f.id, faction: f.faction, kills: f.kills, deaths: f.deaths,
+ damage: Math.round(f.damage), dead: f.dead,
+ })),
+ };
+ }
+
+ // The terminal result a war-standings ledger is built from. Only meaningful once
+ // `phase === ENDED`; returns null before then so callers can't persist a half-match.
+ result(now = 0) {
+ if (this.phase !== ClashPhase.ENDED) return null;
+ const [fa, fb] = this._orderedFactions();
+ return {
+ winner: this.winner, // mint | 'draw'
+ reason: this.endReason,
+ durationMs: Math.max(0, this.endedAt - this.startedAt),
+ endedAt: this.endedAt || now,
+ factions: [this._facResult(fa), this._facResult(fb)],
+ mvp: this._mvp(),
+ };
+ }
+
+ // --- internals ----------------------------------------------------------
+
+ _revive(f) {
+ f.hp = f.maxHp;
+ f.armor = Math.max(0, this.cfg.startArmor | 0);
+ f.dead = false;
+ f.respawnAt = 0;
+ }
+
+ _end(winnerMint, reason, now) {
+ if (this.phase === ClashPhase.ENDED) return;
+ this.phase = ClashPhase.ENDED;
+ this.winner = winnerMint;
+ this.endReason = reason;
+ this.endedAt = now;
+ }
+
+ // Stable ordering of the two factions by insertion order (faction A, faction B) so
+ // scoreA/scoreB and the scoreboard columns never swap between calls.
+ _orderedFactions() {
+ return [...this.factions.values()];
+ }
+
+ _scoreOf(index) {
+ return this._orderedFactions()[index]?.score ?? 0;
+ }
+
+ _facLine(fac) {
+ return {
+ mint: fac.mint, name: fac.name, symbol: fac.symbol, image: fac.image,
+ score: fac.score, alive: this._aliveCount(fac.mint), roster: this.countFaction(fac.mint),
+ };
+ }
+
+ _facResult(fac) {
+ const roster = [...this.fighters.values()].filter((f) => f.faction === fac.mint);
+ return {
+ mint: fac.mint, name: fac.name, symbol: fac.symbol,
+ score: fac.score,
+ kills: roster.reduce((s, f) => s + f.kills, 0),
+ deaths: roster.reduce((s, f) => s + f.deaths, 0),
+ fighters: roster.length,
+ };
+ }
+
+ _aliveCount(mint) {
+ let n = 0;
+ for (const f of this.fighters.values()) if (f.faction === mint && !f.dead) n++;
+ return n;
+ }
+
+ // Match MVP: most kills, then most damage, then fewest deaths. Null in an empty
+ // match. The winning community usually but not always houses the MVP.
+ _mvp() {
+ let best = null;
+ for (const f of this.fighters.values()) {
+ if (f.kills === 0 && f.damage === 0) continue;
+ if (!best
+ || f.kills > best.kills
+ || (f.kills === best.kills && f.damage > best.damage)
+ || (f.kills === best.kills && f.damage === best.damage && f.deaths < best.deaths)) {
+ best = f;
+ }
+ }
+ return best ? { id: best.id, faction: best.faction, kills: best.kills, deaths: best.deaths, damage: Math.round(best.damage) } : null;
+ }
+}
diff --git a/multiplayer/src/index.js b/multiplayer/src/index.js
index c4de86855..c8e637bb3 100644
--- a/multiplayer/src/index.js
+++ b/multiplayer/src/index.js
@@ -21,6 +21,7 @@ import { monitor } from '@colyseus/monitor';
import { WalkRoom } from './rooms/WalkRoom.js';
import { IrlRoom } from './rooms/IrlRoom.js';
+import { ClashRoom } from './rooms/ClashRoom.js';
import { blockStore } from './block-store.js';
import { worldPersistence } from './persistence.js';
import { flushAllPlayers } from './playerStore.js';
@@ -200,6 +201,12 @@ gameServer.define('walk_world', WalkRoom).filterBy(['coin', 'tier']);
// cell; the room itself mirrors a 3×3 window (centre + neighbours) so edge pins
// inside the nearby radius are never missed (see rooms/IrlRoom.js).
gameServer.define('irl_world', IrlRoom).filterBy(['geocell']);
+// Coin Wars (community-vs-community battles). One arena instance per matchKey, so
+// every fighter the /wars lobby hands the same matchKey lands in the same battle —
+// the two coin communities, their score, and the round clock all live in that one
+// room. A fighter must hold the coin they fight for (ClashRoom.onAuth verifies a
+// holder pass for their declared faction). See rooms/ClashRoom.js + clash.js.
+gameServer.define('clash_arena', ClashRoom).filterBy(['matchKey']);
gameServer
.listen(PORT, HOST)
diff --git a/multiplayer/src/rooms/ClashRoom.js b/multiplayer/src/rooms/ClashRoom.js
new file mode 100644
index 000000000..f5ece505c
Binary files /dev/null and b/multiplayer/src/rooms/ClashRoom.js differ
diff --git a/multiplayer/src/war-report.js b/multiplayer/src/war-report.js
new file mode 100644
index 000000000..434560b8a
--- /dev/null
+++ b/multiplayer/src/war-report.js
@@ -0,0 +1,63 @@
+// War result reporting — the game-server → API bridge for Coin Wars. When a clash
+// ends, ClashRoom calls reportBattle() to persist the result into the war ledger the
+// /wars standings are computed from. The POST is HMAC-signed with a shared secret so
+// only this trusted game process can write battle outcomes — a client (or anyone who
+// found the endpoint) can't forge a win for their community. Mirrors the trust model
+// of holder-pass.js, in the other direction.
+
+import crypto from 'node:crypto';
+
+const DEV_SECRET = 'three-ws-war-report-dev-secret';
+
+function secret() {
+ const s = process.env.WAR_RESULT_SECRET || process.env.HOLDER_PASS_SECRET;
+ if (s) return s;
+ if (process.env.NODE_ENV === 'production') {
+ throw new Error('[war-report] WAR_RESULT_SECRET is required in production — refusing to sign with the dev secret.');
+ }
+ return DEV_SECRET;
+}
+
+// Where the three.ws API lives. Defaults to production; override for local/staging.
+function apiBase() {
+ return (process.env.THREE_WS_API_BASE || 'https://three.ws').replace(/\/$/, '');
+}
+
+export function signBattle(bodyString) {
+ return crypto.createHmac('sha256', secret()).update(bodyString).digest('hex');
+}
+
+// Persist one finished battle. `battle` is the shape ClashMatch.result() produces,
+// enriched by the room with the matchKey + network. Returns true on a 2xx, false on
+// any failure — the caller logs but never throws, so a flaky API never crashes the
+// arena or blocks the next match. Best-effort by design: the live result is already
+// broadcast to players; the ledger write is for the league standings.
+export async function reportBattle(battle) {
+ let bodyString;
+ try {
+ bodyString = JSON.stringify({ battle });
+ } catch {
+ return false;
+ }
+ const url = `${apiBase()}/api/wars?action=report`;
+ try {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-war-signature': signBattle(bodyString),
+ },
+ body: bodyString,
+ // Don't let a hung API wedge the arena's match-end path.
+ signal: AbortSignal.timeout(8000),
+ });
+ if (!res.ok) {
+ console.warn(`[war-report] ${url} → ${res.status}`);
+ return false;
+ }
+ return true;
+ } catch (err) {
+ console.warn('[war-report] failed to post battle result:', err?.message || err);
+ return false;
+ }
+}
diff --git a/multiplayer/src/war-standings.js b/multiplayer/src/war-standings.js
new file mode 100644
index 000000000..5c9a642fe
--- /dev/null
+++ b/multiplayer/src/war-standings.js
@@ -0,0 +1,118 @@
+// War standings — the pure league math behind Coin Wars. A ClashMatch produces a
+// result (which community won, the kills/deaths on each side); this module folds a
+// stream of those results into a ranking of coin communities: rating, record,
+// streak, and aggregate K/D. The /api/wars endpoint recomputes standings from the
+// persisted battle ledger with these functions, and the live server can apply a
+// single fresh result incrementally with the same rules — one source of truth for
+// "who's winning the war."
+//
+// Pure and dependency-free (testable on the corrupted box like clash.js/combat.js).
+// Rating is Elo: a community that beats a stronger one climbs more than one that
+// beats a weaker one, so the ladder reflects quality of opposition, not just volume.
+
+export const BASE_RATING = 1000; // every community's rating before its first battle
+export const K_FACTOR = 32; // Elo responsiveness — one upset moves you meaningfully
+
+// Expected win probability for A against B given their ratings (standard Elo logistic).
+export function expectedScore(ratingA, ratingB) {
+ return 1 / (1 + 10 ** ((ratingB - ratingA) / 400));
+}
+
+// A fresh, zeroed standings record for a community. `meta` carries the display
+// identity (name/symbol/image) so a ranking row can render without a second lookup.
+export function emptyRecord(mint, meta = {}) {
+ return {
+ mint,
+ name: meta.name || meta.symbol || 'Community',
+ symbol: meta.symbol || '',
+ image: meta.image || '',
+ rating: BASE_RATING,
+ battles: 0,
+ wins: 0,
+ losses: 0,
+ draws: 0,
+ kills: 0,
+ deaths: 0,
+ streak: 0, // current run: +n consecutive wins, -n consecutive losses, 0 after a draw
+ lastBattleAt: 0, // epoch ms of the most recent battle (recency sort / "active" badge)
+ };
+}
+
+// Apply one battle result to a standings table (Map of mint → record), mutating and
+// returning it. Updates both communities' rating, record, streak, and K/D in lockstep
+// so the table is always internally consistent. A `result` is the shape ClashMatch
+// .result() emits: { winner: mint|'draw', factions: [{mint,name,symbol,kills,deaths}, …], endedAt }.
+export function applyBattle(table, result, metaByMint = {}) {
+ if (!result || !Array.isArray(result.factions) || result.factions.length !== 2) return table;
+ const [fa, fb] = result.factions;
+ const a = ensure(table, fa.mint, metaByMint[fa.mint] || fa);
+ const b = ensure(table, fb.mint, metaByMint[fb.mint] || fb);
+
+ const draw = result.winner === 'draw' || result.winner == null;
+ const aWon = !draw && result.winner === fa.mint;
+ const bWon = !draw && result.winner === fb.mint;
+
+ // Rating: settle both against each other on the same expected scores.
+ const ea = expectedScore(a.rating, b.rating);
+ const eb = 1 - ea;
+ const sa = draw ? 0.5 : aWon ? 1 : 0;
+ const sb = draw ? 0.5 : bWon ? 1 : 0;
+ a.rating = Math.round(a.rating + K_FACTOR * (sa - ea));
+ b.rating = Math.round(b.rating + K_FACTOR * (sb - eb));
+
+ settle(a, { won: aWon, lost: bWon, draw, kills: fa.kills, deaths: fa.deaths, at: result.endedAt });
+ settle(b, { won: bWon, lost: aWon, draw, kills: fb.kills, deaths: fb.deaths, at: result.endedAt });
+ return table;
+}
+
+// Fold a full battle ledger into a ranked standings array. Battles MUST be applied in
+// chronological order for Elo to be path-correct, so we sort by endedAt first. Pass
+// `metaByMint` to override stale display identity from the freshest known names.
+export function computeStandings(battles = [], metaByMint = {}) {
+ const table = new Map();
+ const ordered = [...battles].sort((x, y) => (x.endedAt || 0) - (y.endedAt || 0));
+ for (const battle of ordered) applyBattle(table, battle, metaByMint);
+ return rankStandings(table);
+}
+
+// Turn a standings table into the sorted, rank-stamped array the leaderboard renders.
+// Order: rating desc, then wins, then aggregate kills — a higher-rated community that
+// also wins more sits above one that merely farmed kills. Adds derived winRate + kd.
+export function rankStandings(table) {
+ const rows = [...table.values()].map(decorate);
+ rows.sort((a, b) =>
+ b.rating - a.rating || b.wins - a.wins || b.kills - a.kills || a.mint.localeCompare(b.mint));
+ rows.forEach((row, i) => { row.rank = i + 1; });
+ return rows;
+}
+
+// --- internals --------------------------------------------------------------
+
+function ensure(table, mint, meta) {
+ let rec = table.get(mint);
+ if (!rec) { rec = emptyRecord(mint, meta); table.set(mint, rec); }
+ // Keep identity fresh as later battles carry newer names/symbols.
+ if (meta?.name) rec.name = meta.name;
+ if (meta?.symbol) rec.symbol = meta.symbol;
+ if (meta?.image) rec.image = meta.image;
+ return rec;
+}
+
+function settle(rec, { won, lost, draw, kills = 0, deaths = 0, at = 0 }) {
+ rec.battles += 1;
+ rec.kills += kills | 0;
+ rec.deaths += deaths | 0;
+ if (draw) { rec.draws += 1; rec.streak = 0; }
+ else if (won) { rec.wins += 1; rec.streak = rec.streak > 0 ? rec.streak + 1 : 1; }
+ else if (lost) { rec.losses += 1; rec.streak = rec.streak < 0 ? rec.streak - 1 : -1; }
+ if (at > rec.lastBattleAt) rec.lastBattleAt = at;
+}
+
+function decorate(rec) {
+ const decided = rec.wins + rec.losses;
+ return {
+ ...rec,
+ winRate: decided > 0 ? rec.wins / decided : 0,
+ kd: rec.deaths > 0 ? rec.kills / rec.deaths : rec.kills,
+ };
+}
diff --git a/pages/clash.html b/pages/clash.html
new file mode 100644
index 000000000..cbd446de5
--- /dev/null
+++ b/pages/clash.html
@@ -0,0 +1,132 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Coin Clash · three.ws</title>
+ <meta
+ name="description"
+ content="Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction. The side that taps hardest before the round ends wins the battle."
+ />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/clash" />
+ <meta property="og:title" content="Coin Clash · three.ws" />
+ <meta
+ property="og:description"
+ content="Token-gated community warfare. Hold a coin, enlist in its army, and battle other communities in real time."
+ />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Coin+Clash&amp;d=Token-gated+community+warfare+%E2%80%94+hold+a+coin%2C+enlist%2C+and+battle+other+communities+live.&amp;p=%2Fclash" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Coin Clash · three.ws" />
+ <meta
+ name="twitter:description"
+ content="Token-gated community warfare. Hold a coin, enlist in its army, and battle other communities live."
+ />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Coin+Clash&amp;d=Token-gated+community+warfare+%E2%80%94+hold+a+coin%2C+enlist%2C+and+battle+other+communities+live.&amp;p=%2Fclash" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/clash.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ <link rel="canonical" href="https://three.ws/clash" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Coin Clash","description":"Token-gated community warfare — hold a coin, enlist in its army, and battle other communities live.","url":"https://three.ws/clash","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <meta property="og:locale" content="en_US" />
+ <meta property="og:image:alt" content="Coin Clash — three.ws" />
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <canvas id="cl-field" aria-hidden="true"></canvas>
+ <div class="cl-aurora" aria-hidden="true"></div>
+
+ <main class="cl-shell" aria-labelledby="cl-title">
+ <section class="cl-hero">
+ <p class="cl-kicker">
+ <span class="cl-live-dot" aria-hidden="true"></span>
+ Live community warfare
+ </p>
+ <h1 id="cl-title" class="cl-title">
+ <span class="cl-title-line">COIN</span>
+ <span class="cl-title-line cl-title-em">CLASH</span>
+ </h1>
+ <p class="cl-sub">
+ Every coin community is an army. Hold the coin, enlist, and rally for your faction —
+ the side that taps hardest before the round ends wins the battle and the bragging rights.
+ </p>
+ <dl class="cl-round" aria-label="Round status">
+ <div class="cl-round-stat">
+ <dt>Round</dt>
+ <dd id="cl-round-no">—</dd>
+ </div>
+ <div class="cl-round-stat cl-round-stat-timer">
+ <dt>Ends in</dt>
+ <dd id="cl-round-timer">—</dd>
+ </div>
+ <div class="cl-round-stat">
+ <dt>Armies</dt>
+ <dd id="cl-round-armies">—</dd>
+ </div>
+ </dl>
+ <div class="cl-tabs" role="tablist" aria-label="View">
+ <button type="button" class="cl-tab active" data-tab="arena" role="tab" aria-selected="true">⚔ Arena</button>
+ <button type="button" class="cl-tab" data-tab="standings" role="tab" aria-selected="false">🏆 War Records</button>
+ <a class="cl-tab cl-tab-link" href="/communities">Communities →</a>
+ </div>
+ </section>
+
+ <section id="cl-arena" class="cl-arena" aria-label="Live battles" aria-busy="true"></section>
+ <section id="cl-standings" class="cl-standings" aria-label="All-time war records" hidden></section>
+ </main>
+
+ <!-- Rally dock — appears once you've enlisted in a faction. -->
+ <aside id="cl-rally" class="cl-rally" hidden aria-label="Rally">
+ <div class="cl-rally-inner">
+ <button type="button" class="cl-rally-close" id="cl-rally-close" aria-label="Leave the rally">✕</button>
+ <div class="cl-rally-id">
+ <img id="cl-rally-img" class="cl-rally-img" alt="" />
+ <div class="cl-rally-id-text">
+ <span class="cl-rally-for">Fighting for</span>
+ <strong id="cl-rally-symbol">—</strong>
+ <span id="cl-rally-hold" class="cl-rally-hold"></span>
+ </div>
+ </div>
+
+ <button type="button" id="cl-tap" class="cl-tap" aria-label="Tap to rally">
+ <span class="cl-tap-ring" aria-hidden="true"></span>
+ <span class="cl-tap-label">RALLY</span>
+ <span class="cl-tap-combo" id="cl-combo" aria-hidden="true">×1</span>
+ </button>
+
+ <div class="cl-rally-stats">
+ <div class="cl-rs">
+ <span class="cl-rs-k">Your power</span>
+ <span class="cl-rs-v"><b id="cl-your-power">0</b><i id="cl-your-cap"></i></span>
+ <div class="cl-cap"><span id="cl-cap-fill" class="cl-cap-fill"></span></div>
+ </div>
+ <div class="cl-rs">
+ <span class="cl-rs-k">Army power</span>
+ <span class="cl-rs-v"><b id="cl-army-power">0</b></span>
+ </div>
+ </div>
+ <p class="cl-rally-hint" id="cl-rally-hint">Tap the target or hold <kbd>Space</kbd> to rally.</p>
+ </div>
+ </aside>
+
+ <script type="module" src="/src/clash.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/pages/play/ufo.html b/pages/play/ufo.html
new file mode 100644
index 000000000..fa5ece9ec
--- /dev/null
+++ b/pages/play/ufo.html
@@ -0,0 +1,555 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, maximum-scale=1" />
+ <title>Flappin UFO — dodge asteroids for $THREE · three.ws</title>
+ <meta name="description" content="Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score to the global leaderboard, and represent $THREE holders." />
+ <meta property="og:title" content="Flappin UFO · three.ws" />
+ <meta property="og:description" content="Dodge asteroids in your UFO. Connect your Solana wallet and claim your spot on the $THREE leaderboard." />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/play/ufo" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Flappin+UFO+%E2%80%94+dodge+asteroids+for+%24THREE&d=Pilot+your+UFO+through+asteroids.+Connect+your+Solana+wallet+and+climb+the+%24THREE+leaderboard.&p=%2Fplay%2Fufo" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Flappin UFO — dodge asteroids for $THREE" />
+ <meta name="twitter:description" content="Pilot your UFO through asteroids. Connect your Solana wallet and climb the $THREE leaderboard." />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Flappin+UFO+%E2%80%94+dodge+asteroids+for+%24THREE&d=Pilot+your+UFO+through+asteroids.+Connect+your+Solana+wallet+and+climb+the+%24THREE+leaderboard.&p=%2Fplay%2Fufo" />
+ <link rel="canonical" href="https://three.ws/play/ufo" />
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root {
+ --bg: #06070f;
+ --panel: rgba(12, 14, 24, 0.78);
+ --panel-solid: #0c0e18;
+ --line: rgba(255, 255, 255, 0.08);
+ --ink: #e8edf8;
+ --muted: #8b93b0;
+ --faint: rgba(255, 255, 255, 0.38);
+ --violet: #a78bff;
+ --cyan: #6ee7ff;
+ --gold: #fbbf24;
+ --up: #34d399;
+ --r: 14px;
+ --mono: ui-monospace, "JetBrains Mono", SFMono-Regular, Menlo, monospace;
+ --shadow: 0 18px 50px -20px rgba(0, 0, 0, 0.85), 0 1px 0 rgba(255, 255, 255, 0.04) inset;
+ --blur: saturate(160%) blur(20px);
+ }
+
+ * { box-sizing: border-box; margin: 0; padding: 0; }
+
+ html, body {
+ height: 100%;
+ overflow: hidden;
+ background: var(--bg);
+ color: var(--ink);
+ font: 14px/1.5 Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ overscroll-behavior: none;
+ }
+
+ a { color: inherit; text-decoration: none; }
+ button { font: inherit; color: inherit; cursor: pointer; border: none; background: none; }
+
+ /* ── stars background ───────────────────────────── */
+ .stars {
+ position: fixed; inset: 0; z-index: 0; pointer-events: none;
+ background:
+ radial-gradient(ellipse 80% 60% at 20% 30%, rgba(90, 60, 180, 0.12), transparent 70%),
+ radial-gradient(ellipse 60% 50% at 80% 70%, rgba(30, 80, 160, 0.1), transparent 70%);
+ }
+
+ /* ── game iframe ─────────────────────────────────── */
+ #game-frame {
+ position: fixed;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ border: none;
+ z-index: 1;
+ display: block;
+ background: #000;
+ }
+
+ /* ── top bar ─────────────────────────────────────── */
+ .bar {
+ position: fixed; top: 0; left: 0; right: 0; z-index: 10;
+ display: flex; align-items: center; gap: 12px; padding: 11px 16px;
+ background: linear-gradient(180deg, rgba(6, 7, 15, 0.9) 0%, rgba(6, 7, 15, 0.5) 70%, transparent 100%);
+ pointer-events: none;
+ }
+ .bar > * { pointer-events: auto; }
+ .spacer { flex: 1; }
+
+ .brand {
+ display: inline-flex; align-items: center; gap: 8px;
+ font-weight: 700; font-size: 14px; letter-spacing: -0.02em;
+ opacity: 0.9;
+ }
+ .brand img { width: 20px; height: 20px; border-radius: 5px; }
+ .brand-sep { color: var(--faint); font-weight: 400; margin: 0 2px; }
+ .game-title {
+ font-weight: 700; font-size: 14px; letter-spacing: -0.01em;
+ background: linear-gradient(90deg, var(--violet), var(--cyan));
+ -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;
+ }
+
+ .pill {
+ display: inline-flex; align-items: center; gap: 7px;
+ padding: 7px 12px; border-radius: 999px;
+ border: 1px solid var(--line); background: var(--panel);
+ backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ font-size: 12px; color: var(--muted);
+ transition: border-color .2s, color .2s;
+ }
+
+ .btn {
+ display: inline-flex; align-items: center; gap: 7px;
+ padding: 8px 14px; border-radius: 999px;
+ border: 1px solid var(--line); background: var(--panel);
+ backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ font-weight: 600; font-size: 12.5px; color: var(--ink);
+ transition: transform .12s, border-color .2s, background .2s;
+ white-space: nowrap;
+ }
+ .btn:hover { transform: translateY(-1px); border-color: color-mix(in srgb, var(--violet) 55%, var(--line)); }
+ .btn:active { transform: translateY(0) scale(.97); }
+ .btn.primary {
+ background: linear-gradient(135deg,
+ color-mix(in srgb, var(--violet) 20%, var(--panel)),
+ color-mix(in srgb, var(--cyan) 15%, var(--panel)));
+ border-color: color-mix(in srgb, var(--violet) 45%, var(--line));
+ }
+ .btn.connected {
+ border-color: color-mix(in srgb, var(--up) 50%, var(--line));
+ color: var(--up);
+ }
+
+ .btn-lb {
+ display: inline-flex; align-items: center; gap: 6px;
+ padding: 8px 13px; border-radius: 999px;
+ border: 1px solid var(--line); background: var(--panel);
+ backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ font-weight: 600; font-size: 12px; color: var(--muted);
+ transition: transform .12s, border-color .2s, color .2s;
+ }
+ .btn-lb:hover { transform: translateY(-1px); color: var(--ink); border-color: color-mix(in srgb, var(--violet) 45%, var(--line)); }
+ .btn-lb svg { width: 14px; height: 14px; }
+
+ /* ── leaderboard panel ───────────────────────────── */
+ .panel {
+ position: fixed; z-index: 9; right: 16px; top: 60px;
+ width: 300px; max-width: calc(100vw - 28px);
+ background: var(--panel); backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ border: 1px solid var(--line); border-radius: var(--r); box-shadow: var(--shadow);
+ overflow: hidden;
+ transform: translateX(calc(100% + 20px)); opacity: 0; pointer-events: none;
+ transition: transform .35s cubic-bezier(.22, 1, .36, 1), opacity .25s;
+ }
+ .panel.open {
+ transform: none; opacity: 1; pointer-events: auto;
+ }
+
+ .panel-head {
+ display: flex; align-items: center; justify-content: space-between;
+ padding: 11px 14px; border-bottom: 1px solid var(--line);
+ }
+ .panel-head h2 {
+ font-size: 10.5px; text-transform: uppercase; letter-spacing: .1em;
+ color: var(--faint); font-weight: 600; margin: 0;
+ display: flex; align-items: center; gap: 7px;
+ }
+ .panel-head .live-dot {
+ width: 6px; height: 6px; border-radius: 50%; background: var(--up);
+ animation: pulse 1.8s infinite;
+ }
+ @keyframes pulse { 0%{box-shadow:0 0 0 0 rgba(52,211,153,.5)} 70%{box-shadow:0 0 0 6px rgba(52,211,153,0)} 100%{box-shadow:0 0 0 0 rgba(52,211,153,0)} }
+
+ .panel-close {
+ width: 26px; height: 26px; border-radius: 8px;
+ border: 1px solid var(--line); background: rgba(255,255,255,0.04);
+ display: grid; place-items: center; color: var(--muted);
+ transition: color .15s, border-color .15s;
+ }
+ .panel-close:hover { color: var(--ink); border-color: var(--violet); }
+
+ /* wallet identity box */
+ .identity-box {
+ padding: 12px 14px; border-bottom: 1px solid var(--line);
+ display: none;
+ flex-direction: column; gap: 7px;
+ }
+ .identity-box.show { display: flex; }
+ .identity-label {
+ font-size: 10px; text-transform: uppercase; letter-spacing: .1em; color: var(--faint); font-weight: 600;
+ }
+ .identity-row {
+ display: flex; align-items: center; gap: 8px;
+ }
+ .identity-addr {
+ flex: 1; font: 600 12px/1.3 var(--mono); color: var(--cyan);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .copy-btn {
+ display: inline-flex; align-items: center; gap: 5px;
+ padding: 5px 10px; border-radius: 7px;
+ border: 1px solid color-mix(in srgb, var(--violet) 40%, var(--line));
+ background: color-mix(in srgb, var(--violet) 10%, transparent);
+ font: 600 11px/1 var(--mono); color: var(--violet);
+ transition: background .15s, border-color .15s, transform .1s;
+ white-space: nowrap;
+ }
+ .copy-btn:hover { background: color-mix(in srgb, var(--violet) 18%, transparent); transform: translateY(-1px); }
+ .copy-btn.copied { color: var(--up); border-color: color-mix(in srgb, var(--up) 40%, var(--line)); background: color-mix(in srgb, var(--up) 10%, transparent); }
+ .identity-hint {
+ font-size: 11px; color: var(--muted); line-height: 1.4;
+ }
+
+ /* leaderboard list */
+ .board { max-height: min(55vh, 440px); overflow-y: auto; }
+ .board::-webkit-scrollbar { width: 4px; } .board::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 2px; }
+
+ .lb-row {
+ display: grid; grid-template-columns: 22px 1fr auto; gap: 8px; align-items: center;
+ padding: 9px 14px; border-bottom: 1px solid var(--line);
+ transition: background .15s;
+ }
+ .lb-row:last-child { border-bottom: none; }
+ .lb-row:hover { background: rgba(255,255,255,0.03); }
+ .lb-row.me { background: color-mix(in srgb, var(--violet) 7%, transparent); }
+
+ .lb-rank { font: 700 11.5px/1 var(--mono); color: var(--faint); text-align: center; }
+ .lb-rank.gold { color: var(--gold); }
+ .lb-rank.silver { color: #9ca3af; }
+ .lb-rank.bronze { color: #b45309; }
+
+ .lb-info { min-width: 0; }
+ .lb-name { font-size: 12.5px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .lb-name.wallet { font: 600 11px/1.3 var(--mono); color: var(--cyan); }
+ .lb-sub { font-size: 10.5px; color: var(--muted); margin-top: 1px; }
+
+ .lb-score { text-align: right; }
+ .lb-score b { display: block; font: 700 13px/1 var(--mono); color: var(--ink); }
+ .lb-score small { font: 500 10px/1 var(--mono); color: var(--muted); }
+
+ .lb-empty { padding: 28px 18px; text-align: center; }
+ .lb-empty b { display: block; font-size: 14px; color: var(--ink); margin-bottom: 6px; }
+ .lb-empty p { font-size: 12px; color: var(--muted); line-height: 1.5; }
+
+ .lb-skel {
+ height: 46px; margin: 0; border-bottom: 1px solid var(--line);
+ background: linear-gradient(90deg,
+ rgba(255,255,255,0.03) 25%,
+ rgba(255,255,255,0.06) 37%,
+ rgba(255,255,255,0.03) 63%);
+ background-size: 400% 100%;
+ animation: shimmer 1.4s infinite;
+ }
+ @keyframes shimmer { to { background-position: -400% 0; } }
+
+ /* ── controls hint ───────────────────────────────── */
+ .hint {
+ position: fixed; left: 16px; bottom: 16px; z-index: 9;
+ display: flex; gap: 7px; align-items: center;
+ padding: 7px 12px; border-radius: 999px;
+ background: var(--panel); backdrop-filter: var(--blur); -webkit-backdrop-filter: var(--blur);
+ border: 1px solid var(--line); color: var(--muted); font-size: 11.5px;
+ }
+ .hint kbd {
+ font: 600 10px/1 var(--mono); background: rgba(255,255,255,0.07);
+ border: 1px solid var(--line); border-radius: 4px; padding: 3px 5px; color: var(--ink);
+ }
+
+ /* ── $THREE badge ────────────────────────────────── */
+ .three-badge {
+ display: inline-flex; align-items: center; gap: 5px;
+ padding: 5px 10px; border-radius: 999px;
+ border: 1px solid color-mix(in srgb, var(--violet) 35%, var(--line));
+ background: color-mix(in srgb, var(--violet) 8%, transparent);
+ font: 700 11px/1 var(--mono); color: var(--violet);
+ letter-spacing: .02em;
+ }
+ .three-badge::before { content: '◈'; opacity: .7; }
+
+ /* ── mobile ──────────────────────────────────────── */
+ @media (max-width: 600px) {
+ .bar { padding: 9px 12px; gap: 8px; }
+ .game-title { display: none; }
+ .brand-sep { display: none; }
+ .panel { right: 8px; top: 54px; width: calc(100vw - 16px); }
+ .hint { display: none; }
+ }
+ </style>
+</head>
+<body>
+<div class="stars"></div>
+
+<!-- full-screen game iframe -->
+<iframe
+ id="game-frame"
+ src="https://flappin-ufo.vercel.app"
+ allow="autoplay; fullscreen"
+ title="Flappin UFO"
+></iframe>
+
+<!-- top bar -->
+<header class="bar">
+ <a href="/" class="brand">
+ <img src="/favicon.svg" alt="three.ws" />
+ <span>three.ws</span>
+ </a>
+ <span class="brand-sep">/</span>
+ <span class="game-title">Flappin UFO</span>
+
+ <div class="spacer"></div>
+
+ <span class="three-badge">$THREE</span>
+
+ <button class="btn-lb" id="lb-toggle" aria-label="Toggle leaderboard" title="Leaderboard">
+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round">
+ <rect x="1.5" y="9.5" width="3" height="5" rx=".5" />
+ <rect x="6.5" y="5.5" width="3" height="9" rx=".5" />
+ <rect x="11.5" y="2.5" width="3" height="12" rx=".5" />
+ </svg>
+ <span id="lb-toggle-label">Scores</span>
+ </button>
+
+ <button class="btn primary" id="connect-wallet-btn" onclick="connectWallet()">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M20 12V8a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-4" />
+ <path d="M15 12h6" /><circle cx="15" cy="12" r="1.5" fill="currentColor" />
+ </svg>
+ <span data-wallet-label>Connect Wallet</span>
+ </button>
+</header>
+
+<!-- leaderboard panel -->
+<aside class="panel" id="lb-panel" role="complementary" aria-label="Leaderboard">
+ <div class="panel-head">
+ <h2>
+ <span class="live-dot"></span>
+ Global Leaderboard
+ </h2>
+ <button class="panel-close" onclick="closePanel()" aria-label="Close leaderboard">
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round">
+ <path d="M1 1l10 10M11 1L1 11" />
+ </svg>
+ </button>
+ </div>
+
+ <!-- identity box (wallet connected) -->
+ <div class="identity-box" id="identity-box">
+ <span class="identity-label">Your game name</span>
+ <div class="identity-row">
+ <code class="identity-addr" id="identity-addr"></code>
+ <button class="copy-btn" id="copy-btn" onclick="copyAddr()">Copy</button>
+ </div>
+ <p class="identity-hint">Paste this as your name in-game to appear on the leaderboard.</p>
+ </div>
+
+ <!-- scores list -->
+ <div class="board" id="lb-board">
+ <!-- skeleton -->
+ <div class="lb-skel"></div>
+ <div class="lb-skel"></div>
+ <div class="lb-skel"></div>
+ <div class="lb-skel"></div>
+ <div class="lb-skel"></div>
+ </div>
+</aside>
+
+<!-- controls hint -->
+<div class="hint" id="controls-hint" aria-hidden="true">
+ <kbd>Space</kbd> or <kbd>Click</kbd> to thrust &nbsp;·&nbsp; hold to climb
+</div>
+
+<script>
+(function () {
+ 'use strict';
+
+ const LEADERBOARD_URL = 'https://flappin-ufo.vercel.app/api/leaderboard';
+ const REFRESH_MS = 15_000;
+
+ let walletAddress = null;
+ let panelOpen = false;
+ let refreshTimer = null;
+
+ // ── wallet ──────────────────────────────────────────────
+ function getPhantom() {
+ const p = window.solana;
+ if (!p) return null;
+ return (p.isPhantom || p.isThreeWs) ? p : null;
+ }
+
+ window.connectWallet = async function () {
+ const p = getPhantom();
+ if (!p) { window.open('https://phantom.app/', '_blank', 'noopener'); return; }
+ try {
+ const res = await p.connect();
+ walletAddress = res?.publicKey?.toString?.() || null;
+ onWalletChange(walletAddress);
+ } catch (_) {}
+ };
+
+ function onWalletChange(addr) {
+ walletAddress = addr;
+ const btn = document.getElementById('connect-wallet-btn');
+ const lbl = btn?.querySelector('[data-wallet-label]');
+ if (addr) {
+ const short = addr.slice(0, 4) + '…' + addr.slice(-4);
+ if (lbl) lbl.textContent = short;
+ btn?.classList.add('connected');
+ showIdentity(addr);
+ } else {
+ if (lbl) lbl.textContent = 'Connect Wallet';
+ btn?.classList.remove('connected');
+ hideIdentity();
+ }
+ renderLeaderboard(lastRuns);
+ }
+
+ function showIdentity(addr) {
+ const box = document.getElementById('identity-box');
+ const addrEl = document.getElementById('identity-addr');
+ if (box) box.classList.add('show');
+ if (addrEl) addrEl.textContent = addr;
+ openPanel();
+ }
+
+ function hideIdentity() {
+ document.getElementById('identity-box')?.classList.remove('show');
+ }
+
+ window.copyAddr = function () {
+ if (!walletAddress) return;
+ navigator.clipboard.writeText(walletAddress).then(() => {
+ const btn = document.getElementById('copy-btn');
+ if (!btn) return;
+ btn.classList.add('copied');
+ btn.textContent = 'Copied!';
+ setTimeout(() => { btn.classList.remove('copied'); btn.textContent = 'Copy'; }, 2000);
+ });
+ };
+
+ // detect if Phantom was already connected
+ (function detectExisting() {
+ const p = getPhantom();
+ if (!p) return;
+ p.on('connect', (pk) => onWalletChange(pk?.toString?.() || null));
+ p.on('disconnect', () => onWalletChange(null));
+ if (p.isConnected && p.publicKey) {
+ onWalletChange(p.publicKey.toString());
+ }
+ })();
+
+ // ── panel ────────────────────────────────────────────────
+ function openPanel() {
+ panelOpen = true;
+ document.getElementById('lb-panel')?.classList.add('open');
+ document.getElementById('lb-toggle-label').textContent = 'Hide';
+ if (!refreshTimer) startRefresh();
+ }
+
+ window.closePanel = function () {
+ panelOpen = false;
+ document.getElementById('lb-panel')?.classList.remove('open');
+ document.getElementById('lb-toggle-label').textContent = 'Scores';
+ };
+
+ document.getElementById('lb-toggle').addEventListener('click', () => {
+ panelOpen ? closePanel() : openPanel();
+ });
+
+ // open panel by default on desktop
+ if (window.innerWidth >= 768) openPanel();
+
+ // ── leaderboard ──────────────────────────────────────────
+ let lastRuns = [];
+
+ function rankClass(i) {
+ if (i === 0) return 'gold';
+ if (i === 1) return 'silver';
+ if (i === 2) return 'bronze';
+ return '';
+ }
+
+ function rankSymbol(i) {
+ if (i === 0) return '🥇';
+ if (i === 1) return '🥈';
+ if (i === 2) return '🥉';
+ return String(i + 1);
+ }
+
+ function isWallet(name) {
+ return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(name);
+ }
+
+ function formatName(name) {
+ if (!name) return 'anon';
+ if (isWallet(name)) return name.slice(0, 4) + '…' + name.slice(-4);
+ return name;
+ }
+
+ function isMe(name) {
+ if (!walletAddress || !name) return false;
+ return name.toLowerCase() === walletAddress.toLowerCase();
+ }
+
+ function renderLeaderboard(runs) {
+ lastRuns = runs || [];
+ const board = document.getElementById('lb-board');
+ if (!board) return;
+
+ if (!lastRuns.length) {
+ board.innerHTML = `
+ <div class="lb-empty">
+ <b>No scores yet</b>
+ <p>Be the first to submit a score.<br>Connect your wallet and play!</p>
+ </div>`;
+ return;
+ }
+
+ board.innerHTML = lastRuns.map((r, i) => {
+ const me = isMe(r.name);
+ const wallet = isWallet(r.name);
+ return `<div class="lb-row${me ? ' me' : ''}">
+ <span class="lb-rank ${rankClass(i)}">${rankSymbol(i)}</span>
+ <div class="lb-info">
+ <div class="lb-name${wallet ? ' wallet' : ''}" title="${escHtml(r.name || 'anon')}">${escHtml(formatName(r.name))}</div>
+ <div class="lb-sub">Level ${r.level ?? 1}</div>
+ </div>
+ <div class="lb-score">
+ <b>${(r.score ?? 0).toLocaleString()}</b>
+ <small>pts</small>
+ </div>
+ </div>`;
+ }).join('');
+ }
+
+ function escHtml(s) {
+ return String(s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
+ }
+
+ async function fetchLeaderboard() {
+ try {
+ const r = await fetch(LEADERBOARD_URL, { cache: 'no-store' });
+ if (!r.ok) throw new Error(r.status);
+ const data = await r.json();
+ renderLeaderboard(data.runs || []);
+ } catch (e) {
+ // keep whatever we already rendered; don't wipe on transient error
+ }
+ }
+
+ function startRefresh() {
+ fetchLeaderboard();
+ refreshTimer = setInterval(fetchLeaderboard, REFRESH_MS);
+ }
+
+ // fetch on panel open only
+ if (panelOpen) startRefresh();
+})();
+</script>
+</body>
+</html>
diff --git a/public/changelog.json b/public/changelog.json
index 76625948a..3f56efe20 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T13:25:20.997Z",
+ "generated_at": "2026-06-19T13:45:36.994Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,26 @@
"launch"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "launch",
+ "title": "Coin Clash",
+ "summary": "Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.",
+ "link": "/clash",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-06-19",
+ "type": "launch",
+ "title": "Flappin UFO — dodge asteroids for $THREE",
+ "summary": "Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.",
+ "link": "/play/ufo",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-19",
"type": "update",
@@ -149,6 +169,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-19",
+ "type": "update",
+ "title": "Flappin UFO — a $THREE arcade game is live",
+ "summary": "You can now play Flappin UFO on three.ws at /play/ufo — a Flappy Bird-style space game where you pilot a UFO through asteroid fields. Connect your Solana wallet, copy your address as your in-game name, and submit your score to the global leaderboard. The leaderboard panel refreshes live every 15 seconds and highlights your wallet entry so you can see exactly where you rank among $THREE holders.",
+ "link": "/play/ufo",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-19",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 843be18e9..cec02429e 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,22 @@
<category>launch</category>
<description>Author your agent's brain, memory, body, money, and skills in one place, with a live 3D avatar that updates everywhere as you edit.</description>
</item>
+ <item>
+ <title>Coin Clash</title>
+ <link>https://three.ws/clash</link>
+ <guid isPermaLink="false">2026-06-19:Coin Clash</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.</description>
+ </item>
+ <item>
+ <title>Flappin UFO — dodge asteroids for $THREE</title>
+ <link>https://three.ws/play/ufo</link>
+ <guid isPermaLink="false">2026-06-19:Flappin UFO — dodge asteroids for $THREE</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.</description>
+ </item>
<item>
<title>Agent Studio — one place to build your whole agent, with a live avatar</title>
<link>https://three.ws/agent-studio</link>
@@ -118,6 +134,14 @@
<category>fix</category>
<description>Several navigation links pointed at pages that no longer exist — &quot;View plans&quot; on the agent deploy flow, the Classic viewer menu item, and the API-key links on the AWS welcome and selfie pages — and now go to the right place. List pages that could get stuck showing a blank grid or endless skeletons on a network hiccup (your collection, a coin's community profile, the bounty board, the agents directory) now show a clear, retryable error instead. The $THREE dashboard also replaced a non-working &quot;claim&quot; button with a plain explanation that revenue share is distributed to holders automatically.</description>
</item>
+ <item>
+ <title>Flappin UFO — a $THREE arcade game is live</title>
+ <link>https://three.ws/play/ufo</link>
+ <guid isPermaLink="false">2026-06-19:Flappin UFO — a $THREE arcade game is live</guid>
+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>You can now play Flappin UFO on three.ws at /play/ufo — a Flappy Bird-style space game where you pilot a UFO through asteroid fields. Connect your Solana wallet, copy your address as your in-game name, and submit your score to the global leaderboard. The leaderboard panel refreshes live every 15 seconds and highlights your wallet entry so you can see exactly where you rank among $THREE holders.</description>
+ </item>
<item>
<title>Freeze your agent wallet in one tap — plus hardened custody security</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index a8e27d560..2806f4afd 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-19T13:25:20.982Z",
+ "generated_at": "2026-06-19T13:45:36.982Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -606,6 +606,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/clash",
+ "title": "Coin Clash",
+ "description": "Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.",
+ "added": "2026-06-19",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/leaderboard",
"title": "Trader Leaderboard",
@@ -676,6 +686,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/play/ufo",
+ "title": "Flappin UFO — dodge asteroids for $THREE",
+ "description": "Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.",
+ "added": "2026-06-19",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/smart-money",
"title": "Smart Money Radar — follow the wallets that win on pump.fun",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 132632d56..0d344ed59 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -370,6 +370,12 @@ URL: https://three.ws/launches
Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.
+### Coin Clash
+
+URL: https://three.ws/clash
+
+Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.
+
### Trader Leaderboard
URL: https://three.ws/leaderboard
@@ -412,6 +418,12 @@ URL: https://three.ws/play/arena
Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.
+### Flappin UFO — dodge asteroids for $THREE
+
+URL: https://three.ws/play/ufo
+
+Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.
+
### Smart Money Radar — follow the wallets that win on pump.fun
URL: https://three.ws/smart-money
diff --git a/public/llms.txt b/public/llms.txt
index f3539cc17..ec7eff12f 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -81,6 +81,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Agent Activity — Oracle conviction in real time](https://three.ws/activity): The trading floor: every Oracle conviction action from every autonomous 3D agent on pump.fun, live. Filter by tier and mode, track outcomes, and copy the winners.
- [Launch a Coin](https://three.ws/launch): Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.
- [Agent Launches](https://three.ws/launches): Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.
+- [Coin Clash](https://three.ws/clash): Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.
- [Trader Leaderboard](https://three.ws/leaderboard): Pump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction.
- [Trending — Top Agents & Coins on three.ws](https://three.ws/trending): What’s hot on three.ws right now. Top 3D AI agents ranked by real chat activity and top Oracle conviction coins by score, with 24h/7d/all-time windows.
- [Live Trade Feed — Notable pump.fun Exits](https://three.ws/trades): Real-time feed of every notable pump.fun exit from three.ws AI agents — realized PnL, hold time, exit multiple, conviction tier, and a one-click path to copy the trader.
@@ -88,6 +89,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Pay (x402)](https://three.ws/pay): Pay-per-call gateway: invoke any x402-protocol paid API with a USDC micro-transaction.
- [Agent Wallet (x402 on Solana)](https://three.ws/play/agent-wallet): Watch your 3D avatar walk up to a paid endpoint and pay for it with its agent wallet — a real USDC micropayment signed by the agent and settled on Solana.
- [Sniper Arena — autonomous AI agents trading live](https://three.ws/play/arena): Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.
+- [Flappin UFO — dodge asteroids for $THREE](https://three.ws/play/ufo): Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.
- [Smart Money Radar — follow the wallets that win on pump.fun](https://three.ws/smart-money): A live first-party reputation graph of every pump.fun wallet. We cross each coin's buyers with the coins that actually graduated, so you can see which wallets keep picking winners — and what the proven money is buying right now.
- [Pump.fun Stream](https://three.ws/pumpfun): Mint and trade pump.fun agent tokens on Solana. Live feed of every launch.
- [Pump Live](https://three.ws/pump-live): Real-time feed of every pump.fun launch as it happens, with a 3D agent that reacts live.
diff --git a/public/nav-data.js b/public/nav-data.js
index 7d0cc8c55..439b59377 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -98,6 +98,12 @@ export const NAV_GROUPS = [
badge: 'New',
desc: 'Every coin is a 3D world — drop in & hang out',
},
+ {
+ title: 'Coin Clash',
+ href: '/clash',
+ badge: 'New',
+ desc: 'Token-gated community warfare — hold a coin, enlist, and battle other armies live',
+ },
{
title: 'All pages',
href: '/sitemap',
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 5140d3f7b..ff596ae58 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -65,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 175 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 177 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +77,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 175 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 177 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -493,7 +493,7 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>45</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>47</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
@@ -525,6 +525,13 @@
<span class="sm-desc">Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.</span>
</a>
</li>
+ <li>
+ <a href="/clash">
+ <span class="sm-title">Coin Clash</span>
+ <span class="sm-path">/clash</span>
+ <span class="sm-desc">Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.</span>
+ </a>
+ </li>
<li>
<a href="/leaderboard">
<span class="sm-title">Trader Leaderboard</span>
@@ -574,6 +581,13 @@
<span class="sm-desc">Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&amp;L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.</span>
</a>
</li>
+ <li>
+ <a href="/play/ufo">
+ <span class="sm-title">Flappin UFO — dodge asteroids for $THREE</span>
+ <span class="sm-path">/play/ufo</span>
+ <span class="sm-desc">Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.</span>
+ </a>
+ </li>
<li>
<a href="/smart-money">
<span class="sm-title">Smart Money Radar — follow the wallets that win on pump.fun</span>
diff --git a/src/body-mocap.js b/src/body-mocap.js
new file mode 100644
index 000000000..19039cfa6
--- /dev/null
+++ b/src/body-mocap.js
@@ -0,0 +1,233 @@
+/**
+ * BodyMocap — webcam body/limb motion capture for Three.js humanoid avatars.
+ *
+ * The body counterpart to FaceMocap. Uses MediaPipe Pose Landmarker (from the
+ * already-bundled `@mediapipe/tasks-vision`) to recover 33 world landmarks per
+ * frame, runs them through the pure `pose-solve` solver to get per-bone rotation
+ * deltas, smooths each with damped slerp, and drives the avatar's humanoid bones.
+ *
+ * Pipeline:
+ * webcam → Pose Landmarker → world landmarks → solvePose() →
+ * parent-local quaternion conversion → damped slerp → bone.quaternion
+ *
+ * Designed to compose with FaceMocap on the same avatar: FaceMocap owns morphs +
+ * the head bone; BodyMocap owns the arms, spine, and legs. Neither touches the
+ * other's bones. It attaches to the existing Viewer render loop the same way
+ * FaceMocap does — the caller pushes `bodyMocap.update` into the per-frame hook.
+ */
+
+import { PoseLandmarker, FilesetResolver } from '@mediapipe/tasks-vision';
+import { Quaternion } from 'three';
+import { solvePose } from './runtime/pose-solve.js';
+
+const WASM_URL = 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm';
+const MODEL_URL = 'https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_full/float16/1/pose_landmarker_full.task';
+
+// Canonical bones this module is allowed to drive. Head/neck stay with FaceMocap.
+const DRIVEN_BONES = Object.freeze([
+ 'LeftArm', 'LeftForeArm', 'RightArm', 'RightForeArm',
+ 'Spine', 'LeftUpLeg', 'LeftLeg', 'RightUpLeg', 'RightLeg',
+]);
+
+// Same canonicalization the rest of the app uses to match retargeted rigs
+// (mixamorig:, Armature_, snake_case … → bare lowercase name).
+function canonicalKey(name) {
+ return name
+ .replace(/^mixamorig:?/i, '')
+ .replace(/^[A-Za-z0-9]+[_:]/, '')
+ .toLowerCase();
+}
+
+export class BodyMocap {
+ constructor(opts = {}) {
+ this._landmarker = null;
+ this._video = null;
+ this._stream = null;
+ this._running = false;
+ this._lastVideoTime = -1;
+ this._lastResult = null;
+ this._onPose = null;
+
+ this._mirror = opts.mirror ?? false;
+ this._legs = opts.legs ?? true;
+ // Damping for the per-bone slerp. Higher = snappier, lower = smoother.
+ // Expressed as a per-second rate so motion is framerate-independent.
+ this._stiffness = opts.stiffness ?? 12;
+ this._minVisibility = opts.minVisibility ?? 0.5;
+
+ // Per-driven-bone runtime state: { node, restLocal }.
+ this._bones = new Map();
+
+ // Scratch quaternions — zero per-frame allocation in the hot path.
+ this._qParent = new Quaternion();
+ this._qParentInv = new Quaternion();
+ this._qLocalDelta = new Quaternion();
+ this._qTarget = new Quaternion();
+
+ this._fps = 0; this._fpsFrames = 0; this._fpsLastT = 0;
+
+ this.recording = false;
+ this._recordBuf = [];
+ this._recordT0 = 0;
+ }
+
+ // ── Lifecycle ─────────────────────────────────────────────────────────────
+
+ async init() {
+ const fileset = await FilesetResolver.forVisionTasks(WASM_URL);
+ this._landmarker = await PoseLandmarker.createFromOptions(fileset, {
+ baseOptions: { modelAssetPath: MODEL_URL, delegate: 'GPU' },
+ runningMode: 'VIDEO',
+ numPoses: 1,
+ outputSegmentationMasks: false,
+ });
+ }
+
+ async startWebcam() {
+ this._stream = await navigator.mediaDevices.getUserMedia({
+ video: { width: 640, height: 480, facingMode: 'user' },
+ audio: false,
+ });
+ const video = document.createElement('video');
+ video.srcObject = this._stream;
+ video.autoplay = true;
+ video.playsInline = true;
+ video.muted = true;
+ await new Promise((res) => { video.onloadeddata = res; });
+ this._video = video;
+ return video;
+ }
+
+ /**
+ * Bind to an avatar root. Walks the skeleton, resolves the canonical bones we
+ * drive, and captures each bone's rest local quaternion so target rotations
+ * compose on top of the rig's bind pose rather than replacing it.
+ */
+ attach(avatarRoot) {
+ this._bones.clear();
+ const wanted = new Set(DRIVEN_BONES.map((b) => b.toLowerCase()));
+ const byKey = new Map();
+ avatarRoot.traverse((node) => {
+ if (!node.isBone) return;
+ const key = canonicalKey(node.name);
+ if (wanted.has(key) && !byKey.has(key)) byKey.set(key, node);
+ });
+ for (const canonical of DRIVEN_BONES) {
+ const node = byKey.get(canonical.toLowerCase());
+ if (node) {
+ this._bones.set(canonical, { node, restLocal: node.quaternion.clone() });
+ }
+ }
+ return this._bones.size;
+ }
+
+ start() { this._running = true; }
+
+ stop() {
+ this._running = false;
+ this._stream?.getTracks().forEach((t) => t.stop());
+ this._video = null;
+ this._stream = null;
+ }
+
+ onPoseDetected(cb) { this._onPose = cb; }
+
+ // ── Per-frame ─────────────────────────────────────────────────────────────
+
+ update(dt = 1 / 60) {
+ if (!this._running || !this._landmarker || !this._video) return;
+ if (this._video.readyState < 2) return;
+
+ const ct = this._video.currentTime;
+ if (ct === this._lastVideoTime) return;
+ this._lastVideoTime = ct;
+
+ const now = performance.now();
+ const result = this._landmarker.detectForVideo(this._video, now);
+ this._lastResult = result;
+
+ this._fpsFrames++;
+ if (now - this._fpsLastT >= 500) {
+ this._fps = (this._fpsFrames * 1000) / (now - this._fpsLastT);
+ this._fpsFrames = 0;
+ this._fpsLastT = now;
+ }
+
+ const world = result.worldLandmarks?.[0];
+ const hasPose = !!world;
+ this._onPose?.(hasPose);
+ if (!hasPose) return;
+
+ const { bones } = solvePose(world, {
+ mirror: this._mirror,
+ legs: this._legs,
+ minVisibility: this._minVisibility,
+ });
+
+ this._applyBones(bones, dt);
+
+ if (this.recording) {
+ if (this._recordBuf.length === 0) this._recordT0 = now;
+ const frame = { t: (now - this._recordT0) / 1000, q: {} };
+ for (const [name, q] of Object.entries(bones)) {
+ frame.q[name] = [q.x, q.y, q.z, q.w];
+ }
+ this._recordBuf.push(frame);
+ }
+ }
+
+ /**
+ * Apply solved world-space rest→target deltas to the rig. Converts each delta
+ * into the bone's parent-local frame, composes with the captured rest pose,
+ * and damp-slerps toward it. Bones absent from `solved` hold their current
+ * rotation (occlusion) rather than snapping back to rest.
+ */
+ _applyBones(solved, dt) {
+ const alpha = 1 - Math.exp(-this._stiffness * dt); // framerate-independent damping
+ for (const [name, state] of this._bones) {
+ const worldDelta = solved[name];
+ if (!worldDelta) continue;
+ const { node, restLocal } = state;
+
+ // localDelta = P⁻¹ · worldDelta · P, then target = localDelta · restLocal
+ node.parent.getWorldQuaternion(this._qParent);
+ this._qParentInv.copy(this._qParent).invert();
+ this._qLocalDelta
+ .copy(this._qParentInv)
+ .multiply(worldDelta)
+ .multiply(this._qParent);
+ this._qTarget.copy(this._qLocalDelta).multiply(restLocal);
+
+ node.quaternion.slerp(this._qTarget, alpha);
+ }
+ }
+
+ /** Restore every driven bone to its captured rest pose. */
+ resetToRest() {
+ for (const { node, restLocal } of this._bones.values()) {
+ node.quaternion.copy(restLocal);
+ }
+ }
+
+ // ── Recording / playback (parity with FaceMocap) ──────────────────────────
+
+ startRecording() { this._recordBuf.length = 0; this._recordT0 = 0; this.recording = true; }
+ stopRecording() { this.recording = false; return this.getRecording(); }
+
+ getRecording() {
+ return {
+ format: 'three.ws.body-mocap.v1',
+ duration: this._recordBuf.length ? this._recordBuf[this._recordBuf.length - 1].t : 0,
+ frames: this._recordBuf.slice(),
+ };
+ }
+
+ clearRecording() { this._recordBuf.length = 0; }
+
+ // ── Accessors ─────────────────────────────────────────────────────────────
+
+ getLastResult() { return this._lastResult; }
+ getFps() { return this._fps; }
+ getBoneCount() { return this._bones.size; }
+ get videoElement() { return this._video; }
+}
diff --git a/src/clash.css b/src/clash.css
new file mode 100644
index 000000000..ebae458e2
--- /dev/null
+++ b/src/clash.css
@@ -0,0 +1,413 @@
+/* Coin Clash — token-gated community battle arena.
+ Tokens come from /tokens.css (loaded via /nav.css). No hardcoded palette. */
+
+.cl-shell {
+ max-width: 1100px;
+ margin: 0 auto;
+ padding: clamp(var(--space-6, 24px), 4vw, var(--space-10, 56px)) var(--space-4, 16px) var(--space-12, 80px);
+ position: relative;
+ z-index: 1;
+}
+
+/* ── Ambient field ──────────────────────────────────────────────────────── */
+#cl-field {
+ position: fixed;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ z-index: 0;
+ opacity: 0.5;
+}
+.cl-aurora {
+ position: fixed;
+ inset: -20% -10% auto -10%;
+ height: 60vh;
+ z-index: 0;
+ pointer-events: none;
+ background:
+ radial-gradient(60% 80% at 20% 0%, color-mix(in srgb, var(--danger) 18%, transparent), transparent 70%),
+ radial-gradient(60% 80% at 80% 10%, color-mix(in srgb, var(--accent) 14%, transparent), transparent 70%);
+ filter: blur(40px);
+ opacity: 0.6;
+}
+@media (prefers-reduced-motion: reduce) {
+ #cl-field { display: none; }
+}
+
+/* ── Hero ───────────────────────────────────────────────────────────────── */
+.cl-hero { text-align: center; margin-bottom: var(--space-8, 32px); }
+.cl-kicker {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2, 8px);
+ font: 600 var(--text-2xs, 11px) / 1 var(--font-mono);
+ letter-spacing: 0.14em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ margin: 0 0 var(--space-4, 16px);
+}
+.cl-live-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: var(--radius-pill);
+ background: var(--danger);
+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--danger) 60%, transparent);
+ animation: cl-pulse 1.8s ease-out infinite;
+}
+@keyframes cl-pulse {
+ 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--danger) 55%, transparent); }
+ 70% { box-shadow: 0 0 0 9px transparent; }
+ 100% { box-shadow: 0 0 0 0 transparent; }
+}
+.cl-title {
+ margin: 0;
+ font-family: var(--font-display);
+ font-weight: 800;
+ line-height: 0.92;
+ letter-spacing: -0.02em;
+ font-size: clamp(2.6rem, 9vw, 5.2rem);
+ display: flex;
+ flex-direction: column;
+}
+.cl-title-em {
+ color: transparent;
+ background: linear-gradient(100deg, var(--ink-bright), color-mix(in srgb, var(--danger) 70%, var(--ink-bright)));
+ -webkit-background-clip: text;
+ background-clip: text;
+}
+.cl-sub {
+ max-width: 52ch;
+ margin: var(--space-4, 16px) auto 0;
+ color: var(--ink-dim);
+ font-size: var(--text-base, 1rem);
+ line-height: 1.55;
+}
+
+.cl-round {
+ display: flex;
+ justify-content: center;
+ gap: clamp(var(--space-5, 20px), 6vw, var(--space-9, 48px));
+ margin: var(--space-6, 24px) 0 var(--space-5, 20px);
+}
+.cl-round-stat { text-align: center; }
+.cl-round-stat dt {
+ font: 600 var(--text-2xs, 11px) / 1 var(--font-mono);
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ color: var(--ink-faint);
+ margin-bottom: 6px;
+}
+.cl-round-stat dd {
+ margin: 0;
+ font: 700 var(--text-xl, 1.6rem) / 1 var(--font-display);
+ color: var(--ink-bright);
+ font-variant-numeric: tabular-nums;
+}
+.cl-round-stat-timer dd { color: var(--warn); }
+
+.cl-tabs {
+ display: inline-flex;
+ gap: 4px;
+ padding: 4px;
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ background: var(--surface-1);
+}
+.cl-tab {
+ appearance: none;
+ border: 0;
+ background: transparent;
+ color: var(--ink-dim);
+ font: 600 var(--text-ui, 14px) / 1 var(--font-body);
+ padding: 9px 16px;
+ border-radius: var(--radius-pill);
+ cursor: pointer;
+ text-decoration: none;
+ transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);
+}
+.cl-tab:hover { color: var(--ink-bright); }
+.cl-tab.active { background: var(--surface-3); color: var(--ink-bright); }
+.cl-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.cl-tab-link { color: var(--ink-faint); }
+
+/* ── Arena ──────────────────────────────────────────────────────────────── */
+.cl-arena { display: grid; gap: var(--space-4, 16px); }
+
+.cl-battle {
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-lg);
+ background: var(--surface-1);
+ padding: var(--space-4, 16px) clamp(var(--space-4, 16px), 3vw, var(--space-6, 24px));
+ display: grid;
+ grid-template-columns: 1fr minmax(120px, 1.2fr) 1fr;
+ align-items: center;
+ gap: var(--space-3, 12px);
+ box-shadow: var(--shadow-1);
+ transition: border-color var(--duration-base) var(--ease-standard), transform var(--duration-base) var(--ease-standard);
+ animation: cl-rise var(--duration-slow) var(--ease-out) both;
+}
+.cl-battle:hover { border-color: var(--stroke-strong); }
+@keyframes cl-rise {
+ from { opacity: 0; transform: translateY(10px); }
+ to { opacity: 1; transform: none; }
+}
+
+.cl-side { display: flex; flex-direction: column; align-items: center; gap: var(--space-2, 8px); text-align: center; }
+.cl-side-b { order: 3; }
+.cl-avatar {
+ width: 56px;
+ height: 56px;
+ border-radius: var(--radius-md);
+ object-fit: cover;
+ background: var(--surface-2);
+ border: 1px solid var(--stroke);
+}
+.cl-avatar.cl-avatar-ph {
+ display: grid;
+ place-items: center;
+ font: 800 var(--text-lg) var(--font-display);
+ color: var(--ink-dim);
+}
+.cl-sym { font: 700 var(--text-lg, 1.2rem) / 1 var(--font-display); color: var(--ink-bright); }
+.cl-meta { font: 500 var(--text-2xs, 11px) / 1.3 var(--font-mono); color: var(--ink-faint); }
+.cl-rec {
+ font: 600 var(--text-2xs, 11px) / 1 var(--font-mono);
+ color: var(--ink-dim);
+ letter-spacing: 0.04em;
+}
+.cl-rec b { color: var(--success); }
+.cl-rec i { color: var(--danger); font-style: normal; }
+
+.cl-fight {
+ appearance: none;
+ border: 1px solid var(--stroke-strong);
+ background: var(--surface-2);
+ color: var(--ink-bright);
+ font: 700 var(--text-sm, 12px) / 1 var(--font-body);
+ padding: 8px 14px;
+ border-radius: var(--radius-pill);
+ cursor: pointer;
+ transition: background var(--duration-fast) var(--ease-standard), transform var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard);
+}
+.cl-fight:hover { background: var(--surface-3); border-color: var(--accent); transform: translateY(-1px); }
+.cl-fight:active { transform: translateY(0); }
+.cl-fight:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.cl-fight.is-mine {
+ background: color-mix(in srgb, var(--success) 22%, transparent);
+ border-color: var(--success);
+ color: var(--ink-bright);
+}
+
+/* Center: tug-of-war */
+.cl-vs { order: 2; display: flex; flex-direction: column; align-items: center; gap: var(--space-2, 8px); }
+.cl-tug {
+ position: relative;
+ width: 100%;
+ height: 14px;
+ border-radius: var(--radius-pill);
+ overflow: hidden;
+ background: color-mix(in srgb, var(--accent) 16%, transparent);
+ border: 1px solid var(--stroke);
+}
+.cl-tug-fill {
+ position: absolute;
+ inset: 0 auto 0 0;
+ width: 50%;
+ background: linear-gradient(90deg, color-mix(in srgb, var(--danger) 75%, transparent), var(--danger));
+ transition: width var(--duration-base) var(--ease-standard);
+}
+.cl-tug-mid {
+ position: absolute;
+ top: -3px;
+ bottom: -3px;
+ left: 50%;
+ width: 2px;
+ background: var(--ink-faint);
+ transform: translateX(-50%);
+}
+.cl-powers { display: flex; justify-content: space-between; width: 100%; font: 700 var(--text-md, 13px) / 1 var(--font-mono); }
+.cl-powers .cl-pa { color: var(--danger); }
+.cl-powers .cl-pb { color: var(--accent); }
+.cl-vs-label { font: 800 var(--text-2xs, 11px) / 1 var(--font-display); letter-spacing: 0.16em; color: var(--ink-faint); }
+.cl-mom { font: 500 var(--text-2xs, 11px) / 1 var(--font-mono); color: var(--ink-faint); }
+.cl-mom b { color: var(--warn); }
+
+/* The "b" side accents flip to the cool color for clarity */
+.cl-side-b .cl-fight.is-mine { background: color-mix(in srgb, var(--accent) 22%, transparent); border-color: var(--accent); }
+
+.cl-bye {
+ text-align: center;
+ color: var(--ink-faint);
+ font: 500 var(--text-sm, 12px) / 1.4 var(--font-mono);
+ padding: var(--space-3, 12px);
+ border: 1px dashed var(--stroke);
+ border-radius: var(--radius-lg);
+}
+
+/* States */
+.cl-state {
+ text-align: center;
+ padding: var(--space-9, 48px) var(--space-4, 16px);
+ color: var(--ink-dim);
+ border: 1px dashed var(--stroke);
+ border-radius: var(--radius-lg);
+ background: var(--surface-1);
+}
+.cl-state h2 { margin: 0 0 var(--space-2, 8px); font: 700 var(--text-lg) var(--font-display); color: var(--ink-bright); }
+.cl-state p { margin: 0 auto; max-width: 44ch; line-height: 1.5; }
+.cl-state .cl-fight { margin-top: var(--space-4, 16px); display: inline-block; }
+.cl-skel {
+ height: 110px;
+ border-radius: var(--radius-lg);
+ background: linear-gradient(100deg, var(--surface-1) 30%, var(--surface-2) 50%, var(--surface-1) 70%);
+ background-size: 200% 100%;
+ animation: cl-shimmer 1.4s linear infinite;
+}
+@keyframes cl-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+
+/* ── Standings ──────────────────────────────────────────────────────────── */
+.cl-standings { display: grid; gap: var(--space-2, 8px); }
+.cl-row {
+ display: grid;
+ grid-template-columns: 32px 1fr auto auto;
+ align-items: center;
+ gap: var(--space-3, 12px);
+ padding: var(--space-3, 12px) var(--space-4, 16px);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ background: var(--surface-1);
+ transition: border-color var(--duration-fast) var(--ease-standard);
+}
+.cl-row:hover { border-color: var(--stroke-strong); }
+.cl-rank { font: 800 var(--text-lg) var(--font-display); color: var(--ink-faint); text-align: center; }
+.cl-row:nth-child(1) .cl-rank { color: var(--warn); }
+.cl-row-id { display: flex; align-items: center; gap: var(--space-3, 12px); min-width: 0; }
+.cl-row-id .cl-avatar { width: 38px; height: 38px; }
+.cl-row-id .cl-sym { font-size: var(--text-md); }
+.cl-row-id small { color: var(--ink-faint); font: 500 var(--text-2xs) var(--font-mono); display: block; }
+.cl-wl { font: 700 var(--text-md, 13px) / 1 var(--font-mono); text-align: right; }
+.cl-wl b { color: var(--success); }
+.cl-wl i { color: var(--danger); font-style: normal; }
+.cl-wr { font: 600 var(--text-sm) var(--font-mono); color: var(--ink-dim); text-align: right; min-width: 56px; }
+
+/* ── Rally dock ─────────────────────────────────────────────────────────── */
+.cl-rally {
+ position: fixed;
+ left: 50%;
+ bottom: clamp(12px, 3vh, 28px);
+ transform: translateX(-50%);
+ z-index: 60;
+ width: min(440px, calc(100vw - 24px));
+ animation: cl-dock var(--duration-base) var(--ease-emphasized) both;
+}
+@keyframes cl-dock { from { opacity: 0; transform: translate(-50%, 16px); } to { opacity: 1; transform: translate(-50%, 0); } }
+.cl-rally-inner {
+ position: relative;
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-lg);
+ background: color-mix(in srgb, var(--bg-1) 88%, transparent);
+ backdrop-filter: blur(16px);
+ box-shadow: var(--shadow-3);
+ padding: var(--space-4, 16px);
+ text-align: center;
+}
+.cl-rally-close {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ appearance: none;
+ border: 0;
+ background: transparent;
+ color: var(--ink-faint);
+ font-size: 16px;
+ width: 28px;
+ height: 28px;
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+}
+.cl-rally-close:hover { color: var(--ink-bright); background: var(--surface-2); }
+.cl-rally-id { display: flex; align-items: center; gap: var(--space-3, 12px); text-align: left; margin-bottom: var(--space-3, 12px); }
+.cl-rally-img { width: 42px; height: 42px; border-radius: var(--radius-md); object-fit: cover; background: var(--surface-2); border: 1px solid var(--stroke); }
+.cl-rally-id-text { display: flex; flex-direction: column; line-height: 1.25; min-width: 0; }
+.cl-rally-for { font: 500 var(--text-2xs) var(--font-mono); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.08em; }
+.cl-rally-id-text strong { font: 800 var(--text-lg) var(--font-display); color: var(--ink-bright); }
+.cl-rally-hold { font: 500 var(--text-2xs) var(--font-mono); color: var(--success); }
+
+.cl-tap {
+ position: relative;
+ appearance: none;
+ width: 150px;
+ height: 150px;
+ margin: 0 auto var(--space-3, 12px);
+ display: grid;
+ place-items: center;
+ border-radius: var(--radius-pill);
+ border: 2px solid var(--danger);
+ background: radial-gradient(circle at 50% 35%, color-mix(in srgb, var(--danger) 32%, transparent), color-mix(in srgb, var(--danger) 8%, transparent));
+ color: var(--ink-bright);
+ cursor: pointer;
+ user-select: none;
+ -webkit-user-select: none;
+ touch-action: manipulation;
+ transition: transform 70ms var(--ease-standard), box-shadow 70ms var(--ease-standard);
+ box-shadow: 0 0 0 0 color-mix(in srgb, var(--danger) 40%, transparent);
+}
+.cl-tap:active, .cl-tap.is-hit { transform: scale(0.94); box-shadow: 0 0 36px 2px color-mix(in srgb, var(--danger) 45%, transparent); }
+.cl-tap:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }
+.cl-tap-label { font: 800 var(--text-xl) var(--font-display); letter-spacing: 0.08em; }
+.cl-tap-ring { position: absolute; inset: -2px; border-radius: var(--radius-pill); border: 2px solid transparent; }
+.cl-tap.is-hit .cl-tap-ring { animation: cl-ring 360ms var(--ease-out); }
+@keyframes cl-ring { from { box-shadow: 0 0 0 0 color-mix(in srgb, var(--danger) 50%, transparent); } to { box-shadow: 0 0 0 20px transparent; } }
+.cl-tap-combo {
+ position: absolute;
+ top: 12px;
+ right: 14px;
+ font: 800 var(--text-sm) var(--font-mono);
+ color: var(--warn);
+ opacity: 0;
+ transition: opacity var(--duration-fast);
+}
+.cl-tap-combo.show { opacity: 1; }
+
+/* Floating "+N" power chips on tap */
+.cl-pop {
+ position: absolute;
+ left: 50%;
+ top: 30%;
+ transform: translateX(-50%);
+ font: 800 var(--text-md) var(--font-mono);
+ color: var(--warn);
+ pointer-events: none;
+ animation: cl-float 700ms var(--ease-out) forwards;
+}
+@keyframes cl-float { from { opacity: 1; transform: translate(-50%, 0); } to { opacity: 0; transform: translate(-50%, -42px); } }
+
+.cl-rally-stats { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-3, 12px); margin-bottom: var(--space-2, 8px); }
+.cl-rs { text-align: left; }
+.cl-rs-k { font: 500 var(--text-2xs) var(--font-mono); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.08em; }
+.cl-rs-v { display: block; font: 700 var(--text-lg) var(--font-display); color: var(--ink-bright); font-variant-numeric: tabular-nums; }
+.cl-rs-v i { font-style: normal; color: var(--ink-faint); font-size: var(--text-sm); font-weight: 500; }
+.cl-cap { height: 5px; border-radius: var(--radius-pill); background: var(--surface-3); overflow: hidden; margin-top: 5px; }
+.cl-cap-fill { display: block; height: 100%; width: 0; background: var(--success); transition: width var(--duration-base) var(--ease-standard); }
+.cl-cap-fill.is-full { background: var(--warn); }
+.cl-rally-hint { margin: var(--space-2, 8px) 0 0; font: 500 var(--text-2xs) var(--font-mono); color: var(--ink-faint); }
+.cl-rally-hint kbd {
+ font-family: var(--font-mono);
+ background: var(--surface-3);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-sm);
+ padding: 1px 5px;
+}
+.cl-rally-hint.is-error { color: var(--danger); }
+.cl-rally-hint.is-ok { color: var(--success); }
+
+/* ── Responsive ─────────────────────────────────────────────────────────── */
+@media (max-width: 640px) {
+ .cl-battle { grid-template-columns: 1fr; }
+ .cl-side-b { order: 0; }
+ .cl-vs { order: 1; width: 100%; }
+ .cl-round { gap: var(--space-5, 20px); }
+ .cl-row { grid-template-columns: 28px 1fr auto; }
+ .cl-wr { display: none; }
+}
diff --git a/src/clash.js b/src/clash.js
new file mode 100644
index 000000000..0fee4ffe4
--- /dev/null
+++ b/src/clash.js
@@ -0,0 +1,626 @@
+// Coin Clash — token-gated community battle arena (client).
+//
+// Flow: poll /api/clash/state for the live bracket → render battle cards with a
+// tug-of-war bar → "Fight for X" connects the wallet, signs a faction-bound
+// challenge, and exchanges it for a war pass (server verifies the signature and
+// a live on-chain holding of the coin) → the rally dock opens and every tap is
+// batched and flushed to /api/clash/rally as battle power for that faction.
+//
+// Real data only: factions + records from the API, holdings gated on-chain.
+// The tap UI is pure juice; the server clamps taps and caps per-wallet power, so
+// the leaderboard reflects an army's effort, not a script.
+
+import { initWalletButton, getConnectedWallet, getConnectedWalletAddress } from './wallet.js';
+import { log } from './shared/log.js';
+
+const $ = (id) => document.getElementById(id);
+const API = '/api/clash';
+
+// ── Local game state ─────────────────────────────────────────────────────────
+const game = {
+ state: null, // last /state payload
+ tab: 'arena',
+ pollTimer: null,
+ timerRaf: null,
+ enlist: null, // { token, symbol, image, warPass, amount, walletPower, cap }
+ pendingTaps: 0, // taps accumulated since last flush
+ flushing: false,
+ flushTimer: null,
+ combo: 0,
+ comboTimer: null,
+};
+
+// ── Small DOM helper ─────────────────────────────────────────────────────────
+function el(tag, props = {}, kids = []) {
+ const n = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (v == null) continue;
+ if (k === 'class') n.className = v;
+ else if (k === 'text') n.textContent = v;
+ else if (k === 'html') n.innerHTML = v;
+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);
+ else if (k === 'dataset') Object.assign(n.dataset, v);
+ else n.setAttribute(k, v);
+ }
+ for (const kid of [].concat(kids)) {
+ if (kid == null) continue;
+ n.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);
+ }
+ return n;
+}
+
+function short(addr) {
+ return addr ? `${addr.slice(0, 4)}…${addr.slice(-4)}` : '';
+}
+function fmtNum(n) {
+ n = Math.round(Number(n) || 0);
+ if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`;
+ return String(n);
+}
+function fmtTime(ms) {
+ const s = Math.max(0, Math.floor(ms / 1000));
+ const m = Math.floor(s / 60);
+ const r = s % 60;
+ if (m >= 60) {
+ const h = Math.floor(m / 60);
+ return `${h}h ${m % 60}m`;
+ }
+ return `${m}:${String(r).padStart(2, '0')}`;
+}
+function fmtUsd(n) {
+ n = Number(n) || 0;
+ if (n <= 0) return '';
+ if (n < 0.01) return '<$0.01';
+ return `$${n < 1 ? n.toFixed(3) : n.toLocaleString(undefined, { maximumFractionDigits: 2 })}`;
+}
+
+async function apiGet(action, params = '') {
+ const r = await fetch(`${API}/${action}${params}`, { credentials: 'include' });
+ const body = await r.json().catch(() => ({}));
+ if (!r.ok) throw Object.assign(new Error(body.error_description || body.error || `HTTP ${r.status}`), { status: r.status, code: body.error });
+ return body.data;
+}
+async function apiPost(action, payload) {
+ const r = await fetch(`${API}/${action}`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ const body = await r.json().catch(() => ({}));
+ if (!r.ok) throw Object.assign(new Error(body.error_description || body.error || `HTTP ${r.status}`), { status: r.status, code: body.error });
+ return body.data;
+}
+
+// ── Avatar (image or seeded initials) ────────────────────────────────────────
+function avatar(side, cls = 'cl-avatar') {
+ if (side.image) return el('img', { class: cls, src: side.image, alt: side.symbol || '', loading: 'lazy', referrerpolicy: 'no-referrer' });
+ const label = (side.symbol || side.token || '?').replace(/^\$/, '').slice(0, 2).toUpperCase();
+ return el('div', { class: `${cls} cl-avatar-ph`, text: label, 'aria-hidden': 'true' });
+}
+
+// ── Render: arena ────────────────────────────────────────────────────────────
+function renderArena(data) {
+ const root = $('cl-arena');
+ root.setAttribute('aria-busy', 'false');
+
+ if (!data || (!data.arena?.length && !data.bye)) {
+ root.replaceChildren(emptyState());
+ return;
+ }
+
+ const mine = game.enlist?.token || null;
+ const frag = document.createDocumentFragment();
+
+ for (const bt of data.arena) {
+ frag.appendChild(battleCard(bt, mine));
+ }
+ if (data.bye) {
+ frag.appendChild(
+ el('div', { class: 'cl-bye' }, [
+ `${data.bye.symbol || short(data.bye.token)} drew a bye this round — they advance unopposed. Rally them up for the next clash.`,
+ ]),
+ );
+ }
+ root.replaceChildren(frag);
+}
+
+function sideBlock(side, which, mine) {
+ const isMine = mine && side.token === mine;
+ const rec = side.record || { w: 0, l: 0 };
+ return el('div', { class: `cl-side cl-side-${which}` }, [
+ avatar(side),
+ el('span', { class: 'cl-sym', text: side.symbol || short(side.token) }),
+ el('span', { class: 'cl-meta', text: `${fmtNum(side.members)} members${side.priceUsd ? ` · ${fmtUsd(side.priceUsd)}` : ''}` }),
+ el('span', { class: 'cl-rec', html: `<b>${rec.w}W</b> · <i>${rec.l}L</i>` }),
+ el('button', {
+ class: `cl-fight${isMine ? ' is-mine' : ''}`,
+ type: 'button',
+ text: isMine ? '✓ Your army' : 'Fight',
+ dataset: { token: side.token, symbol: side.symbol || '', image: side.image || '' },
+ 'aria-pressed': isMine ? 'true' : 'false',
+ onclick: () => onFight(side),
+ }),
+ ]);
+}
+
+function battleCard(bt, mine) {
+ const a = bt.a;
+ const b = bt.b;
+ if (!b) {
+ return el('div', { class: 'cl-bye' }, [`${a.symbol || short(a.token)} stands alone this round.`]);
+ }
+ const aPct = Math.round((bt.aShare ?? 0.5) * 100);
+ const center = el('div', { class: 'cl-vs' }, [
+ el('div', { class: 'cl-tug' }, [
+ el('span', { class: 'cl-tug-fill', style: `width:${aPct}%` }),
+ el('span', { class: 'cl-tug-mid' }),
+ ]),
+ el('div', { class: 'cl-powers' }, [
+ el('span', { class: 'cl-pa', text: fmtNum(a.power) }),
+ el('span', { class: 'cl-vs-label', text: 'VS' }),
+ el('span', { class: 'cl-pb', text: fmtNum(b.power) }),
+ ]),
+ el('div', { class: 'cl-mom', html: `momentum <b>×${(a.momentum || 1).toFixed(2)}</b> / <b>×${(b.momentum || 1).toFixed(2)}</b>` }),
+ ]);
+ return el('article', { class: 'cl-battle' }, [sideBlock(a, 'a', mine), center, sideBlock(b, 'b', mine)]);
+}
+
+function emptyState() {
+ return el('div', { class: 'cl-state' }, [
+ el('h2', { text: 'No battles live right now' }),
+ el('p', { text: 'Coin Clash needs at least two active coin communities to field a bracket. Check the communities lobby, then come back when the armies muster.' }),
+ el('a', { class: 'cl-fight', href: '/communities', text: 'Browse communities →' }),
+ ]);
+}
+
+function errorState(message, onRetry) {
+ const node = el('div', { class: 'cl-state' }, [
+ el('h2', { text: 'Couldn’t load the arena' }),
+ el('p', { text: message || 'Something went wrong reaching the battle server.' }),
+ el('button', { class: 'cl-fight', type: 'button', text: 'Try again', onclick: onRetry }),
+ ]);
+ return node;
+}
+
+// ── Render: standings ────────────────────────────────────────────────────────
+async function renderStandings() {
+ const root = $('cl-standings');
+ root.replaceChildren(el('div', { class: 'cl-skel' }), el('div', { class: 'cl-skel' }), el('div', { class: 'cl-skel' }));
+ let data;
+ try {
+ data = await apiGet('leaderboard');
+ } catch (err) {
+ root.replaceChildren(errorState(err.message, () => renderStandings()));
+ return;
+ }
+ const board = data?.board || [];
+ if (!board.length) {
+ root.replaceChildren(
+ el('div', { class: 'cl-state' }, [
+ el('h2', { text: 'No war record yet' }),
+ el('p', { text: 'The first battles haven’t been settled. Enlist, rally, and your faction’s wins will land here.' }),
+ ]),
+ );
+ return;
+ }
+ const frag = document.createDocumentFragment();
+ board.forEach((f, i) => {
+ frag.appendChild(
+ el('div', { class: 'cl-row' }, [
+ el('span', { class: 'cl-rank', text: i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : String(i + 1) }),
+ el('div', { class: 'cl-row-id' }, [
+ avatar(f),
+ el('div', {}, [
+ el('span', { class: 'cl-sym', text: f.symbol || short(f.token) }),
+ el('small', { text: `${fmtNum(f.members)} members · ${fmtNum(f.power)} lifetime power` }),
+ ]),
+ ]),
+ el('span', { class: 'cl-wl', html: `<b>${f.w}W</b> · <i>${f.l}L</i>${f.d ? ` · ${f.d}D` : ''}` }),
+ el('span', { class: 'cl-wr', text: f.winRate == null ? '—' : `${f.winRate}%` }),
+ ]),
+ );
+ });
+ root.replaceChildren(frag);
+}
+
+// ── State polling + round timer ──────────────────────────────────────────────
+async function poll() {
+ try {
+ const data = await apiGet('state');
+ game.state = data;
+ $('cl-round-no').textContent = `#${data.epoch}`;
+ $('cl-round-armies').textContent = String(data.factionCount || 0);
+ if (game.tab === 'arena') renderArena(data);
+ // Keep the rally dock's army number in sync with the broader poll.
+ if (game.enlist) {
+ const side = findSide(data, game.enlist.token);
+ if (side) $('cl-army-power').textContent = fmtNum(side.power);
+ }
+ } catch (err) {
+ if (game.tab === 'arena' && !game.state) {
+ $('cl-arena').replaceChildren(
+ errorState(
+ err.code === 'cc_unconfigured'
+ ? 'Community battles aren’t configured on this deployment yet.'
+ : err.message,
+ () => poll(),
+ ),
+ );
+ $('cl-arena').setAttribute('aria-busy', 'false');
+ }
+ log.warn('clash state poll failed', err);
+ }
+}
+
+function findSide(data, token) {
+ for (const bt of data?.arena || []) {
+ if (bt.a?.token === token) return bt.a;
+ if (bt.b?.token === token) return bt.b;
+ }
+ if (data?.bye?.token === token) return data.bye;
+ return null;
+}
+
+function startTimer() {
+ const tick = () => {
+ if (game.state?.endsAt) {
+ const left = game.state.endsAt - Date.now();
+ $('cl-round-timer').textContent = fmtTime(left);
+ }
+ game.timerRaf = requestAnimationFrame(() => setTimeout(tick, 500));
+ };
+ tick();
+}
+
+// ── Enlist flow ──────────────────────────────────────────────────────────────
+async function ensureWallet() {
+ let addr = getConnectedWalletAddress();
+ if (addr) return addr;
+ const provider = (typeof window !== 'undefined' && window.solana) || null;
+ if (!provider) {
+ window.open('https://phantom.app/', '_blank', 'noopener');
+ return null;
+ }
+ try {
+ const res = await provider.connect();
+ return res?.publicKey?.toString?.() || null;
+ } catch {
+ return null;
+ }
+}
+
+async function onFight(side) {
+ // Already enlisted in this faction → just reopen the dock.
+ if (game.enlist?.token === side.token) {
+ showRally();
+ return;
+ }
+ const btns = [...document.querySelectorAll(`.cl-fight[data-token="${cssEsc(side.token)}"]`)];
+ const setBusy = (t) => btns.forEach((b) => { b.disabled = true; b.textContent = t; });
+ const restore = () => btns.forEach((b) => { b.disabled = false; b.textContent = 'Fight'; });
+
+ setBusy('Connecting…');
+ const wallet = await ensureWallet();
+ if (!wallet) {
+ restore();
+ toast('Connect a Solana wallet to enlist.', true);
+ return;
+ }
+
+ try {
+ setBusy('Signing…');
+ const provider = getConnectedWallet() || window.solana;
+ if (!provider?.signMessage) throw new Error('Wallet can’t sign messages.');
+
+ const { message } = await apiPost('enlist', { token: side.token, wallet });
+ const encoded = new TextEncoder().encode(message);
+ const signed = await provider.signMessage(encoded, 'utf8');
+ const sigBytes = signed?.signature ?? signed;
+ const bs58 = (await import('bs58')).default;
+ const signature = bs58.encode(sigBytes);
+
+ setBusy('Verifying…');
+ const res = await apiPost('enlist-verify', { token: side.token, wallet, message, signature });
+ if (!res.eligible) {
+ restore();
+ toast(`You don’t hold ${side.symbol || 'this coin'} — grab some to join its army.`, true);
+ return;
+ }
+
+ game.enlist = {
+ token: side.token,
+ symbol: side.symbol || short(side.token),
+ image: side.image || '',
+ wallet,
+ warPass: res.warPass,
+ amount: res.amount,
+ usd: res.usd,
+ walletPower: 0,
+ cap: 5000,
+ };
+ openRallyDock();
+ // Refresh "Your army" buttons across the arena.
+ if (game.state) renderArena(game.state);
+ toast(`Enlisted in ${game.enlist.symbol}. Rally!`, false);
+ } catch (err) {
+ restore();
+ if (err?.code === 4001 || /reject/i.test(err?.message || '')) toast('Signature declined.', true);
+ else toast(err.message || 'Enlistment failed.', true);
+ log.warn('enlist failed', err);
+ }
+}
+
+function cssEsc(s) {
+ return (window.CSS && CSS.escape ? CSS.escape(s) : String(s).replace(/["\\]/g, '\\$&'));
+}
+
+// ── Rally dock ───────────────────────────────────────────────────────────────
+function openRallyDock() {
+ const e = game.enlist;
+ $('cl-rally-symbol').textContent = e.symbol;
+ $('cl-rally-hold').textContent = e.usd ? `holding ${fmtUsd(e.usd)}` : `holder · ${short(e.wallet)}`;
+ const img = $('cl-rally-img');
+ if (e.image) {
+ img.src = e.image;
+ img.style.display = '';
+ } else img.style.display = 'none';
+ updateRallyStats();
+ showRally();
+}
+function showRally() {
+ $('cl-rally').hidden = false;
+}
+function hideRally() {
+ $('cl-rally').hidden = true;
+}
+
+function updateRallyStats() {
+ const e = game.enlist;
+ if (!e) return;
+ $('cl-your-power').textContent = fmtNum(e.walletPower);
+ $('cl-your-cap').textContent = ` / ${fmtNum(e.cap)}`;
+ const pct = Math.min(100, (e.walletPower / e.cap) * 100);
+ const fill = $('cl-cap-fill');
+ fill.style.width = `${pct}%`;
+ fill.classList.toggle('is-full', pct >= 100);
+ const side = game.state && findSide(game.state, e.token);
+ if (side) $('cl-army-power').textContent = fmtNum(side.power);
+}
+
+// Tap handling — accumulate locally, flush on a cadence.
+function onTap() {
+ if (!game.enlist) return;
+ if (game.enlist.walletPower >= game.enlist.cap) {
+ setHint('You’ve hit your power cap for this round — your army carries on without you. 🛡️', 'ok');
+ return;
+ }
+ game.pendingTaps += 1;
+ game.combo += 1;
+
+ // Optimistic local bump (server is authoritative on next flush).
+ game.enlist.walletPower = Math.min(game.enlist.cap, game.enlist.walletPower + 1);
+ updateRallyStats();
+ tapJuice();
+ scheduleFlush();
+
+ clearTimeout(game.comboTimer);
+ const comboEl = $('cl-combo');
+ comboEl.textContent = `×${Math.min(99, Math.floor(game.combo / 5) + 1)}`;
+ comboEl.classList.toggle('show', game.combo >= 5);
+ game.comboTimer = setTimeout(() => {
+ game.combo = 0;
+ comboEl.classList.remove('show');
+ }, 1200);
+}
+
+function tapJuice() {
+ const tap = $('cl-tap');
+ tap.classList.remove('is-hit');
+ void tap.offsetWidth; // restart animation
+ tap.classList.add('is-hit');
+ const pop = el('span', { class: 'cl-pop', text: '+1' });
+ tap.appendChild(pop);
+ setTimeout(() => pop.remove(), 700);
+}
+
+function scheduleFlush() {
+ // Flush quickly once a burst settles, or immediately past a batch size.
+ if (game.pendingTaps >= 25) return flush();
+ if (game.flushTimer) return;
+ game.flushTimer = setTimeout(flush, 650);
+}
+
+async function flush() {
+ clearTimeout(game.flushTimer);
+ game.flushTimer = null;
+ if (game.flushing || !game.enlist || game.pendingTaps <= 0) return;
+ const taps = Math.min(50, game.pendingTaps);
+ game.pendingTaps -= taps;
+ game.flushing = true;
+ try {
+ const res = await apiPost('rally', { pass: game.enlist.warPass, taps });
+ // Adopt server-authoritative numbers.
+ game.enlist.walletPower = res.walletPower;
+ game.enlist.cap = res.walletCap;
+ if (game.state) {
+ const side = findSide(game.state, game.enlist.token);
+ if (side) side.power = res.factionPower;
+ }
+ updateRallyStats();
+ if (res.capped) setHint('Power cap reached for this round — well fought, soldier. 🛡️', 'ok');
+ else setHint('Tap the target or hold <kbd>Space</kbd> to rally.');
+ } catch (err) {
+ if (err.status === 401 || err.code === 'pass_invalid') {
+ // Pass expired — re-enlist transparently if the wallet is still around.
+ setHint('Your war pass expired — re-enlisting…', 'error');
+ const token = game.enlist.token;
+ game.enlist = null;
+ hideRally();
+ const live = game.state && findSide(game.state, token);
+ if (live) onFight(live);
+ } else if (err.status === 429) {
+ // Rallying too fast — push the taps back and retry shortly.
+ game.pendingTaps += taps;
+ setHint('Rallying hard! Pacing your taps…');
+ setTimeout(scheduleFlush, 1400);
+ } else {
+ game.pendingTaps += taps;
+ setHint(err.message || 'Rally failed — retrying.', 'error');
+ setTimeout(scheduleFlush, 1500);
+ }
+ log.warn('rally flush failed', err);
+ } finally {
+ game.flushing = false;
+ if (game.pendingTaps > 0) scheduleFlush();
+ }
+}
+
+function setHint(html, kind = '') {
+ const h = $('cl-rally-hint');
+ h.innerHTML = html;
+ h.classList.toggle('is-error', kind === 'error');
+ h.classList.toggle('is-ok', kind === 'ok');
+}
+
+// Lightweight transient toast reusing the rally hint when the dock is hidden.
+let toastTimer = null;
+function toast(msg, isError) {
+ // If the dock is open, surface it inline; else use a floating banner.
+ if (game.enlist && !$('cl-rally').hidden) {
+ setHint(msg, isError ? 'error' : 'ok');
+ return;
+ }
+ let bn = $('cl-toast');
+ if (!bn) {
+ bn = el('div', { id: 'cl-toast' });
+ Object.assign(bn.style, {
+ position: 'fixed', left: '50%', bottom: '24px', transform: 'translateX(-50%)',
+ zIndex: '70', padding: '10px 18px', borderRadius: '999px', maxWidth: '90vw',
+ font: '600 13px/1.3 var(--font-body)', boxShadow: 'var(--shadow-3)',
+ border: '1px solid var(--stroke-strong)', background: 'color-mix(in srgb, var(--bg-1) 92%, transparent)',
+ backdropFilter: 'blur(12px)', textAlign: 'center',
+ });
+ document.body.appendChild(bn);
+ }
+ bn.textContent = msg;
+ bn.style.color = isError ? 'var(--danger)' : 'var(--success)';
+ bn.style.opacity = '1';
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => { bn.style.opacity = '0'; bn.style.transition = 'opacity .3s'; }, 3200);
+}
+
+// ── Tabs ─────────────────────────────────────────────────────────────────────
+function setTab(tab) {
+ game.tab = tab;
+ document.querySelectorAll('.cl-tab[data-tab]').forEach((b) => {
+ const on = b.dataset.tab === tab;
+ b.classList.toggle('active', on);
+ b.setAttribute('aria-selected', on ? 'true' : 'false');
+ });
+ $('cl-arena').hidden = tab !== 'arena';
+ $('cl-standings').hidden = tab !== 'standings';
+ if (tab === 'arena' && game.state) renderArena(game.state);
+ if (tab === 'standings') renderStandings();
+}
+
+// ── Ambient particle field ───────────────────────────────────────────────────
+function startField() {
+ const canvas = $('cl-field');
+ if (!canvas || window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
+ const ctx = canvas.getContext('2d');
+ let w, h, parts;
+ const resize = () => {
+ w = canvas.width = window.innerWidth;
+ h = canvas.height = window.innerHeight;
+ const count = Math.min(70, Math.floor((w * h) / 26000));
+ parts = Array.from({ length: count }, () => ({
+ x: Math.random() * w, y: Math.random() * h,
+ vx: (Math.random() - 0.5) * 0.25, vy: (Math.random() - 0.5) * 0.25,
+ r: Math.random() * 1.6 + 0.4,
+ }));
+ };
+ resize();
+ window.addEventListener('resize', resize, { passive: true });
+ let raf;
+ const draw = () => {
+ ctx.clearRect(0, 0, w, h);
+ ctx.fillStyle = 'rgba(248,113,113,0.5)';
+ for (const p of parts) {
+ p.x += p.vx; p.y += p.vy;
+ if (p.x < 0 || p.x > w) p.vx *= -1;
+ if (p.y < 0 || p.y > h) p.vy *= -1;
+ ctx.beginPath();
+ ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ raf = requestAnimationFrame(draw);
+ };
+ draw();
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) cancelAnimationFrame(raf);
+ else draw();
+ });
+}
+
+// ── Boot ─────────────────────────────────────────────────────────────────────
+function boot() {
+ initWalletButton();
+ startField();
+
+ document.querySelectorAll('.cl-tab[data-tab]').forEach((b) => {
+ b.addEventListener('click', () => setTab(b.dataset.tab));
+ });
+
+ // Rally interactions.
+ const tap = $('cl-tap');
+ tap.addEventListener('pointerdown', (e) => { e.preventDefault(); onTap(); });
+ $('cl-rally-close').addEventListener('click', () => {
+ flush();
+ hideRally();
+ });
+ // Spacebar rallies while the dock is open and focus isn't in a field.
+ let spaceHeld = false;
+ window.addEventListener('keydown', (e) => {
+ if (e.code !== 'Space' && e.key !== ' ') return;
+ if ($('cl-rally').hidden) return;
+ const t = e.target;
+ if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
+ e.preventDefault();
+ if (!spaceHeld) { spaceHeld = true; onTap(); }
+ });
+ window.addEventListener('keyup', (e) => {
+ if (e.code === 'Space' || e.key === ' ') spaceHeld = false;
+ });
+
+ // Re-enlist offer if the wallet changes out from under an active rally.
+ window.addEventListener('wallet:changed', (e) => {
+ const addr = e.detail?.address || null;
+ if (game.enlist && addr && addr !== game.enlist.wallet) {
+ game.enlist = null;
+ hideRally();
+ toast('Wallet switched — enlist again to rally.', false);
+ if (game.state) renderArena(game.state);
+ }
+ });
+
+ // Flush any buffered taps before the tab unloads.
+ window.addEventListener('pagehide', () => {
+ if (game.enlist && game.pendingTaps > 0) {
+ navigator.sendBeacon?.(
+ `${API}/rally`,
+ new Blob([JSON.stringify({ pass: game.enlist.warPass, taps: Math.min(50, game.pendingTaps) })], { type: 'application/json' }),
+ );
+ }
+ });
+
+ startTimer();
+ poll();
+ game.pollTimer = setInterval(() => {
+ if (!document.hidden) poll();
+ }, 5000);
+}
+
+if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);
+else boot();
diff --git a/src/runtime/pose-solve.js b/src/runtime/pose-solve.js
new file mode 100644
index 000000000..e1a052652
--- /dev/null
+++ b/src/runtime/pose-solve.js
@@ -0,0 +1,167 @@
+/**
+ * pose-solve — pure landmark → humanoid bone rotation solver.
+ *
+ * Input: MediaPipe Pose **world** landmarks (BlazePose GHUM, 33 points, metres,
+ * origin at the hip midpoint) as produced by `@mediapipe/tasks-vision`'s
+ * PoseLandmarker `worldLandmarks`. Each landmark is `{ x, y, z, visibility }`.
+ *
+ * Output: a map of canonical bone name → THREE.Quaternion, where each quaternion
+ * is the bone's **world-space orientation delta from its rest (T-pose) direction**
+ * — i.e. the rotation that takes the bone's rest axis onto the measured limb
+ * direction. The runtime (`BodyMocap`) converts these world deltas into each
+ * bone's parent-local frame before applying them, which keeps this module pure
+ * and free of any scene-graph dependency so it can be unit-tested in isolation.
+ *
+ * This is the same family of math Kalidokit performs, re-implemented in-repo to
+ * avoid a new dependency (the codebase already hand-rolls its mocap helpers — see
+ * the note in face-mocap.js). It is deliberately solver-only: no DOM, no webcam,
+ * no three-vrm coupling.
+ *
+ * Coordinate conventions
+ * ──────────────────────
+ * MediaPipe world space: +x → subject's right (in image), +y → down, +z → toward camera
+ * Avatar space (Mixamo): +x → character's left, +y → up, +z → forward (toward viewer)
+ *
+ * The avatar T-pose rest directions (direction a bone points from its head to its
+ * child) are therefore:
+ * LeftArm / LeftForeArm → +x
+ * RightArm / RightForeArm → −x
+ * LeftUpLeg / LeftLeg → −y (down)
+ * RightUpLeg / RightLeg → −y
+ * Spine / Spine1 / Spine2 → +y (up)
+ */
+
+import { Vector3, Quaternion } from 'three';
+
+// ── MediaPipe BlazePose landmark indices ─────────────────────────────────────
+export const LM = Object.freeze({
+ LEFT_SHOULDER: 11, RIGHT_SHOULDER: 12,
+ LEFT_ELBOW: 13, RIGHT_ELBOW: 14,
+ LEFT_WRIST: 15, RIGHT_WRIST: 16,
+ LEFT_HIP: 23, RIGHT_HIP: 24,
+ LEFT_KNEE: 25, RIGHT_KNEE: 26,
+ LEFT_ANKLE: 27, RIGHT_ANKLE: 28,
+});
+
+// Rest (T-pose) bone direction unit vectors in avatar space.
+export const REST_DIR = Object.freeze({
+ LeftArm: new Vector3( 1, 0, 0),
+ LeftForeArm: new Vector3( 1, 0, 0),
+ RightArm: new Vector3(-1, 0, 0),
+ RightForeArm: new Vector3(-1, 0, 0),
+ LeftUpLeg: new Vector3( 0, -1, 0),
+ LeftLeg: new Vector3( 0, -1, 0),
+ RightUpLeg: new Vector3( 0, -1, 0),
+ RightLeg: new Vector3( 0, -1, 0),
+ Spine: new Vector3( 0, 1, 0),
+});
+
+const DEFAULT_MIN_VISIBILITY = 0.5;
+
+// Reusable scratch vectors so the hot path allocates nothing per frame.
+const _a = new Vector3();
+const _b = new Vector3();
+const _dir = new Vector3();
+
+/**
+ * Map a MediaPipe world landmark into avatar space.
+ * @param {{x:number,y:number,z:number}} lm
+ * @param {boolean} mirror — when true, flips X so the avatar mirrors the user
+ * (raise your right hand, the avatar's right hand — as seen by you — rises).
+ * @param {Vector3} out
+ */
+export function landmarkToAvatar(lm, mirror, out = new Vector3()) {
+ const x = mirror ? -lm.x : lm.x;
+ // MP +y is down and +z is toward camera; avatar +y is up and +z is forward.
+ return out.set(x, -lm.y, -lm.z);
+}
+
+function visible(lm, min) {
+ return lm && (lm.visibility == null || lm.visibility >= min);
+}
+
+/**
+ * Solve a limb segment into a world-space rest→target delta quaternion.
+ * @returns {Quaternion|null} null when either endpoint is missing/occluded.
+ */
+function solveSegment(from, to, restDir, mirror, minVis) {
+ if (!visible(from, minVis) || !visible(to, minVis)) return null;
+ landmarkToAvatar(from, mirror, _a);
+ landmarkToAvatar(to, mirror, _b);
+ _dir.subVectors(_b, _a);
+ if (_dir.lengthSq() < 1e-8) return null;
+ _dir.normalize();
+ return new Quaternion().setFromUnitVectors(restDir, _dir);
+}
+
+/**
+ * Solve a full pose frame.
+ *
+ * @param {Array<{x:number,y:number,z:number,visibility?:number}>} world — 33 world landmarks
+ * @param {object} [opts]
+ * @param {boolean} [opts.mirror=false] mirror left/right for a selfie feel
+ * @param {boolean} [opts.legs=true] solve legs (noisy when seated; callers can disable)
+ * @param {number} [opts.minVisibility=0.5] drop joints below this confidence
+ * @returns {{ bones: Record<string, Quaternion>, missing: string[] }}
+ * `bones` holds only the segments that solved this frame; `missing` lists the
+ * canonical names that were dropped (occluded / low confidence) so the runtime
+ * can hold the previous rotation instead of snapping to rest.
+ */
+export function solvePose(world, opts = {}) {
+ const mirror = opts.mirror ?? false;
+ const legs = opts.legs ?? true;
+ const minVis = opts.minVisibility ?? DEFAULT_MIN_VISIBILITY;
+
+ const bones = {};
+ const missing = [];
+ if (!Array.isArray(world) || world.length < 25) {
+ return { bones, missing: ['__no_pose__'] };
+ }
+
+ const seg = (name, fromIdx, toIdx) => {
+ const q = solveSegment(world[fromIdx], world[toIdx], REST_DIR[name], mirror, minVis);
+ if (q) bones[name] = q; else missing.push(name);
+ };
+
+ // Arms — the reliable signal from a single front-facing webcam.
+ seg('LeftArm', LM.LEFT_SHOULDER, LM.LEFT_ELBOW);
+ seg('LeftForeArm', LM.LEFT_ELBOW, LM.LEFT_WRIST);
+ seg('RightArm', LM.RIGHT_SHOULDER, LM.RIGHT_ELBOW);
+ seg('RightForeArm', LM.RIGHT_ELBOW, LM.RIGHT_WRIST);
+
+ // Spine lean — derived from the shoulder-midpoint over the hip-midpoint.
+ const spine = solveSpine(world, mirror, minVis);
+ if (spine) bones.Spine = spine; else missing.push('Spine');
+
+ if (legs) {
+ seg('LeftUpLeg', LM.LEFT_HIP, LM.LEFT_KNEE);
+ seg('LeftLeg', LM.LEFT_KNEE, LM.LEFT_ANKLE);
+ seg('RightUpLeg', LM.RIGHT_HIP, LM.RIGHT_KNEE);
+ seg('RightLeg', LM.RIGHT_KNEE, LM.RIGHT_ANKLE);
+ }
+
+ return { bones, missing };
+}
+
+/**
+ * Spine lean from hip-midpoint → shoulder-midpoint, relative to straight-up.
+ * @returns {Quaternion|null}
+ */
+export function solveSpine(world, mirror, minVis = DEFAULT_MIN_VISIBILITY) {
+ const ls = world[LM.LEFT_SHOULDER], rs = world[LM.RIGHT_SHOULDER];
+ const lh = world[LM.LEFT_HIP], rh = world[LM.RIGHT_HIP];
+ if (![ls, rs, lh, rh].every((p) => visible(p, minVis))) return null;
+
+ landmarkToAvatar(ls, mirror, _a);
+ landmarkToAvatar(rs, mirror, _b);
+ const shoulderMid = _a.clone().add(_b).multiplyScalar(0.5);
+
+ landmarkToAvatar(lh, mirror, _a);
+ landmarkToAvatar(rh, mirror, _b);
+ const hipMid = _a.clone().add(_b).multiplyScalar(0.5);
+
+ _dir.subVectors(shoulderMid, hipMid);
+ if (_dir.lengthSq() < 1e-8) return null;
+ _dir.normalize();
+ return new Quaternion().setFromUnitVectors(REST_DIR.Spine, _dir);
+}
diff --git a/tests/body-mocap-solve.test.js b/tests/body-mocap-solve.test.js
new file mode 100644
index 000000000..d6f5d8ea9
--- /dev/null
+++ b/tests/body-mocap-solve.test.js
@@ -0,0 +1,113 @@
+import { describe, it, expect } from 'vitest';
+import { Vector3 } from 'three';
+import { solvePose, solveSpine, landmarkToAvatar, REST_DIR, LM } from '../src/runtime/pose-solve.js';
+
+// Build a 33-slot landmark array with every joint occluded (visibility 0), then
+// let each test light up only the joints it cares about.
+function blankPose() {
+ return Array.from({ length: 33 }, () => ({ x: 0, y: 0, z: 0, visibility: 0 }));
+}
+
+function set(pose, idx, x, y, z, visibility = 1) {
+ pose[idx] = { x, y, z, visibility };
+}
+
+// Apply a quaternion to a fresh copy of a rest direction.
+function applied(q, restDir) {
+ return restDir.clone().applyQuaternion(q);
+}
+
+describe('landmarkToAvatar', () => {
+ it('flips MediaPipe Y-down/Z-toward-camera into avatar Y-up/Z-forward', () => {
+ const v = landmarkToAvatar({ x: 0.3, y: 0.5, z: 0.2 }, false);
+ expect(v.x).toBeCloseTo(0.3, 6);
+ expect(v.y).toBeCloseTo(-0.5, 6);
+ expect(v.z).toBeCloseTo(-0.2, 6);
+ });
+
+ it('mirror negates X', () => {
+ const v = landmarkToAvatar({ x: 0.3, y: 0.5, z: 0.2 }, true);
+ expect(v.x).toBeCloseTo(-0.3, 6);
+ });
+});
+
+describe('solvePose — arms', () => {
+ it('left arm hanging straight down rotates the +X rest axis onto −Y', () => {
+ const pose = blankPose();
+ set(pose, LM.LEFT_SHOULDER, 0, 0, 0);
+ set(pose, LM.LEFT_ELBOW, 0, 1, 0); // MP +y is down
+ const { bones } = solvePose(pose, { legs: false });
+ expect(bones.LeftArm).toBeDefined();
+ const dir = applied(bones.LeftArm, REST_DIR.LeftArm);
+ expect(dir.x).toBeCloseTo(0, 5);
+ expect(dir.y).toBeCloseTo(-1, 5);
+ expect(dir.z).toBeCloseTo(0, 5);
+ });
+
+ it('forearm solves independently from the upper arm endpoint', () => {
+ const pose = blankPose();
+ set(pose, LM.LEFT_ELBOW, 0, 0, 0);
+ set(pose, LM.LEFT_WRIST, 0, 0, 1); // wrist toward camera (MP +z)
+ const { bones } = solvePose(pose, { legs: false });
+ expect(bones.LeftForeArm).toBeDefined();
+ const dir = applied(bones.LeftForeArm, REST_DIR.LeftForeArm);
+ // avatar +z is forward; MP +z maps to avatar −z
+ expect(dir.z).toBeCloseTo(-1, 5);
+ });
+
+ it('mirror flips the resolved direction across X', () => {
+ const pose = blankPose();
+ set(pose, LM.RIGHT_SHOULDER, 0, 0, 0);
+ set(pose, LM.RIGHT_ELBOW, 2, 0, 0);
+ const plain = solvePose(pose, { legs: false }).bones.RightArm;
+ const mirrored = solvePose(pose, { legs: false, mirror: true }).bones.RightArm;
+ const dirPlain = applied(plain, REST_DIR.RightArm);
+ const dirMirror = applied(mirrored, REST_DIR.RightArm);
+ expect(dirPlain.x).toBeCloseTo(-dirMirror.x, 5);
+ });
+});
+
+describe('solvePose — visibility gating', () => {
+ it('drops a segment when an endpoint is below the visibility threshold', () => {
+ const pose = blankPose();
+ set(pose, LM.LEFT_SHOULDER, 0, 0, 0, 1);
+ set(pose, LM.LEFT_ELBOW, 0, 1, 0, 0.1); // low confidence
+ const { bones, missing } = solvePose(pose, { legs: false, minVisibility: 0.5 });
+ expect(bones.LeftArm).toBeUndefined();
+ expect(missing).toContain('LeftArm');
+ });
+
+ it('reports __no_pose__ for an empty/short landmark array', () => {
+ const { bones, missing } = solvePose([], {});
+ expect(Object.keys(bones)).toHaveLength(0);
+ expect(missing).toContain('__no_pose__');
+ });
+});
+
+describe('solveSpine', () => {
+ it('returns near-identity when the torso is upright', () => {
+ const pose = blankPose();
+ set(pose, LM.LEFT_SHOULDER, -0.2, 0, 0);
+ set(pose, LM.RIGHT_SHOULDER, 0.2, 0, 0);
+ set(pose, LM.LEFT_HIP, -0.2, 1, 0);
+ set(pose, LM.RIGHT_HIP, 0.2, 1, 0);
+ const q = solveSpine(pose, false);
+ expect(q).not.toBeNull();
+ const dir = applied(q, REST_DIR.Spine);
+ // upright torso → spine still points +Y
+ expect(dir.y).toBeCloseTo(1, 5);
+ });
+
+ it('tilts forward when shoulders lean toward the camera', () => {
+ const pose = blankPose();
+ set(pose, LM.LEFT_SHOULDER, -0.2, 0, 0.5);
+ set(pose, LM.RIGHT_SHOULDER, 0.2, 0, 0.5);
+ set(pose, LM.LEFT_HIP, -0.2, 1, 0);
+ set(pose, LM.RIGHT_HIP, 0.2, 1, 0);
+ const q = solveSpine(pose, false);
+ const dir = applied(q, REST_DIR.Spine);
+ // leaning toward camera → spine tip gains −Z (avatar forward)
+ expect(dir.z).toBeLessThan(0);
+ expect(dir.y).toBeGreaterThan(0);
+ });
+});
diff --git a/tests/clash-match.test.js b/tests/clash-match.test.js
new file mode 100644
index 000000000..65e443d1a
--- /dev/null
+++ b/tests/clash-match.test.js
@@ -0,0 +1,256 @@
+// Unit tests for the Coin Wars clash engine (multiplayer/src/clash.js) and the war
+// standings league math (multiplayer/src/war-standings.js). Both are pure modules
+// over the dependency-free combat.js, so they run without the Colyseus schema/room
+// (which can't be imported on the corrupted box) — the same isolation that lets
+// combat.js be tested on its own.
+
+import { describe, it, expect } from 'vitest';
+import { ClashMatch, ClashPhase, CLASH_DEFAULTS } from '../multiplayer/src/clash.js';
+import {
+ computeStandings, applyBattle, rankStandings, expectedScore, BASE_RATING,
+} from '../multiplayer/src/war-standings.js';
+
+const COIN_A = { mint: 'AAA111', name: 'Alpha', symbol: 'ALPHA', image: '' };
+const COIN_B = { mint: 'BBB222', name: 'Bravo', symbol: 'BRAVO', image: '' };
+const SWORD = { kind: 'melee', dmg: 60, range: 2, arc: Math.PI };
+const FIST = { kind: 'melee', dmg: 1, range: 2, arc: Math.PI };
+
+// Deterministic rng so rollDamage is reproducible: 0.5 → mid-swing, no ±variance edge.
+const mid = () => 0.5;
+
+function match(config = {}) {
+ return new ClashMatch({ factions: [COIN_A, COIN_B], config: { respawnMs: 1000, ...config } });
+}
+
+describe('ClashMatch — setup & roster', () => {
+ it('requires exactly two distinct factions', () => {
+ expect(() => new ClashMatch({ factions: [COIN_A] })).toThrow();
+ expect(() => new ClashMatch({ factions: [COIN_A, COIN_A] })).toThrow();
+ expect(() => new ClashMatch({ factions: [COIN_A, COIN_B] })).not.toThrow();
+ });
+
+ it('seats fighters on their faction and enforces the per-team cap', () => {
+ const m = match({ maxPerTeam: 2 });
+ expect(m.addFighter('a1', COIN_A.mint)).toBeTruthy();
+ expect(m.addFighter('a2', COIN_A.mint)).toBeTruthy();
+ expect(m.addFighter('a3', COIN_A.mint)).toBeNull(); // full
+ expect(m.countFaction(COIN_A.mint)).toBe(2);
+ });
+
+ it('rejects fighters for a coin not in the match', () => {
+ const m = match();
+ expect(m.addFighter('x', 'CCC333')).toBeNull();
+ });
+
+ it('only starts once both communities are staffed', () => {
+ const m = match({ minPerTeam: 1 });
+ m.addFighter('a1', COIN_A.mint);
+ expect(m.canStart()).toBe(false);
+ m.addFighter('b1', COIN_B.mint);
+ expect(m.canStart()).toBe(true);
+ });
+});
+
+describe('ClashMatch — combat & scoring', () => {
+ it('ignores attacks before the match is live', () => {
+ const m = match();
+ m.addFighter('a1', COIN_A.mint);
+ m.addFighter('b1', COIN_B.mint);
+ expect(m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: 0 })).toBeNull();
+ });
+
+ it('blocks friendly fire', () => {
+ const m = match();
+ m.addFighter('a1', COIN_A.mint);
+ m.addFighter('a2', COIN_A.mint);
+ m.addFighter('b1', COIN_B.mint);
+ m.start(0);
+ expect(m.resolveAttack('a1', 'a2', SWORD, { rng: mid, now: 1 })).toBeNull();
+ });
+
+ it('damages an enemy and scores a kill for the attacker faction', () => {
+ const m = match({ maxHp: 100 });
+ m.addFighter('a1', COIN_A.mint, { combatLevel: 1 });
+ m.addFighter('b1', COIN_B.mint);
+ m.start(0);
+ // 60 dmg per mid-swing → two hits drop a 100hp fighter.
+ const h1 = m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: 10 });
+ expect(h1.killed).toBe(false);
+ expect(h1.targetHp).toBeGreaterThan(0);
+ const h2 = m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: 20 });
+ expect(h2.killed).toBe(true);
+ expect(h2.scored).toBe(true);
+ expect(m.factions.get(COIN_A.mint).score).toBe(1);
+ expect(m.fighters.get('a1').kills).toBe(1);
+ expect(m.fighters.get('b1').deaths).toBe(1);
+ });
+
+ it('cannot hit a downed fighter until they respawn', () => {
+ const m = match({ respawnMs: 1000 });
+ m.addFighter('a1', COIN_A.mint);
+ m.addFighter('b1', COIN_B.mint);
+ m.start(0);
+ m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: 10 });
+ m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: 20 }); // kill
+ expect(m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: 30 })).toBeNull(); // dead
+ // Respawn at now>=respawnAt brings them back to full.
+ const ev = m.tick(20 + 1000);
+ expect(ev.respawns).toContain('b1');
+ expect(m.fighters.get('b1').dead).toBe(false);
+ expect(m.fighters.get('b1').hp).toBe(100);
+ });
+
+ it('ends the match when a faction reaches the score cap', () => {
+ const m = match({ scoreCap: 2, respawnMs: 0 });
+ m.addFighter('a1', COIN_A.mint);
+ m.addFighter('b1', COIN_B.mint);
+ m.start(0);
+ let t = 0;
+ // One-shot weapon: each pair of calls is a fresh kill after an instant respawn.
+ const kill = () => {
+ m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: ++t });
+ m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: ++t });
+ m.tick(++t); // respawnMs:0 → revive immediately
+ };
+ kill();
+ expect(m.phase).toBe(ClashPhase.LIVE);
+ kill();
+ expect(m.phase).toBe(ClashPhase.ENDED);
+ const res = m.result();
+ expect(res.winner).toBe(COIN_A.mint);
+ expect(res.reason).toBe('score_cap');
+ });
+});
+
+describe('ClashMatch — clock, sudden death & forfeit', () => {
+ it('a level clock goes to sudden death, and first blood ends it', () => {
+ const m = match({ durationMs: 1000, scoreCap: 99 });
+ m.addFighter('a1', COIN_A.mint);
+ m.addFighter('b1', COIN_B.mint);
+ m.start(0);
+ const ev = m.tick(1000); // clock expires level (0-0)
+ expect(ev.phase).toBe(ClashPhase.SUDDEN_DEATH);
+ m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: 1001 });
+ m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: 1002 }); // first blood
+ expect(m.phase).toBe(ClashPhase.ENDED);
+ expect(m.result().winner).toBe(COIN_A.mint);
+ expect(m.result().reason).toBe('sudden_death');
+ });
+
+ it('the leader takes a timeout win', () => {
+ const m = match({ durationMs: 1000, scoreCap: 99 });
+ m.addFighter('a1', COIN_A.mint);
+ m.addFighter('b1', COIN_B.mint);
+ m.start(0);
+ m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: 10 });
+ m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: 20 }); // A leads 1-0
+ const ev = m.tick(1000);
+ expect(ev.ended).toBe(true);
+ expect(m.result().winner).toBe(COIN_A.mint);
+ expect(m.result().reason).toBe('timeout');
+ });
+
+ it('forfeit hands the win to the other community', () => {
+ const m = match();
+ m.addFighter('a1', COIN_A.mint);
+ m.addFighter('b1', COIN_B.mint);
+ m.start(0);
+ m.forfeit(COIN_B.mint, 500);
+ expect(m.result().winner).toBe(COIN_A.mint);
+ expect(m.result().reason).toBe('forfeit');
+ });
+
+ it('result() is null until the match ends', () => {
+ const m = match();
+ m.addFighter('a1', COIN_A.mint);
+ m.addFighter('b1', COIN_B.mint);
+ m.start(0);
+ expect(m.result()).toBeNull();
+ });
+
+ it('crowns an MVP by kills then damage', () => {
+ const m = match({ scoreCap: 99, respawnMs: 0 });
+ m.addFighter('a1', COIN_A.mint);
+ m.addFighter('a2', COIN_A.mint);
+ m.addFighter('b1', COIN_B.mint);
+ m.start(0);
+ let t = 0;
+ // a1 gets the kill; a2 only chips with a fist.
+ m.resolveAttack('a2', 'b1', FIST, { rng: mid, now: ++t });
+ m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: ++t });
+ m.resolveAttack('a1', 'b1', SWORD, { rng: mid, now: ++t });
+ m.forfeit(COIN_B.mint, ++t);
+ expect(m.result().mvp.id).toBe('a1');
+ });
+});
+
+describe('war standings — Elo league math', () => {
+ function battle(winnerMint, aKills, bKills, endedAt) {
+ return {
+ winner: winnerMint,
+ endedAt,
+ factions: [
+ { mint: COIN_A.mint, name: 'Alpha', symbol: 'ALPHA', kills: aKills, deaths: bKills },
+ { mint: COIN_B.mint, name: 'Bravo', symbol: 'BRAVO', kills: bKills, deaths: aKills },
+ ],
+ };
+ }
+
+ it('expectedScore is 0.5 for equal ratings and rises with a lead', () => {
+ expect(expectedScore(1000, 1000)).toBeCloseTo(0.5);
+ expect(expectedScore(1200, 1000)).toBeGreaterThan(0.5);
+ });
+
+ it('a win raises the winner above base and drops the loser below it', () => {
+ const rows = computeStandings([battle(COIN_A.mint, 25, 18, 100)]);
+ const a = rows.find((r) => r.mint === COIN_A.mint);
+ const b = rows.find((r) => r.mint === COIN_B.mint);
+ expect(a.rating).toBeGreaterThan(BASE_RATING);
+ expect(b.rating).toBeLessThan(BASE_RATING);
+ expect(a.wins).toBe(1);
+ expect(b.losses).toBe(1);
+ expect(a.rank).toBe(1);
+ });
+
+ it('tracks win/loss streaks and resets on a draw', () => {
+ const rows = computeStandings([
+ battle(COIN_A.mint, 25, 10, 100),
+ battle(COIN_A.mint, 25, 12, 200),
+ battle('draw', 20, 20, 300),
+ ]);
+ const a = rows.find((r) => r.mint === COIN_A.mint);
+ expect(a.wins).toBe(2);
+ expect(a.draws).toBe(1);
+ expect(a.streak).toBe(0); // draw reset the +2 run
+ });
+
+ it('aggregates K/D and computes win rate', () => {
+ const rows = computeStandings([
+ battle(COIN_A.mint, 25, 10, 100),
+ battle(COIN_B.mint, 8, 25, 200),
+ ]);
+ const a = rows.find((r) => r.mint === COIN_A.mint);
+ expect(a.kills).toBe(33);
+ expect(a.deaths).toBe(35);
+ expect(a.kd).toBeCloseTo(33 / 35);
+ expect(a.winRate).toBeCloseTo(0.5);
+ });
+
+ it('rating is path-consistent regardless of input order (folds chronologically)', () => {
+ const b1 = battle(COIN_A.mint, 25, 10, 100);
+ const b2 = battle(COIN_B.mint, 9, 25, 200);
+ const forward = computeStandings([b1, b2]);
+ const shuffled = computeStandings([b2, b1]);
+ const fa = forward.find((r) => r.mint === COIN_A.mint).rating;
+ const sa = shuffled.find((r) => r.mint === COIN_A.mint).rating;
+ expect(fa).toBe(sa);
+ });
+
+ it('applyBattle + rankStandings compose into the same result as computeStandings', () => {
+ const table = new Map();
+ applyBattle(table, battle(COIN_A.mint, 25, 10, 100));
+ const ranked = rankStandings(table);
+ expect(ranked[0].mint).toBe(COIN_A.mint);
+ expect(ranked[0].rank).toBe(1);
+ });
+});
diff --git a/vite.config.js b/vite.config.js
index 9196fc118..6a7f01f45 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -391,6 +391,7 @@ const appConfig = {
irl: resolve(__dirname, 'pages/irl.html'),
'irl-privacy': resolve(__dirname, 'pages/irl-privacy.html'),
communities: resolve(__dirname, 'pages/communities.html'),
+ clash: resolve(__dirname, 'pages/clash.html'),
'walk-embed': resolve(__dirname, 'pages/walk-embed.html'),
city: resolve(__dirname, 'pages/city.html'),
play: resolve(__dirname, 'pages/play.html'),
@@ -739,6 +740,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/bounties/': resolve(root, 'pages/bounties.html'),
'/launches': resolve(root, 'pages/launches.html'),
'/launches/': resolve(root, 'pages/launches.html'),
+ '/clash': resolve(root, 'pages/clash.html'),
+ '/clash/': resolve(root, 'pages/clash.html'),
'/watchlist': resolve(root, 'pages/watchlist.html'),
'/watchlist/': resolve(root, 'pages/watchlist.html'),
'/leaderboard': resolve(root, 'pages/leaderboard.html'),