-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhitbox-controller.ts
More file actions
1810 lines (1583 loc) · 56.8 KB
/
hitbox-controller.ts
File metadata and controls
1810 lines (1583 loc) · 56.8 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
// Arcade Bongo Cat Hitbox Mapping and Visualization Tool
// Shows button presses and directional inputs on a hitbox-style controller
// Type definitions
type VirtualButton = 'vb1' | 'vb2' | 'vb3' | 'vb4' | 'vb5' | 'vb6' | 'vb7' | 'vb8';
type VirtualDirection = 'vbUp' | 'vbDown' | 'vbRight' | 'vbLeft';
type VirtualInput = VirtualButton | VirtualDirection;
interface ButtonMappings {
vb1: number | AxisMapping;
vb2: number | AxisMapping;
vb3: number | AxisMapping;
vb4: number | AxisMapping;
vb5: number | AxisMapping;
vb6: number | AxisMapping;
vb7: number | AxisMapping;
vb8: number | AxisMapping;
vbUp: number | AxisMapping;
vbDown: number | AxisMapping;
vbRight: number | AxisMapping;
vbLeft: number | AxisMapping;
}
interface CalibrationStep {
name: string;
key: keyof ButtonMappings;
description: string;
}
interface ButtonPosition {
readonly cx: number;
readonly cy: number;
}
interface AxisMapping {
readonly axis: number;
readonly direction: number;
}
// Add error handling types
interface CalibrationError {
step: number;
message: string;
timestamp: number;
}
// Add configuration types
interface AppConfig {
readonly version: string;
readonly defaultMappings: ButtonMappings;
readonly calibrationTimeout: number;
readonly autoHideDelay: number;
}
interface AppState {
isCalibrating: boolean;
currentCalibrationStep: number;
calibrationMappings: Partial<ButtonMappings>;
calibrationAnimationFrame: number | null;
lastCalibrationButtons: boolean[];
waitingForRelease: boolean;
axes: number;
stick: number;
nEjeX: number;
nEjeY: number;
invertX: number;
invertY: number;
gamepad: Gamepad | null;
x: number;
y: number;
pollInterval?: number;
lastCalibrationInput: number | AxisMapping | null;
lastCalibrationAxes: number[];
restingCalibrationAxes: number[];
lastMouseMove: number;
hideTimeout: number | null;
buttonsVisible: boolean;
rAF?: number;
lastArmIndex?: number;
armReturnTimeout?: number | null;
previousButtonStates: boolean[];
lastPressedButtonIndex?: number;
previousDirectionalStates: { left: boolean; right: boolean; up: boolean; down: boolean };
lastPressedDirectional?: string;
}
/**
* State object to hold all mutable state
* Performance improvement: Cache DOM elements to avoid repeated queries
*/
const state: AppState = {
isCalibrating: false,
currentCalibrationStep: 0,
calibrationMappings: {},
calibrationAnimationFrame: null,
lastCalibrationButtons: [],
waitingForRelease: false,
axes: 0,
stick: 0,
nEjeX: 0,
nEjeY: 1,
invertX: 1,
invertY: 1,
gamepad: null,
x: 0,
y: 0,
lastCalibrationInput: null,
lastCalibrationAxes: [],
restingCalibrationAxes: [],
lastMouseMove: Date.now(),
hideTimeout: null,
buttonsVisible: true,
lastArmIndex: -1,
armReturnTimeout: null,
previousButtonStates: [],
lastPressedButtonIndex: -1,
previousDirectionalStates: { left: false, right: false, up: false, down: false },
lastPressedDirectional: '',
};
/**
* Cache DOM elements to improve performance
*/
const domCache = {
buttons: {} as Record<string, HTMLElement | null>,
directionals: {} as Record<string, HTMLElement | null>,
arms: {} as Record<string, HTMLElement | null>,
calibrationElements: {} as Record<string, HTMLElement | null>,
// Initialize cache
init(): void {
// Cache button elements
for (let i = 1; i <= 8; i++) {
this.buttons[`button${i}`] = document.getElementById(`button${i}`);
}
// Cache directional elements
['up', 'down', 'left', 'right', 'leftup', 'left0', 'left1', 'left2', 'left3', 'rightUp'].forEach(id => {
this.directionals[id] = document.getElementById(id);
});
// Cache arm elements
for (let i = 1; i <= 8; i++) {
this.arms[`arm${i}`] = document.getElementById(`arm${i}`);
}
// Cache calibration elements
this.calibrationElements.overlay = document.getElementById('calibration-overlay');
this.calibrationElements.schematicWrapper = document.getElementById('calibration-schematic-wrapper');
this.calibrationElements.highlightGroup = document.getElementById('calibration-highlight-group');
this.calibrationElements.currentButton = document.getElementById('current-button');
this.calibrationElements.progressFill = document.getElementById('progress-fill');
this.calibrationElements.progressText = document.getElementById('progress-text');
}
};
/**
* Application configuration constants
*/
const CONFIG: AppConfig = {
version: '1.2.0',
defaultMappings: {
vb1: 1, vb2: 2, vb3: 7, vb4: 6, vb5: 0, vb6: 3, vb7: 5, vb8: 4,
vbUp: 13, vbDown: 12, vbRight: 15, vbLeft: 14
},
calibrationTimeout: 30000, // 30 seconds
autoHideDelay: 5000, // 5 seconds
} as const;
/**
* Performance and input constants
*/
const INPUT_CONSTANTS = {
AXIS_THRESHOLD: 0.5, // Threshold for axis input detection
AXIS_DEADZONE: 0.2, // Deadzone for axis calibration
MAX_ACTION_BUTTONS: 8, // Maximum number of action buttons
MIN_GAMEPAD_BUTTONS: 4, // Minimum required gamepad buttons
MIN_GAMEPAD_AXES: 2, // Minimum required gamepad axes
MAX_FRAME_TIME: 16.67, // Target frame time (60fps)
PERF_MONITOR_INTERVAL: 1000, // Performance monitoring interval in ms
} as const;
/**
* Animation state constants for better performance
*/
const ANIMATION_CONSTANTS = {
ARM_COUNT: 8,
DIRECTIONAL_COUNT: 4,
NEUTRAL_ARM_INDEX: -1,
NEUTRAL_LEFT_STATE: 0,
LEFT_UP_STATE: 4,
} as const;
/**
* Error handling and validation constants
*/
const VALIDATION_CONSTANTS = {
MAX_RETRY_ATTEMPTS: 3,
DEBOUNCE_DELAY: 1, // Minimum delay between input processing (1ms to allow 60fps)
STATE_RESET_DELAY: 100, // Delay before resetting stale state
} as const;
/**
* Logging utility with different levels
*/
const logger = {
debug: (message: string, ...args: any[]) => {
// Only log debug in development (when not minified)
if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
console.debug(`[BongoCat Debug] ${message}`, ...args);
}
},
info: (message: string, ...args: any[]) => {
console.info(`[BongoCat] ${message}`, ...args);
},
warn: (message: string, ...args: any[]) => {
console.warn(`[BongoCat Warning] ${message}`, ...args);
},
error: (message: string, error?: Error, ...args: any[]) => {
console.error(`[BongoCat Error] ${message}`, error, ...args);
}
};
/**
* Sleep utility function
*/
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Utility: Get gamepad safely with better error handling
*/
function getGamepad(): Gamepad | null {
const result = safeSync(() => {
const gamepads = navigator.getGamepads ? navigator.getGamepads() : [];
// Find the first connected gamepad
for (let i = 0; i < gamepads.length; i++) {
const gamepad = gamepads[i];
if (gamepad && gamepad.connected) {
return gamepad;
}
}
return null;
}, 'Failed to get gamepad', null);
return result ?? null;
}
/**
* Enhanced gamepad connection detection
*/
function detectGamepadSupport(): boolean {
return !!(navigator.getGamepads || (navigator as any).webkitGetGamepads);
}
/**
* Check if gamepad has minimum required inputs
*/
function validateGamepad(gamepad: Gamepad): boolean {
return gamepad.buttons.length >= 4 && gamepad.axes.length >= 2;
}
/**
* Handle mouse movement to reset auto-hide timer
*/
function handleMouseMove(): void {
state.lastMouseMove = Date.now();
// Clear existing timeout
if (state.hideTimeout !== null) {
clearTimeout(state.hideTimeout);
}
// Show config buttons if they were hidden
if (!state.buttonsVisible) {
showConfigButtons();
}
// Set new timeout to hide after 5 seconds
state.hideTimeout = window.setTimeout(() => {
hideConfigButtons();
}, 5000);
}
/**
* Show config buttons
*/
function showConfigButtons(): void {
state.buttonsVisible = true;
const resetButton = document.getElementById('reset-button') as HTMLElement;
const downloadConfig = document.getElementById('download-config') as HTMLElement;
const uploadConfig = document.querySelector('label[for="upload-config"]') as HTMLElement;
const colorPickerBtn = document.getElementById('color-picker-btn') as HTMLElement;
if (resetButton) resetButton.style.opacity = '1';
if (downloadConfig) downloadConfig.style.opacity = '1';
if (uploadConfig) uploadConfig.style.opacity = '1';
if (colorPickerBtn) colorPickerBtn.style.opacity = '1';
}
/**
* Hide config buttons
*/
function hideConfigButtons(): void {
state.buttonsVisible = false;
const resetButton = document.getElementById('reset-button') as HTMLElement;
const downloadConfig = document.getElementById('download-config') as HTMLElement;
const uploadConfig = document.querySelector('label[for="upload-config"]') as HTMLElement;
const colorPickerBtn = document.getElementById('color-picker-btn') as HTMLElement;
if (resetButton) resetButton.style.opacity = '0';
if (downloadConfig) downloadConfig.style.opacity = '0';
if (uploadConfig) uploadConfig.style.opacity = '0';
if (colorPickerBtn) colorPickerBtn.style.opacity = '0';
}
/**
* Utility: Check if a button is pressed
*/
function buttonPressed(b: GamepadButton | number): boolean {
if (typeof b === "object") return b.pressed;
return b === 1.0;
}
/**
* Utility: Check if a directional is pressed (button or axis)
*/
function directionalPressed(gp: Gamepad, mappingKey: keyof ButtonMappings, axisIndex: number, axisValue: number): boolean {
const mapping = buttonMapping[mappingKey];
// Button-based
if (typeof mapping === 'number' && buttonPressed(gp.buttons[mapping])) return true;
// Axis-based
if (typeof axisIndex === 'number' && typeof axisValue === 'number') {
if (Math.round(gp.axes[axisIndex]) === axisValue) return true;
}
return false;
}
/**
* Save calibration to localStorage with error handling
*/
function saveCalibration(): void {
safeSync(() => {
localStorage.setItem(STORAGE_KEYS.CALIBRATION, JSON.stringify(state.calibrationMappings));
logger.info('Calibration saved successfully');
}, 'Failed to save calibration');
}
/**
* Load calibration from localStorage with error handling
*/
function loadCalibration(): boolean {
return safeSync(() => {
const saved = localStorage.getItem(STORAGE_KEYS.CALIBRATION);
if (saved) {
const mappings = JSON.parse(saved) as Partial<ButtonMappings>;
Object.keys(mappings).forEach(key => {
const typedKey = key as keyof ButtonMappings;
buttonMapping[typedKey] = mappings[typedKey]!;
});
logger.info('Calibration loaded successfully');
logger.debug('Loaded button mappings:', buttonMapping);
return true;
}
return false;
}, 'Failed to load calibration', false) ?? false;
}
/**
* Update website background color and save to localStorage
*/
function updateBackgroundColor(color: string): void {
safeSync(() => {
// Get or create our dynamic style element
let styleEl = document.getElementById('dynamic-background-style') as HTMLStyleElement;
if (!styleEl) {
styleEl = document.createElement('style');
styleEl.id = 'dynamic-background-style';
document.head.appendChild(styleEl);
}
// Update the style rule to override the CSS file
styleEl.textContent = `html { background-color: ${color} !important; }`;
localStorage.setItem(STORAGE_KEYS.BACKGROUND_COLOR, color);
logger.debug('Background color updated to:', color);
}, 'Failed to update background color');
}
// Add this to the initialization code to restore saved color
function restoreBackgroundColor(): void {
const savedColor = localStorage.getItem(STORAGE_KEYS.BACKGROUND_COLOR) || '#00ff00';
updateBackgroundColor(savedColor);
logger.debug('Background color restored:', savedColor);
}
/**
* Color conversion utilities
*/
function hsvToRgb(h: number, s: number, v: number): [number, number, number] {
h = ((h % 360) + 360) % 360;
s = Math.max(0, Math.min(100, s)) / 100;
v = Math.max(0, Math.min(100, v)) / 100;
const hi = Math.floor(h / 60) % 6;
const f = h / 60 - Math.floor(h / 60);
const p = v * (1 - s);
const q = v * (1 - f * s);
const t = v * (1 - (1 - f) * s);
let r = 0, g = 0, b = 0;
switch (hi) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
function rgbToHsv(r: number, g: number, b: number): [number, number, number] {
r = r / 255;
g = g / 255;
b = b / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const d = max - min;
let h = 0;
const s = (max === 0 ? 0 : d / max);
const v = max;
if (max !== min) {
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [Math.round(h * 360), Math.round(s * 100), Math.round(v * 100)];
}
function rgbToHex(r: number, g: number, b: number): string {
return '#' + [r, g, b].map(x => {
const hex = Math.max(0, Math.min(255, x)).toString(16);
return hex.length === 1 ? '0' + hex : hex;
}).join('');
}
function hexToRgb(hex: string): [number, number, number] {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
if (!result) return [0, 0, 0];
return [
parseInt(result[1], 16),
parseInt(result[2], 16),
parseInt(result[3], 16)
];
}
/**
* Initialize color picker functionality
*/
function initializeColorPicker(): void {
const colorPickerBtn = document.getElementById('color-picker-btn');
const colorPickerPopup = document.getElementById('color-picker-popup');
const closeBtn = document.getElementById('close-color-picker');
const colorSpectrum = document.getElementById('color-spectrum');
const hueSlider = document.getElementById('hue-slider');
const previewColor = document.getElementById('preview-color');
const hexInput = document.getElementById('hex-input') as HTMLInputElement;
const rgbInputs = {
r: document.getElementById('rgb-r') as HTMLInputElement,
g: document.getElementById('rgb-g') as HTMLInputElement,
b: document.getElementById('rgb-b') as HTMLInputElement
};
const hsvInputs = {
h: document.getElementById('hsv-h') as HTMLInputElement,
s: document.getElementById('hsv-s') as HTMLInputElement,
v: document.getElementById('hsv-v') as HTMLInputElement
};
const cursor = document.getElementById('color-picker-cursor');
const hueCursor = document.getElementById('hue-cursor');
const resetBtn = document.getElementById('reset-color');
const applyBtn = document.getElementById('apply-color');
let currentHue = 0;
let currentSaturation = 100;
let currentValue = 100;
let isDragging = false;
let isHueDragging = false;
// Load saved color
const savedColor = localStorage.getItem('bongo-cat-bg-color') || '#00ff00';
const rgb = hexToRgb(savedColor);
const hsv = rgbToHsv(...rgb);
currentHue = hsv[0];
currentSaturation = hsv[1];
currentValue = hsv[2];
updateColorDisplay();
updateBackgroundColor(savedColor); // Use updateBackgroundColor instead of body.style
function updateColorDisplay() {
const rgb = hsvToRgb(currentHue, currentSaturation, currentValue);
const hex = rgbToHex(...rgb);
// Update spectrum background
if (colorSpectrum) {
colorSpectrum.style.background = `linear-gradient(to right, #fff, hsl(${currentHue}, 100%, 50%))`;
}
// Update preview
if (previewColor) {
previewColor.style.backgroundColor = hex;
}
// Update inputs
if (hexInput) hexInput.value = hex;
if (rgbInputs.r) rgbInputs.r.value = rgb[0].toString();
if (rgbInputs.g) rgbInputs.g.value = rgb[1].toString();
if (rgbInputs.b) rgbInputs.b.value = rgb[2].toString();
if (hsvInputs.h) hsvInputs.h.value = currentHue.toString();
if (hsvInputs.s) hsvInputs.s.value = currentSaturation.toString();
if (hsvInputs.v) hsvInputs.v.value = currentValue.toString();
// Update cursors
if (cursor) {
cursor.style.left = `${currentSaturation}%`;
cursor.style.top = `${100 - currentValue}%`;
}
if (hueCursor) {
hueCursor.style.left = `${(currentHue / 360) * 100}%`;
}
// Preview the color using updateBackgroundColor
updateBackgroundColor(hex);
}
function handleSpectrumClick(e: MouseEvent) {
if (!colorSpectrum) return;
const rect = colorSpectrum.getBoundingClientRect();
const x = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
const y = Math.max(0, Math.min(1, (e.clientY - rect.top) / rect.height));
currentSaturation = x * 100;
currentValue = (1 - y) * 100;
updateColorDisplay();
}
function handleHueClick(e: MouseEvent) {
if (!hueSlider) return;
const rect = hueSlider.getBoundingClientRect();
const x = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
currentHue = x * 360;
updateColorDisplay();
}
// Event Listeners
colorPickerBtn?.addEventListener('click', () => {
if (colorPickerPopup) {
colorPickerPopup.style.display = 'block';
updateColorDisplay();
}
});
// Apply and Reset buttons
applyBtn?.addEventListener('click', () => {
const rgb = hsvToRgb(currentHue, currentSaturation, currentValue);
const hex = rgbToHex(...rgb);
updateBackgroundColor(hex); // Use updateBackgroundColor instead of localStorage directly
if (colorPickerPopup) {
colorPickerPopup.style.display = 'none';
}
});
resetBtn?.addEventListener('click', () => {
const defaultColor = '#00ff00'; // Changed from '#000000' to bright green
const rgb = hexToRgb(defaultColor);
const hsv = rgbToHsv(...rgb);
currentHue = hsv[0];
currentSaturation = hsv[1];
currentValue = hsv[2];
updateColorDisplay();
});
// Close popup when clicking outside
window.addEventListener('click', (e) => {
if (colorPickerPopup &&
!colorPickerPopup.contains(e.target as Node) &&
e.target !== colorPickerBtn) {
colorPickerPopup.style.display = 'none';
// Restore the saved color using updateBackgroundColor
const savedColor = localStorage.getItem('bongo-cat-bg-color') || '#00ff00';
updateBackgroundColor(savedColor);
}
});
closeBtn?.addEventListener('click', () => {
if (colorPickerPopup) {
colorPickerPopup.style.display = 'none';
// Restore the saved color using updateBackgroundColor
const savedColor = localStorage.getItem('bongo-cat-bg-color') || '#00ff00';
updateBackgroundColor(savedColor);
}
});
colorSpectrum?.addEventListener('mousedown', (e) => {
isDragging = true;
handleSpectrumClick(e);
});
hueSlider?.addEventListener('mousedown', (e) => {
isHueDragging = true;
handleHueClick(e);
});
window.addEventListener('mousemove', (e) => {
if (isDragging) handleSpectrumClick(e);
if (isHueDragging) handleHueClick(e);
});
window.addEventListener('mouseup', () => {
isDragging = false;
isHueDragging = false;
});
// Input change handlers
hexInput?.addEventListener('change', () => {
const rgb = hexToRgb(hexInput.value);
const hsv = rgbToHsv(...rgb);
currentHue = hsv[0];
currentSaturation = hsv[1];
currentValue = hsv[2];
updateColorDisplay();
});
Object.values(rgbInputs).forEach(input => {
input?.addEventListener('change', () => {
const rgb: [number, number, number] = [
parseInt(rgbInputs.r?.value || '0'),
parseInt(rgbInputs.g?.value || '0'),
parseInt(rgbInputs.b?.value || '0')
];
const hsv = rgbToHsv(...rgb);
currentHue = hsv[0];
currentSaturation = hsv[1];
currentValue = hsv[2];
updateColorDisplay();
});
});
Object.values(hsvInputs).forEach(input => {
input?.addEventListener('change', () => {
currentHue = parseInt(hsvInputs.h?.value || '0');
currentSaturation = parseInt(hsvInputs.s?.value || '0');
currentValue = parseInt(hsvInputs.v?.value || '0');
updateColorDisplay();
});
});
// Close popup when clicking outside
window.addEventListener('click', (e) => {
if (colorPickerPopup &&
!colorPickerPopup.contains(e.target as Node) &&
e.target !== colorPickerBtn) {
colorPickerPopup.style.display = 'none';
// Restore the saved color using updateBackgroundColor
const savedColor = localStorage.getItem('bongo-cat-bg-color') || '#00ff00';
updateBackgroundColor(savedColor);
}
});
}
/**
* Error handling wrapper for async operations
*/
async function safeAsync<T>(
operation: () => Promise<T>,
errorMessage: string,
fallback?: T
): Promise<T | undefined> {
try {
return await operation();
} catch (error) {
logger.error(errorMessage, error as Error);
return fallback;
}
}
/**
* Error handling wrapper for sync operations
*/
function safeSync<T>(
operation: () => T,
errorMessage: string,
fallback?: T
): T | undefined {
try {
return operation();
} catch (error) {
logger.error(errorMessage, error as Error);
return fallback;
}
}
/**
* Local storage keys
*/
const STORAGE_KEYS = {
CALIBRATION: 'bongo-cat-calibration',
BACKGROUND_COLOR: 'bongo-cat-bg-color',
} as const;
/**
* Button mapping configuration (default/fallback)
*/
const buttonMapping: ButtonMappings = {
vb1: 1, vb2: 2, vb3: 7, vb4: 6, vb5: 0, vb6: 3, vb7: 5, vb8: 4,
vbUp: 13, vbDown: 12, vbRight: 15, vbLeft: 14 // Swapped Up/Down to fix inversion
};
/**
* Calibration steps: directionals first, then action buttons (top row 5-8, bottom row 1-4)
*/
const calibrationSteps: CalibrationStep[] = [
{ name: 'Left', key: 'vbLeft', description: 'Press the LEFT (red, leftmost) button' },
{ name: 'Down', key: 'vbDown', description: 'Press the DOWN (red, upper middle) button' },
{ name: 'Right', key: 'vbRight', description: 'Press the RIGHT (red, rightmost) button' },
{ name: 'Up', key: 'vbUp', description: 'Press the UP (red, large, bottom) button' },
{ name: 'Button 5', key: 'vb5', description: 'Press the button that corresponds to Button 5 (top row, leftmost)' },
{ name: 'Button 6', key: 'vb6', description: 'Press the button that corresponds to Button 6' },
{ name: 'Button 7', key: 'vb7', description: 'Press the button that corresponds to Button 7' },
{ name: 'Button 8', key: 'vb8', description: 'Press the button that corresponds to Button 8 (top row, rightmost)' },
{ name: 'Button 1', key: 'vb1', description: 'Press the button that corresponds to Button 1 (bottom row, leftmost)' },
{ name: 'Button 2', key: 'vb2', description: 'Press the button that corresponds to Button 2' },
{ name: 'Button 3', key: 'vb3', description: 'Press the button that corresponds to Button 3' },
{ name: 'Button 4', key: 'vb4', description: 'Press the button that corresponds to Button 4 (bottom row, rightmost)' }
];
/**
* Calibration schematic button positions (SVG coordinates)
*/
const calibrationButtonPositions: ButtonPosition[] = [
{cx:90, cy:100}, // Left
{cx:140, cy:80}, // Down
{cx:190, cy:100}, // Right
{cx:245, cy:180}, // Up
{cx:260, cy:60}, // 5 (top row, leftmost)
{cx:300, cy:60}, // 6
{cx:340, cy:60}, // 7
{cx:380, cy:60}, // 8 (top row, rightmost)
{cx:260, cy:110}, // 1 (bottom row, leftmost)
{cx:300, cy:110}, // 2
{cx:340, cy:110}, // 3
{cx:380, cy:110}, // 4 (bottom row, rightmost)
];
/**
* Map vb keys to calibrationButtonPositions indices for correct highlight
*/
const buttonPositionIndex: Record<keyof ButtonMappings, number> = {
vbLeft: 0,
vbDown: 1,
vbRight: 2,
vbUp: 3,
vb5: 4,
vb6: 5,
vb7: 6,
vb8: 7,
vb1: 8,
vb2: 9,
vb3: 10,
vb4: 11
};
/**
* Start calibration process
*/
function startCalibration(): void {
state.isCalibrating = true;
state.currentCalibrationStep = 0;
state.calibrationMappings = {};
const gp = getGamepad();
state.lastCalibrationAxes = gp?.axes?.slice() || [];
state.restingCalibrationAxes = gp?.axes?.slice() || [];
// Ensure neutral hands are visible at the start of calibration
resetArmAndHandVisibility();
updateCalibrationUI();
calibrationLoop();
}
/**
* Update calibration overlay UI and highlight
*/
function updateCalibrationUI(): void {
// Hide all overlays
for (let i = 1; i <= 8; i++) {
const btn = document.getElementById(`button${i}`);
if (btn) btn.classList.add('invisible');
}
['up','down','left','right'].forEach(id => {
const el = document.getElementById(id);
if (el) el.classList.add('invisible');
});
// Update schematic SVG highlight
const highlightGroup = document.getElementById('calibration-highlight-group');
if (!highlightGroup) return;
while (highlightGroup.firstChild) highlightGroup.removeChild(highlightGroup.firstChild);
if (state.currentCalibrationStep >= calibrationSteps.length) {
finishCalibration();
return;
}
const step = calibrationSteps[state.currentCalibrationStep];
const progress = (state.currentCalibrationStep / calibrationSteps.length) * 100;
const currentButton = document.getElementById('current-button');
const progressFill = document.getElementById('progress-fill');
const progressText = document.getElementById('progress-text');
if (currentButton) currentButton.textContent = step.name;
if (progressFill) progressFill.style.width = progress + '%';
if (progressText) progressText.textContent = `${state.currentCalibrationStep} of ${calibrationSteps.length} buttons mapped`;
// Draw highlight circle on schematic
let pos = null;
if (step.key.startsWith('vb') && buttonPositionIndex.hasOwnProperty(step.key)) {
pos = calibrationButtonPositions[buttonPositionIndex[step.key as keyof ButtonMappings]];
}
if (pos) {
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', pos.cx.toString());
circle.setAttribute('cy', pos.cy.toString());
circle.setAttribute('r', '28');
circle.setAttribute('fill', 'yellow');
circle.setAttribute('fill-opacity', '0.6');
circle.setAttribute('stroke', '#ff6b6b');
circle.setAttribute('stroke-width', '4');
highlightGroup.appendChild(circle);
}
}
/**
* Main visualization loop with enhanced performance monitoring
*/
function visualizationLoop(): void {
// Performance monitoring
performanceMonitor.measureFrame();
const gp = getGamepad();
if (!gp) {
state.rAF = requestAnimationFrame(visualizationLoop);
return;
}
// Log when gamepad is detected for the first time
if (!state.gamepad) {
logger.info('Gamepad detected, starting visualization');
}
// Validate gamepad state and input manager health
if (!inputStateManager.validateGamepadState(gp) || !inputStateManager.isHealthy()) {
if (!inputStateManager.isHealthy()) {
logger.warn('Input state manager unhealthy, resetting...');
inputStateManager.reset();
}
state.rAF = requestAnimationFrame(visualizationLoop);
return;
}
if (state.isCalibrating) {
handleCalibration(gp);
state.rAF = requestAnimationFrame(visualizationLoop);
return;
}
// Update button overlays with error handling
try {
updateButtonOverlays(gp);
state.gamepad = gp;
} catch (error) {
logger.error('Error in visualization loop:', error instanceof Error ? error : new Error(String(error)));
// Continue the loop even if there's an error
}
state.rAF = requestAnimationFrame(visualizationLoop);
}
/**
* Update all overlays based on gamepad input
* Performance improvement: Use cached DOM elements and batch DOM updates
*/
function updateButtonOverlays(gp: Gamepad): void {
const updates: Array<() => void> = [];
// Process action buttons with better state tracking
const { pressedButtons, currentButtonStates } = processActionButtons(gp, updates);
// Process directionals with improved logic
const { currentDirectionalStates, x, y } = processDirectionals(gp, updates);
// Update arms with optimized logic
const armIndex = updateRightArmState(pressedButtons, currentButtonStates);
// Debug logging for arm state
if (pressedButtons.length > 0 || armIndex !== -1) {
logger.debug(`Pressed buttons: ${pressedButtons}, armIndex: ${armIndex}, lastPressed: ${state.lastPressedButtonIndex}`);
}
// Update left hand with enhanced state management
const leftState = updateLeftHandState(currentDirectionalStates);
// Batch all visual updates
batchVisualUpdates(updates, x, y, leftState, armIndex);
// Execute all DOM updates in a single batch for performance
updates.forEach(update => update());
}
/**
* Process action buttons and return state information
*/
function processActionButtons(gp: Gamepad, updates: Array<() => void>): {
pressedButtons: number[];
currentButtonStates: boolean[];
} {
const pressedButtons: number[] = [];
const currentButtonStates: boolean[] = [];
// Optimized loop with early exit for invalid buttons
for (let i = 1; i <= ANIMATION_CONSTANTS.ARM_COUNT; i++) {
const btn = domCache.buttons[`button${i}`];
if (!btn) continue;
const vbKey = `vb${i}` as keyof ButtonMappings;
const mapping = buttonMapping[vbKey];
let pressed = false;
// Improved input detection with error handling
try {
if (typeof mapping === 'object' && 'axis' in mapping) {
pressed = gp.axes[mapping.axis] !== undefined &&
gp.axes[mapping.axis] > INPUT_CONSTANTS.AXIS_THRESHOLD;
} else if (typeof mapping === 'number' && mapping < gp.buttons.length) {
pressed = buttonPressed(gp.buttons[mapping]);
}
// Debug: log button presses
if (pressed) {
logger.debug(`Button ${i} pressed (mapping: ${JSON.stringify(mapping)})`);
}
} catch (error) {
logger.warn(`Error processing button ${i}:`, error);
pressed = false;
}
currentButtonStates[i - 1] = pressed;
if (pressed) {
pressedButtons.push(i - 1);
}
// Track state changes for last pressed detection
const wasPressed = state.previousButtonStates[i - 1] || false;
if (pressed && !wasPressed) {
state.lastPressedButtonIndex = i - 1;
}
// Batch DOM update
updates.push(() => btn.classList.toggle('invisible', !pressed));
}
// Update previous button states efficiently
state.previousButtonStates = currentButtonStates;
return { pressedButtons, currentButtonStates };
}
/**
* Process directional inputs with improved logic
*/
function processDirectionals(gp: Gamepad, updates: Array<() => void>): {
currentDirectionalStates: { left: boolean; right: boolean; up: boolean; down: boolean };
x: number;
y: number;
} {
let x = 0, y = 0;
const currentDirectionalStates = { left: false, right: false, up: false, down: false };
try {
if (state.axes) {
// Axis-based directional input