Solshine commited on
Commit
b0d63f4
·
verified ·
1 Parent(s): bb63f82

Upload folder using huggingface_hub

Browse files
MusicManager.js CHANGED
@@ -7,7 +7,7 @@ export class MusicManager {
7
  this.analyser = null;
8
  this.currentStyleLabel = '';
9
  this._handFists = [false, false]; // Track fist state per hand
10
- this._doubleFistSent = false; // Prevent repeat sends
11
 
12
  // Spacebar listener at document level — captures regardless of focus
13
  document.addEventListener('keydown', (e) => {
@@ -211,7 +211,7 @@ export class MusicManager {
211
  }
212
 
213
  _sendGestureState() {
214
- if (this._panicMuted) return; // Don't send anything while paused
215
  const now = performance.now();
216
  if (!this._wsReady || now - this._lastSendTime < this._SEND_INTERVAL) return;
217
  this._lastSendTime = now;
@@ -291,30 +291,48 @@ export class MusicManager {
291
  // Synth hand made a fist
292
  this._handFists[0] = true;
293
  this._checkDoubleFist();
294
- this.currentSynthIndex = (this.currentSynthIndex + 1) % this.padPresets.length;
295
- this._gestureState.fistGesture = true;
296
- this._sendGestureState();
297
- // Reset fist state after a short window
298
- setTimeout(() => { this._handFists[0] = false; this._doubleFistSent = false; }, 1000);
299
  }
300
 
301
  setDrumHandFist(isFist) {
302
- // Called when drum hand makes/releases a fist
303
  this._handFists[1] = isFist;
304
- if (isFist) this._checkDoubleFist();
305
- if (!isFist) this._doubleFistSent = false;
 
 
 
 
 
 
 
 
 
306
  }
307
 
308
  _checkDoubleFist() {
309
- if (this._handFists[0] && this._handFists[1] && !this._doubleFistSent) {
310
- this._doubleFistSent = true;
311
- console.log('[Lyria] DOUBLE FIST — BASS DROP!');
312
  if (this._wsReady) {
313
  this._ws.send(JSON.stringify({ type: 'bassdrop' }));
314
  }
315
  }
316
  }
317
 
 
 
 
 
 
 
 
 
 
 
318
  panic() {
319
  // Toggle pause/resume
320
  this._panicMuted = !this._panicMuted;
 
7
  this.analyser = null;
8
  this.currentStyleLabel = '';
9
  this._handFists = [false, false]; // Track fist state per hand
10
+ this._bassDropActive = false; // True while both fists held
11
 
12
  // Spacebar listener at document level — captures regardless of focus
13
  document.addEventListener('keydown', (e) => {
 
211
  }
212
 
213
  _sendGestureState() {
214
+ if (this._panicMuted || this._bassDropActive) return; // Don't send during pause or bass drop
215
  const now = performance.now();
216
  if (!this._wsReady || now - this._lastSendTime < this._SEND_INTERVAL) return;
217
  this._lastSendTime = now;
 
291
  // Synth hand made a fist
292
  this._handFists[0] = true;
293
  this._checkDoubleFist();
294
+ if (!this._bassDropActive) {
295
+ this.currentSynthIndex = (this.currentSynthIndex + 1) % this.padPresets.length;
296
+ this._gestureState.fistGesture = true;
297
+ this._sendGestureState();
298
+ }
299
  }
300
 
301
  setDrumHandFist(isFist) {
 
302
  this._handFists[1] = isFist;
303
+ if (isFist) {
304
+ this._checkDoubleFist();
305
+ } else {
306
+ this._endDoubleFist();
307
+ }
308
+ }
309
+
310
+ // Called by game.js when synth hand opens from fist
311
+ setSynthHandOpen() {
312
+ this._handFists[0] = false;
313
+ this._endDoubleFist();
314
  }
315
 
316
  _checkDoubleFist() {
317
+ if (this._handFists[0] && this._handFists[1] && !this._bassDropActive) {
318
+ this._bassDropActive = true;
319
+ console.log('[Lyria] BASS DROP LOCKED!');
320
  if (this._wsReady) {
321
  this._ws.send(JSON.stringify({ type: 'bassdrop' }));
322
  }
323
  }
324
  }
325
 
326
+ _endDoubleFist() {
327
+ if (this._bassDropActive && !(this._handFists[0] && this._handFists[1])) {
328
+ this._bassDropActive = false;
329
+ console.log('[Lyria] BASS DROP RELEASED');
330
+ if (this._wsReady) {
331
+ this._ws.send(JSON.stringify({ type: 'bassdrop_end' }));
332
+ }
333
+ }
334
+ }
335
+
336
  panic() {
337
  // Toggle pause/resume
338
  this._panicMuted = !this._panicMuted;
Player2Synth.js ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as Tone from 'https://esm.sh/tone';
2
+
3
+ // Player 2: Simple beatpad — each finger triggers a distinct percussion hit
4
+ // Hand height controls pitch, spread controls reverb
5
+ export class Player2Synth {
6
+ constructor() {
7
+ this.isStarted = false;
8
+ this._panicMuted = false;
9
+ this.activePatterns = new Map();
10
+ this.padSynths = this.activePatterns;
11
+ this.currentSynthIndex = 0;
12
+ this.padPresets = [{ name: 'BEATPAD' }];
13
+ this.currentStyleLabel = 'BEATPAD';
14
+ this.scale = ['C2','D2','E2','F2','G2','A2','B2','C3','D3','E3','F3','G3','A3','B3','C4','D4','E4','F4','G4','A4','B4','C5'];
15
+ this._fingerStates = {};
16
+ this._drumCooldowns = {};
17
+ }
18
+
19
+ async start() {
20
+ if (this.isStarted) return;
21
+ await Tone.start();
22
+
23
+ this.limiter = new Tone.Limiter(-3).toDestination();
24
+ this.reverb = new Tone.Reverb({ decay: 1.5, wet: 0.15 }).connect(this.limiter);
25
+
26
+ // Kick — deep thump
27
+ this.kick = new Tone.MembraneSynth({
28
+ pitchDecay: 0.05, octaves: 8,
29
+ envelope: { attack: 0.001, decay: 0.2, sustain: 0, release: 0.3 }
30
+ }).connect(this.limiter);
31
+
32
+ // Snare — noise burst + body
33
+ this.snare = new Tone.NoiseSynth({
34
+ noise: { type: 'white' },
35
+ envelope: { attack: 0.001, decay: 0.12, sustain: 0 }
36
+ }).connect(this.reverb);
37
+
38
+ // Hi-hat — short bright noise
39
+ this.hihat = new Tone.NoiseSynth({
40
+ noise: { type: 'white' },
41
+ envelope: { attack: 0.001, decay: 0.04, sustain: 0 }
42
+ }).connect(this.limiter);
43
+ this.hihat.volume.value = -6;
44
+
45
+ // Clap — layered noise
46
+ this.clap = new Tone.NoiseSynth({
47
+ noise: { type: 'pink' },
48
+ envelope: { attack: 0.001, decay: 0.15, sustain: 0 }
49
+ }).connect(this.reverb);
50
+
51
+ // Percussion — tonal hit (tom/conga)
52
+ this.tom = new Tone.MembraneSynth({
53
+ pitchDecay: 0.08, octaves: 4,
54
+ envelope: { attack: 0.001, decay: 0.15, sustain: 0, release: 0.2 }
55
+ }).connect(this.reverb);
56
+
57
+ // Peruvian flute — breathy sine+triangle with vibrato and delay
58
+ this.flute = new Tone.Synth({
59
+ oscillator: { type: 'sine' },
60
+ envelope: { attack: 0.08, decay: 0.1, sustain: 0.6, release: 0.4 }
61
+ });
62
+ this.fluteVibrato = new Tone.Vibrato({ frequency: 5, depth: 0.15 });
63
+ this.fluteDelay = new Tone.PingPongDelay('4n', 0.25);
64
+ this.fluteDelay.wet.value = 0.3;
65
+ this.flute.connect(this.fluteVibrato);
66
+ this.fluteVibrato.connect(this.fluteDelay);
67
+ this.fluteDelay.connect(this.reverb);
68
+ // Pentatonic flute scale (Andean)
69
+ this._fluteScale = ['E4','G4','A4','B4','D5','E5','G5','A5','B5','D6','E6'];
70
+ this._fluteHeld = false;
71
+
72
+ this.isStarted = true;
73
+ console.log('[Beatpad] Started');
74
+ }
75
+
76
+ // Synth hand: height controls tom pitch, each finger triggers a pad
77
+ updateGesture(handId, gestureData) {
78
+ if (!this.isStarted || this._panicMuted) return;
79
+
80
+ const ext = gestureData.fingerExtensions || {};
81
+ const prev = this._fingerStates;
82
+
83
+ // Thumb = kick, Middle = hihat, Ring = clap, Pinky = tom
84
+ this._triggerOnOpen('thumb', ext.thumb, prev.thumb, () => {
85
+ const note = gestureData.rootNote || 'C2';
86
+ this.kick.triggerAttackRelease(note, '8n');
87
+ });
88
+ this._triggerOnOpen('middle', ext.middle, prev.middle, () => {
89
+ this.hihat.triggerAttackRelease('32n');
90
+ });
91
+ this._triggerOnOpen('ring', ext.ring, prev.ring, () => {
92
+ this.clap.triggerAttackRelease('8n');
93
+ });
94
+ this._triggerOnOpen('pinky', ext.pinky, prev.pinky, () => {
95
+ const note = gestureData.rootNote || 'C3';
96
+ this.tom.triggerAttackRelease(note, '8n');
97
+ });
98
+
99
+ // Index = Peruvian flute — held while finger is up, pitch from hand height
100
+ if ((ext.index || 0) > 0.45) {
101
+ const handY = gestureData.rootNote ? this.scale.indexOf(gestureData.rootNote) : 10;
102
+ const fluteIdx = Math.floor((handY / this.scale.length) * this._fluteScale.length);
103
+ const fluteNote = this._fluteScale[Math.max(0, Math.min(this._fluteScale.length - 1, fluteIdx))];
104
+ if (!this._fluteHeld) {
105
+ this.flute.triggerAttack(fluteNote);
106
+ this._fluteHeld = true;
107
+ } else {
108
+ this.flute.frequency.rampTo(Tone.Frequency(fluteNote).toFrequency(), 0.15);
109
+ }
110
+ } else if (this._fluteHeld) {
111
+ this.flute.triggerRelease();
112
+ this._fluteHeld = false;
113
+ }
114
+
115
+ // Save state for next frame
116
+ this._fingerStates = {
117
+ thumb: ext.thumb || 0,
118
+ index: ext.index || 0,
119
+ middle: ext.middle || 0,
120
+ ring: ext.ring || 0,
121
+ pinky: ext.pinky || 0
122
+ };
123
+
124
+ // Wrist angle controls reverb amount
125
+ const wrist = Math.abs(gestureData.wristAngle || 0);
126
+ if (this.reverb) this.reverb.wet.value = wrist * 0.5;
127
+ }
128
+
129
+ _triggerOnOpen(finger, current, previous, callback) {
130
+ const now = performance.now();
131
+ const cd = this._drumCooldowns[finger] || 0;
132
+ if ((current || 0) > 0.45 && (previous || 0) <= 0.45 && now - cd > 120) {
133
+ this._drumCooldowns[finger] = now;
134
+ callback();
135
+ }
136
+ }
137
+
138
+ // Drum hand: same per-finger triggers but with repeat while held
139
+ updateDrumGesture(gestureData) {
140
+ if (!this.isStarted || this._panicMuted) return;
141
+ const ext = gestureData.fingerExtensions || {};
142
+
143
+ // Retrigger while finger is held open (every 200ms)
144
+ this._retrigger('d_thumb', ext.thumb, () => this.kick.triggerAttackRelease('C1', '8n'));
145
+ this._retrigger('d_index', ext.index, () => this.snare.triggerAttackRelease('16n'));
146
+ this._retrigger('d_middle', ext.middle, () => this.hihat.triggerAttackRelease('32n'));
147
+ this._retrigger('d_ring', ext.ring, () => this.clap.triggerAttackRelease('8n'));
148
+ this._retrigger('d_pinky', ext.pinky, () => this.tom.triggerAttackRelease('G2', '16n'));
149
+ }
150
+
151
+ _retrigger(key, value, callback) {
152
+ const now = performance.now();
153
+ const cd = this._drumCooldowns[key] || 0;
154
+ if ((value || 0) > 0.5 && now - cd > 200) {
155
+ this._drumCooldowns[key] = now;
156
+ callback();
157
+ }
158
+ }
159
+
160
+ triggerFingerTouch(f1, f2) {
161
+ if (!this.isStarted || this._panicMuted) return;
162
+ // Any finger touch = rimshot
163
+ this.tom.triggerAttackRelease('E4', '32n');
164
+ }
165
+
166
+ // Stubs for game.js compatibility
167
+ startArpeggio() {}
168
+ stopArpeggio() {}
169
+ updateArpeggio() {}
170
+ updateArpeggioVolume() {}
171
+ updateFingerExpression() {}
172
+ setProximityFilter() {}
173
+ setSynthHandOpen() {}
174
+ setDrumHandFist() {}
175
+ stopShapeBass() {}
176
+ updateShapeBass() {}
177
+ updateShapeAudio() {}
178
+ cycleSynth() { console.log('[Beatpad] Cycle — only one mode'); }
179
+ panic() { this._panicMuted = !this._panicMuted; }
180
+ handLeft() {}
181
+ ensureAudioActive() { if (Tone.context.state === 'suspended') Tone.context.resume(); }
182
+ getAnalyser() { return null; }
183
+ getAnalyserData() { return new Float32Array(2048); }
184
+ }
ToneMusicManager.js ADDED
@@ -0,0 +1,969 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import * as Tone from 'https://esm.sh/tone';
2
+
3
+ // Original Tone.js Synth Engine — Used for Player 2 in multi mode
4
+ // Each finger's distance from palm is a continuous controller
5
+ // Synth hand: melodic/tonal, Drum hand: percussive/textural
6
+ export class ToneMusicManager {
7
+ constructor() {
8
+ this.padSynths = new Map();
9
+ this.activePatterns = this.padSynths;
10
+
11
+ this.reverb = null;
12
+ this.delay = null;
13
+ this.chorus = null;
14
+ this.analyser = null;
15
+
16
+ this.isStarted = false;
17
+ this.handVolumes = new Map();
18
+ this.fingerCooldowns = new Map();
19
+ this.percCooldown = 0;
20
+
21
+ this.FINGER_COOLDOWN_MS = 120;
22
+ this.PERC_COOLDOWN_MS = 150;
23
+ this.HAND_VELOCITY_THRESHOLD = 0.15;
24
+
25
+ this.fingerIntervals = { index: 0, middle: 3, ring: 7, pinky: 10 };
26
+
27
+ this.scale = [
28
+ 'C1','Eb1','G1','Bb1','C2','Eb2','F2','G2','Bb2',
29
+ 'C3','Eb3','F3','G3','Bb3','C4','Eb4','F4','G4','Bb4','C5','Eb5','F5'
30
+ ];
31
+
32
+ this.padPresets = [
33
+ { name: 'Ambient Sub', oscillator: { type: 'sine' }, envelope: { attack: 0.8, decay: 0.6, sustain: 0.7, release: 1.0 } },
34
+ { name: 'Dub Growl', oscillator: { type: 'sawtooth' }, envelope: { attack: 0.3, decay: 0.5, sustain: 0.5, release: 0.8 } },
35
+ { name: 'Dream Wash', oscillator: { type: 'triangle' }, envelope: { attack: 1.0, decay: 0.8, sustain: 0.6, release: 1.2 } },
36
+ { name: 'Detuned Saw', oscillator: { type: 'fatsawtooth', spread: 40, count: 3 }, envelope: { attack: 0.6, decay: 0.5, sustain: 0.7, release: 1.0 } },
37
+ { name: 'Warm Square', oscillator: { type: 'fatsquare', spread: 20, count: 3 }, envelope: { attack: 0.5, decay: 0.4, sustain: 0.6, release: 0.8 } }
38
+ ];
39
+ this.currentSynthIndex = 0;
40
+
41
+ this._prevExtensions = {};
42
+ this._prevDrumExtensions = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
43
+ this._drumFingerCooldowns = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
44
+
45
+ this._smoothDist = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
46
+ this._smoothDrumDist = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
47
+ this._SMOOTH_ALPHA = 0.3; // balanced: responsive but not jittery
48
+ this._frameCount = 0; // throttle heavy updates to every 3rd frame
49
+ }
50
+
51
+ // Resume AudioContext if browser suspended it (called on clicks + periodically)
52
+ async ensureAudioActive() {
53
+ if (Tone.context.state !== 'running') {
54
+ console.log('AudioContext suspended, resuming...');
55
+ await Tone.context.resume();
56
+ await Tone.start();
57
+ }
58
+ }
59
+
60
+ async start() {
61
+ if (this.isStarted) {
62
+ // Already started — just make sure context is alive
63
+ await this.ensureAudioActive();
64
+ return;
65
+ }
66
+ await Tone.start();
67
+
68
+ try {
69
+
70
+ // === MASTER EFFECTS CHAIN ===
71
+ this.limiter = new Tone.Limiter(-3).toDestination();
72
+ this.reverb = new Tone.Reverb({ decay: 8, preDelay: 0.05, wet: 0.45 }).connect(this.limiter);
73
+ this.delay = new Tone.PingPongDelay({ delayTime: '4n', feedback: 0.4, wet: 0.25 }).connect(this.reverb);
74
+ this.chorus = new Tone.Chorus({ frequency: 2, delayTime: 4, depth: 0.7 }).connect(this.reverb);
75
+ this.chorus.start();
76
+ this.filter = new Tone.Filter(16000, 'lowpass').connect(this.chorus);
77
+ this.analyser = new Tone.Analyser('waveform', 1024);
78
+ this.reverb.connect(this.analyser);
79
+
80
+ // =====================================================================
81
+ // SYNTH HAND — Psychedelic EDM soundboard voices
82
+ // Thumb+Index = volume (pinch). Middle/Ring/Pinky = the instruments.
83
+ // =====================================================================
84
+ this.fingerSynths = {};
85
+
86
+ // === MIDDLE (ROOT): 303 Acid Squelch ===
87
+ // Sawtooth + high-resonance filter sweep. THE psychedelic sound.
88
+ // Distance controls filter cutoff — close=dark, extended=screaming acid
89
+ this._acidFilter = new Tone.Filter({
90
+ frequency: 400, type: 'lowpass', Q: 12, rolloff: -24
91
+ }).connect(this.delay);
92
+ this.fingerSynths.middle = new Tone.MonoSynth({
93
+ oscillator: { type: 'sawtooth' },
94
+ filter: { Q: 12, type: 'lowpass', rolloff: -24 },
95
+ envelope: { attack: 0.005, decay: 0.2, sustain: 0.3, release: 0.3 },
96
+ filterEnvelope: {
97
+ attack: 0.001, decay: 0.2, sustain: 0.1, release: 0.3,
98
+ baseFrequency: 200, octaves: 4, exponent: 2
99
+ }
100
+ }).connect(this._acidFilter);
101
+ this.fingerSynths.middle.volume.value = -4;
102
+
103
+ // === RING (5th): Goa Pluck ===
104
+ // Square wave, fast decay, no sustain — futuristic harp.
105
+ // Drowned in ping-pong delay so a single tap echoes across stereo field.
106
+ this._shimmerReverb = new Tone.Reverb({ decay: 4, preDelay: 0.02, wet: 0.5 }).connect(this.limiter);
107
+ this._pluckDelay = new Tone.PingPongDelay({
108
+ delayTime: '16n', feedback: 0.45, wet: 0.4
109
+ }).connect(this._shimmerReverb);
110
+ this.fingerSynths.ring = new Tone.Synth({
111
+ oscillator: { type: 'square' },
112
+ envelope: { attack: 0.001, decay: 0.12, sustain: 0, release: 0.08 }
113
+ }).connect(this._pluckDelay);
114
+ this.fingerSynths.ring.volume.value = -6;
115
+
116
+ // === PINKY (m7): FM Laser Zap ===
117
+ // Sine + pitch envelope + FM for metallic "pew-pew" sci-fi laser.
118
+ // Distance controls FM depth — close=subtle, extended=full laser
119
+ this.distortion = new Tone.Distortion({ distortion: 0, wet: 0 }).connect(this.limiter);
120
+ this.fingerSynths.pinky = new Tone.FMSynth({
121
+ harmonicity: 8, modulationIndex: 20,
122
+ oscillator: { type: 'sine' },
123
+ envelope: { attack: 0.001, decay: 0.15, sustain: 0, release: 0.1 },
124
+ modulation: { type: 'square' },
125
+ modulationEnvelope: { attack: 0.001, decay: 0.1, sustain: 0, release: 0.05 }
126
+ }).connect(this.distortion);
127
+ this.fingerSynths.pinky.volume.value = -2;
128
+
129
+ // === CONTINUOUS: Acid squelch drone (always-on, distance = filter) ===
130
+ this.middleContinuous = new Tone.Synth({
131
+ oscillator: { type: 'sawtooth' },
132
+ envelope: { attack: 0.4, decay: 0, sustain: 1, release: 0.6 }
133
+ }).connect(this._acidFilter);
134
+ this.middleContinuous.volume.value = -24;
135
+
136
+ // === CONTINUOUS: Ring pluck shimmer drone ===
137
+ this.ringContinuous = new Tone.Synth({
138
+ oscillator: { type: 'triangle' },
139
+ envelope: { attack: 0.8, decay: 0, sustain: 1, release: 1.0 }
140
+ }).connect(this._shimmerReverb);
141
+ this.ringContinuous.volume.value = -30;
142
+
143
+ // === CONTINUOUS: Pinky sub-wobble drone ===
144
+ this.pinkyContinuous = new Tone.Synth({
145
+ oscillator: { type: 'sine' },
146
+ envelope: { attack: 0.5, decay: 0, sustain: 1, release: 0.8 }
147
+ }).connect(this.distortion);
148
+ this.pinkyContinuous.volume.value = -30;
149
+
150
+ // =====================================================================
151
+ // DRUM HAND — Real drum samples, finger distance = repeat rate
152
+ // =====================================================================
153
+ this.drumFingerSynths = {};
154
+
155
+ // Drum sample players — kick, hihat, clap
156
+ this.drumPlayers = new Tone.Players({
157
+ urls: {
158
+ kick: 'assets/kick.wav',
159
+ hihat: 'assets/hihat.wav',
160
+ clap: 'assets/clap.wav'
161
+ },
162
+ onload: () => {
163
+ console.log('Drum samples loaded');
164
+ this._drumPlayersLoaded = true;
165
+ this.drumPlayers.player('kick').volume.value = 0;
166
+ this.drumPlayers.player('hihat').volume.value = -2;
167
+ this.drumPlayers.player('clap').volume.value = 0;
168
+ }
169
+ }).connect(this.limiter);
170
+ this._drumPlayersLoaded = false;
171
+
172
+ // THUMB: Glitch zap trigger
173
+ this.drumThumbSynth = new Tone.FMSynth({
174
+ harmonicity: 6, modulationIndex: 15,
175
+ oscillator: { type: 'square' },
176
+ envelope: { attack: 0.001, decay: 0.05, sustain: 0, release: 0.03 },
177
+ modulation: { type: 'sawtooth' },
178
+ modulationEnvelope: { attack: 0.001, decay: 0.03, sustain: 0, release: 0.02 }
179
+ }).connect(this.delay);
180
+ this.drumThumbSynth.volume.value = -8;
181
+
182
+ // Beat timers
183
+ this._drumBeatTimers = { kick: 0, hihat: 0, clap: 0 };
184
+
185
+ // === DEDICATED TRIGGER SYNTHS (loud, immediate, per-finger) ===
186
+ // These fire on open/close transitions — separate from the BPM sample loop
187
+
188
+ // Kick trigger: punchy membrane, louder than sample
189
+ this._triggerKick = new Tone.MembraneSynth({
190
+ pitchDecay: 0.06, octaves: 6,
191
+ oscillator: { type: 'sine' },
192
+ envelope: { attack: 0.001, decay: 0.3, sustain: 0, release: 0.2 }
193
+ }).connect(this.limiter);
194
+ this._triggerKick.volume.value = 2;
195
+
196
+ // Hihat trigger: bright noise burst
197
+ this._triggerHat = new Tone.NoiseSynth({
198
+ noise: { type: 'white' },
199
+ envelope: { attack: 0.001, decay: 0.05, sustain: 0, release: 0.03 }
200
+ }).connect(this.limiter);
201
+ this._triggerHat.volume.value = -2;
202
+
203
+ // Clap trigger: layered noise with bandpass
204
+ this._clapFilter = new Tone.Filter({ frequency: 1500, type: 'bandpass', Q: 2 }).connect(this.reverb);
205
+ this._triggerClap = new Tone.NoiseSynth({
206
+ noise: { type: 'pink' },
207
+ envelope: { attack: 0.001, decay: 0.1, sustain: 0, release: 0.06 }
208
+ }).connect(this._clapFilter);
209
+ this._triggerClap.volume.value = 0;
210
+
211
+ // Legacy references
212
+ this.kickSynth = new Tone.MembraneSynth({
213
+ pitchDecay: 0.08, octaves: 8,
214
+ oscillator: { type: 'sine' },
215
+ envelope: { attack: 0.001, decay: 0.4, sustain: 0, release: 0.3 }
216
+ }).connect(this.limiter);
217
+ this.kickSynth.volume.value = -4;
218
+ this.hatSynth = new Tone.NoiseSynth({
219
+ noise: { type: 'white' },
220
+ envelope: { attack: 0.001, decay: 0.06, sustain: 0, release: 0.02 }
221
+ }).connect(this.limiter);
222
+ this.hatSynth.volume.value = -8;
223
+ this.pluckSynth = { releaseAll: () => {} };
224
+
225
+ // === SUB-BASS ===
226
+ this.subBass = new Tone.Synth({
227
+ oscillator: { type: 'sine' },
228
+ envelope: { attack: 0.3, decay: 0, sustain: 1, release: 0.8 }
229
+ }).connect(this.limiter);
230
+ this.subBass.volume.value = -18;
231
+
232
+ this.wobbleLFO = new Tone.LFO({ frequency: 0.3, min: -22, max: -12 });
233
+ this.wobbleLFO.connect(this.subBass.volume);
234
+ this.wobbleLFO.start();
235
+
236
+ this._continuousActive = false;
237
+
238
+ // === SHAPE BASS — epic deep bass tied to the white quadrilateral ===
239
+ // Z-depth modulates lowpass filter + distortion (closer = darker/heavier)
240
+ this._shapeBassFilter = new Tone.Filter({
241
+ frequency: 800, type: 'lowpass', Q: 2, rolloff: -24
242
+ }).connect(this.limiter);
243
+ this._shapeBassDistortion = new Tone.Distortion({
244
+ distortion: 0, wet: 0
245
+ }).connect(this._shapeBassFilter);
246
+ this._shapeBass = new Tone.Synth({
247
+ oscillator: { type: 'fatsawtooth', spread: 15, count: 3 },
248
+ envelope: { attack: 0.3, decay: 0, sustain: 1, release: 1.5 }
249
+ }).connect(this._shapeBassDistortion);
250
+ this._shapeBass.volume.value = -10;
251
+ this._shapeBassActive = false;
252
+ this._shapeSubBass = new Tone.Synth({
253
+ oscillator: { type: 'sine' },
254
+ envelope: { attack: 0.5, decay: 0, sustain: 1, release: 1.0 }
255
+ }).connect(this.limiter);
256
+ this._shapeSubBass.volume.value = -8;
257
+
258
+ // Pre-allocate touch synths (no dynamic allocation = no memory leak)
259
+ this._initTouchSynths();
260
+
261
+ } catch(e) {
262
+ console.error('MusicManager start() error:', e);
263
+ }
264
+ this.isStarted = true;
265
+ console.log('Psychedelic EDM engine v2 ready — distance-from-palm control');
266
+ }
267
+
268
+ _smooth(target, key, raw) {
269
+ target[key] += (raw - target[key]) * this._SMOOTH_ALPHA;
270
+ return target[key];
271
+ }
272
+
273
+ // --- Pad Management ---
274
+
275
+ startArpeggio(handId, rootNote, playerIndex) {
276
+ if (!this.isStarted || this.padSynths.has(handId) || this._panicMuted) return;
277
+
278
+ // Per-player preset: player 2 uses a different timbre
279
+ const pIdx = playerIndex || 0;
280
+ const presetIdx = (this.currentSynthIndex + pIdx * 2) % this.padPresets.length;
281
+ const preset = this.padPresets[presetIdx];
282
+
283
+ // Per-player key offset: player 2 transposed up a perfect 4th (5 semitones)
284
+ const keyOffset = (pIdx === 0) ? 1 : Math.pow(2, 5/12); // P4 for player 2
285
+
286
+ // Auto-chord: root + minor 3rd + perfect 5th
287
+ const makePad = (volDb) => {
288
+ const s = new Tone.Synth({
289
+ oscillator: { ...preset.oscillator },
290
+ envelope: { ...preset.envelope }
291
+ });
292
+ s.connect(this.filter);
293
+ s.volume.value = volDb;
294
+ return s;
295
+ };
296
+
297
+ const rootPad = makePad(-10);
298
+ const thirdPad = makePad(-14); // minor 3rd, slightly quieter
299
+ const fifthPad = makePad(-13); // perfect 5th
300
+
301
+ const freq = Tone.Frequency(rootNote).toFrequency() * keyOffset;
302
+ rootPad.triggerAttack(freq, Tone.now());
303
+ thirdPad.triggerAttack(freq * Math.pow(2, 3/12), Tone.now()); // minor 3rd
304
+ fifthPad.triggerAttack(freq * Math.pow(2, 7/12), Tone.now()); // perfect 5th
305
+
306
+ if (this.subBass) this.subBass.triggerAttack(freq / 2, Tone.now());
307
+
308
+ this.padSynths.set(handId, {
309
+ synth: rootPad, thirdSynth: thirdPad, fifthSynth: fifthPad,
310
+ currentRoot: rootNote, keyOffset, playerIndex: pIdx
311
+ });
312
+ this.handVolumes.set(handId, 0.2);
313
+ this.fingerCooldowns.set(handId, { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 });
314
+
315
+ // Start continuous synths
316
+ if (!this._continuousActive) {
317
+ this._continuousActive = true;
318
+ try {
319
+ this.middleContinuous.triggerAttack(freq * 1.498, Tone.now());
320
+ this.ringContinuous.triggerAttack(freq * 2, Tone.now());
321
+ this.pinkyContinuous.triggerAttack(freq / 2, Tone.now());
322
+ } catch(e) {}
323
+ }
324
+ }
325
+
326
+ updateArpeggio(handId, newRootNote) {
327
+ const padData = this.padSynths.get(handId);
328
+ if (!padData || padData.currentRoot === newRootNote) return;
329
+
330
+ const keyOffset = padData.keyOffset || 1;
331
+ const freq = Tone.Frequency(newRootNote).toFrequency() * keyOffset;
332
+ padData.synth.frequency.rampTo(freq, 0.15);
333
+ if (padData.thirdSynth) padData.thirdSynth.frequency.rampTo(freq * Math.pow(2, 3/12), 0.15);
334
+ if (padData.fifthSynth) padData.fifthSynth.frequency.rampTo(freq * Math.pow(2, 7/12), 0.15);
335
+ if (this.subBass) this.subBass.frequency.rampTo(freq / 2, 0.2);
336
+
337
+ try {
338
+ if (this.middleContinuous) this.middleContinuous.frequency.rampTo(freq * Math.pow(2, 3/12), 0.2);
339
+ if (this.ringContinuous) this.ringContinuous.frequency.rampTo(freq * 2, 0.2);
340
+ if (this.pinkyContinuous) this.pinkyContinuous.frequency.rampTo(freq / 2, 0.2);
341
+ } catch(e) {}
342
+
343
+ padData.currentRoot = newRootNote;
344
+ }
345
+
346
+ updateArpeggioVolume(handId, velocity) {
347
+ const padData = this.padSynths.get(handId);
348
+ if (!padData) return;
349
+
350
+ const clamped = Math.max(0, Math.min(1, velocity));
351
+ this.handVolumes.set(handId, clamped);
352
+ const db = -30 + clamped * 26;
353
+ padData.synth.volume.rampTo(db, 0.03);
354
+ if (padData.thirdSynth) padData.thirdSynth.volume.rampTo(db - 4, 0.03);
355
+ if (padData.fifthSynth) padData.fifthSynth.volume.rampTo(db - 3, 0.03);
356
+ }
357
+
358
+ stopArpeggio(handId) {
359
+ const padData = this.padSynths.get(handId);
360
+ if (padData) {
361
+ padData.synth.triggerRelease(Tone.now());
362
+ if (padData.thirdSynth) padData.thirdSynth.triggerRelease(Tone.now());
363
+ if (padData.fifthSynth) padData.fifthSynth.triggerRelease(Tone.now());
364
+ if (this.padSynths.size <= 1 && this.subBass) {
365
+ this.subBass.triggerRelease(Tone.now());
366
+ }
367
+
368
+ if (this.padSynths.size <= 1) {
369
+ this._continuousActive = false;
370
+ try { this.middleContinuous.triggerRelease(Tone.now()); } catch(e) {}
371
+ try { this.ringContinuous.triggerRelease(Tone.now()); } catch(e) {}
372
+ try { this.pinkyContinuous.triggerRelease(Tone.now()); } catch(e) {}
373
+ }
374
+
375
+ if (!this._pendingDisposals) this._pendingDisposals = new Set();
376
+ const synths = [padData.synth, padData.thirdSynth, padData.fifthSynth].filter(Boolean);
377
+
378
+ // Force-dispose oldest if too many pending (prevents memory leak on hand flicker)
379
+ if (this._pendingDisposals.size > 8) {
380
+ const oldest = this._pendingDisposals.values().next().value;
381
+ try { oldest.dispose(); } catch(e) {}
382
+ this._pendingDisposals.delete(oldest);
383
+ }
384
+
385
+ for (const synth of synths) {
386
+ if (!this._pendingDisposals.has(synth)) {
387
+ this._pendingDisposals.add(synth);
388
+ // Disconnect immediately to stop audio, dispose after release tail
389
+ try { synth.disconnect(); } catch(e) {}
390
+ setTimeout(() => {
391
+ try { synth.dispose(); } catch(e) {}
392
+ this._pendingDisposals.delete(synth);
393
+ }, 1000);
394
+ }
395
+ }
396
+ this.padSynths.delete(handId);
397
+ this.handVolumes.delete(handId);
398
+ this.fingerCooldowns.delete(handId);
399
+ }
400
+ }
401
+
402
+ // =====================================================================
403
+ // SYNTH HAND (hand 0)
404
+ // Thumb+Index = volume only. Middle/Ring/Pinky = continuous + triggers
405
+ // Each finger sounds RADICALLY different via separate signal chains
406
+ // =====================================================================
407
+
408
+ updateGesture(handId, gestureData) {
409
+ if (!this.isStarted || this._panicMuted) return;
410
+
411
+ const { fingerStates, handVelocity, rootNote } = gestureData;
412
+ const now = performance.now();
413
+ const cooldowns = this.fingerCooldowns.get(handId);
414
+ if (!cooldowns) return;
415
+
416
+ if (!this._prevExtensions[handId]) {
417
+ this._prevExtensions[handId] = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
418
+ }
419
+ const prevExt = this._prevExtensions[handId];
420
+
421
+ const dist = gestureData.fingerDistances || gestureData.fingerExtensions || {
422
+ thumb: 0.1, index: 0.1, middle: 0.1, ring: 0.1, pinky: 0.1
423
+ };
424
+
425
+ const d = {};
426
+ for (const f of ['thumb', 'index', 'middle', 'ring', 'pinky']) {
427
+ d[f] = this._smooth(this._smoothDist, f, dist[f] || 0);
428
+ }
429
+
430
+ const rootFreq = Tone.Frequency(rootNote).toFrequency();
431
+
432
+ // INDEX: No effect (square/volume finger — fully independent)
433
+
434
+ const doHeavyUpdate = true; // no throttling — responsiveness > CPU savings
435
+
436
+ // === MIDDLE (ROOT): 303 Acid Squelch ===
437
+ // Distance = filter cutoff. Close=dark rumble, extended=screaming acid.
438
+ if (this._acidFilter && doHeavyUpdate) {
439
+ this._acidFilter.frequency.value = 200 + Math.pow(d.middle, 2) * 10000;
440
+ this._acidFilter.Q.value = 6 + d.middle * 12;
441
+ }
442
+ if (this.fingerSynths.middle) {
443
+ if (prevExt.middle < 0.2 && d.middle > 0.35 && (now - cooldowns.middle) > this.FINGER_COOLDOWN_MS) {
444
+ cooldowns.middle = now;
445
+ this.fingerSynths.middle.triggerAttackRelease(
446
+ Tone.Frequency(rootFreq).toNote(), '4n', Tone.now(), 0.9
447
+ );
448
+ }
449
+ }
450
+ if (this.middleContinuous && doHeavyUpdate) {
451
+ this.middleContinuous.volume.rampTo(d.middle < 0.1 ? -Infinity : -36 + d.middle * 22, 0.03);
452
+ }
453
+
454
+ // === RING (5th): Goa Pluck ===
455
+ // Distance = delay feedback + reverb wet. Close=dry tap, extended=echoing cascade
456
+ if (this.fingerSynths.ring) {
457
+ if (prevExt.ring < 0.2 && d.ring > 0.35 && (now - cooldowns.ring) > this.FINGER_COOLDOWN_MS) {
458
+ cooldowns.ring = now;
459
+ const pluckFreq = rootFreq * Math.pow(2, 7/12); // perfect 5th
460
+ this.fingerSynths.ring.triggerAttackRelease(
461
+ Tone.Frequency(pluckFreq).toNote(), '16n', Tone.now(), 0.7 + d.ring * 0.3
462
+ );
463
+ }
464
+ }
465
+ if (doHeavyUpdate) {
466
+ if (this._pluckDelay) {
467
+ this._pluckDelay.feedback.value = 0.2 + d.ring * 0.45;
468
+ this._pluckDelay.wet.value = 0.1 + d.ring * 0.5;
469
+ }
470
+ if (this._shimmerReverb) {
471
+ this._shimmerReverb.wet.value = 0.2 + d.ring * 0.6;
472
+ }
473
+ if (this.ringContinuous) {
474
+ this.ringContinuous.volume.rampTo(d.ring < 0.1 ? -Infinity : -40 + d.ring * 22, 0.03);
475
+ }
476
+ }
477
+
478
+ // === PINKY (m7): FM Laser Zap ===
479
+ // Distance = FM depth + distortion. Close=subtle ping, extended=full laser blast
480
+ if (this.fingerSynths.pinky && doHeavyUpdate) {
481
+ try {
482
+ this.fingerSynths.pinky.modulationIndex.value = 2 + Math.pow(d.pinky, 1.5) * 35;
483
+ this.fingerSynths.pinky.harmonicity.value = 4 + d.pinky * 8;
484
+ } catch(e) {}
485
+ if (prevExt.pinky < 0.2 && d.pinky > 0.35 && (now - cooldowns.pinky) > this.FINGER_COOLDOWN_MS) {
486
+ cooldowns.pinky = now;
487
+ const zapFreq = rootFreq * Math.pow(2, 10/12); // minor 7th
488
+ this.fingerSynths.pinky.triggerAttackRelease(
489
+ Tone.Frequency(zapFreq).toNote(), '8n', Tone.now(), 0.9
490
+ );
491
+ }
492
+ }
493
+ if (doHeavyUpdate) {
494
+ if (this.distortion) {
495
+ this.distortion.distortion = Math.pow(d.pinky, 1.5) * 0.6;
496
+ this.distortion.wet.value = d.pinky * 0.5;
497
+ }
498
+ if (this.pinkyContinuous) {
499
+ this.pinkyContinuous.volume.rampTo(d.pinky < 0.1 ? -Infinity : -40 + d.pinky * 22, 0.03);
500
+ }
501
+ }
502
+
503
+ // === WRIST ANGLE: Massive tonal modulation ===
504
+ {
505
+ // -1 = tilted left, 0 = straight up, +1 = tilted right
506
+ // Controls: master filter cutoff, pad detune, delay time, chorus speed
507
+ const wristAngle = gestureData.wristAngle || 0;
508
+ const absAngle = Math.abs(wristAngle);
509
+
510
+ // Master filter: straight up = bright (16kHz), tilted = dark (200Hz)
511
+ if (this.filter) {
512
+ const filterCutoff = 16000 * Math.pow(0.02, absAngle); // 16kHz → ~300Hz
513
+ this.filter.frequency.rampTo(filterCutoff, 0.03);
514
+ }
515
+
516
+ // Pad detune: tilted = detuned/dissonant, up to ±100 cents
517
+ this.padSynths.forEach(padData => {
518
+ padData.synth.detune.rampTo(wristAngle * 100, 0.03);
519
+ if (padData.thirdSynth) padData.thirdSynth.detune.rampTo(-wristAngle * 60, 0.03);
520
+ if (padData.fifthSynth) padData.fifthSynth.detune.rampTo(wristAngle * 40, 0.03);
521
+ });
522
+
523
+ // Delay time shift: tilted right = longer delay, left = shorter
524
+ if (this.delay) {
525
+ const baseDelay = 0.2; // ~8th note
526
+ const delayShift = baseDelay + wristAngle * 0.15; // 0.05 → 0.35
527
+ try { this.delay.delayTime.rampTo(Math.max(0.01, delayShift), 0.03); } catch(e) {}
528
+ }
529
+
530
+ // Chorus speed: more tilt = faster chorus wobble
531
+ if (this.chorus) {
532
+ this.chorus.frequency.value = 1 + absAngle * 8; // 1→9 Hz
533
+ }
534
+
535
+ // Wobble LFO speed: angle adds to wobble
536
+ if (this.wobbleLFO) {
537
+ this.wobbleLFO.frequency.value = 0.3 + absAngle * 6;
538
+ }
539
+
540
+ // FM continuous: wrist angle adds extra modulation depth
541
+ if (this.middleContinuous) {
542
+ try {
543
+ const angleModBoost = absAngle * 10;
544
+ this.middleContinuous.harmonicity.value = 2 + absAngle * 4;
545
+ } catch(e) {}
546
+ }
547
+
548
+ // === Hand spread → chorus depth (additive with wrist angle) ===
549
+ const spread = gestureData.handSpread || 0;
550
+ if (this.chorus) {
551
+ this.chorus.depth = 0.3 + spread * 0.7;
552
+ }
553
+
554
+ // === DELAY: Controlled by ring (shimmer) ===
555
+ if (this.delay) {
556
+ this.delay.feedback.value = 0.1 + d.ring * 0.55;
557
+ this.delay.wet.value = 0.05 + d.ring * 0.4;
558
+ }
559
+
560
+ // === REVERB: Controlled by combined ring+pinky ===
561
+ if (this.reverb) {
562
+ this.reverb.wet.value = 0.15 + Math.max(d.ring, d.pinky) * 0.5;
563
+ }
564
+
565
+ } // end doHeavyUpdate wrist angle block
566
+
567
+ // Store for next frame
568
+ for (const f of ['thumb', 'index', 'middle', 'ring', 'pinky']) {
569
+ prevExt[f] = d[f];
570
+ }
571
+
572
+ // Percussive hits on sharp hand movement
573
+ if ((now - this.percCooldown) > this.PERC_COOLDOWN_MS) {
574
+ const vx = handVelocity?.x || 0;
575
+ const vy = handVelocity?.y || 0;
576
+ const magnitude = Math.sqrt(vx * vx + vy * vy);
577
+ if (magnitude > this.HAND_VELOCITY_THRESHOLD) {
578
+ this.percCooldown = now;
579
+ if (vy > this.HAND_VELOCITY_THRESHOLD) {
580
+ this.kickSynth.triggerAttackRelease('C1', '8n', Tone.now(), Math.min(1, vy * 3));
581
+ } else if (Math.abs(vx) > this.HAND_VELOCITY_THRESHOLD) {
582
+ this.hatSynth.triggerAttackRelease('16n', Tone.now(), Math.min(1, Math.abs(vx) * 3));
583
+ }
584
+ }
585
+ }
586
+ }
587
+
588
+ // =====================================================================
589
+ // DRUM HAND (hand 1)
590
+ // Fingers held up = drum pattern active (via DrumManager labels)
591
+ // PLUS: continuous distance-based synth percussion from MusicManager
592
+ // Key fix: drum middle is now always-on when extended (not just triggers)
593
+ // =====================================================================
594
+
595
+ updateDrumGesture(gestureData) {
596
+ if (!this.isStarted || this._panicMuted) return;
597
+
598
+ const now = performance.now();
599
+ const prevExt = this._prevDrumExtensions;
600
+ const cooldowns = this._drumFingerCooldowns;
601
+
602
+ const dist = gestureData.fingerDistances || gestureData.fingerExtensions || {
603
+ thumb: 0.1, index: 0.1, middle: 0.1, ring: 0.1, pinky: 0.1
604
+ };
605
+
606
+ const d = {};
607
+ for (const f of ['thumb', 'index', 'middle', 'ring', 'pinky']) {
608
+ d[f] = this._smooth(this._smoothDrumDist, f, dist[f] || 0);
609
+ }
610
+
611
+ // =====================================================================
612
+ // IMMEDIATE TRIGGERS — loud distinct sound on every finger open/close
613
+ // Synth hits (not just samples) so each finger is unmistakable
614
+ // =====================================================================
615
+ const OPEN_THRESH = 0.22;
616
+ const CLOSE_THRESH = 0.12;
617
+
618
+ // MIDDLE: Deep boom on open, short thud on close
619
+ if (prevExt.middle < OPEN_THRESH && d.middle >= OPEN_THRESH) {
620
+ try {
621
+ this._triggerKick.triggerAttackRelease('C1', '8n', Tone.now(), 1.0);
622
+ if (this._drumPlayersLoaded) this.drumPlayers.player('kick').start(Tone.now());
623
+ } catch(e) {}
624
+ } else if (prevExt.middle >= OPEN_THRESH && d.middle < CLOSE_THRESH) {
625
+ try { this._triggerKick.triggerAttackRelease('G1', '32n', Tone.now(), 0.5); } catch(e) {}
626
+ }
627
+
628
+ // RING: Bright tick on open, soft click on close
629
+ if (prevExt.ring < OPEN_THRESH && d.ring >= OPEN_THRESH) {
630
+ try {
631
+ this._triggerHat.triggerAttackRelease('16n', Tone.now(), 1.0);
632
+ if (this._drumPlayersLoaded) this.drumPlayers.player('hihat').start(Tone.now());
633
+ } catch(e) {}
634
+ } else if (prevExt.ring >= OPEN_THRESH && d.ring < CLOSE_THRESH) {
635
+ try { this._triggerHat.triggerAttackRelease('64n', Tone.now(), 0.4); } catch(e) {}
636
+ }
637
+
638
+ // PINKY: Sharp clap on open, soft snap on close
639
+ if (prevExt.pinky < OPEN_THRESH && d.pinky >= OPEN_THRESH) {
640
+ try {
641
+ this._triggerClap.triggerAttackRelease('8n', Tone.now(), 1.0);
642
+ if (this._drumPlayersLoaded) this.drumPlayers.player('clap').start(Tone.now());
643
+ } catch(e) {}
644
+ } else if (prevExt.pinky >= OPEN_THRESH && d.pinky < CLOSE_THRESH) {
645
+ try { this._triggerClap.triggerAttackRelease('32n', Tone.now(), 0.4); } catch(e) {}
646
+ }
647
+
648
+ // THUMB: Zap on open, reverse zap on close
649
+ if (prevExt.thumb < OPEN_THRESH && d.thumb >= OPEN_THRESH) {
650
+ const zapNote = ['C4','Eb4','G4','Bb4'][Math.floor(Math.random() * 4)];
651
+ try { this.drumThumbSynth.triggerAttackRelease(zapNote, '32n', Tone.now(), 0.9); } catch(e) {}
652
+ } else if (prevExt.thumb >= OPEN_THRESH && d.thumb < CLOSE_THRESH) {
653
+ try { this.drumThumbSynth.triggerAttackRelease('C3', '64n', Tone.now(), 0.5); } catch(e) {}
654
+ }
655
+
656
+ // =====================================================================
657
+ // BPM LOOP — plays while finger is held open (secondary layer)
658
+ // Middle=KICK, Ring=HIHAT, Pinky=CLAP
659
+ // =====================================================================
660
+
661
+ const DEAD_ZONE = 0.25; // higher than trigger thresh so loop starts after open
662
+ const MIN_BPM = 20; // very slow ambient pulse
663
+ const MAX_BPM = 100; // chill downtempo cap
664
+
665
+ const distToInterval = (dist) => {
666
+ if (dist < DEAD_ZONE) return Infinity;
667
+ const t = (dist - DEAD_ZONE) / (1 - DEAD_ZONE);
668
+ const bpm = MIN_BPM + Math.pow(t, 1.3) * (MAX_BPM - MIN_BPM);
669
+ return 60000 / bpm;
670
+ };
671
+
672
+ if (this._drumPlayersLoaded) {
673
+ // --- MIDDLE: KICK ---
674
+ const kickInterval = distToInterval(d.middle);
675
+ if (kickInterval < Infinity && (now - this._drumBeatTimers.kick) > kickInterval) {
676
+ this._drumBeatTimers.kick = now;
677
+ try { this.drumPlayers.player('kick').start(Tone.now()); } catch(e) {}
678
+ }
679
+
680
+ // --- RING: HIHAT ---
681
+ const hihatInterval = distToInterval(d.ring);
682
+ if (hihatInterval < Infinity && (now - this._drumBeatTimers.hihat) > hihatInterval) {
683
+ this._drumBeatTimers.hihat = now;
684
+ try { this.drumPlayers.player('hihat').start(Tone.now()); } catch(e) {}
685
+ }
686
+
687
+ // --- PINKY: CLAP ---
688
+ const clapInterval = distToInterval(d.pinky);
689
+ if (clapInterval < Infinity && (now - this._drumBeatTimers.clap) > clapInterval) {
690
+ this._drumBeatTimers.clap = now;
691
+ try { this.drumPlayers.player('clap').start(Tone.now()); } catch(e) {}
692
+ }
693
+ }
694
+
695
+ // (thumb trigger handled above in immediate triggers section)
696
+
697
+ // === WRIST ANGLE: boosts drum volume when tilted ===
698
+ const drumWristAngle = gestureData.wristAngle || 0;
699
+ const drumAbsAngle = Math.abs(drumWristAngle);
700
+ if (this._drumPlayersLoaded) {
701
+ try {
702
+ this.drumPlayers.player('kick').volume.value = 0 + drumAbsAngle * 4;
703
+ this.drumPlayers.player('hihat').volume.value = -2 + drumAbsAngle * 4;
704
+ this.drumPlayers.player('clap').volume.value = 0 + drumAbsAngle * 4;
705
+ } catch(e) {}
706
+ }
707
+
708
+ for (const f of ['thumb', 'index', 'middle', 'ring', 'pinky']) {
709
+ prevExt[f] = d[f];
710
+ }
711
+ }
712
+
713
+ // --- Finger Expression ---
714
+
715
+ updateFingerExpression(params) {
716
+ // Wrist angle now handles most modulation in updateGesture
717
+ }
718
+
719
+ // --- Shape Bass (white quadrilateral = epic bass) ---
720
+
721
+ updateShapeAudio(data) {
722
+ if (!this.isStarted || this._panicMuted) return;
723
+
724
+ const { type, depth, area, anchorCount } = data;
725
+ const hasShape = (type !== 'none' && anchorCount >= 2);
726
+
727
+ // Start/stop the shape bass drone
728
+ if (hasShape && !this._shapeBassActive) {
729
+ this._shapeBassActive = true;
730
+ // Bass note follows the pad root if available, else C2
731
+ let bassNote = 'C2';
732
+ this.padSynths.forEach(pd => {
733
+ if (pd.currentRoot) {
734
+ const freq = Tone.Frequency(pd.currentRoot).toFrequency();
735
+ bassNote = Tone.Frequency(freq / 2).toNote(); // one octave below pad
736
+ }
737
+ });
738
+ try {
739
+ this._shapeBass.triggerAttack(bassNote, Tone.now());
740
+ this._shapeSubBass.triggerAttack(Tone.Frequency(bassNote).toFrequency() / 2, Tone.now());
741
+ } catch(e) {}
742
+ } else if (!hasShape && this._shapeBassActive) {
743
+ this._shapeBassActive = false;
744
+ try {
745
+ this._shapeBass.triggerRelease(Tone.now());
746
+ this._shapeSubBass.triggerRelease(Tone.now());
747
+ } catch(e) {}
748
+ }
749
+
750
+ if (!hasShape) return;
751
+
752
+ // === Z-DEPTH MODULATION ===
753
+ // depth is typically -0.2 (close) to 0 (far)
754
+ // Map to 0 (far/bright) → 1 (close/dark)
755
+ const proximity = Math.max(0, Math.min(1, (-depth - 0) / 0.15));
756
+
757
+ // Filter: far = open (2000Hz), close = dark (100Hz)
758
+ if (this._shapeBassFilter) {
759
+ this._shapeBassFilter.frequency.value = 2000 - proximity * 1800;
760
+ this._shapeBassFilter.Q.value = 1 + proximity * 6;
761
+ }
762
+
763
+ // Distortion: more when close
764
+ if (this._shapeBassDistortion) {
765
+ this._shapeBassDistortion.distortion = proximity * 0.6;
766
+ this._shapeBassDistortion.wet.value = proximity * 0.5;
767
+ }
768
+
769
+ // Volume scales with shape area (bigger shape = louder bass)
770
+ const vol = -18 + area * 14;
771
+ try {
772
+ this._shapeBass.volume.rampTo(vol, 0.03);
773
+ this._shapeSubBass.volume.rampTo(vol - 4, 0.03);
774
+ } catch(e) {}
775
+
776
+ // === BASS BEAT PULSE — controlled by synth hand ring finger distance ===
777
+ // Ring finger distance sets beat rate of the shape bass (0=off, 1=fast pulse)
778
+ const ringDist = this._smoothDist.ring || 0;
779
+ if (ringDist > 0.15 && this._shapeBassActive) {
780
+ const beatBPM = 15 + ringDist * 85; // 15-100 BPM, ambient throb
781
+ const beatMs = 60000 / beatBPM;
782
+ if (!this._shapeBeatTimer) this._shapeBeatTimer = 0;
783
+ const now = performance.now();
784
+ if (now - this._shapeBeatTimer > beatMs) {
785
+ this._shapeBeatTimer = now;
786
+ // Pulse the bass volume for rhythmic throb
787
+ try {
788
+ this._shapeBass.volume.rampTo(vol + 6, 0.01);
789
+ this._shapeBass.volume.rampTo(vol, 0.08);
790
+ this._shapeSubBass.volume.rampTo(vol, 0.01);
791
+ this._shapeSubBass.volume.rampTo(vol - 4, 0.08);
792
+ } catch(e) {}
793
+ }
794
+ }
795
+
796
+ // Track pad root for bass note following
797
+ if (this._shapeBassActive) {
798
+ this.padSynths.forEach(pd => {
799
+ if (pd.currentRoot) {
800
+ const freq = Tone.Frequency(pd.currentRoot).toFrequency();
801
+ try {
802
+ this._shapeBass.frequency.rampTo(freq / 2, 0.1);
803
+ this._shapeSubBass.frequency.rampTo(freq / 4, 0.1);
804
+ } catch(e) {}
805
+ }
806
+ });
807
+ }
808
+ }
809
+
810
+ // --- Finger Touch Sounds ---
811
+ // Unique sound per finger, triggered when any two fingertips meet
812
+
813
+ // Pre-allocate touch synths (called once during start)
814
+ _initTouchSynths() {
815
+ // Pre-allocated melodic pluck synths — each plays a different pentatonic note
816
+ // Routed through delay for lush echo cascade (Goa pluck style)
817
+ this._touchSynths = {};
818
+ const touchDest = this._pluckDelay || this.delay || this.limiter;
819
+
820
+ // All 5 fingers get the same pluck voice but play different notes
821
+ const makePluck = (vol) => {
822
+ const s = new Tone.Synth({
823
+ oscillator: { type: 'triangle' },
824
+ envelope: { attack: 0.001, decay: 0.15, sustain: 0, release: 0.12 }
825
+ }).connect(touchDest);
826
+ s.volume.value = vol;
827
+ return s;
828
+ };
829
+
830
+ this._touchSynths.thumb = makePluck(-4);
831
+ this._touchSynths.index = makePluck(-4);
832
+ this._touchSynths.middle = makePluck(-2);
833
+ this._touchSynths.ring = makePluck(-2);
834
+ this._touchSynths.pinky = makePluck(-4);
835
+
836
+ // Pentatonic note per finger (C minor pentatonic, different octaves)
837
+ this._touchNotes = {
838
+ thumb: ['C5', 'Eb5', 'G5'],
839
+ index: ['Bb4', 'C5', 'Eb5'],
840
+ middle: ['G4', 'Bb4', 'C5'],
841
+ ring: ['Eb5', 'G5', 'Bb5'],
842
+ pinky: ['C6', 'Eb6', 'G6']
843
+ };
844
+
845
+ this._touchCooldown = 0;
846
+ }
847
+
848
+ triggerFingerTouch(finger1, finger2) {
849
+ if (!this.isStarted || this._panicMuted || !this._touchSynths) return;
850
+
851
+ const now = performance.now();
852
+ if ((now - this._touchCooldown) < 100) return; // debounce
853
+ this._touchCooldown = now;
854
+
855
+ const fingerPriority = ['pinky', 'ring', 'middle', 'index', 'thumb'];
856
+ const primary = fingerPriority.indexOf(finger1) < fingerPriority.indexOf(finger2) ? finger1 : finger2;
857
+
858
+ try {
859
+ const notes = this._touchNotes[primary];
860
+ if (notes && this._touchSynths[primary]) {
861
+ const note = notes[Math.floor(Math.random() * notes.length)];
862
+ this._touchSynths[primary].triggerAttackRelease(note, '16n', Tone.now(), 0.8);
863
+ }
864
+ } catch(e) {}
865
+ }
866
+
867
+ // --- Timbre Cycling ---
868
+
869
+ cycleSynth() {
870
+ if (!this.isStarted) return;
871
+
872
+ const activePads = [];
873
+ this.padSynths.forEach((padData, handId) => {
874
+ activePads.push({ handId, root: padData.currentRoot });
875
+ padData.synth.triggerRelease(Tone.now());
876
+ if (padData.thirdSynth) padData.thirdSynth.triggerRelease(Tone.now());
877
+ if (padData.fifthSynth) padData.fifthSynth.triggerRelease(Tone.now());
878
+ for (const s of [padData.synth, padData.thirdSynth, padData.fifthSynth].filter(Boolean)) {
879
+ try { s.disconnect(); } catch(e) {}
880
+ setTimeout(() => { try { s.dispose(); } catch(e) {} }, 1000);
881
+ }
882
+ });
883
+ this.padSynths.clear();
884
+
885
+ this.currentSynthIndex = (this.currentSynthIndex + 1) % this.padPresets.length;
886
+ const preset = this.padPresets[this.currentSynthIndex];
887
+ console.log(`Switched to pad preset ${this.currentSynthIndex}: ${preset.name}`);
888
+
889
+ setTimeout(() => {
890
+ activePads.forEach(({ handId, root }) => {
891
+ this.startArpeggio(handId, root);
892
+ });
893
+ }, 100);
894
+ }
895
+
896
+ // --- Proximity Filter ---
897
+
898
+ setProximityFilter(value) {
899
+ if (this.filter) {
900
+ const cutoff = 16000 * Math.pow(0.075, value);
901
+ this.filter.frequency.rampTo(cutoff, 0.2);
902
+ }
903
+ }
904
+
905
+ // --- PANIC ---
906
+
907
+ panic() {
908
+ this._panicMuted = true;
909
+ setTimeout(() => { this._panicMuted = false; }, 1000);
910
+
911
+ this.padSynths.forEach((padData) => {
912
+ try { padData.synth.triggerRelease(Tone.now()); } catch(e) {}
913
+ try { if (padData.harmonySynth) padData.harmonySynth.triggerRelease(Tone.now()); } catch(e) {}
914
+ setTimeout(() => {
915
+ try { padData.synth.dispose(); } catch(e) {}
916
+ try { if (padData.harmonySynth) padData.harmonySynth.dispose(); } catch(e) {}
917
+ }, 500);
918
+ });
919
+ this.padSynths.clear();
920
+ this.handVolumes.clear();
921
+ this.fingerCooldowns.clear();
922
+
923
+ if (this.subBass) try { this.subBass.triggerRelease(Tone.now()); } catch(e) {}
924
+
925
+ try { this.middleContinuous.triggerRelease(Tone.now()); } catch(e) {}
926
+ try { this.ringContinuous.triggerRelease(Tone.now()); } catch(e) {}
927
+ try { this.pinkyContinuous.triggerRelease(Tone.now()); } catch(e) {}
928
+ this._continuousActive = false;
929
+
930
+ // Reset glitch beat timers
931
+ this._drumBeatTimers = { kick: 0, hihat: 0, clap: 0 };
932
+ this._shapeBeatTimer = 0;
933
+
934
+ // Stop shape bass
935
+ this._shapeBassActive = false;
936
+ try { this._shapeBass.triggerRelease(Tone.now()); } catch(e) {}
937
+ try { this._shapeSubBass.triggerRelease(Tone.now()); } catch(e) {}
938
+ if (this._shapeBassFilter) this._shapeBassFilter.frequency.value = 800;
939
+ if (this._shapeBassDistortion) { this._shapeBassDistortion.distortion = 0; this._shapeBassDistortion.wet.value = 0; }
940
+
941
+ if (this.fingerSynths) {
942
+ for (const finger of ['index', 'middle', 'ring', 'pinky']) {
943
+ try { this.fingerSynths[finger].triggerRelease(Tone.now()); } catch(e) {}
944
+ }
945
+ }
946
+
947
+ if (this.wobbleLFO) {
948
+ this.wobbleLFO.stop();
949
+ setTimeout(() => { try { this.wobbleLFO.start(); } catch(e) {} }, 1000);
950
+ }
951
+
952
+ if (this.filter) this.filter.frequency.value = 16000;
953
+ if (this.reverb) this.reverb.wet.value = 0.35;
954
+ if (this.delay) { this.delay.wet.value = 0.2; this.delay.feedback.value = 0.35; }
955
+ if (this.chorus) this.chorus.depth = 0.6;
956
+ if (this.distortion) { this.distortion.distortion = 0; this.distortion.wet.value = 0; }
957
+
958
+ this._prevDrumExtensions = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
959
+ this._drumFingerCooldowns = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
960
+ this._smoothDist = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
961
+ this._smoothDrumDist = { thumb: 0, index: 0, middle: 0, ring: 0, pinky: 0 };
962
+
963
+ console.log('PANIC — all sound killed');
964
+ }
965
+
966
+ getAnalyser() {
967
+ return this.analyser;
968
+ }
969
+ }
backend/gesture_interpreter.py CHANGED
@@ -14,38 +14,42 @@ SYSTEM_PROMPT = """DJ AI. Output ONLY JSON: {"prompts":[{"text":"desc","weight":
14
  1-4 prompts, weights 0.1-3.0, under 10 words each.
15
  IMPORTANT: Describe ONLY genre, instruments, and texture. Never mention tempo, brightness, density, volume — those are controlled separately by the API.
16
 
17
- HAND HEIGHT = genre zone:
18
- - HIGH=shoegaze, chillout, ambient, dream pop, new age, world fusion, Balinese gamelan
19
- - MID-HIGH=melodic techno, progressive trance, synthwave, Afro house, tribal house
20
- - MID=IDM, electronica, trip-hop, lo-fi, downtempo, dub, world beats, cumbia digital
21
- - MID-LOW=dark techno, industrial, acid house, garage, grime, tribal jungle, kuduro
22
- - LOW=neurofunk DnB, filthy dubstep, breakcore, jungle, gabber, ragga jungle
23
-
24
- SPREAD = production style:
25
- - CLOSED=solo instrument, dry, monophonic, raw, stripped
26
- - OPEN=ensemble, polyphonic, orchestral, world percussion, chorus, wet
27
-
28
- FINGERS each add one instrument — be creative, vary every time, draw from global music:
29
- - THUMB=melodic (lead, pluck, vocal chop, kalimba, sitar, kora, Rhodes, flute, didgeridoo, steel drum)
30
- - INDEX=sequenced (arp, gated stab, chord hit, sidechain pump, trance gate, marimba roll)
31
- - MIDDLE=bass (acid 303, reese, wobble, growl, FM bass, moog, dub bass, djembe bass)
32
- - RING=percussive (amen break, tabla, djembe, bongo, conga, taiko, industrial hit, shaker, surdo)
33
- - PINKY=texture (vinyl crackle, rain, jungle birds, tape hiss, ocean waves, throat singing, wind chimes, granular)
34
-
35
- TILTED=detuned dissonant. SHAPE=sub-bass drone. DRUMS=tribal breakbeat world percussion.
36
- "Evolve gradually"=shift one element. "Change direction"=new genre entirely."""
 
 
 
 
37
 
38
  SEED_EXAMPLES = [
39
- {"role": "user", "content": "Hand HIGH, OPEN, PINKY up rest down, STILL.\n\nEvolve gradually."},
40
- {"role": "assistant", "content": '{"prompts":[{"text":"shoegaze dream pop washed guitars","weight":1.5},{"text":"granular shimmer field recording","weight":0.8}]}'},
41
- {"role": "user", "content": "Hand LOW, CLOSED, INDEX+MIDDLE+RING up, TILTED, FAST.\n\nChange direction."},
42
- {"role": "assistant", "content": '{"prompts":[{"text":"neurofunk DnB filthy reese","weight":2.0},{"text":"trance gate stab sequence","weight":1.5},{"text":"amen break chopped snares","weight":1.3}]}'},
43
- {"role": "user", "content": "Hand MID-HIGH, OPEN, THUMB+PINKY up, STILL.\n\nEvolve gradually."},
44
- {"role": "assistant", "content": '{"prompts":[{"text":"synthwave Rhodes melody line","weight":1.3},{"text":"vinyl crackle tape warmth","weight":0.8},{"text":"progressive trance pads","weight":1.0}]}'},
45
- {"role": "user", "content": "Hand MID-LOW, MEDIUM, MIDDLE+RING up, DRUMS.\n\nChange direction."},
46
- {"role": "assistant", "content": '{"prompts":[{"text":"tribal jungle kuduro percussion","weight":2.0},{"text":"acid 303 distorted growl","weight":1.5}]}'},
47
- {"role": "user", "content": "Hand MID, OPEN, THUMB+RING+PINKY up, DRUMS, STILL.\n\nEvolve gradually."},
48
- {"role": "assistant", "content": '{"prompts":[{"text":"Afro house kora melody","weight":1.3},{"text":"djembe conga tribal groove","weight":1.5},{"text":"jungle birds field recording","weight":0.7}]}'},
49
  ]
50
 
51
 
@@ -53,8 +57,8 @@ class GestureInterpreter:
53
  def __init__(self, ollama_url: str = OLLAMA_URL, model: str = MODEL_NAME):
54
  self.ollama_url = ollama_url
55
  self.model = model
56
- # Tight timeout — 3s max, fail fast
57
- self.client = httpx.AsyncClient(timeout=3.0)
58
  self._ollama_dead = False # True = skip Ollama entirely (connection refused)
59
  self._consecutive_failures = 0
60
  self.using_fallback = False # Exposed to server for frontend indicator
@@ -173,11 +177,18 @@ class GestureInterpreter:
173
  elif vol < 0.25:
174
  parts.append("QUIET")
175
 
176
- # Individual fingers
177
  fingers = g.get("fingerExtensions", {})
178
- up = [f.upper() for f in ["thumb", "index", "middle", "ring", "pinky"] if fingers.get(f, 0) > 0.4]
179
- if up:
180
- parts.append(f"{'+'.join(up)} up")
 
 
 
 
 
 
 
181
  else:
182
  parts.append("all down")
183
 
@@ -209,39 +220,58 @@ class GestureInterpreter:
209
  fingers = g.get("fingerExtensions", {})
210
  wrist = abs(g.get("wristAngle", 0.0))
211
 
212
- # Genre from 5-zone height
213
  if hand_y > 0.8:
214
- prompts.append({"text": "shoegaze dream pop ambient gamelan", "weight": 1.3})
215
  elif hand_y > 0.6:
216
- prompts.append({"text": "melodic techno Afro house tribal", "weight": 1.2})
217
  elif hand_y > 0.4:
218
- prompts.append({"text": "dub electronica world beats cumbia", "weight": 1.0})
219
  elif hand_y > 0.2:
220
- prompts.append({"text": "tribal jungle kuduro acid house", "weight": 1.4})
221
  else:
222
- prompts.append({"text": "ragga jungle neurofunk breakcore", "weight": 1.8})
223
 
224
- # Production style from spread
225
- if spread > 0.65:
226
- prompts.append({"text": "ensemble world percussion orchestral", "weight": 0.8})
227
- elif spread < 0.3:
228
- prompts.append({"text": "solo monophonic raw stripped", "weight": 0.8})
229
-
230
- # Per-finger instruments — world diversity
231
- if fingers.get("thumb", 0) > 0.4:
232
- prompts.append({"text": "kalimba kora melody steel drum", "weight": 1.5})
233
- if fingers.get("index", 0) > 0.4:
234
- prompts.append({"text": "gated arpeggio marimba sequence", "weight": 1.3})
235
- if fingers.get("middle", 0) > 0.4:
236
- prompts.append({"text": "acid 303 dub bass reese wobble", "weight": 1.5})
237
- if fingers.get("ring", 0) > 0.4:
238
- prompts.append({"text": "djembe tabla conga taiko break", "weight": 1.3})
239
- if fingers.get("pinky", 0) > 0.4:
240
- prompts.append({"text": "jungle birds wind chimes shimmer", "weight": 1.0})
241
-
242
- if wrist > 0.4:
243
- prompts.append({"text": "detuned dissonant warped", "weight": wrist * 2})
 
 
 
 
 
 
 
 
 
 
 
 
244
  if g.get("shapeActive"):
245
- prompts.append({"text": "sub-bass drone didgeridoo", "weight": 1.5})
 
 
 
 
 
 
 
246
 
247
  return prompts[:4] if prompts else [{"text": "ambient electronic soundscape", "weight": 1.0}]
 
14
  1-4 prompts, weights 0.1-3.0, under 10 words each.
15
  IMPORTANT: Describe ONLY genre, instruments, and texture. Never mention tempo, brightness, density, volume — those are controlled separately by the API.
16
 
17
+ HAND POSITION on screen changes the music. NO guitars, NO rock, NO sirens.
18
+ HIGH on screen = ambient, ethereal, floaty, dreamy, spacious, psybient, celestial
19
+ LOW on screen = heavy, wet, drippy, bass, DnB, riddim, neurofunk, filthy
20
+
21
+ HEIGHT controls genre smoothly — always keep it CATCHY with a melodic anchor or rhythmic hook:
22
+ - TOP=transcendent ambient, astral psybient, cosmic drift, celestial pads, ethereal drone
23
+ - HIGH=liquid DnB, dreamy trance, atmospheric jungle, psychedelic chillout, melodic halftime
24
+ - MID=psychedelic glitch-hop, trippy breaks, halftime neurohop groove, bouncy acid electronica
25
+ - LOW=half-time DnB, squishy neuro bass, granular stutter edits, punchy neurohop beat
26
+ - BOTTOM=filthy neurofunk, drippy riddim, tearout DnB, amen jungle carnage, deathstep
27
+
28
+ ALWAYS include one CATCHY element — a repetitive melodic hook, earworm pluck, or rhythmic motif.
29
+ SPREAD = texture richness (continuous — more spread = more layers + psychedelic effects)
30
+ VOLUME/PINCH = intensity (continuous)
31
+
32
+ Each FINGER adds a layer — weight scales with how far the finger extends. Be creative:
33
+ - THUMB=catchy melodic hook (pentatonic synth pluck earworm, crystal lead, singing bowl, emotional melody)
34
+ - INDEX=sequenced (liquid arp, granular stutter edit, glitch chop, tape stop, sidechain pump)
35
+ - MIDDLE=bass (squishy neuro bass, reese wobble, acid 303, drippy sub, FM growl, moog squelch)
36
+ - RING=percussive (halftime DnB groove, amen break, tribal drums, punchy snare, organic foley percussion)
37
+ - PINKY=psychedelic (swirling delay tails, cosmic dust, aurora shimmer, rain, tape warmth, vinyl crackle)
38
+
39
+ TILTED=LFO modulation detuned warped. SHAPE=sub-bass foundation. DRUMS=breakbeat rhythm.
40
+ "Evolve gradually"=shift one element. "Change direction"=new genre."""
41
 
42
  SEED_EXAMPLES = [
43
+ {"role": "user", "content": "Hand TOP, OPEN, PINKY FULL, THUMB half, STILL.\n\nEvolve gradually."},
44
+ {"role": "assistant", "content": '{"prompts":[{"text":"transcendent astral psybient drift","weight":2.0},{"text":"cosmic dust swirling delay tails","weight":1.1},{"text":"catchy pentatonic singing bowl melody","weight":0.8}]}'},
45
+ {"role": "user", "content": "Hand BOTTOM, MEDIUM, MIDDLE FULL, RING FULL, INDEX half, FAST.\n\nChange direction."},
46
+ {"role": "assistant", "content": '{"prompts":[{"text":"filthy drippy neurofunk DnB","weight":2.5},{"text":"squishy neuro bass granular stutter","weight":2.0},{"text":"catchy repetitive synth pluck hook","weight":1.5}]}'},
47
+ {"role": "user", "content": "Hand MID, OPEN, THUMB FULL, INDEX FULL, RING half, STILL.\n\nEvolve gradually."},
48
+ {"role": "assistant", "content": '{"prompts":[{"text":"half-time DnB groove punchy neurohop","weight":2.0},{"text":"catchy pentatonic synth pluck earworm","weight":1.8},{"text":"granular stutter edits tape stops","weight":1.2}]}'},
49
+ {"role": "user", "content": "Hand HIGH, OPEN, THUMB FULL, PINKY FULL, STILL.\n\nEvolve gradually."},
50
+ {"role": "assistant", "content": '{"prompts":[{"text":"liquid DnB dreamy atmospheric","weight":1.5},{"text":"crystal lead emotional melody hook","weight":1.3},{"text":"swirling psychedelic delay tails","weight":1.0}]}'},
51
+ {"role": "user", "content": "Hand LOW, CLOSED, MIDDLE FULL, DRUMS, FAST.\n\nChange direction."},
52
+ {"role": "assistant", "content": '{"prompts":[{"text":"squishy neuro bass design wobble","weight":2.5},{"text":"half-time punchy neurohop beat","weight":2.0},{"text":"organic foley percussion glitch","weight":1.0}]}'},
53
  ]
54
 
55
 
 
57
  def __init__(self, ollama_url: str = OLLAMA_URL, model: str = MODEL_NAME):
58
  self.ollama_url = ollama_url
59
  self.model = model
60
+ # 8s timeout — allows cold model reload, still fast enough
61
+ self.client = httpx.AsyncClient(timeout=8.0)
62
  self._ollama_dead = False # True = skip Ollama entirely (connection refused)
63
  self._consecutive_failures = 0
64
  self.using_fallback = False # Exposed to server for frontend indicator
 
177
  elif vol < 0.25:
178
  parts.append("QUIET")
179
 
180
+ # Individual fingers with continuous intensity
181
  fingers = g.get("fingerExtensions", {})
182
+ finger_parts = []
183
+ for f in ["thumb", "index", "middle", "ring", "pinky"]:
184
+ v = fingers.get(f, 0)
185
+ if v > 0.7:
186
+ finger_parts.append(f"{f.upper()} FULL")
187
+ elif v > 0.4:
188
+ finger_parts.append(f"{f.upper()} half")
189
+ # below 0.4 = not mentioned (down)
190
+ if finger_parts:
191
+ parts.append(", ".join(finger_parts))
192
  else:
193
  parts.append("all down")
194
 
 
220
  fingers = g.get("fingerExtensions", {})
221
  wrist = abs(g.get("wristAngle", 0.0))
222
 
223
+ # Genre smoothly from height — ambient top, DnB bottom
224
  if hand_y > 0.8:
225
+ prompts.append({"text": "transcendent astral psybient celestial", "weight": 2.0})
226
  elif hand_y > 0.6:
227
+ prompts.append({"text": "liquid DnB dreamy atmospheric melodic", "weight": 1.5})
228
  elif hand_y > 0.4:
229
+ prompts.append({"text": "psychedelic glitch-hop neurohop groove", "weight": 1.5})
230
  elif hand_y > 0.2:
231
+ prompts.append({"text": "half-time DnB squishy neuro bass", "weight": 2.0})
232
  else:
233
+ prompts.append({"text": "filthy drippy neurofunk DnB carnage", "weight": 2.5})
234
 
235
+ # Always add a catchy hook element
236
+ prompts.append({"text": "catchy repetitive pentatonic synth hook", "weight": 1.2})
237
+
238
+ # Spread = smooth texture + psychedelic effects
239
+ if spread > 0.3:
240
+ prompts.append({"text": "swirling psychedelic delay tails pads", "weight": round(spread * 1.5, 2)})
241
+ else:
242
+ prompts.append({"text": "stripped raw intimate dry", "weight": round((1.0 - spread) * 1.0, 2)})
243
+
244
+ # Per-finger — smooth weight from extension distance
245
+ thumb = fingers.get("thumb", 0)
246
+ index = fingers.get("index", 0)
247
+ middle = fingers.get("middle", 0)
248
+ ring = fingers.get("ring", 0)
249
+ pinky = fingers.get("pinky", 0)
250
+
251
+ if thumb > 0.25:
252
+ prompts.append({"text": "catchy pentatonic pluck earworm melody", "weight": round(thumb * 2.0, 2)})
253
+ if index > 0.25:
254
+ prompts.append({"text": "granular stutter glitch tape stop edit", "weight": round(index * 1.8, 2)})
255
+ if middle > 0.25:
256
+ prompts.append({"text": "squishy neuro bass reese wobble growl", "weight": round(middle * 2.5, 2)})
257
+ if ring > 0.25:
258
+ prompts.append({"text": "half-time punchy groove foley percussion", "weight": round(ring * 2.0, 2)})
259
+ if pinky > 0.25:
260
+ prompts.append({"text": "swirling delay cosmic dust aurora", "weight": round(pinky * 1.5, 2)})
261
+
262
+ # Wrist tilt = warped detuned character, weight scales with tilt
263
+ if wrist > 0.3:
264
+ prompts.append({"text": "warped detuned LFO modulation", "weight": round(wrist * 1.5, 2)})
265
+
266
+ # Shape = sub-bass, character shifts with height
267
  if g.get("shapeActive"):
268
+ if hand_y > 0.5:
269
+ prompts.append({"text": "deep clean rolling sub-bass foundation", "weight": 1.3})
270
+ else:
271
+ prompts.append({"text": "massive distorted sub-bass rumble", "weight": 1.6})
272
+
273
+ # Drum hand = rhythm emphasis
274
+ if g.get("drumHandActive"):
275
+ prompts.append({"text": "driving rhythmic percussion groove", "weight": 1.2})
276
 
277
  return prompts[:4] if prompts else [{"text": "ambient electronic soundscape", "weight": 1.0}]
backend/lyria_manager.py CHANGED
@@ -20,6 +20,9 @@ class LyriaManager:
20
  self._ctx_manager = None
21
  self._playing = False
22
  self._current_bpm = None
 
 
 
23
 
24
  async def connect(self):
25
  """Connect to Lyria RealTime and start playing."""
@@ -81,28 +84,81 @@ class LyriaManager:
81
  self._playing = False
82
  print("[Lyria] Disconnected")
83
 
84
- async def update_prompts(self, prompts: list[dict]):
85
- """Update weighted prompts. prompts = [{"text": "...", "weight": 1.0}, ...]"""
 
86
  if not self.session:
87
  return
88
- # Cap at 4 prompts — too many dilutes the musical intent
89
  prompts = prompts[:4]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  weighted = [
91
  types.WeightedPrompt(text=p["text"], weight=p.get("weight", 1.0))
92
  for p in prompts
93
  ]
94
  try:
95
  await self.session.set_weighted_prompts(prompts=weighted)
96
- print(f"[Lyria] Prompts updated: {[p['text'][:30] for p in prompts]}")
 
97
  except Exception as e:
98
- print(f"[Lyria] Prompt update error: {e}")
99
 
100
  async def update_config(self, config: dict):
101
  """Update Lyria generation config from mapped gesture parameters."""
102
  if not self.session:
103
  return
104
 
105
- kwargs = {"music_generation_mode": "DIVERSITY"}
 
 
106
  if "brightness" in config:
107
  kwargs["brightness"] = config["brightness"]
108
  if "density" in config:
 
20
  self._ctx_manager = None
21
  self._playing = False
22
  self._current_bpm = None
23
+ self._current_prompts = None # Last settled prompts
24
+ self._target_prompts = None # Prompts we're fading toward
25
+ self._fade_task = None # Active crossfade task
26
 
27
  async def connect(self):
28
  """Connect to Lyria RealTime and start playing."""
 
84
  self._playing = False
85
  print("[Lyria] Disconnected")
86
 
87
+ async def update_prompts(self, prompts: list[dict], instant: bool = False):
88
+ """Cross-fade from current prompts to new prompts over several steps.
89
+ Set instant=True for immediate slam (e.g. bass drop)."""
90
  if not self.session:
91
  return
 
92
  prompts = prompts[:4]
93
+
94
+ if instant or not self._current_prompts:
95
+ # Immediate update — no blending
96
+ self._current_prompts = prompts
97
+ self._target_prompts = None
98
+ await self._send_prompts(prompts)
99
+ return
100
+
101
+ # Start a cross-fade: old prompts fade out, new prompts fade in
102
+ # Cancel any in-progress fade
103
+ if self._fade_task and not self._fade_task.done():
104
+ self._fade_task.cancel()
105
+
106
+ self._target_prompts = prompts
107
+ self._fade_task = asyncio.create_task(self._crossfade())
108
+
109
+ async def _crossfade(self):
110
+ """Gradually blend from current prompts to target over ~4 seconds."""
111
+ steps = 4
112
+ delay = 1.0 # seconds between steps
113
+ old = self._current_prompts or []
114
+ new = self._target_prompts or []
115
+
116
+ try:
117
+ for step in range(1, steps + 1):
118
+ t = step / steps # 0.25, 0.5, 0.75, 1.0
119
+ blended = []
120
+ # Fade out old prompts
121
+ for p in old:
122
+ w = p.get("weight", 1.0) * (1.0 - t)
123
+ if w > 0.05:
124
+ blended.append({"text": p["text"], "weight": round(w, 2)})
125
+ # Fade in new prompts
126
+ for p in new:
127
+ w = p.get("weight", 1.0) * t
128
+ if w > 0.05:
129
+ blended.append({"text": p["text"], "weight": round(w, 2)})
130
+
131
+ await self._send_prompts(blended[:6]) # allow up to 6 during blend
132
+ await asyncio.sleep(delay)
133
+
134
+ # Settle on new prompts
135
+ self._current_prompts = new
136
+ self._target_prompts = None
137
+ except asyncio.CancelledError:
138
+ # New fade started, this one is superseded
139
+ pass
140
+
141
+ async def _send_prompts(self, prompts: list[dict]):
142
+ """Send prompts to Lyria."""
143
  weighted = [
144
  types.WeightedPrompt(text=p["text"], weight=p.get("weight", 1.0))
145
  for p in prompts
146
  ]
147
  try:
148
  await self.session.set_weighted_prompts(prompts=weighted)
149
+ labels = [f"{p['text'][:25]}({p.get('weight',1.0):.1f})" for p in prompts]
150
+ print(f"[Lyria] Prompts: {labels}")
151
  except Exception as e:
152
+ print(f"[Lyria] Prompt send error: {e}")
153
 
154
  async def update_config(self, config: dict):
155
  """Update Lyria generation config from mapped gesture parameters."""
156
  if not self.session:
157
  return
158
 
159
+ kwargs = {}
160
+ if "music_generation_mode" in config:
161
+ kwargs["music_generation_mode"] = config["music_generation_mode"]
162
  if "brightness" in config:
163
  kwargs["brightness"] = config["brightness"]
164
  if "density" in config:
backend/server.py CHANGED
@@ -85,6 +85,7 @@ async def websocket_endpoint(websocket: WebSocket):
85
  last_config_update = 0
86
  CONFIG_THROTTLE = 1.0 # only update Lyria config every 1s
87
  paused = False
 
88
 
89
  def _gesture_changed_significantly(prev, curr):
90
  """Check if hands moved enough to warrant a music change."""
@@ -130,8 +131,8 @@ async def websocket_endpoint(websocket: WebSocket):
130
  msg = json.loads(raw)
131
 
132
  if msg["type"] == "gesture":
133
- if paused:
134
- continue # Skip ALL processing while paused
135
 
136
  gesture_data = msg["data"]
137
  current_gesture_state = gesture_data
@@ -202,27 +203,22 @@ async def websocket_endpoint(websocket: WebSocket):
202
  print("[Server] RESUMED")
203
 
204
  elif msg["type"] == "bassdrop":
205
- # Double fist = EPIC BASS DROP
206
- print("[Server] BASS DROP!")
 
207
  await lyria.update_prompts([
208
- {"text": "massive epic bass drop impact", "weight": 3.0},
209
- {"text": "sub-bass earthquake explosion", "weight": 2.5},
210
- ])
211
  await lyria.update_config({"density": 0.95, "brightness": 0.3})
212
- # Revert after 5 seconds
213
- async def _revert_drop():
214
- import asyncio
215
- await asyncio.sleep(5)
216
- # Restore to current gesture-based state
217
- if current_gesture_state:
218
- cfg = _map_gesture_to_lyria_config(current_gesture_state)
219
- await lyria.update_config(cfg)
220
- prompt_text = await interpreter.interpret(
221
- current_gesture_state, force_new_direction=True
222
- )
223
- if prompt_text:
224
- await lyria.update_prompts(prompt_text)
225
- asyncio.create_task(_revert_drop())
226
 
227
  elif msg["type"] == "hands_lost":
228
  # All hands gone — fade out
@@ -238,32 +234,45 @@ async def websocket_endpoint(websocket: WebSocket):
238
 
239
 
240
  def _map_gesture_to_lyria_config(gesture_data: dict) -> dict:
241
- """Map hand tracking directly to Lyria API physics — no text prompts needed for these."""
242
  config = {}
243
-
244
- # Hand height → brightness (low=dark/bassy, high=crisp/bright)
245
  hand_y = gesture_data.get("handY", 0.5)
246
- config["brightness"] = max(0.0, min(1.0, hand_y))
247
-
248
- # Hand spread → density (closed=sparse, open=busy/complex)
249
  spread = gesture_data.get("handSpread", 0.5)
250
- config["density"] = max(0.0, min(1.0, spread))
251
-
252
- # Volume/pinch → boosts density (louder pinch = more intensity)
253
  volume = gesture_data.get("volume", 0.5)
254
- config["density"] = max(0.0, min(1.0, config["density"] * (0.4 + volume * 0.6)))
255
-
256
- # Wrist tilt → darken brightness (filter sweep effect)
257
  wrist = gesture_data.get("wristAngle", 0.0)
258
- config["brightness"] *= (1.0 - abs(wrist) * 0.5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
 
260
- # Drum hand tempo → BPM (finger extension = faster)
 
 
 
 
261
  drum_tempo = gesture_data.get("drumTempo")
262
  if drum_tempo is not None:
263
- bpm = int(60 + drum_tempo * 140) # 60-200
264
- config["bpm"] = max(60, min(200, bpm))
 
265
 
266
- # Mute toggles for buildups/breakdowns
267
  config["mute_drums"] = gesture_data.get("muteDrums", False)
268
  config["mute_bass"] = gesture_data.get("muteBass", False)
269
 
 
85
  last_config_update = 0
86
  CONFIG_THROTTLE = 1.0 # only update Lyria config every 1s
87
  paused = False
88
+ bassdrop_active = False
89
 
90
  def _gesture_changed_significantly(prev, curr):
91
  """Check if hands moved enough to warrant a music change."""
 
131
  msg = json.loads(raw)
132
 
133
  if msg["type"] == "gesture":
134
+ if paused or bassdrop_active:
135
+ continue # Skip ALL processing while paused or bass dropping
136
 
137
  gesture_data = msg["data"]
138
  current_gesture_state = gesture_data
 
203
  print("[Server] RESUMED")
204
 
205
  elif msg["type"] == "bassdrop":
206
+ # Double fist = EPIC BASS DROP — locks out all other signals
207
+ bassdrop_active = True
208
+ print("[Server] BASS DROP LOCKED!")
209
  await lyria.update_prompts([
210
+ {"text": "filthy dubstep glitch-hop bass drop", "weight": 3.0},
211
+ {"text": "wobble growl riddim impact", "weight": 2.5},
212
+ ], instant=True)
213
  await lyria.update_config({"density": 0.95, "brightness": 0.3})
214
+
215
+ elif msg["type"] == "bassdrop_end":
216
+ # Fists released — restore normal mode
217
+ if bassdrop_active:
218
+ bassdrop_active = False
219
+ print("[Server] BASS DROP RELEASED")
220
+ prev_gesture_state = {} # force fresh update on next gesture
221
+ last_qwen_time = 0
 
 
 
 
 
 
222
 
223
  elif msg["type"] == "hands_lost":
224
  # All hands gone — fade out
 
234
 
235
 
236
  def _map_gesture_to_lyria_config(gesture_data: dict) -> dict:
237
+ """Smooth continuous mapping — hand position smoothly morphs all physics."""
238
  config = {}
 
 
239
  hand_y = gesture_data.get("handY", 0.5)
 
 
 
240
  spread = gesture_data.get("handSpread", 0.5)
 
 
 
241
  volume = gesture_data.get("volume", 0.5)
 
 
 
242
  wrist = gesture_data.get("wristAngle", 0.0)
243
+ fingers = gesture_data.get("fingerExtensions", {})
244
+
245
+ # Always DIVERSITY mode — more creative, exploratory
246
+ config["music_generation_mode"] = "DIVERSITY"
247
+
248
+ # Hand height smoothly controls brightness (high=airy, low=dark heavy)
249
+ config["brightness"] = max(0.0, min(1.0, 0.3 + hand_y * 0.65))
250
+
251
+ # Spread smoothly controls density (closed=sparse, open=dense)
252
+ config["density"] = max(0.0, min(1.0, 0.2 + spread * 0.7))
253
+
254
+ # Volume/pinch boosts density
255
+ config["density"] = max(0.0, min(1.0, config["density"] * (0.5 + volume * 0.5)))
256
+
257
+ # Finger activity subtly boosts brightness
258
+ finger_vals = [v for v in fingers.values() if isinstance(v, (int, float))]
259
+ avg_ext = sum(finger_vals) / max(len(finger_vals), 1)
260
+ config["brightness"] = min(1.0, config["brightness"] + avg_ext * 0.1)
261
+
262
+ # Wrist tilt darkens (filter sweep)
263
+ config["brightness"] *= (1.0 - abs(wrist) * 0.4)
264
 
265
+ # BPM: top=110 ambient, mid=172 halftime neurohop, bottom=174 DnB
266
+ if hand_y > 0.6:
267
+ base_bpm = int(110 + (1.0 - hand_y) * 80) # 110-142 ambient→melodic
268
+ else:
269
+ base_bpm = int(172 + (0.6 - hand_y) * 5) # 172-175 halftime/DnB zone
270
  drum_tempo = gesture_data.get("drumTempo")
271
  if drum_tempo is not None:
272
+ config["bpm"] = max(60, min(200, int(60 + drum_tempo * 140)))
273
+ else:
274
+ config["bpm"] = base_bpm
275
 
 
276
  config["mute_drums"] = gesture_data.get("muteDrums", False)
277
  config["mute_bass"] = gesture_data.get("muteBass", False)
278
 
game.js CHANGED
@@ -218,7 +218,8 @@ function _ts_generator(thisArg, body) {
218
  import * as THREE from 'three';
219
  import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; // Import GLTFLoader
220
  import { HandLandmarker, FilesetResolver } from 'https://esm.sh/@mediapipe/tasks-vision@0.10.14';
221
- import { MusicManager } from './MusicManager.js'; // Import the MusicManager
 
222
  // Tone.js shim — Lyria version doesn't use Tone directly
223
  const Tone = {
224
  now: () => 0,
@@ -260,7 +261,7 @@ export var Game = /*#__PURE__*/ function() {
260
  this.gameState = 'loading'; // loading, ready, tracking, error
261
  this.gameOverText = null; // Will be repurposed or simplified
262
  this.clock = new THREE.Clock();
263
- this.musicManager = new MusicManager(); // Create an instance of MusicManager
264
  this.waveformVisualizer = null; // To be initialized
265
  // this.drumManager = new DrumManager(); // DrumManager is now a static module, no instance needed
266
  this.lastLandmarkPositions = [
@@ -790,11 +791,12 @@ export var Game = /*#__PURE__*/ function() {
790
  var handX = (1 - normX_visible) * canvasWidth - canvasWidth / 2;
791
  var handY = (1 - normY_visible) * canvasHeight - canvasHeight / 2;
792
  hand.anchorPos.set(handX, handY, 1);
793
- // Multi-player routing: hands 0,1 = player 0; hands 2,3 = player 1
794
  var maxHandIdx = _this1._multiplayerEnabled ? 4 : 2;
795
  var playerIndex = Math.floor(i / 2);
796
  var isSynthHand = (i % 2 === 0);
797
  var isDrumHand = (i % 2 === 1);
 
798
  if (i >= maxHandIdx) {
799
  // Hand not active in current mode
800
  } else if (isSynthHand) {
@@ -802,8 +804,13 @@ export var Game = /*#__PURE__*/ function() {
802
  var isFistNow = _this1._isFist(smoothedLandmarks);
803
  if (isFistNow && !hand.isFist) {
804
  // Fist gesture was just made
805
- _this1.musicManager.cycleSynth();
806
- _this1.musicManager.stopArpeggio(i); // Stop any old arpeggio
 
 
 
 
 
807
  }
808
  hand.isFist = isFistNow;
809
  var noteIndex = Math.floor((1 - normY_visible) * scale.length);
@@ -830,8 +837,8 @@ export var Game = /*#__PURE__*/ function() {
830
  // Use apparent palm size as proxy (bigger = closer)
831
  // palmSize is in normalized coords (0-1), typical range 0.03 (far) to 0.2 (close)
832
  var proximity = Math.max(0, Math.min(1, (palmSize - 0.03) / 0.12));
833
- if (_this1.musicManager.setProximityFilter) {
834
- _this1.musicManager.setProximityFilter(proximity);
835
  }
836
  _this1._updateHandLines(i, smoothedLandmarks, videoParams, canvasWidth, canvasHeight, {
837
  note: note,
@@ -840,13 +847,13 @@ export var Game = /*#__PURE__*/ function() {
840
  });
841
  if (!isFistNow) {
842
  // Start/Restart arpeggio if the hand just appeared OR if it just opened from a fist.
843
- var arpeggioIsActive = _this1.musicManager.activePatterns.has(i);
844
  if (!wasVisible || !arpeggioIsActive) {
845
- _this1.musicManager.startArpeggio(i, note, playerIndex);
846
  } else {
847
- _this1.musicManager.updateArpeggio(i, note);
848
  }
849
- _this1.musicManager.updateArpeggioVolume(i, velocity);
850
  // --- Finger Distance-from-Palm Controls ---
851
  // Each finger's Euclidean distance from palm center, normalized by palm size
852
  var wrist = smoothedLandmarks[0];
@@ -885,8 +892,8 @@ export var Game = /*#__PURE__*/ function() {
885
  var isTouching = tdist < touchThreshold;
886
  if (isTouching && !wasTouching) {
887
  // Fingers just came together — trigger touch sound
888
- if (_this1.musicManager.triggerFingerTouch) {
889
- _this1.musicManager.triggerFingerTouch(fNames[fi], fNames[fj]);
890
  }
891
  }
892
  _this1._fingerTouchState[pairKey] = isTouching;
@@ -913,7 +920,7 @@ export var Game = /*#__PURE__*/ function() {
913
  spreadSum += Math.sqrt(sdx*sdx + sdy*sdy);
914
  }
915
  var handSpread = Math.max(0, Math.min(1, (spreadSum / 4) / (palmSize * 2)));
916
- _this1.musicManager.updateFingerExpression({
917
  fingerDistances: fingerDistances,
918
  middleFinger: middleExt,
919
  ringFinger: ringExt,
@@ -943,7 +950,7 @@ export var Game = /*#__PURE__*/ function() {
943
  var wristToMcp_dy = palmCenter.y - wrist.y;
944
  var wristAngleRad = Math.atan2(wristToMcp_dx, -wristToMcp_dy); // 0=up, +π/2=right
945
  var wristAngle = Math.max(-1, Math.min(1, wristAngleRad / (Math.PI / 2))); // normalize to -1..1
946
- _this1.musicManager.updateGesture(i, {
947
  fingerStates: fingerStates,
948
  prevFingerStates: prevFS,
949
  fingerDistances: fingerDistances,
@@ -966,15 +973,15 @@ export var Game = /*#__PURE__*/ function() {
966
  _this1._prevFingerDistances[i] = Object.assign({}, fingerDistances);
967
  } else {
968
  // If it is a fist, make sure the arpeggio is stopped
969
- _this1.musicManager.stopArpeggio(i);
970
  }
971
  } else if (isDrumHand) {
972
  var fingerStates = _this1._getFingerStates(smoothedLandmarks);
973
  if (playerIndex === 0) drumManager.updateActiveDrums(fingerStates);
974
- // Detect fist on drum hand for double-fist bass drop
975
  var drumIsFist = _this1._isFist(smoothedLandmarks);
976
- if (_this1.musicManager.setDrumHandFist) {
977
- _this1.musicManager.setDrumHandFist(drumIsFist);
978
  }
979
  _this1._updateHandLines(i, smoothedLandmarks, videoParams, canvasWidth, canvasHeight, {
980
  fingerStates: fingerStates
@@ -1013,8 +1020,8 @@ export var Game = /*#__PURE__*/ function() {
1013
  var dwasTouching = _this1._drumFingerTouchState[dpairKey] || false;
1014
  var disTouching = dtdist < drumTouchThreshold;
1015
  if (disTouching && !dwasTouching) {
1016
- if (_this1.musicManager.triggerFingerTouch) {
1017
- _this1.musicManager.triggerFingerTouch(dFNames[dfi], dFNames[dfj]);
1018
  }
1019
  }
1020
  _this1._drumFingerTouchState[dpairKey] = disTouching;
@@ -1025,8 +1032,8 @@ export var Game = /*#__PURE__*/ function() {
1025
  var drumWristToMcp_dy = drumPalmCenter.y - drumWrist.y;
1026
  var drumWristAngleRad = Math.atan2(drumWristToMcp_dx, -drumWristToMcp_dy);
1027
  var drumWristAngle = Math.max(-1, Math.min(1, drumWristAngleRad / (Math.PI / 2)));
1028
- if (_this1.musicManager.updateDrumGesture) {
1029
- _this1.musicManager.updateDrumGesture({
1030
  fingerStates: fingerStates,
1031
  fingerDistances: drumFingerDistances,
1032
  fingerExtensions: {
@@ -1043,14 +1050,14 @@ export var Game = /*#__PURE__*/ function() {
1043
  hand.lineGroup.visible = true;
1044
  } else {
1045
  if (wasVisible) {
1046
- if (i === 0) {
1047
- _this1.musicManager.stopArpeggio(i);
1048
- // Kill sub-bass and plucks when music hand leaves
1049
- if (_this1.musicManager.subBass) {
1050
- try { _this1.musicManager.subBass.triggerRelease(Tone.now()); } catch(e) {}
1051
  }
1052
- if (_this1.musicManager.pluckSynth) {
1053
- try { _this1.musicManager.pluckSynth.releaseAll(Tone.now()); } catch(e) {}
1054
  }
1055
  } else if (i % 2 === 1) {
1056
  if (Math.floor(i / 2) === 0) drumManager.updateActiveDrums({});
@@ -1712,7 +1719,17 @@ export var Game = /*#__PURE__*/ function() {
1712
  if (_this.handLandmarker && _this.handLandmarker.setOptions) {
1713
  _this.handLandmarker.setOptions({ numHands: newNumHands });
1714
  }
1715
- console.log('Multiplayer: ' + (_this._multiplayerEnabled ? 'ON (4 hands)' : 'OFF (2 hands)'));
 
 
 
 
 
 
 
 
 
 
1716
  };
1717
 
1718
  console.log('Game event listeners set up.');
 
218
  import * as THREE from 'three';
219
  import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; // Import GLTFLoader
220
  import { HandLandmarker, FilesetResolver } from 'https://esm.sh/@mediapipe/tasks-vision@0.10.14';
221
+ import { MusicManager } from './MusicManager.js'; // Lyria-based
222
+ let _Player2Synth = null; // Lazy-loaded when multi mode is first enabled
223
  // Tone.js shim — Lyria version doesn't use Tone directly
224
  const Tone = {
225
  now: () => 0,
 
261
  this.gameState = 'loading'; // loading, ready, tracking, error
262
  this.gameOverText = null; // Will be repurposed or simplified
263
  this.clock = new THREE.Clock();
264
+ this.musicManager = new MusicManager();
265
  this.waveformVisualizer = null; // To be initialized
266
  // this.drumManager = new DrumManager(); // DrumManager is now a static module, no instance needed
267
  this.lastLandmarkPositions = [
 
791
  var handX = (1 - normX_visible) * canvasWidth - canvasWidth / 2;
792
  var handY = (1 - normY_visible) * canvasHeight - canvasHeight / 2;
793
  hand.anchorPos.set(handX, handY, 1);
794
+ // Multi-player routing: hands 0,1 = player 0 (Lyria); hands 2,3 = player 1 (Tone.js)
795
  var maxHandIdx = _this1._multiplayerEnabled ? 4 : 2;
796
  var playerIndex = Math.floor(i / 2);
797
  var isSynthHand = (i % 2 === 0);
798
  var isDrumHand = (i % 2 === 1);
799
+ var mgr = (playerIndex === 1 && _this1._multiplayerEnabled && _this1._player2Synth) ? _this1._player2Synth : _this1.musicManager;
800
  if (i >= maxHandIdx) {
801
  // Hand not active in current mode
802
  } else if (isSynthHand) {
 
804
  var isFistNow = _this1._isFist(smoothedLandmarks);
805
  if (isFistNow && !hand.isFist) {
806
  // Fist gesture was just made
807
+ mgr.cycleSynth();
808
+ mgr.stopArpeggio(i);
809
+ } else if (!isFistNow && hand.isFist) {
810
+ // Fist just released
811
+ if (mgr.setSynthHandOpen) {
812
+ mgr.setSynthHandOpen();
813
+ }
814
  }
815
  hand.isFist = isFistNow;
816
  var noteIndex = Math.floor((1 - normY_visible) * scale.length);
 
837
  // Use apparent palm size as proxy (bigger = closer)
838
  // palmSize is in normalized coords (0-1), typical range 0.03 (far) to 0.2 (close)
839
  var proximity = Math.max(0, Math.min(1, (palmSize - 0.03) / 0.12));
840
+ if (mgr.setProximityFilter) {
841
+ mgr.setProximityFilter(proximity);
842
  }
843
  _this1._updateHandLines(i, smoothedLandmarks, videoParams, canvasWidth, canvasHeight, {
844
  note: note,
 
847
  });
848
  if (!isFistNow) {
849
  // Start/Restart arpeggio if the hand just appeared OR if it just opened from a fist.
850
+ var arpeggioIsActive = mgr.activePatterns.has(i);
851
  if (!wasVisible || !arpeggioIsActive) {
852
+ mgr.startArpeggio(i, note, playerIndex);
853
  } else {
854
+ mgr.updateArpeggio(i, note);
855
  }
856
+ mgr.updateArpeggioVolume(i, velocity);
857
  // --- Finger Distance-from-Palm Controls ---
858
  // Each finger's Euclidean distance from palm center, normalized by palm size
859
  var wrist = smoothedLandmarks[0];
 
892
  var isTouching = tdist < touchThreshold;
893
  if (isTouching && !wasTouching) {
894
  // Fingers just came together — trigger touch sound
895
+ if (mgr.triggerFingerTouch) {
896
+ mgr.triggerFingerTouch(fNames[fi], fNames[fj]);
897
  }
898
  }
899
  _this1._fingerTouchState[pairKey] = isTouching;
 
920
  spreadSum += Math.sqrt(sdx*sdx + sdy*sdy);
921
  }
922
  var handSpread = Math.max(0, Math.min(1, (spreadSum / 4) / (palmSize * 2)));
923
+ mgr.updateFingerExpression({
924
  fingerDistances: fingerDistances,
925
  middleFinger: middleExt,
926
  ringFinger: ringExt,
 
950
  var wristToMcp_dy = palmCenter.y - wrist.y;
951
  var wristAngleRad = Math.atan2(wristToMcp_dx, -wristToMcp_dy); // 0=up, +π/2=right
952
  var wristAngle = Math.max(-1, Math.min(1, wristAngleRad / (Math.PI / 2))); // normalize to -1..1
953
+ mgr.updateGesture(i, {
954
  fingerStates: fingerStates,
955
  prevFingerStates: prevFS,
956
  fingerDistances: fingerDistances,
 
973
  _this1._prevFingerDistances[i] = Object.assign({}, fingerDistances);
974
  } else {
975
  // If it is a fist, make sure the arpeggio is stopped
976
+ mgr.stopArpeggio(i);
977
  }
978
  } else if (isDrumHand) {
979
  var fingerStates = _this1._getFingerStates(smoothedLandmarks);
980
  if (playerIndex === 0) drumManager.updateActiveDrums(fingerStates);
981
+ // Detect fist on drum hand for double-fist bass drop (Player 1 only)
982
  var drumIsFist = _this1._isFist(smoothedLandmarks);
983
+ if (mgr.setDrumHandFist) {
984
+ mgr.setDrumHandFist(drumIsFist);
985
  }
986
  _this1._updateHandLines(i, smoothedLandmarks, videoParams, canvasWidth, canvasHeight, {
987
  fingerStates: fingerStates
 
1020
  var dwasTouching = _this1._drumFingerTouchState[dpairKey] || false;
1021
  var disTouching = dtdist < drumTouchThreshold;
1022
  if (disTouching && !dwasTouching) {
1023
+ if (mgr.triggerFingerTouch) {
1024
+ mgr.triggerFingerTouch(dFNames[dfi], dFNames[dfj]);
1025
  }
1026
  }
1027
  _this1._drumFingerTouchState[dpairKey] = disTouching;
 
1032
  var drumWristToMcp_dy = drumPalmCenter.y - drumWrist.y;
1033
  var drumWristAngleRad = Math.atan2(drumWristToMcp_dx, -drumWristToMcp_dy);
1034
  var drumWristAngle = Math.max(-1, Math.min(1, drumWristAngleRad / (Math.PI / 2)));
1035
+ if (mgr.updateDrumGesture) {
1036
+ mgr.updateDrumGesture({
1037
  fingerStates: fingerStates,
1038
  fingerDistances: drumFingerDistances,
1039
  fingerExtensions: {
 
1050
  hand.lineGroup.visible = true;
1051
  } else {
1052
  if (wasVisible) {
1053
+ var leaveMgr = (Math.floor(i / 2) === 1 && _this1._multiplayerEnabled && _this1._player2Synth) ? _this1._player2Synth : _this1.musicManager;
1054
+ if (i % 2 === 0) {
1055
+ leaveMgr.stopArpeggio(i);
1056
+ if (leaveMgr.subBass) {
1057
+ try { leaveMgr.subBass.triggerRelease(Tone.now()); } catch(e) {}
1058
  }
1059
+ if (leaveMgr.pluckSynth) {
1060
+ try { leaveMgr.pluckSynth.releaseAll(Tone.now()); } catch(e) {}
1061
  }
1062
  } else if (i % 2 === 1) {
1063
  if (Math.floor(i / 2) === 0) drumManager.updateActiveDrums({});
 
1719
  if (_this.handLandmarker && _this.handLandmarker.setOptions) {
1720
  _this.handLandmarker.setOptions({ numHands: newNumHands });
1721
  }
1722
+ // Lazy-load Player 2 beatpad on first multi enable
1723
+ if (_this._multiplayerEnabled && !_this._player2Synth) {
1724
+ import('./Player2Synth.js').then(function(mod) {
1725
+ _this._player2Synth = new mod.Player2Synth();
1726
+ _this._player2Synth.start();
1727
+ console.log('[Multi] Player 2 beatpad loaded');
1728
+ }).catch(function(e) {
1729
+ console.error('[Multi] Failed to load Player 2 synth:', e);
1730
+ });
1731
+ }
1732
+ console.log('Multiplayer: ' + (_this._multiplayerEnabled ? 'ON (4 hands — P2: beatpad)' : 'OFF (2 hands)'));
1733
  };
1734
 
1735
  console.log('Game event listeners set up.');
index.html CHANGED
@@ -46,18 +46,18 @@
46
  <div id="controls-hint" class="hidden">
47
  <div class="hint-title">HYPERSPACE JAM — LYRIA AI</div>
48
  <div class="hint-grid">
49
- <span class="hint-icon">↕️</span><span class="hint-desc">Hand HIGH = ambient/shoegaze · LOW = DnB/dubstep</span>
50
- <span class="hint-icon">🖐️</span><span class="hint-desc">Spread wide = dense layers · Closed = minimal</span>
51
- <span class="hint-icon">👌</span><span class="hint-desc">Pinch thumb+index = intensity</span>
52
- <span class="hint-icon">👍</span><span class="hint-desc">Thumb = melody · Index = arp · Middle = bass</span>
53
- <span class="hint-icon">🤟</span><span class="hint-desc">Ring = percussion · Pinky = texture/atmosphere</span>
54
- <span class="hint-icon">🤲</span><span class="hint-desc">Tilt wrist = filter sweep + dissonance</span>
55
- <span class="hint-icon">🤚</span><span class="hint-desc">2nd hand = drums + BPM control</span>
56
- <span class="hint-icon">⬜</span><span class="hint-desc">Both hands shape = sub-bass drone</span>
57
- <span class="hint-icon">✊✊</span><span class="hint-desc">Both fists = EPIC BASS DROP</span>
58
  <span class="hint-icon">🧘</span><span class="hint-desc">Hold still = lock the groove</span>
59
  </div>
60
- <div class="hint-fade">SPACE = pause/resume · D = displacement · ? = this menu</div>
61
  </div>
62
 
63
  </div>
 
46
  <div id="controls-hint" class="hidden">
47
  <div class="hint-title">HYPERSPACE JAM — LYRIA AI</div>
48
  <div class="hint-grid">
49
+ <span class="hint-icon">↕️</span><span class="hint-desc">TOP = ambient psybient · MID = glitch-hop neurohop · LOW = filthy DnB</span>
50
+ <span class="hint-icon">🖐️</span><span class="hint-desc">Spread = psychedelic layers + delay · Closed = stripped raw</span>
51
+ <span class="hint-icon">👌</span><span class="hint-desc">Pinch = intensity · Finger distance = smooth fade per layer</span>
52
+ <span class="hint-icon">👍</span><span class="hint-desc">Thumb = catchy earworm hook · Index = glitch stutter/tape stop</span>
53
+ <span class="hint-icon">🤟</span><span class="hint-desc">Middle = squishy neuro bass · Ring = halftime groove · Pinky = cosmic delay</span>
54
+ <span class="hint-icon">🤲</span><span class="hint-desc">Tilt wrist = warped LFO modulation</span>
55
+ <span class="hint-icon">🤚</span><span class="hint-desc">2nd hand = rhythm + BPM override</span>
56
+ <span class="hint-icon">⬜</span><span class="hint-desc">Shape = sub-bass foundation (clean high / distorted low)</span>
57
+ <span class="hint-icon">✊✊</span><span class="hint-desc">Both fists = DUBSTEP GLITCH-HOP BASS DROP</span>
58
  <span class="hint-icon">🧘</span><span class="hint-desc">Hold still = lock the groove</span>
59
  </div>
60
+ <div class="hint-fade">SPACE = pause/resume · MULTI = 4-hand (P2 = beatpad + flute) · ? = this menu</div>
61
  </div>
62
 
63
  </div>