Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
3013 lines (2551 loc) · 112 KB
/
Copy pathscript.js
File metadata and controls
3013 lines (2551 loc) · 112 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Web Audio Waveform Generator
* Advanced waveform synthesis with harmonic generation and real-time visualization
*/
import HandGestures from "./handGestures.js";
class WaveformGenerator {
constructor() {
// Audio context and nodes
this.audioContext = null;
this.mainOscillator = null;
this.harmonicOscillators = [];
this.amOscillator = null;
this.fmOscillator = null;
this.gainNode = null;
this.amGainNode = null;
this.masterGainNode = null;
this.analyser = null;
this.isPlaying = false;
// Waveform parameters
this.frequency = 440;
this.amplitude = 0.5;
this.waveType = 'sine';
this.phase = 0;
this.volume = 0.5;
this.smoothing = 0.1; // Square wave smoothing factor
this.dutyCycle = 50; // Square wave duty cycle percentage
// Harmonics array - each harmonic has frequency multiplier and amplitude
this.harmonics = [];
// Modulation parameters
this.amEnabled = false;
this.amFreq = 5;
this.amDepth = 0.5;
this.fmEnabled = false;
this.fmFreq = 5;
this.fmDepth = 50;
// Display parameters - default to show 2 full cycles
this.timeScale = this.calculateTimeScaleForCycles(2); // ms per division for 2 cycles
this.ampScale = 1.0; // volts per division
// Canvas and visualization
this.canvas = document.getElementById('waveformCanvas');
this.ctx = this.canvas.getContext('2d');
this.animationId = null;
// Sample rate and buffer for waveform calculation
this.sampleRate = 44100;
this.bufferSize = 2048;
this.waveformData = new Float32Array(this.bufferSize);
this.init();
// Set initial time scale in UI after initialization
setTimeout(() => {
document.getElementById('timeScale').value = this.timeScale;
document.getElementById('timeScaleValue').textContent = this.timeScale.toFixed(2);
}, 0);
// Initialize hand gestures system with video overlay control
this.initializeVideoGestures();
// Initialize melody controls with copy/paste functionality
this.initializeMelodyInput();
// Update melody name display after initialization
setTimeout(() => {
this.updateMelodyNameDisplay();
}, 100);
}
/**
* Calculate time scale to display specified number of cycles
*/
calculateTimeScaleForCycles(cycles) {
// Assuming canvas shows 10 divisions horizontally
const divisions = 10;
const period = 1000 / this.frequency; // period in ms
return (cycles * period) / divisions;
}
/**
* Initialize melody controls with copy/paste functionality
*/
initializeMelodyInput() {
const copyMelodyBtn = document.getElementById('copyMelody');
const pasteMelodyBtn = document.getElementById('pasteMelody');
if (!copyMelodyBtn || !pasteMelodyBtn) {
console.warn('Melody control elements not found');
return;
}
// Add event listeners
copyMelodyBtn.addEventListener('click', () => {
this.copyMelodyToClipboard();
});
pasteMelodyBtn.addEventListener('click', () => {
this.pasteMelodyFromClipboard();
});
}
/**
* Copy current melody to clipboard as JSON
*/
copyMelodyToClipboard() {
try {
const melodyJSON = JSON.stringify(this.melodyGuide, null, 2);
navigator.clipboard.writeText(melodyJSON).then(() => {
this.showToast('Melody copied to clipboard!', 'success');
}).catch(() => {
// Fallback for older browsers
this.fallbackCopyToClipboard(melodyJSON);
});
} catch (error) {
this.showToast('Error copying melody: ' + error.message, 'error');
console.error('Melody copy error:', error);
}
}
/**
* Paste melody from clipboard and load it
*/
async pasteMelodyFromClipboard() {
try {
const clipboardText = await navigator.clipboard.readText();
this.loadMelodyFromJSON(clipboardText);
} catch (error) {
// If clipboard API fails, show a prompt for manual paste
const pastedText = prompt('Paste melody JSON here:');
if (pastedText) {
this.loadMelodyFromJSON(pastedText);
}
}
}
/**
* Load melody from JSON string
*/
loadMelodyFromJSON(jsonString) {
try {
const melodyData = JSON.parse(jsonString);
// Validate melody structure
if (!melodyData.tempo || !Array.isArray(melodyData.notes)) {
throw new Error('Invalid melody format. Must have "tempo" and "notes" array.');
}
// Extract unique note names from melody (excluding rests)
const melodyNoteNames = new Set();
for (let i = 0; i < melodyData.notes.length; i++) {
const note = melodyData.notes[i];
if (!Array.isArray(note) || note.length !== 2) {
throw new Error(`Invalid note at index ${i}. Each note must be [noteName, duration].`);
}
const [noteName, duration] = note;
if (typeof noteName !== 'string' || typeof duration !== 'number') {
throw new Error(`Invalid note at index ${i}. Format: ["NoteName", durationNumber].`);
}
// Add non-rest notes to the set for frequency calculation
if (noteName.trim() !== '' && noteName !== ' ') {
melodyNoteNames.add(noteName);
}
}
// Calculate frequencies for all notes in the melody
const calculatedNotes = this.calculateNotesAndFrequencies(Array.from(melodyNoteNames));
// Validate that all notes could be calculated
for (const noteName of melodyNoteNames) {
if (!calculatedNotes.noteNames.includes(noteName)) {
throw new Error(`Unable to calculate frequency for note "${noteName}". Please use standard notation (e.g., C4, F#5, Bb3).`);
}
}
// Update the notes and frequencies arrays
this.notes = calculatedNotes.frequencies;
this.noteNames = calculatedNotes.noteNames;
// Apply the new melody
this.melodyGuide = melodyData;
// If the loaded melody doesn't have a name, provide a default
if (!this.melodyGuide.name || this.melodyGuide.name.trim() === '') {
this.melodyGuide.name = 'Custom Melody';
}
// Update melody name display
this.updateMelodyNameDisplay();
// Handle keyboard overlay updates (both oscilloscope and video modes)
this.updateKeyboardAfterMelodyLoad();
// Reset song guide if active
if (this.songGuideActive) {
this.currentSongNoteIndex = 0;
this.clearNoteTimer();
this.updateSongGuideDisplay();
}
// Calculate how many original notes vs padding notes
const originalNotesCount = Array.from(melodyNoteNames).length;
const paddingNotesCount = calculatedNotes.noteNames.length - originalNotesCount;
this.showToast(`Melody loaded successfully! ${calculatedNotes.noteNames.length} notes available (${originalNotesCount} melody + ${paddingNotesCount} padding).`, 'success');
} catch (error) {
this.showToast('Error loading melody: ' + error.message, 'error');
console.error('Melody load error:', error);
}
}
/**
* Fallback copy method for older browsers
*/
fallbackCopyToClipboard(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed';
textArea.style.opacity = '0';
document.body.appendChild(textArea);
textArea.select();
try {
document.execCommand('copy');
this.showToast('Melody copied to clipboard!', 'success');
} catch (err) {
this.showToast('Failed to copy melody. Please copy manually.', 'error');
console.error('Fallback copy failed:', err);
}
document.body.removeChild(textArea);
}
/**
* Update the melody name display in the UI
*/
updateMelodyNameDisplay() {
const melodyNameElement = document.getElementById('currentMelodyName');
if (!melodyNameElement) {
console.warn('Melody name display element not found');
return;
}
// Get melody name from current melody guide
const melodyName = this.melodyGuide?.name || 'Untitled Melody';
melodyNameElement.textContent = melodyName;
console.log(`Updated melody name display: "${melodyName}"`);
}
/**
* Setup hand gesture event handlers (extracted for reuse when recreating instances)
*/
setupHandGestureEventHandlers() {
if (!this.handGestures) {
console.warn('Cannot setup event handlers: handGestures instance not available');
return;
}
// Set up hand gesture event handlers
this.handGestures.events.on('move', (x, y, data) => {
// Don't process musical input if hovering over UI elements
if (data && data.hoveredElement) {
return;
}
// x coordinate is already properly adjusted by MediaPipe based on flip state
// x is 0 to 100, map to frequency notes
let frequency = 2000 - (x * 15);
// Calculate note index based on hand position
const noteIndex = Math.floor(x / (100 / this.notes.length));
frequency = this.notes[noteIndex];
if (!frequency) { return; }
this.frequency = frequency;
this.updateAudioFrequency();
this.updateWaveform();
// Update keyboard highlighting based on pinch state
const isPinching = this.handGestures.isPinchActive();
this.updateKeyboardHighlight(noteIndex, isPinching);
});
this.handGestures.events.on('pinch', (pinch) => {
// Don't toggle playback if hovering over UI elements
if (this.handGestures.hoveredElement) {
return;
}
this.togglePlayback(pinch ? 'on' : 'off');
});
}
/**
* Calculate frequencies for notes and return sorted arrays with padding
*/
calculateNotesAndFrequencies(noteNames) {
const noteFrequencyPairs = [];
const midiNumbers = [];
// Calculate frequency and MIDI number for each valid note
for (const noteName of noteNames) {
const frequency = this.noteNameToFrequency(noteName);
const midiNumber = this.noteNameToMIDI(noteName);
if (frequency !== null && midiNumber !== null) {
noteFrequencyPairs.push({ name: noteName, frequency: frequency, midi: midiNumber });
midiNumbers.push(midiNumber);
}
}
// Add padding notes (one semitone below lowest and one semitone above highest)
if (midiNumbers.length > 0) {
const lowestMidi = Math.min(...midiNumbers);
const highestMidi = Math.max(...midiNumbers);
// Add lower padding note (one semitone below)
const lowerPaddingMidi = lowestMidi - 1;
if (lowerPaddingMidi >= 0) {
const lowerPaddingNote = this.midiToNoteName(lowerPaddingMidi);
const lowerPaddingFreq = this.noteNameToFrequency(lowerPaddingNote);
if (lowerPaddingNote && lowerPaddingFreq !== null) {
noteFrequencyPairs.push({
name: lowerPaddingNote,
frequency: lowerPaddingFreq,
midi: lowerPaddingMidi,
isPadding: true
});
}
}
// Add higher padding note (one semitone above)
const higherPaddingMidi = highestMidi + 1;
if (higherPaddingMidi <= 127) {
const higherPaddingNote = this.midiToNoteName(higherPaddingMidi);
const higherPaddingFreq = this.noteNameToFrequency(higherPaddingNote);
if (higherPaddingNote && higherPaddingFreq !== null) {
noteFrequencyPairs.push({
name: higherPaddingNote,
frequency: higherPaddingFreq,
midi: higherPaddingMidi,
isPadding: true
});
}
}
}
// Sort by frequency (ascending)
noteFrequencyPairs.sort((a, b) => a.frequency - b.frequency);
// Extract sorted arrays
const sortedNoteNames = noteFrequencyPairs.map(pair => pair.name);
const sortedFrequencies = noteFrequencyPairs.map(pair => pair.frequency);
return {
noteNames: sortedNoteNames,
frequencies: sortedFrequencies
};
}
/**
* Convert note name to frequency using equal temperament tuning
* @param {string} noteName - Note name in format like "A4", "C#5", "Bb3"
* @returns {number|null} - Frequency in Hz, or null if invalid note name
*/
noteNameToFrequency(noteName) {
try {
const midiNumber = this.noteNameToMIDI(noteName);
if (midiNumber === null) return null;
// Calculate frequency using equal temperament: f = 440 * 2^((n-69)/12)
// Where 69 is the MIDI number for A4 (440 Hz)
const frequency = 440 * Math.pow(2, (midiNumber - 69) / 12);
return Math.round(frequency * 100) / 100; // Round to 2 decimal places
} catch (error) {
console.warn(`Invalid note name: ${noteName}`);
return null;
}
}
/**
* Convert note name to MIDI number
* @param {string} noteName - Note name in format like "A4", "C#5", "Bb3"
* @returns {number|null} - MIDI number (0-127), or null if invalid
*/
noteNameToMIDI(noteName) {
const notePattern = /^([A-G])([#b]?)(\d+)$/;
const match = noteName.match(notePattern);
if (!match) return null;
const [, noteLetter, accidental, octaveStr] = match;
const octave = parseInt(octaveStr);
// Validate octave range (MIDI supports 0-10, but we'll be more restrictive)
if (octave < 0 || octave > 10) return null;
// Base MIDI numbers for each note in octave 0
const baseNotes = {
'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11
};
let midiNumber = baseNotes[noteLetter] + (octave + 1) * 12;
// Apply accidentals
if (accidental === '#') {
midiNumber += 1;
} else if (accidental === 'b') {
midiNumber -= 1;
}
// Validate MIDI range
if (midiNumber < 0 || midiNumber > 127) return null;
return midiNumber;
}
/**
* Convert MIDI number to note name (using sharps for black keys)
* @param {number} midiNumber - MIDI number (0-127)
* @returns {string|null} - Note name in format like "A4", "C#5", or null if invalid
*/
midiToNoteName(midiNumber) {
if (midiNumber < 0 || midiNumber > 127) return null;
const octave = Math.floor(midiNumber / 12) - 1;
const noteInOctave = midiNumber % 12;
// Note names using sharps for black keys
const noteNames = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
return `${noteNames[noteInOctave]}${octave}`;
}
/**
* Update keyboard overlay after melody load, handling both modes properly
*/
updateKeyboardAfterMelodyLoad() {
const wasVisible = this.keyboardOverlay && this.keyboardOverlay.classList.contains('visible');
// Recreate keyboard overlay with new notes
this.createKeyboardOverlay();
// If we're in video mode (gestures running), handle special updates
if (this.gesturesRunning) {
// Show keyboard overlay if it was visible before
if (wasVisible) {
this.showKeyboardOverlay();
}
// Update overlay coverage to ensure proper positioning
setTimeout(() => {
this.updateOverlayCoverage();
}, 50);
// Re-register clickable elements with the hand gestures system
// This ensures the gesture interaction system knows about the updated keyboard
this.registerClickableElements();
// Update hand gestures system with new note mapping
// The move event handler will use the updated this.notes and this.noteNames arrays
console.log(`Updated gesture keyboard: ${this.noteNames.length} notes ranging from ${this.noteNames[0]} to ${this.noteNames[this.noteNames.length - 1]}`);
}
}
/**
* Initialize video gestures system with overlay controls
*/
initializeVideoGestures() {
// Get video section and overlay elements (now in oscilloscope overlay)
const videoSection = document.getElementById('video-section');
const videoOverlay = document.getElementById('video-overlay');
const gesturePlayBtn = document.getElementById('gesturePlayBtn');
// Track gesture system state
this.gesturesInitialized = false;
this.gesturesRunning = false;
this.hasEverUsedVideoMode = false; // Track if user has ever entered video mode
this.handGestures = null; // Will be created when needed
// Melody guide for GTA San Andreas theme
// 1/4 = quarter note, 1/2 = half note, 1 = whole note
// tempo 60 bpm means 1 second per quarter note
// empty string or ' ' = rest
this.melodyGuide = {
name: 'GTA San Andreas Theme',
tempo: 60,
notes: [
['D5', 1/8],
['D6', 1/8],
['Bb5', 1/8],
['A5', 1/16],
['Bb5', 1/16],
['A5', 1/16],
['G5', 1/16],
['A5', 1/16],
['G5', 1/16],
['A5', 1/8],
[' ', 1/8],
['F5', 1/8],
['G5', 1/16],
['F5', 1/16],
['G5', 1/8],
['A5', 1/8],
['D5', 1/8],
['G5', 1/8],
['F5', 1/8],
[' ', 1/8],
]
};
// Calculate frequencies for notes in default melody with padding
const defaultMelodyNotes = new Set();
this.melodyGuide.notes.forEach(([noteName]) => {
if (noteName.trim() !== '' && noteName !== ' ') {
defaultMelodyNotes.add(noteName);
}
});
// Calculate and set notes/frequencies from default melody (includes padding)
const calculatedNotes = this.calculateNotesAndFrequencies(Array.from(defaultMelodyNotes));
this.notes = calculatedNotes.frequencies;
this.noteNames = calculatedNotes.noteNames;
console.log(`Default melody loaded: ${calculatedNotes.noteNames.length} total notes (${defaultMelodyNotes.size} melody + ${calculatedNotes.noteNames.length - defaultMelodyNotes.size} padding)`);
// Current active note index for keyboard highlighting
this.currentNoteIndex = -1;
// Song guide state
this.songGuideActive = false;
this.currentSongNoteIndex = 0;
this.noteHoldTimer = null;
this.noteHoldDuration = 0;
this.requiredHoldTime = 500; // ms to hold note (calculated per note)
this.restTimer = null; // Timer for handling rest notes
this.isMaximized = false;
// Create keyboard overlay
this.createKeyboardOverlay();
// Flip button will be created as part of video controls when gestures start
// Event handlers will be set up when HandGestures instance is created
// Set up stop overlay functionality
this.setupStopOverlay();
// Set up gesture play button
gesturePlayBtn.addEventListener('click', async () => {
// Directly start gestures instead of just showing the overlay
try {
// Show video overlay
this.showVideoOverlay();
// Show loading state
gesturePlayBtn.innerHTML = '<span style="opacity: 0.8;">📹 Starting...</span>';
// Always create a new HandGestures instance to avoid MediaPipe WebAssembly corruption
// This is necessary because MediaPipe cannot reliably be reinitialized after close()
if (!this.gesturesInitialized || !this.handGestures) {
// Small delay to ensure complete cleanup of previous instance
await new Promise(resolve => setTimeout(resolve, 200));
// Create fresh HandGestures instance
this.handGestures = new HandGestures({
width: 640, // Reduced size to help with WebGL memory
height: 480,
moveMode: 'absolute',
pinchThreshold: 30,
alwaysEmitMove: true, // Enable move events without gestures
alwaysShowDots: true, // Always show thumb/index dots
});
// Store flip state for keyboard overlay synchronization
this.isVideoFlipped = this.handGestures.settings.flipHorizontal;
// Set up hand gesture event handlers for the new instance
this.setupHandGestureEventHandlers();
// Initialize gestures system
const initSuccess = await this.handGestures.init();
if (!initSuccess) {
throw new Error('Failed to initialize hand gestures. This may be due to WebGL limitations or hardware compatibility issues. Try refreshing the page or using a different browser.');
}
this.gesturesInitialized = true;
}
// Attach to video section and start
const videoSection = document.getElementById('video-section');
this.handGestures.attachTo(videoSection);
this.handGestures.showVisualization();
const startSuccess = await this.handGestures.start();
if (!startSuccess) {
throw new Error('Failed to start hand gestures');
}
this.gesturesRunning = true;
// Mark that user has now used video mode (remove attention animation)
if (!this.hasEverUsedVideoMode) {
this.hasEverUsedVideoMode = true;
this.removeAttentionAnimation();
}
// Show stop overlay
this.showStopOverlay();
// Show keyboard overlay
this.showKeyboardOverlay();
// Apply initial video transform for proper mirroring
const video = this.handGestures.getVideoElement();
if (video) {
if (this.isVideoFlipped) {
// Flipped mode: show actual camera view (with centering)
video.style.transform = 'translate(-50%, -50%) scaleX(1)';
} else {
// Normal mode: mirror the video for natural interaction (with centering)
video.style.transform = 'translate(-50%, -50%) scaleX(-1)';
}
}
// Register clickable elements for gesture interaction
this.registerClickableElements();
// Hide play corner button and video mode corner button
this.hideCornerButtons();
this.showToast('Hover and pinch to play notes.', 'success', 7000);
// Reset button text
gesturePlayBtn.innerHTML = '📹';
} catch (error) {
console.error('Error starting hand gestures:', error);
this.showToast('Failed to start camera: ' + error.message, 'error');
// Reset button
gesturePlayBtn.innerHTML = '📹';
// Hide video overlay on error
this.hideVideoOverlay();
// Ensure clean state after error
this.gesturesInitialized = false;
this.handGestures = null;
}
});
}
/**
* Create keyboard overlay for visual note zones
*/
createKeyboardOverlay() {
const videoSection = document.getElementById('video-section');
// Remove existing keyboard overlay if it exists
const existingKeyboard = document.getElementById('keyboard-overlay');
if (existingKeyboard) {
existingKeyboard.remove();
}
// Create keyboard overlay container
const keyboardOverlay = document.createElement('div');
keyboardOverlay.id = 'keyboard-overlay';
keyboardOverlay.className = 'keyboard-overlay';
// Create keys for each note
this.noteNames.forEach((noteName, index) => {
const key = document.createElement('div');
key.className = 'keyboard-key';
key.dataset.noteIndex = index;
key.textContent = noteName;
key.title = `${noteName} (${this.notes[index].toFixed(1)} Hz)`;
keyboardOverlay.appendChild(key);
});
videoSection.appendChild(keyboardOverlay);
this.keyboardOverlay = keyboardOverlay;
// Apply horizontal flip if video is flipped
this.updateKeyboardOrientation();
}
/**
* Update keyboard orientation to sync with video flip state
*/
updateKeyboardOrientation() {
if (!this.keyboardOverlay) {
return;
}
// MediaPipe coordinates are consistent regardless of flip setting
// Keep keyboard overlay orientation consistent with coordinate system
this.keyboardOverlay.style.transform = 'scaleX(1)';
}
/**
* Update keyboard highlighting based on current note and pinch state
*/
updateKeyboardHighlight(noteIndex, isPinching = false) {
if (!this.keyboardOverlay) {
return;
}
// Remove previous highlighting from all keys
if (this.currentNoteIndex >= 0) {
const prevKey = this.keyboardOverlay.children[this.currentNoteIndex];
if (prevKey) {
prevKey.classList.remove('active', 'hover');
}
}
// Add appropriate highlighting to current note
if (noteIndex >= 0 && noteIndex < this.noteNames.length) {
const currentKey = this.keyboardOverlay.children[noteIndex];
if (currentKey) {
if (isPinching) {
// Show active state when pinching
currentKey.classList.add('active');
currentKey.classList.remove('hover');
// Handle song guide if active
this.handleSongGuideInput(noteIndex);
} else {
// Show hover state when not pinching
currentKey.classList.add('hover');
currentKey.classList.remove('active');
// Clear note timer if not pinching
this.clearNoteTimer();
}
}
}
this.currentNoteIndex = noteIndex;
}
/**
* Handle song guide input and timing
*/
handleSongGuideInput(noteIndex) {
if (!this.songGuideActive || this.currentSongNoteIndex >= this.melodyGuide.notes.length) {
return;
}
const currentSongNote = this.melodyGuide.notes[this.currentSongNoteIndex];
const targetNoteName = currentSongNote[0];
const currentNoteName = this.noteNames[noteIndex];
// Check if correct note is being pinched
if (currentNoteName === targetNoteName) {
// Start timer if not already running
if (!this.noteHoldTimer) {
this.startNoteTimer(noteIndex);
}
} else {
// Wrong note, clear timer
this.clearNoteTimer();
}
}
/**
* Start note hold timer with visual fill effect
*/
startNoteTimer(noteIndex) {
const startTime = Date.now();
this.noteHoldDuration = 0;
const updateTimer = () => {
this.noteHoldDuration = Date.now() - startTime;
const fillPercent = Math.min(100, (this.noteHoldDuration / this.requiredHoldTime) * 100);
// Update visual fill
const currentKey = this.keyboardOverlay.children[noteIndex];
if (currentKey) {
currentKey.style.setProperty('--fill-percent', `${fillPercent}%`);
currentKey.classList.add('timer-fill');
}
if (this.noteHoldDuration >= this.requiredHoldTime) {
// Note held long enough, advance to next
this.advanceToNextNote();
this.clearNoteTimer();
} else if (this.noteHoldTimer) {
// Continue timer
this.noteHoldTimer = requestAnimationFrame(updateTimer);
}
};
this.noteHoldTimer = requestAnimationFrame(updateTimer);
}
/**
* Clear note hold timer and visual effects
*/
clearNoteTimer() {
if (this.noteHoldTimer) {
cancelAnimationFrame(this.noteHoldTimer);
this.noteHoldTimer = null;
}
// Clear visual fill from all keys
Array.from(this.keyboardOverlay.children).forEach(key => {
key.classList.remove('timer-fill');
key.style.removeProperty('--fill-percent');
});
this.noteHoldDuration = 0;
}
/**
* Handle rest notes by waiting for the specified duration
*/
handleRestNote() {
// Clear any existing rest timer
if (this.restTimer) {
clearTimeout(this.restTimer);
this.restTimer = null;
}
// Wait for the required rest duration then advance
this.restTimer = setTimeout(() => {
this.restTimer = null;
this.advanceToNextNote();
}, this.requiredHoldTime);
}
/**
* Advance to next note in song guide
*/
advanceToNextNote() {
this.currentSongNoteIndex++;
if (this.currentSongNoteIndex >= this.melodyGuide.notes.length) {
// Song completed - restart from beginning
this.showToast('Song completed! Restarting... 🎉', 'success', 2000);
this.currentSongNoteIndex = 0;
this.updateSongGuideDisplay();
} else {
this.updateSongGuideDisplay();
}
}
/**
* Update song guide visual display
*/
updateSongGuideDisplay() {
if (!this.songGuideActive || !this.keyboardOverlay) {
return;
}
// Clear previous target highlighting
Array.from(this.keyboardOverlay.children).forEach(key => {
key.classList.remove('target');
});
// Highlight current target note
if (this.currentSongNoteIndex < this.melodyGuide.notes.length) {
const currentSongNote = this.melodyGuide.notes[this.currentSongNoteIndex];
const targetNoteName = currentSongNote[0];
const noteDuration = currentSongNote[1];
// Calculate required hold time based on note duration and tempo
// 60 bpm = 1000ms per quarter note
const quarterNoteTime = (60 / this.melodyGuide.tempo) * 1000;
this.requiredHoldTime = quarterNoteTime * (noteDuration / 0.25); // 0.25 = 1/4 note
// Handle rests
if (targetNoteName.trim() === '' || targetNoteName === ' ') {
this.handleRestNote();
return;
}
const targetNoteIndex = this.noteNames.indexOf(targetNoteName);
if (targetNoteIndex >= 0) {
const targetKey = this.keyboardOverlay.children[targetNoteIndex];
if (targetKey) {
targetKey.classList.add('target');
}
}
}
}
/**
* Clear song guide visual display
*/
clearSongGuideDisplay() {
if (!this.keyboardOverlay) {
return;
}
Array.from(this.keyboardOverlay.children).forEach(key => {
key.classList.remove('target', 'timer-fill');
key.style.removeProperty('--fill-percent');
});
// Clear rest timer if active
if (this.restTimer) {
clearTimeout(this.restTimer);
this.restTimer = null;
}
}
/**
* Register clickable elements for gesture interaction
*/
registerClickableElements() {
if (!this.handGestures) return;
// Clear previous registrations
this.handGestures.clearClickableElements();
// Register stop button
const stopButton = document.getElementById('stop-btn');
if (stopButton) {
this.handGestures.registerClickableElement(stopButton, () => {
this.stopVideoGestures();
});
}
// Register flip button (top left corner)
const flipBtn = document.getElementById('flip-btn');
if (flipBtn) {
this.handGestures.registerClickableElement(flipBtn, () => {
this.toggleCameraFlip();
});
}
// Maximize functionality removed
const songGuideBtn = document.getElementById('song-guide-btn');
if (songGuideBtn) {
this.handGestures.registerClickableElement(songGuideBtn, () => {
this.toggleSongGuide();
});
}
}
/**
* Show keyboard overlay
*/
showKeyboardOverlay() {
if (this.keyboardOverlay) {
this.keyboardOverlay.classList.add('visible');
// Ensure perfect coverage after showing
setTimeout(() => this.updateOverlayCoverage(), 50);
}
}
/**
* Hide keyboard overlay
*/
hideKeyboardOverlay() {
if (this.keyboardOverlay) {
this.keyboardOverlay.classList.remove('visible');
// Clear any active highlighting
this.updateKeyboardHighlight(-1, false);
// Also clear all highlighting from all keys
Array.from(this.keyboardOverlay.children).forEach(key => {
key.classList.remove('active', 'hover');
});
}
}
/**
* Show video controls when gestures are running
*/
showStopOverlay() {
const videoSection = document.getElementById('video-section');
// Create video controls if they don't exist
let videoControls = document.getElementById('video-controls');
if (!videoControls) {
videoControls = document.createElement('div');
videoControls.id = 'video-controls';
videoControls.className = 'video-controls';
// Left side controls
const leftControls = document.createElement('div');
leftControls.className = 'video-controls-left';
// Flip button
const flipBtn = document.createElement('button');
flipBtn.id = 'flip-btn';
flipBtn.className = 'video-control-btn';
flipBtn.textContent = '↔';
flipBtn.title = 'Flip Camera';