Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(club): put a bouncer and a door line outside the club instead of a quiet alley
ni3ae088e6cf5d95
diff --git a/pages/club.html b/pages/club.htmlindex ddeed107f..ab9174771 100644--- a/pages/club.html+++ b/pages/club.html@@ -1003,6 +1003,82 @@.club-minimap-tag { display: none; }}+ /* Speech bubbles over the line outside the door (src/club-queue.js pins+ each one over a head every frame). Above the scene canvas, below the+ walk-in controls. The outer element is positioned by transform, so it+ only ever transitions opacity; the pop lives on the body inside it. */+ .club-bubbles {+ position: fixed;+ inset: 0;+ z-index: 9410;+ overflow: hidden;+ pointer-events: none;+ }+ .club-bubble {+ position: absolute;+ left: 0;+ top: 0;+ width: max-content;+ max-width: min(230px, calc(100vw - 32px));+ padding-bottom: 9px; /* room for the tail */+ opacity: 0;+ will-change: transform, opacity;+ transition: opacity var(--duration-base) var(--ease-standard);+ }+ .club-bubble.is-visible { opacity: 1; }+ .club-bubble.is-offscreen { opacity: 0; transition: none; }+ .club-bubble-body {+ position: relative;+ display: block;+ padding: 8px 12px 9px;+ border-radius: 14px;+ border: 1px solid rgba(255, 255, 255, 0.16);+ background: rgba(8, 6, 16, 0.86);+ box-shadow: 0 8px 22px -12px rgba(0, 0, 0, 0.85);+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ color: #fff;+ font-size: 13px;+ line-height: 1.35;+ text-wrap: pretty;+ transform: translateY(6px) scale(0.9);+ transform-origin: 50% 100%;+ transition: transform var(--duration-base) var(--ease-standard);+ }+ .club-bubble.is-visible .club-bubble-body { transform: none; }+ .club-bubble-body::after {+ content: '';+ position: absolute;+ left: 50%;+ bottom: -6px;+ width: 10px;+ height: 10px;+ margin-left: -5px;+ border-right: 1px solid rgba(255, 255, 255, 0.16);+ border-bottom: 1px solid rgba(255, 255, 255, 0.16);+ background: rgba(8, 6, 16, 0.92);+ transform: rotate(45deg);+ }+ /* The ones who started early: warmer border, slurred italics, a wobble. */+ .club-bubble.is-drunk .club-bubble-body {+ border-color: rgba(255, 138, 59, 0.5);+ font-style: italic;+ }+ .club-bubble.is-drunk .club-bubble-body::after { border-color: rgba(255, 138, 59, 0.5); }+ .club-bubble.is-drunk.is-visible .club-bubble-body { animation: club-bubble-wobble 2.6s ease-in-out infinite; }+ @keyframes club-bubble-wobble {+ 0%, 100% { transform: rotate(-2.2deg); }+ 50% { transform: rotate(2.2deg) translateY(-1px); }+ }+ @media (max-width: 480px) {+ .club-bubble { max-width: min(190px, calc(100vw - 32px)); }+ .club-bubble-body { font-size: 12px; padding: 7px 10px 8px; }+ }+ @media (prefers-reduced-motion: reduce) {+ .club-bubble, .club-bubble-body { transition: none; }+ .club-bubble.is-drunk.is-visible .club-bubble-body { animation: none; }+ }+.club-controls-hint {position: fixed;left: 50%;@@ -1072,6 +1148,50 @@50% { transform: translate(-50%, calc(-50% - 5px)) scale(1); }}+ /* Bouncer speech bubble: positioned by transform every frame, so only+ opacity transitions here (a transform transition would fight the pin). */+ .club-bouncer-bubble {+ position: fixed;+ left: 0;+ top: 0;+ z-index: 9510; /* above the cover card: his lines narrate the check */+ width: max-content;+ max-width: min(300px, calc(100vw - 24px));+ padding: 10px 14px 11px;+ border-radius: 14px 14px 14px 4px;+ border: 1px solid rgba(74, 214, 255, 0.45);+ background: rgba(8, 6, 16, 0.88);+ box-shadow: 0 0 30px -8px rgba(74, 214, 255, 0.65), 0 8px 24px -12px rgba(0, 0, 0, 0.8);+ backdrop-filter: blur(8px);+ -webkit-backdrop-filter: blur(8px);+ color: #fff;+ font-size: 14px;+ line-height: 1.4;+ pointer-events: none;+ opacity: 0;+ visibility: hidden;+ will-change: transform, opacity;+ transition: opacity var(--duration-base) var(--ease-standard), visibility 0s linear var(--duration-base);+ }+ .club-bouncer-bubble.is-visible { opacity: 1; visibility: visible; transition-delay: 0s; }+ .club-bouncer-bubble.is-offscreen { opacity: 0; }+ .club-bouncer-name {+ display: block;+ margin-bottom: 3px;+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: #4ad6ff;+ }+ .club-bouncer-line { display: block; text-wrap: pretty; }+ @media (max-width: 480px) {+ .club-bouncer-bubble { font-size: 13px; padding: 9px 12px 10px; }+ }+ @media (prefers-reduced-motion: reduce) {+ .club-bouncer-bubble { transition: none; }+ }+/* Touch joystick — repositions to first touch on the left of screen. */.club-joystick {position: fixed;@@ -2006,6 +2126,9 @@avatar in the alley, then the walk through the club house after youpay. Sits behind the cover card, above the pole stage. --><canvas id="club-door-canvas" class="club-door-canvas" aria-hidden="true"></canvas>+ <!-- What the line outside the door is saying (src/club-queue.js). Ambient+ scenery like the canvas under it, so it stays out of the a11y tree. -->+ <div id="club-bubbles" class="club-bubbles" aria-hidden="true"></div><!-- Cinematic intro + real load progress while the alley streams in. --><div id="club-loader" class="club-loader" role="status" aria-live="polite">@@ -2048,6 +2171,12 @@<button id="club-door-prompt" type="button" class="club-door-prompt" aria-label="Enter the club" data-i18n-html="club.enter_the_club_e" data-i18n-attr="aria-label:club.enter_the_club_arialabel">Enter the club <kbd>E</kbd></button>+ <!-- The bouncer's speech bubble (src/club-bouncer.js pins it over his head+ in the alley). A live region, so his lines are announced too. -->+ <div id="club-bouncer-bubble" class="club-bouncer-bubble" role="status" aria-live="polite">+ <span class="club-bouncer-name">Bouncer</span>+ <span class="club-bouncer-line"></span>+ </div><div id="club-joystick" class="club-joystick" aria-hidden="true"><div id="club-joystick-knob" class="club-joystick-knob"></div></div>diff --git a/src/club-bouncer.js b/src/club-bouncer.jsnew file mode 100644index 000000000..6e6154775--- /dev/null+++ b/src/club-bouncer.js@@ -0,0 +1,484 @@+// /club bouncer: the doorman standing beside the alley door.+//+// The cover card (src/club-gate.js) has always said "the bouncer checks your+// wallet on-chain"; this module puts him in the scene. He is a real rigged+// avatar (a bundled humanoid GLB, tinted into a black suit and shades) planted+// beside the modelled door in the alley (src/club-entrance.js), a head taller+// than you. He watches you walk up (head + shoulders track the player), calls+// the cover as you approach, and acts out every beat of the x402 cover flow,+// driven by the `club:door-state` events the gate emits:+//+// queue → tells you the price checking → looks down at the list+// admitted → nods you through (by tier) denied → shakes his head+//+// Click or tap him and he explains how the club works, one line at a time, so+// a first-time visitor learns the loop (cover, then tips put a dancer on the+// pole) without leaving the alley. Walk into him and he holds his ground.+//+// Speech renders in a DOM bubble (#club-bouncer-bubble, an aria-live region)+// projected over his head each frame. Any load failure degrades to no bouncer:+// the door, the cover card and the walk-in all work without him.++import { Box3, Group, Quaternion, Raycaster, Vector3 } from 'three';+import { AnimationManager } from './animation-manager.js';+import { log } from './shared/log.js';++export const BOUNCER_AVATAR_URL = '/avatars/realistic-male.glb';++const BOUNCER_HEIGHT = 1.98; // the player is 1.75; he should loom+const SUIT_TINT = 0x16161c; // multiplies the outfit textures down to a black suit+const SUIT_MESH = /outfit|footwear/i;++// Stance: how far out from the door's centre line he stands, and how far off+// the wall. Wide enough that he never blocks the doorway you walk into.+const SIDE_CLEARANCE = 0.75;+const WALL_STANDOFF = 0.6;+const MAX_STANDOFF = 4.2; // how far out he will look for level ground (past any steps)+const LEVEL_TOLERANCE = 0.12; // floor must match the player's walking level this closely+const BODY_CLEARANCE = 0.42;+const CLEARANCE_RAYS = 16; // fine enough that a stair corner can't slip between two rays+// The player can't walk through him.+export const BOUNCER_RADIUS = 0.62;++const NOTICE_RANGE = 7.5; // first line as you come down the alley+const HEAD_YAW_LIMIT = 1.05;+const HEAD_PITCH_LIMIT = 0.32;+const BODY_YAW_LIMIT = 0.7;+const BODY_SHARE = 0.4; // fraction of the turn the shoulders take; the head takes the rest++// One-shots + the "reading the list" loop, in preference order. Anything the+// rig can't play is skipped; he simply holds his idle stance for that beat.+const CLIP_IDLE = 'idle';+const CLIP_CHECKING = 'lookdown';+const CLIPS_ADMIT = ['nod', 'xbot-agree'];+const CLIPS_DENY = ['xbot-head-shake'];+const REACTION_CLIPS = [CLIP_CHECKING, ...CLIPS_ADMIT, ...CLIPS_DENY];++const LINES = {+ notice: "Cover's a penny tonight. Step up to the door.",+ atDoor: 'One cent, USDC. Wallet out when you are ready.',+ queue: 'One cent gets you in for the whole night.',+ leftLine: 'Door stays here. Come back when you are ready.',+ checking: 'Hold still. Reading your wallet on-chain.',+ admittedNew: 'First night? You are good. Enjoy yourself.',+ admittedRegular: 'Good to see you again. Head on in.',+ admittedVip: 'Back again, boss. Go right through.',+ denied: 'Not tonight.',+ bump: 'Easy. The door is right there.',+};+// Tap-to-talk: how the club works, in the order a newcomer needs it.+const EXPLAINERS = [+ 'Cover is one cent of USDC, paid over x402 on Solana. It settles before the rope drops.',+ 'One cover lasts the night on this device. Reload and you walk straight in.',+ 'Inside there are three poles. A tenth of a cent tips a dancer, and the tip is what starts the routine.',+ 'I read the paying wallet on-chain: the ban list, and how many nights you have been here.',+ 'Regulars get remembered. Come back enough and you walk in as a VIP.',+];++const UP = new Vector3(0, 1, 0);+const DOWN = new Vector3(0, -1, 0);+const _v = new Vector3();+const _head = new Vector3();+const _right = new Vector3();+const _q = new Quaternion();+const _pq = new Quaternion();+const _pqInv = new Quaternion();+const _box = new Box3();++function clamp(v, lo, hi) { return v < lo ? lo : v > hi ? hi : v; }+function wrapAngle(a) {+ a %= Math.PI * 2;+ if (a > Math.PI) a -= Math.PI * 2;+ if (a < -Math.PI) a += Math.PI * 2;+ return a;+}++// Scale the rig to `height` and put its feet on the group's origin. A model+// with no measurable bounds is left as authored rather than scaled to nothing.+function standAtHeight(model, height) {+ _box.setFromObject(model, true);+ const tall = _box.max.y - _box.min.y;+ if (Number.isFinite(tall) && tall > 0) model.scale.multiplyScalar(height / tall);+ _box.setFromObject(model, true);+ if (Number.isFinite(_box.min.y)) model.position.y -= _box.min.y;+}++export class ClubBouncer {+ /**+ * @param {object} opts+ * @param {import('three').Scene} opts.scene+ * @param {import('three').Object3D} opts.model the loaded bouncer GLB scene+ * @param {Array} opts.manifest animation manifest (name→url defs)+ * @param {object|null} opts.idleClipJson pre-fetched idle clip (shared with the player)+ * @param {HTMLElement|null} opts.bubbleEl the speech bubble element+ * @param {boolean} [opts.reducedMotion]+ */+ constructor({ scene, model, manifest, idleClipJson, bubbleEl, reducedMotion = false }) {+ this.scene = scene;+ this.model = model;+ this.bubbleEl = bubbleEl || null;+ this.bubbleText = this.bubbleEl?.querySelector('.club-bouncer-line') || null;+ this.reducedMotion = reducedMotion;++ this.group = new Group();+ this.group.name = 'club-bouncer';+ this.group.visible = false;+ this.group.add(model);++ this._dressForTheDoor(model);+ standAtHeight(model, BOUNCER_HEIGHT);++ this.anim = new AnimationManager();+ this.anim.attach(model, { avatarUrl: BOUNCER_AVATAR_URL });+ this.drivable = this.anim.supportsCanonicalClips();+ const defs = (Array.isArray(manifest) ? manifest : []).filter((d) => REACTION_CLIPS.includes(d?.name));+ this.anim.setAnimationDefs([{ name: CLIP_IDLE, url: '/animations/clips/idle.json', loop: true }, ...defs]);+ if (idleClipJson) this.anim.injectClip(CLIP_IDLE, idleClipJson, { loop: true });++ this.headBone = null;+ model.traverse((n) => {+ if (!this.headBone && n.isBone && /(^|[:_])head$/i.test(n.name || '')) this.headBone = n;+ });+ this._headBase = new Quaternion();+ this._headBaseValid = false;+ this._headYaw = 0;+ this._headPitch = 0;++ this.mounted = false;+ this.baseYaw = 0;+ this.position = this.group.position;+ this._state = 'idle'; // idle | checking | admitted | denied+ this._noticed = false;+ this._wasNearDoor = false;+ this._explainIndex = 0;+ this._bubbleTimer = 0;+ this._lastBump = 0;+ this._raycaster = new Raycaster();++ this._onDoorState = (e) => this._react(e?.detail || {});+ window.addEventListener('club:door-state', this._onDoorState);+ }++ // Outfit + shoes go black (the colour multiplies the garment textures), the+ // glasses the rig already wears read as shades. Materials are cloned first so+ // a crowd member sharing this GLB through another loader is never recoloured.+ _dressForTheDoor(model) {+ model.traverse((n) => {+ if (!n.isMesh) return;+ n.castShadow = false;+ n.frustumCulled = false; // skinned bounds lag the pose; he is always near the door anyway+ if (!SUIT_MESH.test(n.name || '')) return;+ const dress = (m) => {+ const c = m.clone();+ c.color.setHex(SUIT_TINT);+ if ('roughness' in c) c.roughness = Math.min(1, (c.roughness ?? 0.8) * 0.9);+ return c;+ };+ n.material = Array.isArray(n.material) ? n.material.map(dress) : dress(n.material);+ });+ }++ /**+ * Plant him beside the door, on the ground the player actually walks. The+ * modelled door can sit up a flight of steps with a plinth along the wall, so+ * rather than trust a fixed offset he walks the line out from the doorway+ * until he finds a spot that is level with the alley floor and clear of+ * geometry at shin and chest height. Of the two sides he takes the one that+ * posts him closer to the door, and the roomier one on a tie.+ *+ * @param {object} ctx+ * @param {import('three').Object3D} ctx.envRoot+ * @param {{dir:import('three').Vector3, door:import('three').Vector3, spawn:import('three').Vector3}} ctx.path+ * @param {{size:import('three').Vector3}|null} ctx.doorAnchor+ */+ async mount({ envRoot, path, doorAnchor }) {+ if (!this.drivable) return false; // never stand a T-pose at the door+ const dir = path.dir;+ const perp = new Vector3(dir.z, 0, -dir.x);+ const doorWidth = doorAnchor+ ? Math.abs(dir.z) * doorAnchor.size.x + Math.abs(dir.x) * doorAnchor.size.z+ : 1.5;+ const lateral = Math.max(doorWidth / 2, SIDE_CLEARANCE) + 0.55;+ const searchStart = performance.now();+ const groundY = this._floorAt(envRoot, path.spawn.x, path.spawn.z) ?? 0;++ const posts = [1, -1]+ .map((side) => this._findPost(envRoot, path.door, dir, perp, side * lateral, groundY))+ .filter(Boolean)+ .sort((a, b) => (Math.abs(a.standoff - b.standoff) > 0.25 ? a.standoff - b.standoff : b.room - a.room));+ // No clear, level spot on either side (a door boxed in by props): stand at+ // the wall offset on whatever floor is there rather than not show up.+ const fallback = path.door.clone().addScaledVector(perp, lateral).addScaledVector(dir, WALL_STANDOFF);+ const spot = posts[0] || { p: fallback, floor: this._floorAt(envRoot, fallback.x, fallback.z) ?? groundY };++ log.info('[club-bouncer] posted', posts[0] ? `${posts[0].standoff.toFixed(1)}m off the door` : 'at the wall (no clear level spot)', `in ${Math.round(performance.now() - searchStart)}ms`);++ this.group.position.set(spot.p.x, spot.floor, spot.p.z);+ this.baseYaw = Math.atan2(dir.x, dir.z);+ this.group.rotation.y = this.baseYaw;+ this.scene.add(this.group);++ const playing = await this.anim.play(CLIP_IDLE);+ if (!playing) {+ this.scene.remove(this.group);+ return false;+ }+ this.group.visible = true;+ this.mounted = true;+ return true;+ }++ // Walk out from the wall along one side of the doorway and return the first+ // spot that is level with the alley floor and has room for a body.+ _findPost(envRoot, door, dir, perp, lateral, groundY) {+ for (let standoff = WALL_STANDOFF; standoff <= MAX_STANDOFF; standoff += 0.2) {+ const p = door.clone().addScaledVector(perp, lateral).addScaledVector(dir, standoff);+ const floor = this._floorAt(envRoot, p.x, p.z);+ if (floor == null || Math.abs(floor - groundY) > LEVEL_TOLERANCE) continue;+ if (!this._bodyClear(envRoot, p, floor)) continue;+ return { p, floor, standoff, room: this._openRoom(envRoot, p, perp, Math.sign(lateral)) };+ }+ return null;+ }++ // Nothing solid within a body's width at shin or chest height. The venue's+ // materials are double-sided, so a point inside a solid fails this too.+ _bodyClear(envRoot, p, floor) {+ for (const h of [0.15, 0.95]) {+ for (let i = 0; i < CLEARANCE_RAYS; i++) {+ const a = (i / CLEARANCE_RAYS) * Math.PI * 2;+ this._raycaster.set(_v.set(p.x, floor + h, p.z), _right.set(Math.sin(a), 0, Math.cos(a)));+ this._raycaster.far = BODY_CLEARANCE;+ if (this._raycaster.intersectObject(envRoot, true).length) return false;+ }+ }+ return true;+ }++ _floorAt(envRoot, x, z) {+ this._raycaster.set(_v.set(x, 1.2, z), DOWN);+ this._raycaster.far = 1.6;+ const hit = this._raycaster.intersectObject(envRoot, true)[0];+ return hit ? Math.max(0, hit.point.y) : null;+ }++ // How far he could step sideways before hitting a wall: the roomier side of+ // the door is where a doorman would actually stand.+ _openRoom(envRoot, p, perp, side) {+ this._raycaster.set(_v.set(p.x, 1.0, p.z), perp.clone().multiplyScalar(side));+ this._raycaster.far = 6;+ const hit = this._raycaster.intersectObject(envRoot, true)[0];+ return hit ? hit.distance : 6;+ }++ /** The alley door no longer takes a cover (paid, venue swapped): stand down. */+ unmount() {+ if (!this.mounted) return;+ this.mounted = false;+ this.group.visible = false;+ this.scene.remove(this.group);+ this._hideBubble();+ }++ /**+ * Per-frame: advance his clip, track the player with head + shoulders, fire+ * proximity lines, and pin the speech bubble over his head.+ *+ * @param {number} dt+ * @param {import('three').Vector3} playerPos+ * @param {import('three').Camera} camera+ * @param {{nearDoor:boolean, interactive:boolean}} ctx+ */+ update(dt, playerPos, camera, { nearDoor = false, interactive = true } = {}) {+ if (!this.mounted) return;++ // Restore the clip-driven head pose before the mixer ticks, so the look-at+ // offset below never accumulates on a rig whose clip has no head track.+ if (this.headBone && this._headBaseValid) this.headBone.quaternion.copy(this._headBase);+ this.anim.update(dt);++ const dx = playerPos.x - this.group.position.x;+ const dz = playerPos.z - this.group.position.z;+ const dist = Math.hypot(dx, dz);+ this._track(dt, dx, dz, dist);++ if (interactive && this._state === 'idle') {+ if (!this._noticed && dist < NOTICE_RANGE) {+ this._noticed = true;+ this.say(LINES.notice, 4200);+ }+ if (nearDoor && !this._wasNearDoor) this.say(LINES.atDoor, 4200);+ }+ this._wasNearDoor = nearDoor;++ this._pinBubble(camera);+ }++ // Shoulders take part of the turn, the head the rest, both eased and clamped+ // so he reads as a man watching you, not a turret. While he reads the list+ // he looks at the list, not at you.+ _track(dt, dx, dz, dist) {+ const watching = this._state !== 'checking' && dist > 0.2;+ const toPlayer = watching ? wrapAngle(Math.atan2(dx, dz) - this.baseYaw) : 0;+ const ease = this.reducedMotion ? 1 : 1 - Math.exp(-5 * dt);++ const bodyTarget = clamp(toPlayer * BODY_SHARE, -BODY_YAW_LIMIT, BODY_YAW_LIMIT);+ const bodyYaw = wrapAngle(this.group.rotation.y - this.baseYaw);+ this.group.rotation.y = this.baseYaw + bodyYaw + (bodyTarget - bodyYaw) * ease;++ if (!this.headBone) return;+ const bodyNow = wrapAngle(this.group.rotation.y - this.baseYaw);+ const yawTarget = watching ? clamp(wrapAngle(toPlayer - bodyNow), -HEAD_YAW_LIMIT, HEAD_YAW_LIMIT) : 0;+ // He is taller than you, so meeting your eye means looking down a touch.+ const pitchTarget = watching+ ? clamp(Math.atan2(BOUNCER_HEIGHT - 1.75, Math.max(dist, 0.6)), 0, HEAD_PITCH_LIMIT)+ : 0;+ this._headYaw += (yawTarget - this._headYaw) * ease;+ this._headPitch += (pitchTarget - this._headPitch) * ease;++ this._headBase.copy(this.headBone.quaternion);+ this._headBaseValid = true;+ if (Math.abs(this._headYaw) < 1e-3 && Math.abs(this._headPitch) < 1e-3) return;++ // Build the offset in world space (yaw about world up, pitch about his+ // right), then carry it into the head's parent space so it composes with+ // whatever the clip posed, on any rig's bone orientation convention.+ const facing = this.group.rotation.y + this._headYaw;+ _right.set(Math.cos(facing), 0, -Math.sin(facing));+ _q.setFromAxisAngle(_right, this._headPitch);+ _q.multiply(_pq.setFromAxisAngle(UP, this._headYaw));+ this.headBone.parent.getWorldQuaternion(_pq);+ _pqInv.copy(_pq).invert();+ this.headBone.quaternion.premultiply(_pq).premultiply(_q).premultiply(_pqInv);+ }++ // ── Cover flow ───────────────────────────────────────────────────────────+ _react({ state, tier, reason }) {+ if (!this.mounted) return;+ switch (state) {+ case 'queue':+ // Re-entering the queue from a failed/cancelled pay lands here too.+ if (this._state !== 'idle') this._settle();+ this.say(LINES.queue, 5200);+ break;+ case 'hidden':+ this._settle();+ this.say(LINES.leftLine, 3600);+ break;+ case 'checking':+ this._state = 'checking';+ this.say(LINES.checking, 0);+ if (this.anim.canPlay(CLIP_CHECKING)) this.anim.crossfadeTo(CLIP_CHECKING, 0.3).catch(() => {});+ break;+ case 'admitted':+ this._state = 'admitted';+ this.say(tier === 'vip' ? LINES.admittedVip : tier === 'regular' ? LINES.admittedRegular : LINES.admittedNew, 0);+ this._playFirst(CLIPS_ADMIT);+ break;+ case 'denied':+ this._state = 'denied';+ this.say(reason ? `${reason} ${LINES.denied}` : LINES.denied, 0);+ this._playFirst(CLIPS_DENY);+ break;+ }+ }++ _settle() {+ this._state = 'idle';+ this.anim.crossfadeTo(CLIP_IDLE, 0.35).catch(() => {});+ }++ _playFirst(names) {+ if (this.reducedMotion) { this.anim.crossfadeTo(CLIP_IDLE, 0.3).catch(() => {}); return; }+ const name = names.find((n) => this.anim.canPlay(n));+ if (name) this.anim.playOnce(name, { settleTo: CLIP_IDLE, fade: 0.25 }).catch(() => {});+ else this.anim.crossfadeTo(CLIP_IDLE, 0.3).catch(() => {});+ }++ // ── Interaction ──────────────────────────────────────────────────────────+ /** True when a pointer ray (already set on `raycaster`) lands on him. */+ hitTest(raycaster) {+ if (!this.mounted) return false;+ return raycaster.intersectObject(this.group, true).length > 0;+ }++ /** Tap-to-talk: the next "how the club works" line. */+ explain() {+ if (!this.mounted || this._state !== 'idle') return;+ this.say(EXPLAINERS[this._explainIndex % EXPLAINERS.length], 6200);+ this._explainIndex++;+ }++ /**+ * Keep the player out of his body. Mutates `pos` (x/z) and returns true when+ * it had to push; he says so, at most once every few seconds.+ */+ resolveCollision(pos, now) {+ if (!this.mounted) return false;+ const dx = pos.x - this.group.position.x;+ const dz = pos.z - this.group.position.z;+ const d = Math.hypot(dx, dz);+ if (d >= BOUNCER_RADIUS) return false;+ const k = d > 1e-4 ? BOUNCER_RADIUS / d : 0;+ pos.x = this.group.position.x + (d > 1e-4 ? dx * k : BOUNCER_RADIUS);+ pos.z = this.group.position.z + dz * k;+ if (this._state === 'idle' && now - this._lastBump > 6000) {+ this._lastBump = now;+ this.say(LINES.bump, 2600);+ }+ return true;+ }++ // ── Speech bubble ────────────────────────────────────────────────────────+ /** Show a line over his head. `ms` of 0 holds it until the next line. */+ say(text, ms = 4000) {+ if (!this.bubbleEl || !this.bubbleText) return;+ if (this._bubbleTimer) { clearTimeout(this._bubbleTimer); this._bubbleTimer = 0; }+ this.bubbleText.textContent = text;+ this.bubbleEl.classList.add('is-visible');+ if (ms > 0) this._bubbleTimer = setTimeout(() => this._hideBubble(), ms);+ }++ /** Drop whatever he is saying (the walk-in is moving on). */+ hush() { this._hideBubble(); }++ _hideBubble() {+ if (this._bubbleTimer) { clearTimeout(this._bubbleTimer); this._bubbleTimer = 0; }+ this.bubbleEl?.classList.remove('is-visible');+ }++ _pinBubble(camera) {+ const el = this.bubbleEl;+ if (!el || !el.classList.contains('is-visible')) return;+ if (this.headBone) this.headBone.getWorldPosition(_head);+ else _head.copy(this.group.position).setY(this.group.position.y + BOUNCER_HEIGHT * 0.93);+ _head.y += 0.34;+ _v.copy(_head).project(camera);+ const behind = _v.z > 1 || _v.z < -1;+ el.classList.toggle('is-offscreen', behind);+ if (behind) return;+ // Keep the bubble on the glass even when he is at the edge of frame.+ const w = window.innerWidth, h = window.innerHeight;+ const half = Math.min(150, w / 2 - 12);+ const x = clamp((_v.x * 0.5 + 0.5) * w, half + 12, w - half - 12);+ const y = clamp((-_v.y * 0.5 + 0.5) * h, 96, h - 24);+ el.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) translate(-50%, -100%)`;+ }++ dispose() {+ window.removeEventListener('club:door-state', this._onDoorState);+ this.unmount();+ try { this.anim.dispose?.(); } catch (err) { log.warn('[club-bouncer] anim dispose failed', err); }+ // He is off the scene graph by now, so the entrance's scene-wide dispose+ // never reaches him: release his GPU resources here.+ this.model.traverse((n) => {+ if (!n.isMesh) return;+ n.geometry?.dispose?.();+ for (const m of Array.isArray(n.material) ? n.material : [n.material]) {+ if (!m) continue;+ for (const k in m) { if (m[k]?.isTexture) m[k].dispose(); }+ m.dispose?.();+ }+ });+ }+}diff --git a/src/club-crowd.js b/src/club-crowd.jsindex fff1c4782..cc0d638b9 100644--- a/src/club-crowd.js+++ b/src/club-crowd.js@@ -18,11 +18,16 @@// • clone once per instance (SkeletonUtils), leave frustum culling on, cast no// shadows, and stagger instantiation so a swap never stalls the walk.//+// A room can also hand mount() a `lineup`: directed slots (the door line outside+// the club, src/club-queue.js) that are filled first, in order, at exact spots+// with their own clip pool, heading and height. Whatever budget is left after+// the lineup scatters as usual.+//// Any failure degrades silently to a smaller (or empty) crowd — the walk-in and// the pole stage always work without it. A rig the canonical clip library can't// drive is skipped rather than left standing in a bind/T-pose.-import { AnimationMixer, Box3, Group, Raycaster, Vector3 } from 'three';+import { AnimationMixer, Box3, Group, LoopOnce, Raycaster, Vector3 } from 'three';import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';import { gltfLoader } from './loaders/gltf.js';import { AnimationManager } from './animation-manager.js';@@ -33,7 +38,11 @@ import { log } from './shared/log.js';// dropped — the crowd falls back to whatever else retargeted on that rig.const IDLE_CLIPS = ['idle', 'av-idle-breath', 'av-waiting', 'av-chilling', 'av-leaning-wall', 'av-listening-music', 'av-smoking'];const DANCE_CLIPS = ['twerk', 'dance', 'rumba', 'av-dance-shuffle', 'av-rap-dance', 'av-headbang', 'av-banging-tunes', 'av-cheering', 'av-boxer-dance', 'av-offabean-dance', 'michelle-samba-dance'];-const ALL_CROWD_CLIPS = [...new Set([...IDLE_CLIPS, ...DANCE_CLIPS])];+// Extra clips only directed lineup members use: the drunks (a slowed walk for+// the stagger, a head-down slump) and the short one-shot gestures a member+// plays while they talk. All small files.+const LINEUP_CLIPS = ['walk', 'lookdown', 'shrug', 'nod', 'point'];+const ALL_CROWD_CLIPS = [...new Set([...IDLE_CLIPS, ...DANCE_CLIPS, ...LINEUP_CLIPS])];// Public 3D avatars to pull for the crowd. Larger page than the entrance's agent// switcher (limit=24) so a populated room shows real variety; deduped by GLB URL@@ -54,6 +63,8 @@ const DANCE_RATIO = [0.18, 0.32, 0.6];// Don't leave a room feeling dead when the gallery is unreachable — cycle the// bundled rigs up to this floor (still capped by the device budget).const LIVELY_FLOOR = 9;+// Unique rigs a directed lineup may download; longer lines reuse them as clones.+const LINEUP_DISTINCT = 6;const DOWN = new Vector3(0, -1, 0);const _box = new Box3();@@ -225,34 +236,52 @@ export class ClubCrowd {* @param {{minX:number,maxX:number,minZ:number,maxZ:number}} ctx.bounds walkable bounds* @param {{spawn:import('three').Vector3, door:import('three').Vector3}} ctx.path* @param {number} ctx.roomIndex+ * @param {Array<{x:number,z:number}>} [ctx.avoid] occupied floor points (the door's bouncer)+ * @param {{slots:Array<object>, onMember?:(inst:object, slot:object)=>void}} [ctx.lineup]+ * directed members placed before any scatter. Each slot carries+ * `{x, y, z, yaw, clips, height?, timeScale?}`; `onMember` fires as each one+ * lands so the caller can direct it (speech, sway, gestures).+ * @param {number} [ctx.max] head-count for this room only, overriding the+ * constructor cap (the door line is longer than an interior's scatter)*/- mount({ envRoot, bounds, path, roomIndex = 0 }) {+ mount({ envRoot, bounds, path, roomIndex = 0, avoid = [], lineup = null, max = null }) {if (this._disposed || this.max <= 0) return;this.clear();+ // Seed the spacing check so nobody spawns on a spot that is already taken.+ this._placed = avoid.map((p) => ({ x: p.x, z: p.z }));const gen = ++this._gen;const root = new Group();root.name = 'club-crowd';this.scene.add(root);this._root = root;- this._populate({ gen, root, envRoot, bounds, path, roomIndex })+ const cap = Number.isFinite(max) ? Math.max(0, Math.floor(max)) : this.max;+ this._populate({ gen, root, envRoot, bounds, path, roomIndex, lineup, cap }).catch((err) => log.warn('[club-crowd] populate failed', err));}- async _populate({ gen, root, envRoot, bounds, path, roomIndex }) {+ async _populate({ gen, root, envRoot, bounds, path, roomIndex, lineup, cap }) {await this.load();if (gen !== this._gen) return; // room swapped while we were fetching+ const slots = (lineup?.slots || []).slice(0, cap);+ if (slots.length) {+ await this._populateLineup({ gen, root, path, slots, onMember: lineup.onMember });+ if (gen !== this._gen) return;+ }+ const budget = cap - slots.length;+ if (budget <= 0) return;+// Build the target roster: as many distinct avatars as the budget allows,// shuffled so each room differs. If the live roster is thin (gallery down),// cycle the bundled rigs up to a lively floor so the room never feels dead.const distinct = shuffle(this._roster);- const targets = distinct.slice(0, this.max);- const floor = Math.min(this.max, LIVELY_FLOOR);+ const targets = distinct.slice(0, budget);+ const floor = Math.min(budget, LIVELY_FLOOR);for (let i = 0; targets.length < floor && distinct.length; i++) {targets.push(distinct[i % distinct.length]);}- if (this._roster.length > this.max) {- log.info(`[club-crowd] roster ${this._roster.length} exceeds budget ${this.max} — showing ${this.max} this room`);+ if (this._roster.length > budget) {+ log.info(`[club-crowd] roster ${this._roster.length} exceeds budget ${budget} — showing ${budget} this room`);}const danceRatio = DANCE_RATIO[Math.min(roomIndex, DANCE_RATIO.length - 1)] ?? 0.3;@@ -275,6 +304,29 @@ export class ClubCrowd {}}+ // Fill the directed slots in order. Downloads stay bounded no matter how long+ // the line is: at most LINEUP_DISTINCT unique rigs are fetched and the rest of+ // the line reuses them as clones at different heights. An undrivable rig is+ // swapped for the next one in the pool so a slot never stays empty while a+ // working rig exists.+ async _populateLineup({ gen, root, path, slots, onMember }) {+ const pool = shuffle(this._roster).slice(0, LINEUP_DISTINCT);+ let cursor = 0;+ for (const slot of slots) {+ let tpl = null;+ for (let tries = 0; tries < pool.length && !tpl; tries++) {+ const cand = await this._template(pool[cursor++ % pool.length].url);+ if (gen !== this._gen) return;+ if (cand?.scene && cand.drivable) tpl = cand;+ }+ if (!tpl) return; // no drivable rig at all: an empty line beats a T-posed one+ const inst = this._spawn(root, tpl, slot, path, false, slot);+ this._placed.push({ x: slot.x, z: slot.z });+ try { onMember?.(inst, slot); } catch (err) { log.warn('[club-crowd] lineup onMember failed', err); }+ await new Promise((r) => setTimeout(r, 0));+ }+ }+// Find a clear floor point: inside the bounds, off the walk lane, away from// the spawn, and not on top of another crowd member. Null when none found._pickSpot(envRoot, bounds, path) {@@ -306,11 +358,12 @@ export class ClubCrowd {return hit ? Math.max(0, hit.point.y) : 0;}- _spawn(root, tpl, spot, path, wantDance) {- const clip = this._pickClip(tpl, wantDance);+ _spawn(root, tpl, spot, path, wantDance, slot = null) {+ const clip = this._pickClip(tpl, wantDance, slot?.clips);const model = cloneSkinnedScene(tpl.scene);model.traverse((n) => { if (n.isMesh) n.castShadow = false; });- scaleToHeight(model, MIN_HEIGHT + Math.random() * (MAX_HEIGHT - MIN_HEIGHT));+ const height = slot?.height || MIN_HEIGHT + Math.random() * (MAX_HEIGHT - MIN_HEIGHT);+ scaleToHeight(model, height);groundFeet(model);const group = new Group();@@ -321,23 +374,53 @@ export class ClubCrowd {const cx = (path.spawn.x + path.door.x) / 2;const cz = (path.spawn.z + path.door.z) / 2;const faceYaw = Math.atan2(cx - spot.x, cz - spot.z);- group.rotation.y = wantDance+ if (Number.isFinite(slot?.yaw)) group.rotation.y = slot.yaw;+ else group.rotation.y = wantDance? Math.random() * Math.PI * 2: faceYaw + (Math.random() - 0.5) * 1.1;root.add(group);let mixer = null;+ let base = null;if (clip) {mixer = new AnimationMixer(model);- const action = mixer.clipAction(clip);- action.time = Math.random() * (clip.duration || 1); // desync the loop- action.play();+ base = mixer.clipAction(clip);+ base.time = Math.random() * (clip.duration || 1); // desync the loop+ if (slot?.timeScale) base.timeScale = slot.timeScale;+ base.play();}- this._instances.push({ group, mixer, model });+ const inst = { group, mixer, model, base, height, clips: tpl.clips, gesturing: false };+ this._instances.push(inst);+ return inst;+ }++ /**+ * Play a short one-shot gesture (a shrug, a nod, a point) over a member's+ * loop, then settle back into the loop. The first name this rig can play+ * wins; a rig with none of them just keeps looping. No-op mid-gesture.+ */+ gesture(inst, names) {+ if (!inst?.mixer || !inst.base || inst.gesturing) return;+ const name = names.find((n) => inst.clips.has(n));+ if (!name) return;+ const { mixer, base } = inst;+ const act = mixer.clipAction(inst.clips.get(name));+ act.reset();+ act.setLoop(LoopOnce, 1);+ act.clampWhenFinished = true;+ act.crossFadeFrom(base, 0.3, false).play();+ inst.gesturing = true;+ const onFinished = (e) => {+ if (e.action !== act) return;+ mixer.removeEventListener('finished', onFinished);+ base.reset().crossFadeFrom(act, 0.35, false).play();+ inst.gesturing = false;+ };+ mixer.addEventListener('finished', onFinished);}- _pickClip(tpl, wantDance) {- const pool = wantDance ? DANCE_CLIPS : IDLE_CLIPS;+ _pickClip(tpl, wantDance, preferred = null) {+ const pool = preferred?.length ? preferred : wantDance ? DANCE_CLIPS : IDLE_CLIPS;const avail = pool.filter((n) => tpl.clips.has(n));const pick = avail.length ? avail[Math.floor(Math.random() * avail.length)] : null;// Always fall back to a held clip so the member is never a static T-pose.diff --git a/src/club-entrance.js b/src/club-entrance.jsindex 64da9ea11..9eec752a2 100644--- a/src/club-entrance.js+++ b/src/club-entrance.js@@ -5,7 +5,8 @@// joystick) and look around (drag). We never auto-walk you. You spawn OUTSIDE// in the alley and walk up to the neon door; step into range and a prompt// appears — press E, tap, or click — and the cover-charge card (src/club-gate.js)-// asks you to pay. Pay the cover and you keep walking, under your own control,+// asks you to pay. The bouncer (src/club-bouncer.js) stands beside that door,+// watches you walk up, and acts out each beat of the cover flow. Pay the cover and you keep walking, under your own control,// through each place in turn — a gallery hall, then the Space Smugglers club// house interior — until you reach the strip club itself (the pole stage, in// src/club.js), where you tip dancers to perform.@@ -55,6 +56,8 @@ import {import { gltfLoader, disposeGltfLoader } from './loaders/gltf.js';import { AnimationManager } from './animation-manager.js';import { ClubCrowd } from './club-crowd.js';+import { ClubDoorLine } from './club-queue.js';+import { ClubBouncer, BOUNCER_AVATAR_URL } from './club-bouncer.js';import { detectProfile, PROFILES, createFrameWatchdog } from './club-perf.js';import { getPowerSaver } from './shared/frame-governor.js';import { log } from './shared/log.js';@@ -71,6 +74,11 @@ const PASS_KEY = 'club:pass:v1';// Hard cap on background crowd bodies per room. Each member is a full skinned// GLB rig (not an instanced mesh), so we keep the floor light for load + perf.const MAX_CROWD_PER_SCENE = 5;+// The alley is the exception: outside the door there is a line (src/club-queue.js),+// and a line of five reads as nobody waiting. Every body past the sixth unique rig+// is a clone, so the extra cost is skinning, not downloads; still tiered so a weak+// GPU gets a short line rather than a slow one.+const DOOR_LINE_BODIES = { high: 11, medium: 8, low: 5 };const MOVE_CLIPS = new Set(['idle', 'walk']);// Canonical URLs for the player's locomotion clips, kept independent of the// manifest so they survive a failed/empty manifest fetch. These back the@@ -288,9 +296,12 @@ async function start(canvasEl) {// ready the moment you walk into it. The loader bar tracks real bytes.// Clip JSON is fetched in the same parallel batch so idle is guaranteed// ready before the first render frame — no T-pose on entry.- const [firstGltf, avatarGltf, manifest, idleClipJson, walkClipJson] = await Promise.all([+ // The bouncer rides the same batch so he is at his post on the first frame+ // instead of popping in beside the door; a failed load just means no bouncer.+ const [firstGltf, avatarGltf, bouncerGltf, manifest, idleClipJson, walkClipJson] = await Promise.all([loader.loadAsync(SEQUENCE[0].url, (e) => setLoaderProgress('alley', e)),loader.loadAsync(AVATAR_URL, (e) => setLoaderProgress('avatar', e)),+ loader.loadAsync(BOUNCER_AVATAR_URL).catch((err) => { log.warn('[club-entrance] bouncer load failed', err); return null; }),fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => (r.ok ? r.json() : [])).catch(() => []),fetch('/animations/clips/idle.json', { cache: 'force-cache' }).then((r) => r.ok ? r.json() : null).catch(() => null),fetch('/animations/clips/walk.json', { cache: 'force-cache' }).then((r) => r.ok ? r.json() : null).catch(() => null),@@ -309,12 +320,14 @@ async function start(canvasEl) {let paid = false;let currentCover = false;let env = null, doorAnchor = null, path = null, occluder = null;+ let bouncer = null; // works the cover door only; stands down once you are past itmountVenue(0);function mountVenue(i) {const v = SEQUENCE[i];if (occluder) { scene.remove(occluder); disposeObject(occluder); occluder = null; }if (env) { disposeObject(env.root); scene.remove(env.root); }+ if (!v.cover) bouncer?.unmount();env = mountEnvironment(scene, loaded[i].scene);// Anchor to the modelled door so the prompt + neon frame land on the real// doorway; interiors skip this and exit down their longest dimension.@@ -373,9 +386,38 @@ async function start(canvasEl) {bundled: BUNDLED_AGENTS,});crowd.load(); // background fetch of roster + clip data; mount() awaits it+ // The line outside the door: only the cover venue (the alley) has one.+ let doorLine = null;const refreshCrowd = () => {if (!env) return;- crowd.mount({ envRoot: env.root, bounds: env.bounds, path, roomIndex: venueIndex });+ doorLine?.dispose();+ doorLine = null;+ if (SEQUENCE[venueIndex].cover) {+ try {+ doorLine = new ClubDoorLine({+ scene,+ crowd,+ envRoot: env.root,+ path,+ doorAnchor,+ count: DOOR_LINE_BODIES[profile.tier] ?? DOOR_LINE_BODIES.medium,+ bubblesEl: document.getElementById('club-bubbles'),+ reducedMotion: prefersReducedMotion,+ });+ } catch (err) {+ log.warn('[club-entrance] door line failed', err);+ }+ }+ crowd.mount({+ lineup: doorLine?.lineup,+ max: doorLine ? doorLine.count : undefined,+ envRoot: env.root,+ bounds: env.bounds,+ path,+ roomIndex: venueIndex,+ // Nobody in the crowd stands on the bouncer's spot.+ avoid: bouncer?.mounted ? [bouncer.position] : [],+ });};// ── Door marker — a neon frame at the end of the alley you walk up to ────@@ -401,6 +443,24 @@ async function start(canvasEl) {const camRay = new Raycaster();placeSpawn();++ // ── Bouncer: the doorman beside the cover door ──────────────────────────+ if (bouncerGltf && currentCover) {+ bouncer = new ClubBouncer({+ scene,+ model: bouncerGltf.scene,+ manifest,+ idleClipJson,+ bubbleEl: document.getElementById('club-bouncer-bubble'),+ reducedMotion: prefersReducedMotion,+ });+ const posted = await bouncer.mount({ envRoot: env.root, path, doorAnchor }).catch((err) => {+ log.warn('[club-entrance] bouncer mount failed', err);+ return false;+ });+ if (!posted) { bouncer.dispose(); bouncer = null; }+ }+refreshCrowd(); // populate the opening room (alley)// Cast straight down from waist height to find the walkable floor.@@ -533,12 +593,14 @@ async function start(canvasEl) {canvasEl.addEventListener('pointerup', endPointer);canvasEl.addEventListener('pointercancel', endPointer);- // Click the neon door directly to enter.+ // Click the neon door directly to enter, or the bouncer to hear how the+ // club works.const raycaster = new Raycaster();const onClick = (e) => {if (!inputEnabled || look.moved) return;const ndc = new Vector2((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1);raycaster.setFromCamera(ndc, camera);+ if (bouncer?.hitTest(raycaster)) { bouncer.explain(); return; }if (raycaster.intersectObject(doorMarker.group, true).length) tryEnter();};canvasEl.addEventListener('click', onClick);@@ -789,6 +851,7 @@ async function start(canvasEl) {// place fades out and the next one fades in for you to keep walking.function advance() {nearDoor = false;+ bouncer?.hush();if (isFinalVenue()) {setJourneyStep(SEQUENCE.length); // light the Stage steppushClarity(1); // stepping onto the floor — fully open the bed@@ -866,6 +929,8 @@ async function start(canvasEl) {anim.update(dt);crowd.update(dt);updateCamera(dt);+ bouncer?.update(dt, rig.position, camera, { nearDoor, interactive: inputEnabled && phase === 'walk' });+ doorLine?.update(dt, rig.position, camera, { nearDoor, paid });if (phase === 'walk') minimap.update(rig.position, rig.rotation.y, nearDoor, now / 1000, prefersReducedMotion);// Key + fill follow the avatar so the patch of alley you're walking is lit.@@ -893,6 +958,7 @@ async function start(canvasEl) {// Fade the current place out, mount the next, then fade it in.const k = Math.min(1, elapsed / 0.6);canvasEl.style.opacity = String(1 - k);+ doorLine?.setOpacity(1 - k);if (k >= 1) {const next = loaded[venueIndex + 1];if (next && next !== 'error') {@@ -975,6 +1041,8 @@ async function start(canvasEl) {const speed = MOVE_SPEED * Math.min(1, len);rig.position.x = clamp(rig.position.x + wx * speed * dt, env.bounds.minX, env.bounds.maxX);rig.position.z = clamp(rig.position.z + wz * speed * dt, env.bounds.minZ, env.bounds.maxZ);+ // The bouncer holds his ground: you walk around him, not through him.+ bouncer?.resolveCollision(rig.position, performance.now());// Face travel direction (shortest-arc yaw lerp).const targetYaw = Math.atan2(wx, wz);rig.rotation.y = lerpAngle(rig.rotation.y, targetYaw, 1 - Math.exp(-12 * dt));@@ -1041,6 +1109,7 @@ async function start(canvasEl) {// Cover's paid and the rope drops — crack the door open so the bed clears// its first step the moment the walk-in dance starts.pushClarity(clarityForVenue(venueIndex));+ doorLine?.admitted(); // the people still waiting watch you get waved throughawait celebrateAdmission();advance();}@@ -1109,7 +1178,9 @@ async function start(canvasEl) {agentBrowseBtn?.removeEventListener('click', onBrowseAgents);onAdmit = null;try { anim.dispose?.(); } catch {}+ try { doorLine?.dispose(); } catch {}try { crowd.dispose(); } catch {}+ try { bouncer?.dispose(); } catch {}disposeObject(scene);composer.dispose();renderer.dispose();diff --git a/src/club-gate.js b/src/club-gate.jsindex 51eef6fc0..a52a01f39 100644--- a/src/club-gate.js+++ b/src/club-gate.js@@ -7,6 +7,7 @@// room is already warm the moment you're admitted.//// Flow: queue → [Pay cover] → x402 modal → checking → admitted | denied+// Each step is mirrored to the doorman in the alley via `club:door-state`.//// A paid wallet's pass is cached locally for its lifetime, so a reload within// the night re-enters without paying again (the cover endpoint mirrors this@@ -126,16 +127,17 @@ async function payCover(root, { payBtn, msgEl, tierEl }) {await wait(900);if (pass.admitted === false || pass.banned) {- setState(root, 'denied');+ const reason = pass.reason || 'Not on the list tonight.';+ setState(root, 'denied', { reason });const reasonEl = root.querySelector('#club-door-reason');- if (reasonEl) reasonEl.textContent = pass.reason || 'Not on the list tonight.';+ if (reasonEl) reasonEl.textContent = reason;return;}// In. Cache the pass and announce the tier, then drop the rope.writePass(pass);if (tierEl) tierEl.textContent = welcomeFor(pass);- setState(root, 'admitted');+ setState(root, 'admitted', { tier: pass.tier, visits: pass.visits });await wait(1100);openDoor(root);} catch (err) {@@ -183,8 +185,11 @@ function openDoor(root, { silent = false } = {}) {}}-function setState(root, state) {+// Every state change is also announced on `club:door-state`, so the 3D bouncer+// in the alley (src/club-bouncer.js) acts out the same beat the card shows.+function setState(root, state, detail = {}) {root.dataset.state = state;+ window.dispatchEvent(new CustomEvent('club:door-state', { detail: { ...detail, state } }));}function setMsg(el, text, kind) {diff --git a/src/club-queue.js b/src/club-queue.jsnew file mode 100644index 000000000..4f5751041--- /dev/null+++ b/src/club-queue.js@@ -0,0 +1,847 @@+// /club door line: the queue outside the club.+//+// The alley (src/club-entrance.js) used to be a quiet set with a few avatars+// scattered around it. This module turns it into the outside of a club on a busy+// night: a line of people waiting along the wall beside the door, held back by+// a velvet rope on brass stanchions, talking to each other in speech bubbles,+// with a neon sign over the doorway and a couple of people who started the+// night early: one swaying in the line, one staggering around the alley, one+// slumped against the wall.+//+// Three parts, split so the logic is testable without a GPU:+//+// planDoorLine() pure layout. Given the door, the approach axis and three+// probes (floor height, wall distance, line of sight) it+// returns where everyone stands, where the rope runs and+// where the drunk staggers. It reads the real geometry, so it+// works in any alley: the line hugs whichever side of the door+// has room, and bends down the alley when the wall runs out.+// QueueChatter pure conversation director. Deals scripted exchanges to+// neighbours in the line, solo mutters to the drunks, and+// reactions to what the player does (walking up to the door+// past everyone, brushing the line, getting let in).+// ClubDoorLine the scene side: probes the environment, builds the rope and+// sign, hands the slots to ClubCrowd (src/club-crowd.js) as a+// directed lineup, animates the drunks, and pins the DOM+// speech bubbles over heads every frame.+//+// The bodies are ordinary crowd members: real platform avatars retargeted onto+// the shared clip library. The clip library has no "drunk" animation, so the+// drunks are procedural: a slowed clip plus a lean about the feet built from+// incommensurate sines, and for the stagger a weaving walk along a short beat.+// Everything here is ambient. Any failure degrades to a quieter alley; the door,+// the cover card and the walk-in never depend on it.++import {+ CanvasTexture,+ CylinderGeometry,+ Group,+ Mesh,+ MeshBasicMaterial,+ MeshStandardMaterial,+ PlaneGeometry,+ QuadraticBezierCurve3,+ Raycaster,+ SphereGeometry,+ SRGBColorSpace,+ TubeGeometry,+ Vector3,+} from 'three';++// ── Layout constants (metres) ────────────────────────────────────────────────+// `along` runs sideways from the door's centre line, `out` runs from the wall+// face into the alley.+const HEAD_GAP = 2.4; // the head of the line starts this far from the door: clear of the doorman+const STEP = 0.58; // spacing along the wall; with the zig-zag below, neighbours sit ~0.85 apart+const ROW_NEAR = 0.5; // wall-side row+const ROW_FAR = 1.1; // alley-side row+const LEAN_OUT = 0.3; // a leaner stands with their back on the brick+const ROPE_OUT = 1.72; // the rope runs outside the far row+const BEND_STEP = 0.8; // spacing once the line turns down the alley+const EDGE_MARGIN = 0.4; // floor must continue this far past a slot (no standing on a ledge)+const FLOOR_TOLERANCE = 0.3; // the line stays on one level: no slot up the door steps+const POST_SPACING = 1.5;+const POST_HEIGHT = 0.98;++// What people in a line do with their bodies while they wait.+const WAIT_CLIPS = ['av-waiting', 'av-idle-breath', 'av-chilling', 'av-listening-music', 'av-smoking', 'idle'];+const LEAN_CLIPS = ['av-leaning-wall', 'av-chilling', 'idle'];+const SWAY_CLIPS = ['av-listening-music', 'av-idle-breath', 'idle'];+const SLUMP_CLIPS = ['lookdown', 'av-idle-breath', 'idle'];+const STAGGER_CLIPS = ['walk'];+const TALK_GESTURES = ['shrug', 'nod', 'point'];++const SIGN_TEXT = 'POLE CLUB';++// ── Pure layout ──────────────────────────────────────────────────────────────++function lerpAngle(a, b, t) {+ let d = (b - a) % (Math.PI * 2);+ if (d > Math.PI) d -= Math.PI * 2;+ if (d < -Math.PI) d += Math.PI * 2;+ return a + d * t;+}++/**+ * Lay out the door line from real geometry probes.+ *+ * @param {object} o+ * @param {{x:number,z:number}} o.door the spot just in front of the door+ * @param {{x:number,z:number}} o.dir unit vector from the door out into the alley+ * @param {number} o.count total bodies available (device budget)+ * @param {(x:number,z:number)=>number|null} o.floorAt floor height, null over a void+ * @param {(x:number,z:number,dx:number,dz:number)=>number|null} o.wallDistance+ * distance to the first surface at chest height along a direction+ * @param {(ax:number,az:number,bx:number,bz:number)=>boolean} o.clearBetween+ * true when nothing solid sits between two floor points+ * @param {()=>number} [o.rng]+ * @returns {{side:number, wallOut:number, slots:Array<object>, posts:Array<{x:number,y:number,z:number}>, beat:object|null}}+ */+export function planDoorLine({ door, dir, count, floorAt, wallDistance, clearBetween, rng = Math.random }) {+ const perp = { x: dir.z, z: -dir.x };+ const at = (side, along, out) => ({+ x: door.x + perp.x * side * along + dir.x * out,+ z: door.z + perp.z * side * along + dir.z * out,+ });++ // Split the budget: a full night has a stagger and a slump besides the line.+ const total = Math.max(0, Math.floor(count) || 0);+ const wantStagger = total >= 5;+ const wantSlump = total >= 8;+ const lineTarget = total - (wantStagger ? 1 : 0) - (wantSlump ? 1 : 0);++ // Walk each side of the door outward and keep the side that fits more people.+ const sides = [1, -1].map((side) => walkSide(side));+ sides.sort((a, b) => b.line.length - a.line.length);+ const best = sides[0];+ const side = best.side;++ function walkSide(s) {+ // Where is the wall face, measured along `dir` from the door point? The+ // door itself is usually recessed, so probe beside it, not through it.+ const probe = at(s, HEAD_GAP, 1.5);+ const w = wallDistance(probe.x, probe.z, -dir.x, -dir.z);+ const wallOut = w == null || w > 4 ? 0 : 1.5 - w;++ const line = [];+ const head = at(s, HEAD_GAP, wallOut + ROW_NEAR);+ const refFloor = floorAt(head.x, head.z);+ if (refFloor == null) return { side: s, wallOut, line, bendAt: null };++ const standable = (p, prev) => {+ const y = floorAt(p.x, p.z);+ if (y == null || Math.abs(y - refFloor) > FLOOR_TOLERANCE) return null;+ if (prev && !clearBetween(prev.x, prev.z, p.x, p.z)) return null;+ return y;+ };++ // Along the wall, zig-zagging between the two rows so it reads as a crowd+ // two abreast rather than a row of fence posts.+ let prev = null;+ let lastAlong = HEAD_GAP;+ for (let k = 0; line.length < lineTarget; k++) {+ const along = HEAD_GAP + k * STEP;+ const near = k % 2 === 0;+ const p = at(s, along, wallOut + (near ? ROW_NEAR : ROW_FAR));+ const edge = at(s, along + EDGE_MARGIN, wallOut + ROW_FAR);+ const y = standable(p, prev);+ if (y == null || floorAt(edge.x, edge.z) == null) break;+ line.push({ ...p, y, along, near, bent: false });+ prev = p;+ lastAlong = along;+ }++ // Out of wall: the line turns the corner and carries on down the alley.+ let bendAt = null;+ if (line.length && line.length < lineTarget) {+ bendAt = lastAlong;+ for (let j = 1; line.length < lineTarget; j++) {+ const lateral = lastAlong - (j % 2 ? 0 : 0.34);+ const p = at(s, lateral, wallOut + ROW_FAR + j * BEND_STEP);+ const y = standable(p, prev);+ if (y == null) break;+ line.push({ ...p, y, along: lateral, near: false, bent: true });+ prev = p;+ }+ }+ return { side: s, wallOut, line, bendAt };+ }++ const { wallOut, line, bendAt } = best;+ const towardDoor = Math.atan2(-perp.x * side, -perp.z * side);+ const towardWall = Math.atan2(-dir.x, -dir.z);+ const outFromWall = Math.atan2(dir.x, dir.z);++ // Who is the drunk in the line: second from the back, where they hold nobody up.+ const swayIndex = line.length >= 4 ? line.length - 2 : -1;++ const slots = line.map((p, i) => {+ const base = p.bent ? towardWall : towardDoor;+ // Neighbours pair off (0-1, 2-3, ...) and half turn toward each other, the+ // way people do when they are mid-conversation in a queue.+ const partner = line[i % 2 === 0 ? i + 1 : i - 1];+ let yaw = base + (rng() - 0.5) * 0.4;+ if (partner) yaw = lerpAngle(yaw, Math.atan2(partner.x - p.x, partner.z - p.z), 0.42);++ const drunk = i === swayIndex ? 'sway' : null;+ // A few people in the wall row put their back on the brick.+ const lean = !drunk && p.near && !p.bent && i > 0 && i % 4 === 2;+ const spot = lean ? at(side, p.along, wallOut + LEAN_OUT) : p;+ return {+ role: 'line',+ order: i,+ x: spot.x,+ y: p.y,+ z: spot.z,+ yaw: lean ? outFromWall + (rng() - 0.5) * 0.3 : yaw,+ clips: drunk ? SWAY_CLIPS : lean ? LEAN_CLIPS : WAIT_CLIPS,+ timeScale: drunk ? 0.6 : 0.9 + rng() * 0.2,+ drunk,+ };+ });++ // The staggering drunk works a short beat in the open alley on the far side+ // of the door; the slumped one props up the wall over there.+ let beat = null;+ if (wantStagger && slots.length) {+ const a = at(-side, 1.9, wallOut + 2.5);+ let b = null;+ for (const reach of [4.1, 3.4, 2.9]) {+ const c = at(-side, reach, wallOut + 3.4);+ if (floorAt(c.x, c.z) != null && clearBetween(a.x, a.z, c.x, c.z)) { b = c; break; }+ }+ const ya = floorAt(a.x, a.z);+ if (b && ya != null) {+ beat = { a, b };+ slots.splice(Math.min(3, slots.length), 0, {+ role: 'stagger', x: a.x, y: ya, z: a.z,+ yaw: Math.atan2(b.x - a.x, b.z - a.z),+ clips: STAGGER_CLIPS, timeScale: 0.55, drunk: 'stagger',+ });+ }+ }+ if (wantSlump && slots.length) {+ const p = at(-side, 2.5, wallOut + 0.42);+ const y = floorAt(p.x, p.z);+ if (y != null && Math.abs(y - slots[0].y) <= FLOOR_TOLERANCE) {+ slots.push({+ role: 'slump', x: p.x, y, z: p.z,+ yaw: outFromWall + (rng() - 0.5) * 0.5,+ clips: SLUMP_CLIPS, timeScale: 0.5, drunk: 'slump',+ });+ }+ }++ // Rope: outside the far row from the head of the line to its tail, turning+ // the corner with the line when it bends.+ const posts = [];+ if (line.length) {+ const tailAlong = (bendAt ?? line[line.length - 1].along);+ const corners = [[HEAD_GAP - 0.55, wallOut + ROPE_OUT]];+ if (bendAt == null) {+ corners.push([tailAlong + 0.55, wallOut + ROPE_OUT]);+ } else {+ const last = line[line.length - 1];+ const lastOut = (last.x - door.x) * dir.x + (last.z - door.z) * dir.z;+ corners.push([bendAt - 0.85, wallOut + ROPE_OUT]);+ corners.push([bendAt - 0.85, lastOut + 0.5]);+ }+ for (let i = 0; i < corners.length; i++) {+ const [a0, o0] = corners[i];+ if (i === 0) { pushPost(a0, o0); continue; }+ const [ap, op] = corners[i - 1];+ const len = Math.hypot(a0 - ap, o0 - op);+ const n = Math.max(1, Math.ceil(len / POST_SPACING));+ for (let k = 1; k <= n; k++) pushPost(ap + ((a0 - ap) * k) / n, op + ((o0 - op) * k) / n);+ }+ }+ function pushPost(along, out) {+ const p = at(side, along, out);+ const y = floorAt(p.x, p.z);+ if (y != null) posts.push({ x: p.x, y, z: p.z });+ }++ return { side, wallOut, slots, posts, beat };+}++// ── Pure conversation director ───────────────────────────────────────────────++// Two people, next to each other in the line. `a` is nearer the door.+export const EXCHANGES = [+ [['a', 'How long have you been out here?'], ['b', 'Since the last block confirmed.']],+ [['a', 'The cover is one cent. One.'], ['b', 'And you still asked me to spot you.']],+ [['a', 'Is it true a tip puts a dancer on the pole?'], ['b', 'A tenth of a cent. Settles on Solana. I checked.']],+ [['a', 'Who is dancing tonight?'], ['b', 'Whoever gets tipped first. That is the whole point.']],+ [['a', 'I can hear the bass through the wall.'], ['b', 'Wait until that door opens.']],+ [['a', 'Think the bouncer remembers me?'], ['b', 'He reads your wallet. He remembers everything.']],+ [['a', 'I hold $THREE. Does that get me in faster?'], ['b', 'Gets you respect. The line is still the line.']],+ [['a', 'These shoes were a mistake.'], ['b', 'You say that every night.']],+ [['a', 'Save my spot? I need to find a bathroom.'], ['b', 'No.']],+ [['a', 'What even is x402?'], ['b', 'You pay, the door opens. No account, no forms.'], ['a', 'That is it?'], ['b', 'That is it.']],+ [['a', 'Is this the line for the club or the wallet drainer?'], ['b', 'Club. The drainer has a much nicer website.']],+ [['a', 'My pass from last night should still work.'], ['b', 'It lasts the night. It is tomorrow.']],+ [['a', 'I am only staying for one song.'], ['b', 'You said that at the last three poles.']],+ [['a', 'Do they take cash?'], ['b', 'They take USDC. Cash is for the dumpster.']],+ [['a', 'We have moved two steps in twenty minutes.'], ['b', 'Two steps closer than we were.']],+];++// A sober neighbour and the drunk swaying in the line beside them.+export const DRUNK_EXCHANGES = [+ [['sober', 'You good?'], ['drunk', 'Never better. *hic*']],+ [['drunk', 'Is thish the line for tacos?'], ['sober', 'It is the line for the club.'], ['drunk', 'Even better.']],+ [['drunk', 'I love you guys. All of you.'], ['sober', 'We met four minutes ago.']],+ [['sober', 'Maybe get some water first.'], ['drunk', 'Water is jusht beer with no ambition.']],+ [['drunk', 'Hold my shpot. I need to lie down.'], ['sober', 'You are standing in it.']],+];++export const SOLO = {+ sway: ['*hic*', 'I am fine. I am FINE.', 'Who keeps moving the wall?', 'One more song. Jusht one.'],+ stagger: [+ 'I tipped a lamp post. No dancer came out.',+ 'The ground is shpinning clockwise. Bullish.',+ 'Where did I park my wallet?',+ '*hic* ...which way is the door?',+ 'I am not lost. The alley is lost.',+ ],+ slump: ['Just resting my eyes.', 'Tell the bouncer I am shober.', 'Five more minutes.', 'Zzz...'],+};++export const REACTIONS = {+ // The player walks straight up to the door, past everyone waiting.+ cut: [[['head', 'Hey! There is a line!'], ['second', 'Every night. Somebody with a wallet walks right up.']]],+ // The player drifts into the line itself.+ brush: ['Back of the line is that way.', 'Personal space. Ever heard of it?', 'Easy. We are all waiting here.'],+ staggerBump: ['Whoa. There are two of you.', 'Heyyy. You are my besht friend.', 'Shorry. The floor moved.'],+ admitted: [[['head', 'Unbelievable.'], ['second', 'It was one cent. We could have done that.']]],+};++const BRUSH_RANGE = 1.0;+const STAGGER_BUMP_RANGE = 1.5;+const REACTION_COOLDOWN = 11; // seconds between proximity reactions++export function lineDuration(text) {+ return Math.min(6, Math.max(2.2, 1.4 + text.length * 0.06));+}++// A deck that deals every card before it repeats one.+function makeDeck(items, rng) {+ let pile = [];+ return () => {+ if (!pile.length) {+ pile = items.slice();+ for (let i = pile.length - 1; i > 0; i--) {+ const j = Math.floor(rng() * (i + 1));+ [pile[i], pile[j]] = [pile[j], pile[i]];+ }+ }+ return pile.pop();+ };+}++export class QueueChatter {+ /**+ * @param {object} o+ * @param {(member:object, text:string, seconds:number)=>void} o.say+ * @param {()=>number} [o.rng]+ */+ constructor({ say, rng = Math.random }) {+ this.say = say;+ this.rng = rng;+ this.members = [];+ this.pending = []; // [{ at, member, text, dur }] sorted by time+ this.clock = 0;+ this.busyUntil = 0;+ this.nextAmbientAt = 2.5;+ this.nextReactionAt = 0;+ this.cutSeen = false;+ this._decks = {+ exchange: makeDeck(EXCHANGES, rng),+ drunkExchange: makeDeck(DRUNK_EXCHANGES, rng),+ sway: makeDeck(SOLO.sway, rng),+ stagger: makeDeck(SOLO.stagger, rng),+ slump: makeDeck(SOLO.slump, rng),+ brush: makeDeck(REACTIONS.brush, rng),+ staggerBump: makeDeck(REACTIONS.staggerBump, rng),+ };+ }++ /** Register a member as they arrive: `{ role, order, drunk, position }`. */+ add(member) {+ this.members.push(member);+ }++ _line() {+ return this.members.filter((m) => m.role === 'line').sort((a, b) => a.order - b.order);+ }++ // Queue a scripted run of lines, one after another. `cast` maps a script's+ // speaker key to a member. Anything already queued is dropped: the newest+ // thing happening in the alley wins.+ _run(script, cast, startIn = 0) {+ this.pending = [];+ let at = Math.max(this.clock, this.busyUntil) + startIn;+ for (const [who, text] of script) {+ const member = cast[who];+ if (!member) continue;+ const dur = lineDuration(text);+ this.pending.push({ at, member, text, dur });+ at += dur + 0.35;+ }+ this.busyUntil = at;+ this.nextAmbientAt = at + 1.2 + this.rng() * 2.6;+ }++ _interrupt(script, cast) {+ this.busyUntil = this.clock; // talk over whatever was being said+ this._run(script, cast);+ }++ _scheduleAmbient(playerPos) {+ const line = this._line();+ const drunks = this.members.filter((m) => m.drunk && m.role !== 'line');+ const swayer = line.find((m) => m.drunk === 'sway');++ // Adjacent pairs, nearest the player first so the talk happens where they+ // are looking most of the time.+ const pairs = [];+ for (let i = 0; i + 1 < line.length; i++) {+ if (line[i + 1].order === line[i].order + 1) pairs.push([line[i], line[i + 1]]);+ }+ const dist = (m) => (playerPos ? Math.hypot(m.position.x - playerPos.x, m.position.z - playerPos.z) : 0);+ pairs.sort((p, q) => dist(p[0]) - dist(q[0]));++ const roll = this.rng();+ const soloists = swayer ? [...drunks, swayer] : drunks;+ if (soloists.length && (roll < 0.34 || !pairs.length)) {+ const who = soloists[Math.floor(this.rng() * soloists.length)];+ this._run([['solo', this._decks[who.drunk]()]], { solo: who });+ return;+ }+ if (!pairs.length) { this.nextAmbientAt = this.clock + 2; return; }++ const near = pairs.slice(0, Math.max(1, Math.ceil(pairs.length / 2)));+ const pool = this.rng() < 0.65 ? near : pairs;+ const [a, b] = pool[Math.floor(this.rng() * pool.length)];+ if (a.drunk || b.drunk) {+ this._run(this._decks.drunkExchange(), { drunk: a.drunk ? a : b, sober: a.drunk ? b : a });+ } else {+ this._run(this._decks.exchange(), { a, b });+ }+ }++ /**+ * @param {number} dt+ * @param {{playerPos?:{x:number,z:number}, nearDoor?:boolean, paid?:boolean}} ctx+ */+ update(dt, { playerPos = null, nearDoor = false, paid = false } = {}) {+ this.clock += dt;++ if (playerPos && !paid) this._proximity(playerPos, nearDoor);++ while (this.pending.length && this.pending[0].at <= this.clock) {+ const u = this.pending.shift();+ this.say(u.member, u.text, u.dur);+ }+ if (!this.pending.length && this.clock >= this.nextAmbientAt && this.members.length) {+ this._scheduleAmbient(playerPos);+ }+ }++ _proximity(playerPos, nearDoor) {+ const line = this._line();+ if (nearDoor && !this.cutSeen && line.length) {+ this.cutSeen = true;+ this._interrupt(REACTIONS.cut[0], { head: line[0], second: line[1] });+ this.nextReactionAt = this.clock + REACTION_COOLDOWN;+ return;+ }+ if (this.clock < this.nextReactionAt) return;+ const within = (m, r) => Math.hypot(m.position.x - playerPos.x, m.position.z - playerPos.z) < r;+ const stagger = this.members.find((m) => m.role === 'stagger' && within(m, STAGGER_BUMP_RANGE));+ const brushed = stagger ? null : line.find((m) => within(m, BRUSH_RANGE));+ const who = stagger || brushed;+ if (!who) return;+ const text = stagger ? this._decks.staggerBump() : who.drunk ? this._decks.sway() : this._decks.brush();+ this._interrupt([['solo', text]], { solo: who });+ this.nextReactionAt = this.clock + REACTION_COOLDOWN;+ }++ /** The cover settled and the player is being waved through. */+ admitted() {+ const line = this._line();+ if (line.length) this._interrupt(REACTIONS.admitted[0], { head: line[0], second: line[1] });+ }+}++// ── Scene side ───────────────────────────────────────────────────────────────++const MAX_BUBBLES = 3;+const BUBBLE_RANGE = 17; // metres; past this a bubble is too small to read++const _head = new Vector3();+const _a = new Vector3();+const _b = new Vector3();++export class ClubDoorLine {+ /**+ * @param {object} o+ * @param {import('three').Scene} o.scene+ * @param {import('./club-crowd.js').ClubCrowd} o.crowd used for talk gestures+ * @param {import('three').Object3D} o.envRoot the mounted alley, for probes+ * @param {{door:import('three').Vector3, dir:import('three').Vector3}} o.path+ * @param {{center:import('three').Vector3, size:import('three').Vector3}|null} o.doorAnchor+ * @param {number} o.count bodies the device can afford+ * @param {HTMLElement|null} o.bubblesEl container for speech bubbles+ * @param {boolean} [o.reducedMotion]+ */+ constructor({ scene, crowd, envRoot, path, doorAnchor, count, bubblesEl, reducedMotion = false }) {+ this.scene = scene;+ this.crowd = crowd;+ this.envRoot = envRoot;+ this.bubblesEl = bubblesEl;+ this.reducedMotion = reducedMotion;+ this.members = [];+ this.bubbles = new Map(); // member → { el, until }+ this.time = 0;+ this._ray = new Raycaster();+ this._disposed = false;++ this.plan = planDoorLine({+ door: { x: path.door.x, z: path.door.z },+ dir: { x: path.dir.x, z: path.dir.z },+ count,+ floorAt: (x, z) => this._floorAt(x, z),+ wallDistance: (x, z, dx, dz) => this._cast(x, 1.0, z, dx, dz, 8),+ clearBetween: (ax, az, bx, bz) => {+ const len = Math.hypot(bx - ax, bz - az);+ if (len < 1e-3) return true;+ const hit = this._cast(ax, 0.9, az, (bx - ax) / len, (bz - az) / len, len + 0.3);+ return hit == null;+ },+ });++ this.chatter = new QueueChatter({ say: (m, text, dur) => this._say(m, text, dur) });++ this.props = new Group();+ this.props.name = 'club-door-line';+ if (this.plan.posts.length > 1) this.props.add(buildRope(this.plan.posts));+ const sign = this._buildSign(path, doorAnchor);+ if (sign) this.props.add(sign);+ scene.add(this.props);++ /** Hand this to ClubCrowd.mount() as `lineup`. */+ this.lineup = {+ slots: this.plan.slots,+ onMember: (inst, slot) => this._addMember(inst, slot),+ };+ }++ /** Bodies this line wants from the crowd budget. */+ get count() {+ return this.plan.slots.length;+ }++ _cast(x, y, z, dx, dz, far) {+ this._ray.set(_a.set(x, y, z), _b.set(dx, 0, dz).normalize());+ this._ray.far = far;+ const hit = this._ray.intersectObject(this.envRoot, true)[0];+ return hit ? hit.distance : null;+ }++ // Same floor band the player and the crowd sample: waist height down, so a+ // sculpture top or an awning is never mistaken for the ground.+ _floorAt(x, z) {+ this._ray.set(_a.set(x, 1.2, z), _b.set(0, -1, 0));+ this._ray.far = 1.6;+ const hit = this._ray.intersectObject(this.envRoot, true)[0];+ return hit ? Math.max(0, hit.point.y) : null;+ }++ // A neon sign on the brick over the doorway. Drawn once to a canvas; unlit and+ // not tone mapped, so the bloom pass makes it glow like the door frame below.+ _buildSign(path, doorAnchor) {+ if (typeof document === 'undefined') return null;+ const dir = path.dir;+ const topY = doorAnchor ? doorAnchor.center.y + doorAnchor.size.y / 2 : 2.7;+ const y = topY + 0.62;+ // Find the wall face above the door: cast back at the building from out in+ // the alley, at sign height.+ const from = _head.copy(path.door).addScaledVector(dir, 3);+ const d = this._cast(from.x, y, from.z, -dir.x, -dir.z, 8);+ if (d == null) return null; // nothing to hang it on++ const cv = document.createElement('canvas');+ cv.width = 1024;+ cv.height = 256;+ const ctx = cv.getContext('2d');+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.font = "italic 800 150px 'Inter', system-ui, sans-serif";+ ctx.lineJoin = 'round';+ // Three passes: a wide soft halo, the coloured tube, a hot white core.+ ctx.shadowColor = '#ff3bd6';+ ctx.shadowBlur = 46;+ ctx.strokeStyle = '#ff3bd6';+ ctx.lineWidth = 14;+ ctx.strokeText(SIGN_TEXT, 512, 132);+ ctx.shadowBlur = 16;+ ctx.lineWidth = 7;+ ctx.strokeStyle = '#ff8ae6';+ ctx.strokeText(SIGN_TEXT, 512, 132);+ ctx.shadowBlur = 0;+ ctx.lineWidth = 2.5;+ ctx.strokeStyle = '#fff4fd';+ ctx.strokeText(SIGN_TEXT, 512, 132);++ const map = new CanvasTexture(cv);+ map.colorSpace = SRGBColorSpace;+ const mat = new MeshBasicMaterial({ map, transparent: true, toneMapped: false, depthWrite: false });+ const mesh = new Mesh(new PlaneGeometry(2.9, 0.725), mat);+ mesh.position.copy(from).addScaledVector(dir, -(d - 0.07)).setY(y);+ mesh.rotation.y = Math.atan2(dir.x, dir.z);+ mesh.name = 'club-sign';+ this._signMat = mat;+ return mesh;+ }++ _addMember(inst, slot) {+ if (this._disposed) return;+ const member = {+ inst,+ role: slot.role,+ order: slot.order ?? -1,+ drunk: slot.drunk,+ position: inst.group.position, // live: the stagger moves+ baseYaw: slot.yaw,+ phase: Math.random() * Math.PI * 2,+ floorY: slot.y,+ floorTimer: 0,+ // stagger state+ u: 0,+ heading: 1,+ pause: 0,+ walking: true,+ };+ inst.group.rotation.order = 'YXZ'; // yaw first, then lean about the feet+ this.members.push(member);+ this.chatter.add(member);+ }++ _say(member, text, seconds) {+ if (!this.bubblesEl || this._disposed) return;+ let b = this.bubbles.get(member);+ if (!b) {+ if (this.bubbles.size >= MAX_BUBBLES) return; // the alley is loud enough+ const el = document.createElement('div');+ el.className = 'club-bubble';+ if (member.drunk) el.classList.add('is-drunk');+ const body = document.createElement('span');+ body.className = 'club-bubble-body';+ el.appendChild(body);+ this.bubblesEl.appendChild(el);+ b = { el, body, until: 0, lift: 0 };+ this.bubbles.set(member, b);+ }+ b.body.textContent = text;+ b.until = this.time + seconds;+ // Next frame, so the entry transition runs from the hidden state.+ requestAnimationFrame(() => b.el.classList.add('is-visible'));+ if (!member.drunk && !this.reducedMotion) this.crowd.gesture(member.inst, TALK_GESTURES);+ }++ /**+ * Per frame: run the conversation, move the drunks, pin the bubbles.+ *+ * @param {number} dt+ * @param {import('three').Vector3} playerPos+ * @param {import('three').Camera} camera+ * @param {{nearDoor?:boolean, paid?:boolean}} ctx+ */+ update(dt, playerPos, camera, { nearDoor = false, paid = false } = {}) {+ if (this._disposed) return;+ this.time += dt;+ this.chatter.update(dt, { playerPos, nearDoor, paid });+ if (!this.reducedMotion) for (const m of this.members) this._moveDrunk(m, dt);+ this._pinBubbles(camera);+ }++ /** The cover settled: the line watches the player get waved through. */+ admitted() {+ this.chatter.admitted();+ }++ // Procedural drunkenness. The lean is a sum of sines whose periods never line+ // up, so it never reads as a loop; it pivots at the feet because the group+ // origin is the floor point.+ _moveDrunk(m, dt) {+ if (!m.drunk) return;+ const t = this.time + m.phase;+ const g = m.inst.group;+ if (m.drunk === 'sway' || m.drunk === 'slump') {+ const amp = m.drunk === 'sway' ? 1 : 0.55;+ g.rotation.z = (Math.sin(t * 0.83) * 0.07 + Math.sin(t * 0.31) * 0.035) * amp;+ g.rotation.x = (Math.sin(t * 0.57 + 1.3) * 0.045 + 0.02) * amp;+ g.rotation.y = m.baseYaw + Math.sin(t * 0.23) * 0.12 * amp;+ return;+ }+ const beat = this.plan.beat;+ if (m.drunk !== 'stagger' || !beat) return;++ if (m.pause > 0) {+ // Stopped at the end of the beat, swaying on the spot and finding the+ // way back round.+ m.pause -= dt;+ g.rotation.z = Math.sin(t * 0.9) * 0.09;+ g.rotation.x = 0.04 + Math.sin(t * 0.6) * 0.05;+ const back = Math.atan2((beat.b.x - beat.a.x) * m.heading, (beat.b.z - beat.a.z) * m.heading);+ g.rotation.y = lerpAngle(g.rotation.y, back, 1 - Math.exp(-1.4 * dt));+ if (m.pause <= 0) this._setStaggerClip(m, true);+ return;+ }++ const len = Math.hypot(beat.b.x - beat.a.x, beat.b.z - beat.a.z) || 1;+ // Lurching pace: never steady, sometimes nearly stopping.+ const speed = Math.max(0.08, 0.42 + Math.sin(t * 0.9) * 0.24 + Math.sin(t * 2.3) * 0.08);+ m.u += (m.heading * speed * dt) / len;+ if (m.u >= 1 || m.u <= 0) {+ m.u = Math.min(1, Math.max(0, m.u));+ m.heading *= -1;+ m.pause = 1.6 + Math.random() * 2.2;+ this._setStaggerClip(m, false);+ }+ const fx = (beat.b.x - beat.a.x) / len, fz = (beat.b.z - beat.a.z) / len;+ const weave = Math.sin(t * 1.15) * 0.3 + Math.sin(t * 0.47) * 0.16;+ const weaveRate = Math.cos(t * 1.15) * 0.345 + Math.cos(t * 0.47) * 0.075;+ const x = beat.a.x + (beat.b.x - beat.a.x) * m.u + fz * weave;+ const z = beat.a.z + (beat.b.z - beat.a.z) * m.u - fx * weave;++ // Step up and down kerbs like everyone else: resample the floor a few+ // times a second and ease onto it.+ m.floorTimer -= dt;+ if (m.floorTimer <= 0) {+ m.floorTimer = 0.16;+ const y = this._floorAt(x, z);+ if (y != null) m.floorY = y;+ }+ g.position.set(x, g.position.y + (m.floorY - g.position.y) * (1 - Math.exp(-10 * dt)), z);++ // Body follows the weave: heading swings with the sideways drift and the+ // torso leans into it, always a little too far forward.+ const travel = Math.atan2(fx * m.heading, fz * m.heading);+ const yawTarget = travel + Math.atan2(weaveRate, speed) * 0.6 * m.heading;+ g.rotation.y = lerpAngle(g.rotation.y, yawTarget, 1 - Math.exp(-5 * dt));+ g.rotation.z = -weaveRate * 0.32 + Math.sin(t * 2.1) * 0.03;+ g.rotation.x = 0.07 + Math.sin(t * 1.3) * 0.04;+ if (m.inst.base) m.inst.base.timeScale = 0.35 + speed * 0.75;+ }++ // Crossfade the stagger between its slowed walk and a standing sway.+ _setStaggerClip(m, walking) {+ const { inst } = m;+ if (!inst.mixer || !inst.base || m.walking === walking) return;+ m.walking = walking;+ const restClip = inst.clips.get('av-idle-breath') || inst.clips.get('idle');+ if (!restClip) return;+ const rest = inst.mixer.clipAction(restClip);+ const [from, to] = walking ? [rest, inst.base] : [inst.base, rest];+ to.reset();+ to.timeScale = walking ? 0.6 : 0.55;+ to.play();+ from.crossFadeTo(to, 0.45, false);+ }++ _pinBubbles(camera) {+ if (!this.bubbles.size) return;+ const w = window.innerWidth, h = window.innerHeight;+ const placed = [];+ for (const [member, b] of this.bubbles) {+ if (this.time >= b.until) {+ if (b.el.classList.contains('is-visible')) {+ b.el.classList.remove('is-visible');+ b.removeAt = this.time + 0.3; // let the exit transition finish+ } else if (this.time >= (b.removeAt || 0)) {+ b.el.remove();+ this.bubbles.delete(member);+ }+ }+ const g = member.inst.group;+ const headUp = member.inst.height * (member.drunk === 'slump' ? 0.98 : 1.06) + 0.12;+ _head.set(g.position.x, g.position.y + headUp, g.position.z);+ const dist = _head.distanceTo(camera.position);+ _head.project(camera);+ const hidden = _head.z > 1 || _head.z < -1 || dist > BUBBLE_RANGE;+ b.el.classList.toggle('is-offscreen', hidden);+ if (hidden) continue;++ const bw = b.el.offsetWidth || 160;+ let x = (_head.x * 0.5 + 0.5) * w;+ let y = (-_head.y * 0.5 + 0.5) * h;+ // Keep the whole bubble on screen, and lift it over a neighbour's so+ // two people talking at once never print on top of each other.+ x = Math.min(w - bw / 2 - 10, Math.max(bw / 2 + 10, x));+ for (const p of placed) {+ if (Math.abs(p.x - x) < (p.w + bw) / 2 && Math.abs(p.y - y) < p.h + 6) y = p.y - p.h - 8;+ }+ y = Math.max((b.el.offsetHeight || 40) + 10, y);+ placed.push({ x, y, w: bw, h: b.el.offsetHeight || 40 });+ const scale = Math.min(1, Math.max(0.74, 5.2 / dist));+ b.el.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) translate(-50%, -100%) scale(${scale.toFixed(3)})`;+ }+ }++ /** Fade the speech layer with the scene canvas as the alley dissolves. */+ setOpacity(k) {+ if (this.bubblesEl) this.bubblesEl.style.opacity = String(k);+ }++ dispose() {+ if (this._disposed) return;+ this._disposed = true;+ for (const b of this.bubbles.values()) b.el.remove();+ this.bubbles.clear();+ if (this.bubblesEl) this.bubblesEl.style.opacity = '';+ this.scene.remove(this.props);+ this.props.traverse((n) => {+ if (!n.isMesh) return;+ n.geometry?.dispose?.();+ n.material?.map?.dispose?.();+ n.material?.dispose?.();+ });+ this.members = [];+ }+}++// Brass stanchions joined by a sagging velvet rope. Two shared materials and a+// handful of small meshes: the whole run costs less than one crowd member.+function buildRope(posts) {+ const group = new Group();+ group.name = 'club-rope';+ const brass = new MeshStandardMaterial({ color: 0xd4a94e, metalness: 0.95, roughness: 0.28 });+ const velvet = new MeshStandardMaterial({ color: 0x9b0f33, roughness: 0.85, metalness: 0, emissive: 0x3a0512, emissiveIntensity: 0.6 });+ const pole = new CylinderGeometry(0.028, 0.028, POST_HEIGHT, 12);+ const foot = new CylinderGeometry(0.17, 0.19, 0.04, 20);+ const cap = new SphereGeometry(0.055, 14, 10);++ for (const p of posts) {+ const post = new Group();+ const shaft = new Mesh(pole, brass);+ shaft.position.y = POST_HEIGHT / 2;+ const base = new Mesh(foot, brass);+ base.position.y = 0.02;+ const top = new Mesh(cap, brass);+ top.position.y = POST_HEIGHT + 0.03;+ post.add(shaft, base, top);+ post.position.set(p.x, p.y, p.z);+ group.add(post);+ }+ for (let i = 0; i + 1 < posts.length; i++) {+ const a = posts[i], b = posts[i + 1];+ const hookA = new Vector3(a.x, a.y + POST_HEIGHT - 0.06, a.z);+ const hookB = new Vector3(b.x, b.y + POST_HEIGHT - 0.06, b.z);+ const mid = hookA.clone().add(hookB).multiplyScalar(0.5);+ mid.y -= 0.34; // the control point sits below the sag it produces+ const curve = new QuadraticBezierCurve3(hookA, mid, hookB);+ group.add(new Mesh(new TubeGeometry(curve, 14, 0.022, 8, false), velvet));+ }+ return group;+}diff --git a/tests/club-bouncer.test.js b/tests/club-bouncer.test.jsnew file mode 100644index 000000000..7eb269c58--- /dev/null+++ b/tests/club-bouncer.test.js@@ -0,0 +1,257 @@+// Tests for the /club bouncer (src/club-bouncer.js): where he stands relative+// to the door, that the player can't walk through him, and that he acts out+// each `club:door-state` beat the cover gate emits.+//+// Builds a synthetic canonical rig + an in-memory idle clip (no GLB, no fetch,+// no WebGL), mirroring animation-playonce.test.js. vitest runs under+// `environment: 'node'`, so `window` is a bare EventTarget with a viewport and+// the speech bubble is a minimal classList/textContent stand-in.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ AnimationClip,+ Bone,+ BoxGeometry,+ Float32BufferAttribute,+ Group,+ Mesh,+ MeshBasicMaterial,+ Object3D,+ PerspectiveCamera,+ QuaternionKeyframeTrack,+ Raycaster,+ Scene,+ Skeleton,+ SkinnedMesh,+ Uint16BufferAttribute,+ Vector3,+ VectorKeyframeTrack,+} from 'three';+import { ClubBouncer, BOUNCER_RADIUS } from '../src/club-bouncer.js';++const RIG_BONES = ['Hips', 'Spine', 'Chest', 'Neck', 'Head', 'LeftArm', 'RightArm', 'LeftUpLeg'];++function makeRig(boneNames = RIG_BONES) {+ const root = new Object3D();+ const bones = boneNames.map((name) => {+ const b = new Bone();+ b.name = name;+ return b;+ });+ for (let i = 1; i < bones.length; i++) bones[i - 1].add(bones[i]);+ // A real skinned body (every vertex on the hips) so the bouncer can measure+ // and scale it the way it does a loaded GLB.+ const body = new BoxGeometry(0.5, 1.8, 0.3);+ body.translate(0, 0.9, 0);+ const verts = body.attributes.position.count;+ body.setAttribute('skinIndex', new Uint16BufferAttribute(new Uint16Array(verts * 4), 4));+ const weights = new Float32Array(verts * 4);+ for (let i = 0; i < verts; i++) weights[i * 4] = 1;+ body.setAttribute('skinWeight', new Float32BufferAttribute(weights, 4));+ const mesh = new SkinnedMesh(body, new MeshBasicMaterial());+ mesh.add(bones[0]);+ mesh.bind(new Skeleton(bones));+ root.add(mesh);+ return root;+}++function idleClipJson() {+ const tracks = [+ new QuaternionKeyframeTrack('Hips.quaternion', [0, 1], [0, 0, 0, 1, 0, 0, 0, 1]),+ new QuaternionKeyframeTrack('Spine.quaternion', [0, 1], [0, 0, 0, 1, 0, 0, 0, 1]),+ new QuaternionKeyframeTrack('LeftArm.quaternion', [0, 1], [0, 0, 0, 1, 0, 0, 0, 1]),+ new VectorKeyframeTrack('Hips.position', [0, 1], [0, 1, 0, 0, 1, 0]),+ ];+ return AnimationClip.toJSON(new AnimationClip('idle', 1, tracks));+}++function makeBubble() {+ const classes = new Set();+ const line = { textContent: '' };+ return {+ line,+ style: {},+ classList: {+ add: (c) => classes.add(c),+ remove: (c) => classes.delete(c),+ contains: (c) => classes.has(c),+ toggle: (c, on) => (on ? classes.add(c) : classes.delete(c)),+ },+ querySelector: () => line,+ };+}++// A flat alley floor, optionally with a wall close on one side of the door.+function makeAlley({ wallAtX = null, steps = false } = {}) {+ const env = new Group();+ const floor = new Mesh(new BoxGeometry(40, 0.2, 40), new MeshBasicMaterial());+ floor.position.y = -0.1;+ env.add(floor);+ if (wallAtX != null) {+ const wall = new Mesh(new BoxGeometry(0.2, 6, 40), new MeshBasicMaterial());+ wall.position.set(wallAtX, 3, 0);+ env.add(wall);+ }+ if (steps) {+ // A door up a flight of steps, with a plinth running along the wall.+ const stairs = new Mesh(new BoxGeometry(2.6, 0.8, 1.4), new MeshBasicMaterial());+ stairs.position.set(0, 0.4, 0.7);+ const plinth = new Mesh(new BoxGeometry(40, 0.5, 0.6), new MeshBasicMaterial());+ plinth.position.set(0, 0.25, 0.3);+ env.add(stairs, plinth);+ }+ env.updateMatrixWorld(true);+ return env;+}++// The door sits at the origin; the alley (and the player) lie toward +Z.+const PATH = { dir: new Vector3(0, 0, 1), door: new Vector3(0, 0, 0.35), spawn: new Vector3(0, 0, 4.5) };+const DOOR_ANCHOR = { size: new Vector3(1.4, 2.4, 0.2) };++function doorState(detail) {+ window.dispatchEvent(new CustomEvent('club:door-state', { detail }));+}++describe('ClubBouncer', () => {+ let scene, bubble, camera, bouncer;++ beforeEach(() => {+ vi.stubGlobal('window', Object.assign(new EventTarget(), { innerWidth: 1440, innerHeight: 860 }));+ scene = new Scene();+ bubble = makeBubble();+ camera = new PerspectiveCamera(55, 1440 / 860, 0.08, 200);+ camera.position.set(0, 1.6, 8);+ camera.lookAt(0, 1.2, 0);+ camera.updateMatrixWorld(true);+ bouncer = new ClubBouncer({ scene, model: makeRig(), manifest: [], idleClipJson: idleClipJson(), bubbleEl: bubble });+ });++ afterEach(() => {+ bouncer.dispose();+ vi.unstubAllGlobals();+ });++ it('stands beside the doorway, off the wall, facing down the alley', async () => {+ expect(await bouncer.mount({ envRoot: makeAlley(), path: PATH, doorAnchor: DOOR_ANCHOR })).toBe(true);+ expect(bouncer.mounted).toBe(true);+ expect(bouncer.group.visible).toBe(true);+ // Clear of the door opening (half its width) with room to walk past him.+ expect(Math.abs(bouncer.position.x)).toBeGreaterThan(DOOR_ANCHOR.size.x / 2 + BOUNCER_RADIUS * 0.5);+ // On the alley side of the door plane, not inside the wall.+ expect(bouncer.position.z).toBeGreaterThan(PATH.door.z);+ expect(bouncer.position.y).toBeCloseTo(0, 5);+ // Facing the approaching player (+Z).+ expect(bouncer.group.rotation.y).toBeCloseTo(0, 5);+ });++ it('posts on the pavement at the foot of the steps, never on or inside them', async () => {+ await bouncer.mount({ envRoot: makeAlley({ steps: true }), path: PATH, doorAnchor: DOOR_ANCHOR });+ expect(bouncer.position.y).toBeCloseTo(0, 5); // the level the player walks, not the stair top+ expect(bouncer.position.z).toBeGreaterThan(0.6 + 0.4); // clear of the plinth face+ // A body's width from the stair block on every side.+ const dx = Math.max(0, Math.abs(bouncer.position.x) - 1.3);+ const dz = Math.max(0, bouncer.position.z - 1.4);+ expect(Math.hypot(dx, dz)).toBeGreaterThanOrEqual(0.4);+ });++ it('takes the roomier side of the door', async () => {+ await bouncer.mount({ envRoot: makeAlley({ wallAtX: 2.2 }), path: PATH, doorAnchor: DOOR_ANCHOR });+ expect(bouncer.position.x).toBeLessThan(0);+ });++ it('never posts a rig the clip library cannot drive', async () => {+ const prop = new ClubBouncer({ scene, model: new Object3D(), manifest: [], idleClipJson: idleClipJson(), bubbleEl: makeBubble() });+ expect(await prop.mount({ envRoot: makeAlley(), path: PATH, doorAnchor: DOOR_ANCHOR })).toBe(false);+ expect(prop.mounted).toBe(false);+ expect(prop.group.visible).toBe(false);+ prop.dispose();+ });++ it('holds his ground when the player walks into him, and says so once', async () => {+ await bouncer.mount({ envRoot: makeAlley(), path: PATH, doorAnchor: DOOR_ANCHOR });+ const player = bouncer.position.clone().add(new Vector3(0.1, 0, 0.1));+ expect(bouncer.resolveCollision(player, 10_000)).toBe(true);+ expect(Math.hypot(player.x - bouncer.position.x, player.z - bouncer.position.z)).toBeCloseTo(BOUNCER_RADIUS, 5);+ expect(bubble.line.textContent).toMatch(/Easy/);++ bubble.line.textContent = '';+ player.copy(bouncer.position).add(new Vector3(0.1, 0, 0));+ bouncer.resolveCollision(player, 11_000); // within the cooldown: pushes, stays quiet+ expect(bubble.line.textContent).toBe('');++ const clear = bouncer.position.clone().add(new Vector3(2, 0, 0));+ expect(bouncer.resolveCollision(clear, 20_000)).toBe(false);+ });++ it('calls the cover once as you come down the alley, then again at the door', async () => {+ await bouncer.mount({ envRoot: makeAlley(), path: PATH, doorAnchor: DOOR_ANCHOR });+ bouncer.update(0.016, new Vector3(0, 0, 20), camera, { nearDoor: false });+ expect(bubble.classList.contains('is-visible')).toBe(false);++ bouncer.update(0.016, new Vector3(0, 0, 5), camera, { nearDoor: false });+ expect(bubble.line.textContent).toMatch(/penny/);++ bubble.line.textContent = '';+ bouncer.update(0.016, new Vector3(0, 0, 4), camera, { nearDoor: false });+ expect(bubble.line.textContent).toBe(''); // noticed already++ bouncer.update(0.016, new Vector3(0, 0, 1.5), camera, { nearDoor: true });+ expect(bubble.line.textContent).toMatch(/One cent/);+ });++ it('acts out the cover flow the gate announces', async () => {+ await bouncer.mount({ envRoot: makeAlley(), path: PATH, doorAnchor: DOOR_ANCHOR });++ doorState({ state: 'checking' });+ expect(bubble.line.textContent).toMatch(/Reading your wallet/);+ bouncer.explain(); // busy with the list: no small talk+ expect(bubble.line.textContent).toMatch(/Reading your wallet/);++ doorState({ state: 'admitted', tier: 'vip' });+ expect(bubble.line.textContent).toMatch(/boss/);+ doorState({ state: 'admitted', tier: 'regular' });+ expect(bubble.line.textContent).toMatch(/again/);+ doorState({ state: 'admitted', tier: 'new' });+ expect(bubble.line.textContent).toMatch(/First night/);++ doorState({ state: 'denied', reason: 'Wallet is on the ban list.' });+ expect(bubble.line.textContent).toBe('Wallet is on the ban list. Not tonight.');++ // A failed or cancelled pay drops back to the queue: he is approachable again.+ doorState({ state: 'queue' });+ bouncer.explain();+ expect(bubble.line.textContent).toMatch(/x402/);+ });++ it('watches the player without ever over-rotating his head', async () => {+ await bouncer.mount({ envRoot: makeAlley(), path: PATH, doorAnchor: DOOR_ANCHOR });+ // Player directly behind him: far outside what a neck can do.+ const behind = bouncer.position.clone().add(new Vector3(0, 0, -6));+ for (let i = 0; i < 240; i++) bouncer.update(1 / 60, behind, camera, { nearDoor: false });+ const settled = bouncer.headBone.quaternion.clone();+ expect(2 * Math.acos(Math.min(1, Math.abs(settled.w)))).toBeLessThan(1.2);+ // The look-at is re-derived each frame, never stacked onto the last one.+ for (let i = 0; i < 240; i++) bouncer.update(1 / 60, behind, camera, { nearDoor: false });+ expect(bouncer.headBone.quaternion.angleTo(settled)).toBeLessThan(1e-3);+ });++ it('is clickable while posted and stands down once the cover is paid', async () => {+ await bouncer.mount({ envRoot: makeAlley(), path: PATH, doorAnchor: DOOR_ANCHOR });+ const hitbox = new Mesh(new BoxGeometry(0.6, 1.9, 0.4), new MeshBasicMaterial());+ hitbox.position.y = 0.95;+ bouncer.group.add(hitbox);+ bouncer.group.updateMatrixWorld(true);+ const ray = new Raycaster(new Vector3(bouncer.position.x, 1, 10), new Vector3(0, 0, -1));+ expect(bouncer.hitTest(ray)).toBe(true);++ bouncer.say('anything', 0);+ bouncer.unmount();+ expect(bouncer.hitTest(ray)).toBe(false);+ expect(bubble.classList.contains('is-visible')).toBe(false);+ expect(scene.children.includes(bouncer.group)).toBe(false);++ bubble.line.textContent = '';+ doorState({ state: 'checking' }); // off duty: ignores the gate+ expect(bubble.line.textContent).toBe('');+ });+});