-
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathclub.js
More file actions
2638 lines (2425 loc) · 105 KB
/
Copy pathclub.js
File metadata and controls
2638 lines (2425 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// /club — three.ws Pole Club
//
// A dark 3D venue with three pole stages arranged in a half-arc. Each pole has
// a "Tip $0.001 to dance" button bound to /api/x402/dance-tip via the x402
// drop-in modal (window.X402.pay). Three distinct dancers stand at their poles
// facing the crowd; once the buyer's USDC settles, that slot's dancer steps
// onto her pole and performs the selected routine for ~12s, then returns to her
// idle stance at the pole. No tip, no routine.
import {
AdditiveBlending,
AmbientLight,
Box3,
BufferAttribute,
BufferGeometry,
Timer,
Color,
ConeGeometry,
DoubleSide,
EquirectangularReflectionMapping,
Fog,
Group,
HemisphereLight,
Mesh,
MeshBasicMaterial,
PerspectiveCamera,
PMREMGenerator,
PointLight,
Points,
PointsMaterial,
Scene,
SpotLight,
SRGBColorSpace,
Vector3,
NoToneMapping,
} from 'three';
import {
EffectComposer,
RenderPass,
EffectPass,
BloomEffect,
ToneMappingEffect,
VignetteEffect,
SMAAEffect,
ToneMappingMode,
} from 'postprocessing';
import { HDRLoader } from 'three/addons/loaders/HDRLoader.js';
import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
import { gltfLoader } from './loaders/gltf.js';
import { REQUIRED_VENUE_EMPTIES, collectVenueEmpties, resolveVenueAnchors } from './club-venue.js';
import { AnimationManager } from './animation-manager.js';
import { ClubCamera } from './club-camera.js';
import { ClubAudio, styleAudioFor, TRACK_LABELS } from './club-audio.js';
import { playSequence, ticketSteps } from './club-sequence.js';
import { detectProfile, PROFILES, createFrameWatchdog, isMobileLayout } from './club-perf.js';
import {
createFrameGovernor, trackWindowFocus, getPowerSaver, setPowerSaver, onPowerSaverChange,
FPS_ACTIVE, FPS_IDLE, FPS_SAVER,
} from './shared/frame-governor.js';
import { log } from './shared/log.js';
import { emptyStateHTML } from './shared/state-kit.js';
import { createRenderer } from './webgl-support.js';
const AVATAR_URL = '/avatars/default.glb';
const MANIFEST_URL = '/animations/manifest.json';
const POLE_GLB_URL = '/club/props/pole.glb';
const STAGE_GLB_URL = '/club/props/stage.glb';
// Authored nightclub interior + equirectangular HDRI for PBR reflections.
// Both are required — a 404 surfaces an error in the UI; the page does NOT
// fall back to a procedural scene. See public/club/assets/LICENSES.md for
// the named-empty contract these files must satisfy (the contract itself
// lives in src/club-venue.js so it can be unit-tested in isolation).
const VENUE_GLB_URL = '/club/venue/club-venue.glb';
const VENUE_HDRI_URL = '/club/venue/club-hdri.hdr';
// Clips we actually use — keeps the manifest pre-fetch small. Every name here
// must exist in /animations/manifest.json (built by `npm run build:animations`);
// a style sold by /api/x402/dance-tip may only chain clips from this set, or a
// paid routine would crossfade to a no-op and leave the dancer frozen.
const REQUIRED_CLIPS = new Set([
'idle', 'dance', 'rumba', 'silly', 'thriller', 'capoeira', 'walk',
'av-walk-feminine', 'twerk',
]);
const WALK_CLIP = 'av-walk-feminine';
// Guaranteed-present clip every dancer can drive. Used as the failsafe routine
// when a ticket's requested clips can't be loaded on the chosen rig, so a paid
// tip always yields a real performance (Hard rule 9: ship a working fallback).
const FALLBACK_CLIP = 'dance';
const TIP_ENDPOINT = '/api/x402/dance-tip';
const TIPS_HISTORY_URL = '/api/club/tips?limit=20';
const TIPS_STREAM_URL = '/api/club/tips/stream';
// ── Stage layout ─────────────────────────────────────────────────────────
// Poles in a half-arc facing the camera (count = POLE_COUNT). Backstage is behind the bar at
// negative Z so dancers visibly walk out before mounting the pole.
const STAGE_RADIUS = 4.2;
const POLE_COUNT = 3;
const POLE_HEIGHT = 3.6;
const PERFORMANCE_FADE = 0.45; // seconds for clip crossfade
// Top of the stage GLB. Authored in scripts/build-club-props.mjs at y=0.18.
// Mirrored here so the dancer rig + pole base sit on the disc face.
const STAGE_TOP_Y = 0.18;
const POLES = Array.from({ length: POLE_COUNT }, (_, i) => {
// Spread across an arc from -55° to +55° at the front of the room.
const t = POLE_COUNT === 1 ? 0.5 : i / (POLE_COUNT - 1);
const angle = -Math.PI * 0.31 + t * Math.PI * 0.62;
return {
id: String(i + 1),
x: Math.sin(angle) * STAGE_RADIUS,
z: -Math.cos(angle) * STAGE_RADIUS + 1.4, // shift forward of camera focus
// Backstage spawn point — same X as pole, deeper into the room.
backstageX: Math.sin(angle) * (STAGE_RADIUS + 0.6),
backstageZ: -Math.cos(angle) * (STAGE_RADIUS + 0.6) - 2.4,
yaw: angle + Math.PI, // face the camera (poles look outward)
};
});
const prefersReducedMotion = typeof window !== 'undefined' &&
window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// ── DOM ───────────────────────────────────────────────────────────────────
const canvas = document.getElementById('club-canvas');
const polesPanel = document.getElementById('club-poles');
const statusEl = document.getElementById('club-status');
const tipFeedEl = document.getElementById('club-tip-feed');
const feedStatusEl = document.getElementById('club-feed-status');
const lbRowsEl = document.getElementById('club-lb-rows');
const lbTabsEls = document.querySelectorAll('.club-lb-tab');
// Upgrade the static "No tips yet" line to a guided empty state (C06). Cleared
// by renderTipRow() the moment the first tip settles.
if (tipFeedEl) {
tipFeedEl.innerHTML = emptyStateHTML({
compact: true,
live: true,
icon: '💸',
title: 'No tips yet',
body: 'Tip a dancer and they take the pole — every tip lands here live, paid on-chain for $0.001. Be the first.',
});
}
function setStatus(text, { kind = 'info' } = {}) {
if (!statusEl) return;
statusEl.textContent = text;
statusEl.dataset.kind = kind;
statusEl.hidden = false;
clearTimeout(setStatus._t);
setStatus._t = setTimeout(() => { statusEl.hidden = true; }, 3500);
}
function fmtUsd(atomics, decimals = 6) {
if (atomics == null) return '';
const n = Number(atomics) / 10 ** decimals;
if (n < 0.01) return `$${n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')}`;
return `$${n.toFixed(2)}`;
}
// Dedupe ring: the local x402 echo and the SSE channel both deliver the same
// settled tip. Whichever wins the race renders the row; the loser is dropped
// by ticket_id. Capped so it doesn't grow without bound on a long session.
const DEDUPE_MAX = 50;
const renderedTicketIds = new Set();
const renderedOrder = [];
function rememberTicketId(id) {
if (!id || renderedTicketIds.has(id)) return false;
renderedTicketIds.add(id);
renderedOrder.push(id);
while (renderedOrder.length > DEDUPE_MAX) {
renderedTicketIds.delete(renderedOrder.shift());
}
return true;
}
function formatTimestamp(isoOrDate) {
try {
const d = isoOrDate instanceof Date ? isoOrDate : new Date(isoOrDate);
if (isNaN(d.getTime())) return '';
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
} catch { return ''; }
}
// Render one tip into the feed. Accepts both the server row shape
// (snake_case from /api/club/tips and SSE `tip` events) and the local
// x402 ticket shape (camelCase from window.X402.pay).
function renderTipRow(rowLike, { live = false, prepend = true } = {}) {
if (!tipFeedEl || !rowLike) return;
const ticketId = rowLike.ticket_id ?? rowLike.ticketId ?? null;
if (ticketId && !rememberTicketId(ticketId)) return;
const dancerId = String(rowLike.dancer ?? '?').replace(/[<>&"]/g, '');
const dancerIdx = parseInt(dancerId, 10) - 1;
const dancerName = DANCER_META[dancerIdx]?.name || `Dancer ${dancerId}`;
const label = rowLike.label ?? rowLike.dance ?? 'dance';
const payer = rowLike.payer ?? null;
const amountAtomics = rowLike.amount_atomics ?? rowLike.amountAtomics ?? null;
const network = rowLike.network ?? '';
const timestamp = rowLike.created_at ?? rowLike.startsAt ?? new Date().toISOString();
tipFeedEl.querySelector('.club-feed-empty')?.remove();
tipFeedEl.querySelector('.tws-es')?.remove();
const row = document.createElement('div');
row.className = 'club-tip-row';
if (live) row.classList.add('is-live');
const who = payer ? `${payer.slice(0, 4)}...${payer.slice(-4)}` : 'someone';
const safeLabel = String(label).replace(/[<>&]/g, '');
const time = formatTimestamp(timestamp);
row.innerHTML = `
<span class="club-tip-time">${time}</span>
<span class="club-tip-mid"><span class="club-tip-who">${who}</span> tipped ${dancerName} → ${safeLabel}</span>
<span class="club-tip-amt">${fmtUsd(amountAtomics)}</span>
`;
if (prepend) {
tipFeedEl.prepend(row);
} else {
tipFeedEl.appendChild(row);
}
// Max 20 visible entries; oldest fade out.
while (tipFeedEl.children.length > 20) {
const oldest = tipFeedEl.lastElementChild;
if (oldest) {
oldest.classList.add('is-fading');
oldest.addEventListener('animationend', () => oldest.remove(), { once: true });
}
}
// If this tip is for the currently-viewed pole, flash its spotlight + card.
if (live) {
flashPoleCard(dancerId);
// Play tip sound via audio system.
try {
if (audio.ctx && !audio.muted) {
playTipSound(audio.ctx, audio.master);
}
} catch {}
}
}
function setFeedStatus(text, kind) {
if (!feedStatusEl) return;
if (!text) {
feedStatusEl.hidden = true;
feedStatusEl.textContent = '';
delete feedStatusEl.dataset.kind;
return;
}
feedStatusEl.textContent = text;
feedStatusEl.dataset.kind = kind || 'info';
feedStatusEl.hidden = false;
}
// Load the most-recent tips for a fresh page load. Tries twice (one retry
// after 4 s) so a transient network blip doesn't leave the feed empty.
async function loadInitialTips({ attempt = 0 } = {}) {
try {
const r = await fetch(TIPS_HISTORY_URL, { cache: 'no-store' });
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const data = await r.json();
const tips = Array.isArray(data?.tips) ? data.tips : [];
// Server returns newest-first; reverse so the newest ends up at the
// top after sequential prepend.
for (const t of tips.slice().reverse()) {
renderTipRow(t, { live: false });
}
setFeedStatus(null);
} catch (err) {
log.warn('[club] tip history failed', err);
if (attempt === 0) {
setFeedStatus("Couldn't load tip history — retrying", 'error');
setTimeout(() => loadInitialTips({ attempt: 1 }), 4000);
} else {
setFeedStatus("Couldn't load tip history", 'error');
}
}
}
// Backfill tips after an SSE reconnect: fetch recent history and render any
// rows the dedup cache hasn't seen, so a gap during the outage is closed. New
// rows flash as live; already-seen rows are dropped by rememberTicketId.
async function backfillTips() {
try {
const r = await fetch(TIPS_HISTORY_URL, { cache: 'no-store' });
if (!r.ok) return;
const data = await r.json();
const tips = Array.isArray(data?.tips) ? data.tips : [];
// Oldest-first so sequential prepend leaves newest on top.
for (const t of tips.slice().reverse()) {
renderTipRow(t, { live: true });
}
} catch (err) {
log.warn('[club] tip backfill failed', err);
}
}
// Subscribe to the SSE channel. Reconnects with exponential backoff + jitter
// after an error; after 3 consecutive failures shows a "live updates paused"
// badge. On every successful (re)connection it backfills from the tips REST
// endpoint so any tips that landed while the socket was down still appear — the
// per-ticket dedup in renderTipRow keeps backfill from duplicating live rows.
const SSE_BASE_DELAY_MS = 1000; // first retry ~1s
const SSE_MAX_DELAY_MS = 30000; // cap backoff at 30s during a long outage
function subscribeTipStream() {
if (typeof window.EventSource !== 'function') {
setFeedStatus('Live updates paused', 'paused');
return null;
}
let es = null;
let consecutiveFailures = 0;
let reconnectTimer = 0;
let closedByUser = false;
// First open is a cold start (initial history already loaded separately);
// only reconnections trigger a gap-filling backfill.
let reconnecting = false;
const open = () => {
if (closedByUser) return;
try {
es = new EventSource(TIPS_STREAM_URL);
} catch (err) {
log.warn('[club] EventSource init failed', err);
scheduleReconnect();
return;
}
es.addEventListener('hello', () => {
consecutiveFailures = 0;
setFeedStatus(null);
// Pull anything missed while the socket was down. Dedup makes this safe.
if (reconnecting) {
reconnecting = false;
backfillTips();
}
});
es.addEventListener('tip', (e) => {
try {
const row = JSON.parse(e.data);
renderTipRow(row, { live: true });
} catch (err) {
log.warn('[club] tip event parse failed', err);
}
});
es.onerror = () => {
// EventSource auto-reconnects in some browsers but keeps the
// closed socket in CONNECTING state and re-fires onerror in a
// spin. Explicitly close + schedule so the failure counter
// advances predictably and the badge timing is honest.
try { es?.close(); } catch {}
es = null;
reconnecting = true;
consecutiveFailures += 1;
if (consecutiveFailures >= 3) {
setFeedStatus('Live updates paused', 'paused');
}
scheduleReconnect();
};
};
const scheduleReconnect = () => {
if (closedByUser) return;
clearTimeout(reconnectTimer);
// Exponential backoff: 1s, 2s, 4s, 8s… capped at 30s, with full jitter so
// many reconnecting clients don't thunder the endpoint in lockstep.
const exp = Math.min(SSE_BASE_DELAY_MS * 2 ** (consecutiveFailures - 1), SSE_MAX_DELAY_MS);
const delay = Math.round(exp / 2 + Math.random() * (exp / 2));
reconnectTimer = setTimeout(open, delay);
};
open();
window.addEventListener('beforeunload', () => {
closedByUser = true;
clearTimeout(reconnectTimer);
try { es?.close(); } catch {}
});
return {
close() {
closedByUser = true;
clearTimeout(reconnectTimer);
try { es?.close(); } catch {}
},
};
}
// ── Perf profile (boot-time pick from real capability signals) ───────────
// One profile picked once, then applied to the renderer, lights, and any
// future scene additions (mirror ball, volumetric cones, crowd, postFX).
// Mid-session, the animate-loop watchdog can swap us down one tier if a
// phone starts throttling; profile is exposed on window so prompts 01–04
// can read it without an explicit import cycle.
let activeProfile = PROFILES[detectProfile()];
if (typeof window !== 'undefined') window.__clubProfile = activeProfile;
// ── Renderer / scene ──────────────────────────────────────────────────────
// Guarded construction: on a device that can't grant a WebGL context (no GPU,
// blocklisted driver, headless UA, or an exhausted mobile-Safari context budget)
// this mounts an on-brand "3D unavailable" panel over the canvas and throws a
// typed WebGLUnavailableError. The throw halts the rest of this module's
// top-level boot cleanly — no cascade of "renderer is undefined" follow-on
// errors — and the error reporter recognises the typed signal as a benign
// capability limit and suppresses it. Replaces the bare `new WebGLRenderer`
// that surfaced "Error creating WebGL context." as an uncaught crash on /club.
const renderer = createRenderer({ canvas, antialias: false, alpha: false }, { fallback: canvas });
renderer.setPixelRatio(activeProfile.pixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = SRGBColorSpace;
renderer.toneMapping = NoToneMapping;
renderer.shadowMap.enabled = activeProfile.shadows;
const scene = new Scene();
scene.background = new Color(0x07050b);
scene.fog = new Fog(0x07050b, 9, 28);
// scene.environment is set inside bootstrap() once the equirectangular HDRI
// (public/club/venue/club-hdri.hdr) has been pre-filtered through
// PMREMGenerator.fromEquirectangular. We intentionally do NOT seed the env
// with a RoomEnvironment lightprobe — PBR materials read straight from the
// loaded HDRI so reflections match the authored interior, not a generic
// neutral sphere.
// Soft room light so the avatars aren't pitch black — but kept low so the
// spotlights do the talking.
scene.add(new AmbientLight(0x150b1a, 0.55));
const hemi = new HemisphereLight(0xff6abf, 0x110820, 0.35);
hemi.position.set(0, 6, 0);
scene.add(hemi);
const camera = new PerspectiveCamera(46, window.innerWidth / window.innerHeight, 0.05, 80);
camera.position.set(0, 1.8, 6.0);
camera.lookAt(0, 1.4, -1.5);
// ── Postprocessing pipeline ─────────────────────────────────────────────
// pmndrs EffectComposer replaces direct renderer.render(). Bloom makes the
// neon elements glow, tone mapping gives cinematic colour, vignette darkens
// the edges, and SMAA handles anti-aliasing at the compositing stage (so
// we disable the renderer's built-in MSAA above).
const bloomEffect = new BloomEffect({
intensity: 1.2,
luminanceThreshold: 0.3,
luminanceSmoothing: 0.08,
mipmapBlur: true,
});
const toneMappingEffect = new ToneMappingEffect({ mode: ToneMappingMode.ACES_FILMIC });
const vignetteEffect = new VignetteEffect({ darkness: 0.45, offset: 0.35 });
const smaaEffect = new SMAAEffect();
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
composer.addPass(new EffectPass(camera, bloomEffect, toneMappingEffect, vignetteEffect));
composer.addPass(new EffectPass(camera, smaaEffect));
const clubCam = new ClubCamera(camera, {
onModeChange: (mode) => {
updateFreeCamChip(mode);
document.querySelector('#club-stage')?.setAttribute('data-cam-mode', mode);
},
});
document.querySelector('#club-stage')?.setAttribute('data-cam-mode', clubCam.getMode());
// ── Authored venue ───────────────────────────────────────────────────────
// The floor, walls, ceiling, bar, neon strips, and crowd silhouettes all
// live inside public/club/venue/club-venue.glb. They're added to the scene
// in bootstrap() once GLTFLoader resolves; the named empties inside that
// GLB (stage.NN, backstage.door.NN, truss.spot.NN, truss.mirrorball,
// bar.backsplash.neon) are what drive pole + spotlight placement below.
// ── Poles + spotlights ───────────────────────────────────────────────────
const POLE_COLORS = [0xff3bd6, 0x4ad6ff, 0xff8a3b, 0x9b5dff];
// Dancer registry — display names, bios, accent palette, and the avatar each
// dancer wears. A local `avatar` path loads that GLB directly; an `avatarId`
// is resolved through /api/avatars/:id at boot (see resolveDancerAvatarUrl).
// The three rigs are deliberately DISTINCT and, critically, VERIFIED-DRIVABLE:
// the club's clip library retargets idle/walk onto them so each dancer idles in
// her resting stance and her legs actually move when she walks to the pole —
// never a T-pose. Only swap a rig here for another the clip library can drive
// (gallery rigs that fail retarget bind in their T-pose). attachAvatar still
// falls back to the default rig if a rig ever isn't drivable, and each dancer is
// tinted with her pole's accent color so the three read as a set.
const DANCER_META = [
{ name: 'Dylan', bio: 'Neon pink heat. Fast, precise, relentless.', palette: 'pink', avatarId: '25195a2e-130c-4da5-8cad-8e7490d69b45' },
{ name: 'Nich', bio: 'Cyan cool. Fluid, hypnotic, in control.', palette: 'cyan', avatar: '/avatars/michelle.glb' },
{ name: 'Boss Vernington', bio: 'Amber muscle. Pure power on the pole.', palette: 'amber', avatarId: 'd92b292e-c2db-40cb-bf88-3e141c6b0057' },
];
// Every dancer is scaled to this standing height (metres) so a mix of
// differently-authored gallery avatars reads as one lineup.
const DANCER_HEIGHT_M = 1.75;
// An idle pose that renders shorter than this (metres) has collapsed — the rig's
// skeleton didn't drive the clip, so the dancer is flattened invisibly on the
// disc and re-grounding can't rescue her; she falls back to a known-good rig.
// Set well below DANCER_HEIGHT_M so a genuinely short (but standing) pose passes.
const MIN_IDLE_STANDING_M = 1.2;
/**
* Scale a freshly-cloned avatar root to `targetHeight` and ground its feet at
* local y=0, measuring with the skinning-aware (`precise`) bounding box so a
* rig with a scaled skeleton root or far-flung bind pose still sizes correctly.
* Called before the root is parented, so its world space equals its local space
* and the measured box is directly usable to offset `position.y`.
*
* @param {import('three').Object3D} root
* @param {number} targetHeight
*/
function fitRigToHeight(root, targetHeight) {
root.updateMatrixWorld(true);
root.traverse((n) => { if (n.isSkinnedMesh) n.skeleton?.update?.(); });
let box = new Box3().setFromObject(root, true);
const height = box.max.y - box.min.y;
if (Number.isFinite(height) && height > 0.05) {
const scale = Math.min(8, Math.max(0.05, targetHeight / height));
root.scale.multiplyScalar(scale);
root.updateMatrixWorld(true);
box = new Box3().setFromObject(root, true);
}
if (Number.isFinite(box.min.y)) root.position.y -= box.min.y;
}
class PoleStation {
constructor(idx, layout) {
this.idx = idx;
this.layout = layout;
this.id = layout.id;
this.stageTopY = STAGE_TOP_Y;
// Stage + pole GLBs are attached later in attachProps(); construct only
// the lights, the rig holder, and lifecycle state here so the station
// exists before async assets finish loading.
// Spotlight — colored, focused on the pole base.
const spot = new SpotLight(POLE_COLORS[idx % POLE_COLORS.length], 0, 12, Math.PI / 7, 0.4, 1.6);
spot.position.set(layout.x, 6.0, layout.z + 0.5);
spot.target.position.set(layout.x, 0.0, layout.z);
spot.castShadow = activeProfile.shadows;
if (activeProfile.shadowMapSize > 0) {
spot.shadow.mapSize.set(activeProfile.shadowMapSize, activeProfile.shadowMapSize);
}
spot.shadow.bias = -0.0008;
scene.add(spot);
scene.add(spot.target);
this.spot = spot;
// Dancers now stand at their pole even when idle, so the idle spotlight
// is bright enough to present them ("hot and ready") rather than the
// dim wash that made sense when the pole was empty between tips.
this.spotIdleIntensity = 1.6;
this.spotActiveIntensity = 12.0;
spot.intensity = this.spotIdleIntensity;
// Volumetric beam — a translucent cone of light from the spot down to the
// stage, additively blended so it reads as haze in the air rather than a
// solid object. A per-vertex gradient (bright at the source → black at the
// floor) gives the soft falloff without a custom shader; opacity tracks the
// spotlight and pulses with the beat (see the render loop). The single
// biggest "it feels real" upgrade for the room.
const beamH = 6.0;
const beamGeo = new ConeGeometry(1.15, beamH, 28, 1, true);
const beamColor = new Color(POLE_COLORS[idx % POLE_COLORS.length]);
const bpos = beamGeo.attributes.position;
const bcol = new Float32Array(bpos.count * 3);
for (let i = 0; i < bpos.count; i += 1) {
const t = (bpos.getY(i) + beamH / 2) / beamH; // 1 at the apex, 0 at the floor
const f = t * t; // bias the glow toward the source
bcol[i * 3] = beamColor.r * f;
bcol[i * 3 + 1] = beamColor.g * f;
bcol[i * 3 + 2] = beamColor.b * f;
}
beamGeo.setAttribute('color', new BufferAttribute(bcol, 3));
const beamMat = new MeshBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0,
blending: AdditiveBlending,
depthWrite: false,
side: DoubleSide,
fog: false,
toneMapped: false,
});
const beam = new Mesh(beamGeo, beamMat);
beam.position.set(layout.x, beamH / 2, layout.z); // apex at the spot height, base on the floor
beam.renderOrder = 2;
scene.add(beam);
this.beam = beam;
this.beamMat = beamMat;
this.beamBaseOpacity = 0.05;
// Floor accent point light — sits at the base of the pole.
const accent = new PointLight(POLE_COLORS[idx % POLE_COLORS.length], 0.9, 4.5, 1.6);
accent.position.set(layout.x, 0.6, layout.z);
scene.add(accent);
this.accent = accent;
// Dancer rig — stands at the pole, facing the crowd. We populate the
// skinned mesh later in attachAvatar(); position + yaw are set here so
// the rig is home the instant the avatar attaches.
this.rig = new Group();
this.rig.position.copy(this.homePos);
this.rig.rotation.y = layout.yaw;
scene.add(this.rig);
this.anim = null;
this.skinned = null;
this.stage = null; // root group from stage.glb
this.pole = null; // root group from pole.glb
// Current performance lifecycle.
this.activeTicket = null; // backend ticket id
this.activeUntil = 0; // ms epoch — informational; sequence loop drives end
this.performing = false;
this.walkPhase = 'idle'; // 'idle' | 'to-pole' | 'dancing' | 'returning'
this._phaseTarget = this.rig.position.clone();
// Render-loop coupled sleepers (sleep() resolves them in tick()).
// Wall-clock setTimeout would drift if the tab is throttled or paused;
// driving sleep off the render clock keeps choreography frame-aligned.
this._clockSec = 0;
this._sleepers = [];
}
/**
* Snap this station's stage / backstage / spotlight positions onto the
* world-space anchors harvested from the venue GLB. Called from
* bootstrap() AFTER the venue loads but BEFORE attachProps so the cloned
* stage disc / pole geo land on the authored stage.NN empties rather
* than the analytical fallback baked into the POLES array.
*
* Mutates `this.layout` in place — downstream code (attachProps,
* startPerformance, tick) reads layout each frame, so a single override
* pass at boot is enough.
*
* @param {object} anchors
* @param {import('three').Vector3} [anchors.stagePos]
* @param {import('three').Vector3} [anchors.backstagePos]
* @param {import('three').Vector3} [anchors.spotPos]
*/
applyVenueOverrides({ stagePos, backstagePos, spotPos } = {}) {
if (stagePos) {
this.layout.x = stagePos.x;
this.layout.z = stagePos.z;
this.accent.position.set(stagePos.x, 0.6, stagePos.z);
// Idle home tracks the pole — restand the rig there (unless she's
// mid-performance, in which case tick() owns the position).
if (this.walkPhase === 'idle') {
this.rig.position.copy(this.homePos);
this._phaseTarget = this.homePos;
}
}
if (backstagePos) {
// Backstage anchor is retained for choreography that wants a deeper
// off-stage point, but dancers idle at the pole now, not backstage.
this.layout.backstageX = backstagePos.x;
this.layout.backstageZ = backstagePos.z;
}
if (spotPos) {
this.spot.position.set(spotPos.x, spotPos.y, spotPos.z);
}
// Spotlight always re-aims at the (possibly new) stage center.
this.spot.target.position.set(this.layout.x, 0.0, this.layout.z);
}
/**
* Clone the pole + stage GLB templates into this station. Called from
* bootstrap() once both .glb files have finished loading. Each station gets
* its own clone so material tints (per-pole accent emissive) don't leak.
*/
attachProps({ poleTemplate, stageTemplate }) {
const accent = new Color(POLE_COLORS[this.idx % POLE_COLORS.length]);
const stage = stageTemplate.clone(true);
stage.position.set(this.layout.x, 0, this.layout.z);
stage.traverse((n) => {
if (!n.isMesh) return;
n.receiveShadow = true;
if (n.material) {
n.material = n.material.clone();
if (n.material.emissive) {
if (n.name === 'stage.led.ring') {
n.material.emissive = accent.clone();
n.material.emissiveIntensity = 1.2;
} else {
n.material.emissive.lerp(accent, 0.4);
}
}
}
});
scene.add(stage);
this.stage = stage;
const pole = poleTemplate.clone(true);
pole.position.set(this.layout.x, this.stageTopY, this.layout.z);
pole.traverse((n) => {
if (!n.isMesh) return;
n.castShadow = true;
n.receiveShadow = false;
if (n.material && n.material.metalness >= 0.9) {
// Subtle per-pole tint on the chrome only (skip dark brackets / bolts).
n.material = n.material.clone();
if (!n.material.emissive) n.material.emissive = new Color(0x000000);
n.material.emissive = accent.clone().multiplyScalar(0.04);
}
});
scene.add(pole);
this.pole = pole;
}
/**
* Clone a template GLB into a tinted, floor-aligned avatar root ready to
* drop into the rig. Pure — no scene-graph mutation — so attachAvatar can
* build a candidate, test whether its rig animates, and discard it for the
* fallback without leaving a half-attached mesh behind.
* @param {import('three').Object3D} template
*/
_buildAvatarRoot(template) {
const root = cloneSkinnedScene(template);
root.traverse((n) => {
if (!n.isMesh) return;
n.castShadow = true;
n.receiveShadow = false;
if (n.material && 'envMapIntensity' in n.material) {
n.material = n.material.clone();
n.material.envMapIntensity = 0.6;
// Tint each dancer subtly with the pole's accent color so the
// dancers are visually distinct even before the spotlight kicks in.
if (n.material.emissive) {
n.material.emissive = new Color(POLE_COLORS[this.idx % POLE_COLORS.length]);
n.material.emissiveIntensity = 0.05;
}
}
});
// Normalize size + ground the feet. Gallery avatars come from many
// pipelines (CharacterStudio, Unreal, RPM, uploads) at wildly different
// scales and skeleton offsets — one ships 3m tall and floating, another
// sub-metre. A plain rest-pose AABB (setFromObject without `precise`)
// reads the bind-pose geometry, which for a skinned rig can bear no
// relation to the posed silhouette. Measuring with `precise: true` runs
// each vertex through SkinnedMesh.getVertexPosition (applies bone skinning),
// so we get the real standing bounds — then scale every dancer to one
// height and drop her feet onto y=0 so the lineup reads as a set.
fitRigToHeight(root, DANCER_HEIGHT_M);
return root;
}
/**
* Plant the live (idle) pose's feet on the stage and report her standing
* height. fitRigToHeight grounds the *bind* pose, but a retargeted idle can
* carry its own vertical offset — some rigs idle a full metre below the bind
* feet line, sinking the dancer through the disc. Measuring the posed skinned
* bounds (precise) and dropping the avatar root by the floor gap re-plants her
* on the stage. Returns the rendered height (m) so the caller can detect a
* collapsed retarget that grounding alone can't rescue.
* @returns {number}
*/
_groundAndMeasureIdle() {
const root = this.skinned;
if (!root || !this.anim) return 0;
// play() only queues the action; advance the mixer one frame so the idle
// pose is realized on the skeleton before we measure it.
this.anim.update(0.1);
root.updateMatrixWorld(true);
root.traverse((n) => { if (n.isSkinnedMesh) n.skeleton?.update?.(); });
const box = new Box3().setFromObject(root, true);
if (!Number.isFinite(box.min.y) || !Number.isFinite(box.max.y)) return 0;
// The rig holder sits at world y=0; drop the avatar root so her lowest
// vertex (her feet) lands on that plane — the rig's yaw-only transform
// leaves the vertical axis untouched, so the world offset applies directly.
root.position.y -= box.min.y;
return box.max.y - box.min.y;
}
/**
* Bind the pre-fetched locomotion clips (idle + walk) into this dancer's
* mixer so the first `play('idle')` resolves from memory — no network fetch,
* no T-pose window. No-op until the boot pre-fetch has populated the shared
* `locomotionClips` map (e.g. an offline boot where it stayed empty); the
* AnimationManager then lazy-loads as before. Each call retargets the same
* raw clip onto whatever rig is currently attached, so it's correct on both
* the chosen rig and the fallback rig.
*/
_injectLocomotion() {
if (!this.anim || !locomotionClips) return;
for (const [name, json] of Object.entries(locomotionClips)) {
this.anim.injectClip(name, json, { loop: true });
}
}
/**
* Attach this dancer's avatar. `template` is her chosen GLB; `fallback` is
* the known-good default rig. Every shipped avatar is verified drivable, but
* we still confirm the clip library can retarget onto the chosen rig at
* runtime — if not, we silently swap to the fallback so a dancer is never
* frozen mid-stage (Hard rule 9: no errors without solutions).
* @param {import('three').Object3D} template
* @param {Array} animationDefs
* @param {import('three').Object3D} [fallback]
*/
attachAvatar(template, animationDefs, fallback = null) {
this.anim = new AnimationManager();
let root = this._buildAvatarRoot(template);
this.rig.add(root);
this.anim.attach(root);
if (!this.anim.supportsCanonicalClips() && fallback && fallback !== template) {
log.warn(`[club] dancer ${this.id} rig not drivable — falling back to default avatar`);
this.anim.detach();
this.rig.remove(root);
root = this._buildAvatarRoot(fallback);
this.rig.add(root);
this.anim.attach(root);
}
this.skinned = root;
this.anim.setAnimationDefs(animationDefs);
this._injectLocomotion();
// Await idle so we can detect a retarget that doesn't leave her standing —
// rejected outright (fallen-pose guard) or collapsed to a flat pose (the
// skeleton didn't drive the clip) — and swap to the fallback rig rather
// than leave a dancer sunk through the disc or flattened invisibly on it.
// On whichever rig does stand, re-ground her idle pose so her feet sit on
// the stage: fitRigToHeight grounds the bind pose, but a retargeted idle
// can impose its own vertical offset (some rigs idle a metre low). With the
// locomotion clips injected above, idle binds synchronously — the dancer's
// first rendered frame is her resting stance, never a T-pose.
this.anim.play('idle').then((ok) => {
const standing = ok ? this._groundAndMeasureIdle() : 0;
if (standing >= MIN_IDLE_STANDING_M) return;
if (!fallback || fallback === template) return;
log.warn(`[club] dancer ${this.id} idle not standing (${standing.toFixed(2)}m) — falling back to default avatar`);
this.anim.detach();
this.rig.remove(root);
const fbRoot = this._buildAvatarRoot(fallback);
this.rig.add(fbRoot);
this.anim.attach(fbRoot);
this.skinned = fbRoot;
this.anim.setAnimationDefs(animationDefs);
this._injectLocomotion();
this.anim.play('idle').then((ok2) => { if (ok2) this._groundAndMeasureIdle(); }).catch(() => {});
}).catch(() => {});
// Pre-load the walk clip so the first tip's walk starts immediately
// without a network round-trip mid-performance.
this.anim.ensureLoaded(WALK_CLIP).catch(() => {});
}
/**
* Hot-swap this dancer's avatar to a different rig at runtime. Tears down
* the current mixer + rig, then re-attaches the chosen template through the
* same drivable-rig verification path used at boot (attachAvatar), so an
* un-retargetable pick falls back to the default rather than freezing.
*
* The cloned root shares geometry/materials with `template`
* (SkeletonUtils.clone), so we only unparent the old root — disposing it
* would corrupt the shared template other stations may reuse.
*
* @param {import('three').Object3D} template
* @param {import('three').Object3D} [fallback]
*/
swapAvatar(template, fallback = null) {
// Cancel any in-flight performance: drop to idle, resolve pending
// render-clock sleepers so a running playSequence unblocks and exits
// (its isCancelled sees performing === false), and re-home the rig.
const wasPerforming = this.performing;
this.performing = false;
this.walkPhase = 'idle';
while (this._sleepers.length) this._sleepers.pop().resolve();
this.activeTicket = null;
// If a performance was interrupted, release the auto-cam and signal
// the audio mixer — _endPerformance() won't run because walkPhase is
// now 'idle', so we duplicate its cam+audio cleanup here.
if (wasPerforming) {
if (this._autoCammed && clubCam.getMode() === 'auto') {
clubCam.setFree();
}
this._autoCammed = false;
try {
window.dispatchEvent(new CustomEvent('club:performance-end', {
detail: { dancer: this.id, ticket: null },
}));
} catch {}
}
this.anim?.detach();
if (this.skinned) {
this.rig.remove(this.skinned);
this.skinned = null;
}
this.rig.position.copy(this.homePos);
this.rig.rotation.y = this.layout.yaw;
this._phaseTarget = this.homePos;
this._spotTarget = this.spotIdleIntensity;
this._accentTarget = 0.4;
updatePoleCardStatus(this.id, 'idle');
this.attachAvatar(template, animationDefs, fallback);
}
get backstagePos() {
return new Vector3(this.layout.backstageX, 0, this.layout.backstageZ);
}
// Idle home: standing just in front of the pole, facing the crowd. She steps
// onto the pole (poleBasePos) when a tip lands, then returns here.
get homePos() {
return new Vector3(this.layout.x, 0, this.layout.z + 0.5);
}
get poleBasePos() {
return new Vector3(this.layout.x, 0, this.layout.z + 0.02);
}
async startPerformance(ticket) {
this.activeTicket = ticket;
this.performing = true;
this.activeUntil = Date.now() + (ticket.durationSec || 12) * 1000;
this.walkPhase = 'to-pole';
this._phaseTarget = this.poleBasePos;
// Spotlight ramps up while the dancer walks on stage.
this._spotTarget = this.spotActiveIntensity;
this._accentTarget = 2.4;
// Auto-cam: if the user opted in and no manual VIP/house shot is active,
// switch to an orbiting auto-cam for the duration. We remember that the
// auto-cam started this transition so we can release it on end.
if (autoFollow && clubCam.getMode() === 'free') {
this._autoCammed = true;
clubCam.setAuto(this.layout);
} else {
this._autoCammed = false;
}
// Update pole card status.
updatePoleCardStatus(this.id, 'performing');
// Crossfade idle → walking → dance once the dancer reaches the pole.
await this.anim?.crossfadeTo(WALK_CLIP, PERFORMANCE_FADE);
}
/**
* Render-loop coupled sleep. Resolves when `_clockSec` has advanced past
* the requested duration. Used by playSequence between crossfades so
* choreography stays aligned with the mixer's frame clock even when the
* tab is throttled (where setTimeout would still fire on its own schedule
* and desync from the visible animation).
*
* @param {number} ms
* @returns {Promise<void>}
*/
sleep(ms) {
if (!Number.isFinite(ms) || ms <= 0) return Promise.resolve();
return new Promise((resolve) => {
this._sleepers.push({ wakeAt: this._clockSec + ms / 1000, resolve });
});
}
async _arriveAtPole() {
this.walkPhase = 'dancing';
const requested = ticketSteps(this.activeTicket).length
? ticketSteps(this.activeTicket)
: [{ clip: this.activeTicket?.clip || FALLBACK_CLIP, durationSec: this.activeTicket?.durationSec || 12 }];
// A tip is real on-chain money — never let a missing or un-retargetable
// clip leave her standing frozen at the pole. Drop steps this rig can't
// drive; if that empties the routine, perform the always-present fallback
// clip for the routine's full duration so the payer always sees a dance.
let steps = this.anim ? requested.filter((s) => this.anim.canPlay(s.clip)) : requested;
if (!steps.length) {
const total = requested.reduce((acc, s) => acc + (Number(s.durationSec) || 0), 0)
|| this.activeTicket?.durationSec || 12;
steps = [{ clip: FALLBACK_CLIP, durationSec: total }];
}
try {
await playSequence({
anim: this.anim,
steps,
fadeSec: PERFORMANCE_FADE,
isCancelled: () => !this.performing,
sleep: (ms) => this.sleep(ms),
});
} catch (err) {
// A playback fault must still release the stage — fall through to the
// walk-off below rather than stranding her mid-routine.
log.warn(`[club] dancer ${this.id} performance playback failed`, err);
}
// Sequence finished (or was cancelled) — step the dancer back off the
// pole to her idle home. Cancellation is a fast-path: performing is
// already false, so _endPerformance won't toggle it back, but the
// walking + audio cleanup still runs.
if (this.walkPhase === 'dancing') await this._endPerformance();
}
async _endPerformance() {
this.performing = false;
this.walkPhase = 'returning';
this._phaseTarget = this.homePos;
this._spotTarget = this.spotIdleIntensity;
this._accentTarget = 0.4;
// Release auto-cam back to free if we were the ones who took it.