-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
1883 lines (1559 loc) · 59.8 KB
/
main.js
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
// Imports
import * as THREE from './libs/build/three.module.js';
import { EffectComposer } from './libs/postprocessing/EffectComposer.js';
import { RenderPass } from './libs/postprocessing/RenderPass.js';
import { OrbitControls } from './libs/controls/OrbitControls.js';
import { GLTFLoader } from './libs/loaders/GLTFLoader.js';
import { RGBELoader } from './libs/loaders/RGBELoader.js';
import * as dat from './libs/dat.gui.module.js';
import { UnrealBloomPass } from './libs/postprocessing/UnrealBloomPass.js';
import { RenderPixelatedPass } from './libs/postprocessing/RenderPixelatedPass.js';
import { BokehPass } from './libs/postprocessing/BokehPass.js';
import { GlitchPass } from './libs/postprocessing/GlitchPass.js';
import { ShaderPass } from './libs/postprocessing/ShaderPass.js';
import { SepiaShader } from './libs/shaders/SepiaShader.js';
import { FilmPass } from './libs/postprocessing/FilmPass.js';
import { DotScreenPass } from './libs/postprocessing/DotScreenPass.js';
import { AsciiEffect } from './libs/effects/AsciiEffect.js'; // Assuming you have the AsciiEffect.js file
import { AnaglyphEffect } from './libs/effects/AnaglyphEffect.js';
let asciiFolder; // Declare it here and initialize later in setupGUI()
// 🔹 Add this to the global variable section:
let asciiPass = null;
let anaglyphEffect;
let asciiEffect, appContainer;
let modelIndex = 0;
// ✅ Define the model index globally
let currentModelIndex = 0;
// === MIDI Integration === //
let midiAccess = null;
let midiOutput = null;
let camera, scene, renderer, composer, gui;
let ambientLight, pixelationPass, bloomPass, bokehPass, glitchPass, filterPass;
let currentModel = null;
let videoTexture = null;
const hdrLoader = new RGBELoader(); // HDR Loader
let pmremGenerator; // PMREM Generator for HDR environment mapping
// Rotation step: 1/8 of a full rotation (in radians)
const ROTATION_STEP = Math.PI / 4;
const webcamSettings = {
brightness: 0.5, // Default brightness for the webcam feed
};
let container; // Declare container as a global variable
// Add Object Transform controls to the GUI
const transformSettings = {
positionX: 0,
positionY: 0,
positionZ: 0,
rotationX: 0,
rotationY: 0,
rotationZ: 0,
};
// Add Texture Navigation Settings
const textureNavigation = {
offsetX: 0.5, // Default X offset (centered)
offsetY: 0.5, // Default Y offset (centered)
};
const asciiSettings = {
contrast: 50, // Initial contrast level
font: "monospace", // Default font
invert: false,
};
// Add lighting management
// Lighting settings with color property
const lightingSettings = {
type: 'DirectionalLight',
intensity: 4.0,
color: '#ffffff' // Default color
};
let currentLight = null;
// Model paths and settings
const modelPaths = {
macbook: './models/macbook/scene.gltf',
iphone: './models/iphone/scene.gltf',
macintoshclassic: './models/macintoshclassic/scene.gltf',
};
let currentModelName = null;
const modelSettings = { model: 'macbook' };
const textureSettings = {
zoom: 1,
pixelSize: 1,
};
const dofSettings = {
focus: 1.0,
aperture: 0.025,
maxblur: 0.01,
};
const glitchSettings = {
enabled: false,
goWild: false,
};
const filterSettings = {
filter: 'none',
};
// Function to dynamically load custom fonts
function loadCustomFonts() {
const style = document.createElement('style');
style.innerHTML = `
@font-face {
font-family: 'Digital7';
src: url('./libs/fonts/digital-7 (mono).ttf') format('truetype');
}
@font-face {
font-family: 'Pixel Arial';
src: url('./libs/fonts/PIXEARG_.TTF') format('truetype');
}
@font-face {
font-family: 'Pockota';
src: url('./libs/fonts/Pockota-Regular.otf') format('opentype');
}
@font-face {
font-family: 'Pockota-Black';
src: url('./libs/fonts/Pockota-BlackItalic.otf') format('opentype');
}
@font-face {
font-family: 'Your Groovy Font';
src: url('./libs/fonts/Your Groovy Font.otf') format('opentype');
}
`;
document.head.appendChild(style);
console.log("Custom fonts loaded.");
}
// Call this function during initialization
loadCustomFonts();
// ✅ Clears the current model before loading a new one
function clearCurrentModel() {
if (currentModel) {
scene.remove(currentModel);
currentModel.traverse((child) => {
if (child.isMesh) {
child.geometry.dispose();
if (Array.isArray(child.material)) {
child.material.forEach(mat => mat.dispose());
} else {
child.material.dispose();
}
}
});
currentModel = null;
}
}
const asciiFontOptions = {
fonts: [
"monospace",
"Courier New",
"Digital7",
"Pixel Arial",
"Pockota",
"Your Groovy Font",
],
selectedFont: "monospace", // Default font
};
init();
animate();
// Ensure `modelTransformConfigs` and `currentModelName` are defined and valid
const modelTransformConfigs = {
macbook: { rotationMatrix: new THREE.Matrix3() },
iphone: { rotationMatrix: new THREE.Matrix3() },
macintoshclassic: { rotationMatrix: new THREE.Matrix3() },
};
const videoShaderMaterial = new THREE.ShaderMaterial({
uniforms: {
videoTexture: { value: null },
brightness: { value: 1.0 },
rotation: { value: 0.0 },
scale: { value: 1.0 },
flip: { value: 1.0 },
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform sampler2D videoTexture;
uniform float brightness;
uniform float rotation;
uniform float scale;
uniform float flip;
varying vec2 vUv;
void main() {
// Center the UV coordinates
vec2 centeredUV = vUv - 0.5;
// Apply rotation
float cosRot = cos(rotation);
float sinRot = sin(rotation);
vec2 rotatedUV = vec2(
centeredUV.x * cosRot - centeredUV.y * sinRot,
centeredUV.x * sinRot + centeredUV.y * cosRot
);
// Apply uniform scaling and flipping
vec2 scaledUV = rotatedUV / scale;
// Apply flipping along the X-axis
scaledUV.x *= flip;
// Return to UV space with offsets applied
vec2 transformedUV = scaledUV + vec2(0.5, 0.5);
// Fetch the color from the video texture
vec4 color = texture2D(videoTexture, transformedUV);
// Apply brightness adjustment
gl_FragColor = vec4(color.rgb * brightness, color.a);
}
`,
});
function init() {
appContainer = document.createElement('div');
document.body.appendChild(appContainer);
// Camera
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.25, 20);
camera.position.set(5, 1, 3);
// Scene
scene = new THREE.Scene();
// HDR Background
new RGBELoader().setPath('./libs/textures/').load('./spot1Lux.hdr', (texture) => {
texture.mapping = THREE.EquirectangularReflectionMapping;
scene.background = texture;
scene.environment = texture;
});
// Lights
setupLights();
// Initialize MIDI Access
function initMIDI() {
if (navigator.requestMIDIAccess) {
navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);
} else {
console.error("Web MIDI API not supported in this browser.");
}
}
function onMIDISuccess(midi) {
midiAccess = midi;
// Connect to MIDI Output
for (let output of midiAccess.outputs.values()) {
midiOutput = output;
console.log(`Connected to MIDI Output: ${output.name}`);
break;
}
// Listen for MIDI Input
for (let input of midiAccess.inputs.values()) {
input.onmidimessage = handleMIDIMessage;
}
initializePadLights();
}
function onMIDIFailure() {
console.error("Could not access MIDI devices.");
}
// Send MIDI Messages to light up pads
function sendMIDIMessage(command, note, velocity) {
if (midiOutput) {
midiOutput.send([command, note, velocity]);
}
}
// Initialize pad lights
function initializePadLights() {
// Light up all color pads with default colors
for (let note = 0; note < 32; note++) {
const colorCode = hslToAPCColor((note % 8) * 45, 1);
sendMIDIMessage(0x90, note, colorCode);
}
}
// Convert HSL to APC Mini color codes
function hslToAPCColor(hue, saturation) {
if (saturation < 0.3) return 1; // Green (Low Saturation)
if (hue < 60) return 5; // Yellow
if (hue < 120) return 1; // Green
if (hue < 180) return 7; // Lime
if (hue < 240) return 4; // Blue
if (hue < 300) return 3; // Red
return 6; // Orange
}
// Function to cycle through models
function cycleModels() {
const modelKeys = Object.keys(modelPaths);
// Increment index and loop back to 0 if at the end
currentModelIndex = (currentModelIndex + 1) % modelKeys.length;
// Load the model at the new index
loadModelByIndex(currentModelIndex);
}
// Handle MIDI Messages
// Handle MIDI Messages
function handleMIDIMessage(event) {
const [status, note, velocity] = event.data;
const command = status & 0xf0;
if (command === 0xB0) { // Control Change for sliders
handleSliderControl(note, velocity);
} else if (command === 0x90 && velocity > 0) { // Note On
handleButtonPress(note, velocity);
} else if (command === 0x80 || (command === 0x90 && velocity === 0)) { // Note Off
handleButtonRelease(note); // ✅ Correctly defined below
}
}
// === 1. Improved Check for ASCII Effect ===
function isAsciiEffectActive() {
return asciiEffect && appContainer.contains(asciiEffect.domElement);
}
function handleButtonRelease(note) {
console.log(`Button ${note} released`);
if (note < 32) {
resetLightColor(note); // 🟢 Reset Color Pads on release
} else if (note >= 40 && note <= 46) {
lightUpButton(note, 4); // 🔵 Keep Effects pads blue
} else if (note === 47) {
lightUpButton(note, 3); // 🔴 Keep Reset button red
}
}
function setPadColors() {
if (!midiOutput) {
console.warn("⚠️ MIDI Output not initialized.");
return;
}
// APC Mini Color Codes (Double-check with your device documentation)
const COLOR_OFF = 0;
const COLOR_GREEN = 1;
const COLOR_RED = 3;
const COLOR_YELLOW = 5;
// Helper function to light up a pad
function lightPad(note, color) {
midiOutput.send([0x90, note, color]);
}
// 1. Row 1 (56–63): Yellow
for (let note = 56; note <= 63; note++) {
lightPad(note, COLOR_YELLOW);
}
// 2. Row 2 (48–55): Keep existing logic (no change)
// 3. **Effects Row (40–46): Set to RED (Always On)**
for (let note = 40; note <= 47; note++) {
lightPad(note, COLOR_RED);
}
// 4. Row 4 (32–39): Green
for (let note = 32; note <= 39; note++) {
lightPad(note, COLOR_GREEN);
}
// 5. Color Picker Pads (0–31): Yellow
for (let note = 0; note <= 31; note++) {
lightPad(note, COLOR_YELLOW);
}
// 6. Last Row (64–71): Red
for (let note = 64; note <= 71; note++) {
lightPad(note, COLOR_RED);
}
// 7. **New Addition**: Buttons 82–92 → Yellow
for (let note = 82; note <= 92; note++) {
lightPad(note, COLOR_YELLOW);
}
console.log("🔆 Pad colors successfully updated.");
}
function onMIDIInit() {
initMIDI(); // Existing MIDI setup
setTimeout(setPadColors, 500); // Delay to ensure proper initialization
}
// === 2. Corrected ASCII Contrast Control ===
function handleAsciiContrastControl(note, velocity) {
if (!isAsciiEffectActive()) {
console.warn("⚠️ ASCII effect is not active. Contrast buttons are disabled.");
resetAsciiButtonLights(); // Turn off lights if ASCII isn't active
return;
}
// Adjust contrast if ASCII effect is active
const contrastMapping = {
48: 9,
49: 19,
50: 39,
51: 49,
52: 59,
53: 69,
54: 79,
55: 89
};
if (contrastMapping.hasOwnProperty(note)) {
asciiSettings.contrast = contrastMapping[note];
updateAsciiEffect();
console.log(`🎨 ASCII Contrast set to: ${asciiSettings.contrast}`);
updateAsciiButtonLights(note); // Light up the active button
}
}
// === 3. Update Button Lights for ASCII Contrast ===
function updateAsciiButtonLights(activeNote) {
for (let i = 48; i <= 55; i++) {
const lightValue = (i === activeNote) ? 127 : 0; // Light up active button
if (midiOutput) {
midiOutput.send([0x90, i, lightValue]);
}
}
}// === 4. Reset Lights When ASCII Effect is Off ===
function resetAsciiButtonLights() {
for (let i = 48; i <= 55; i++) {
if (midiOutput) {
midiOutput.send([0x90, i, 0]); // Turn off all lights
}
}
}
// === 5. Updated handleButtonPress to Integrate New Function ===
function handleButtonPress(note, velocity) {
console.log(`Button ${note} pressed with velocity ${velocity}`);
if (note === 46) {
// Toggle Glitch Effect
glitchSettings.enabled = !glitchSettings.enabled;
glitchPass.enabled = glitchSettings.enabled;
console.log(`🌀 Glitch Effect ${glitchSettings.enabled ? 'enabled' : 'disabled'}`);
lightUpButton(note, glitchSettings.enabled ? 3 : 0); // Light up in red if enabled
}
else if (note >= 48 && note <= 55) {
handleAsciiContrastControl(note, velocity); // ✅ Handle ASCII contrast
} else if (note >= 40 && note <= 46) {
const effects = ['sepia', 'film', 'blackandwhite', 'halftone', 'ascii', 'anaglyph'];
applyFilter(effects[note - 40]);
} else if (note === 47) {
resetEffects();
} else if (note === 71) {
loadNextModel();
}
else if (note >= 40 && note <= 45) {
const effects = ['sepia', 'film', 'blackandwhite', 'halftone', 'ascii', 'anaglyph'];
applyFilter(effects[note - 40]);
} else if (note === 47) {
resetEffects();
} else if (note === 71) {
loadNextModel();
} else if (note >= 64 && note <= 67) {
rotateCurrentModel(note);
} else if (note === 68) {
loadHDRBackground('spot1lux.hdr');
} else if (note === 69) {
loadHDRBackground('moonless_golf_1k.hdr');
} else if (note === 70) {
loadHDRBackground('quarry_01_1k.hdr');
} else if (note === 98) {
window.location.reload();
} else if (note >= 32 && note <= 39) {
handleLightControl(note, velocity);
} else if (note < 32) {
adjustLightColor(note);
} else if (note >= 82 && note <= 89) {
adjustLightIntensity(note);
} else if (note >= 56 && note <= 63) {
// Map buttons 56–63 to brightness range [0, 5]
const minBrightness = 0.0;
const maxBrightness = 5.0;
const step = (maxBrightness - minBrightness) / 7; // 8 buttons, 7 intervals
const index = note - 56;
webcamSettings.brightness = minBrightness + index * step;
videoShaderMaterial.uniforms.brightness.value = webcamSettings.brightness;
console.log(`Screen Brightness set to: ${webcamSettings.brightness}`);
}
}
function handleLightControl(note, velocity) {
const buttonValue = velocity / 127;
switch (note) {
case 32: // Move Light Z → +8
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = 30;
console.log("🔦 Light moved to Z: +8");
}
break;
case 33:
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = 12;
console.log("🔦 Light moved to Z: +6");
}
break;
case 34:
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = 8;
console.log("🔦 Light moved to Z: +4");
}
break;
case 35:
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = 4;
console.log("🔦 Light moved to Z: +2");
}
break;
case 36: // Center Position
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = 0;
console.log("🔦 Light moved to Z: 0 (Center)");
}
break;
case 37:
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = -2;
console.log("🔦 Light moved to Z: -2");
}
break;
case 38:
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = -4;
console.log("🔦 Light moved to Z: -4");
}
break;
case 39: // Move Light Z → -8
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = -8;
console.log("🔦 Light moved to Z: -8");
}
break;
default:
console.warn(`Unhandled light control button: ${note}`);
break;
}
}
// Function to rotate the current model on Y and Z axes
function rotateCurrentModel(note) {
if (!currentModel) {
console.warn("⚠️ No model loaded to rotate.");
return;
}
switch (note) {
case 64:
transformSettings.rotationZ += ROTATION_STEP; // Rotate +Y
console.log("🔄 Rotated +1/8 on Y-axis");
break;
case 65:
transformSettings.rotationZ -= ROTATION_STEP; // Rotate -Y
console.log("🔄 Rotated -1/8 on Y-axis");
break;
case 66:
transformSettings.rotationY -= ROTATION_STEP; // Rotate -Y
console.log("🔄 Rotated -1/8 on Y-axis");
break;
case 67:
transformSettings.rotationY += ROTATION_STEP; // Rotate +Y
console.log("🔄 Rotated +1/8 on Y-axis");
break;
default:
console.warn("🚫 Invalid button for rotation.");
return;
}
// ✅ Apply the updated rotation while preserving position
updateObjectTransform();
}
function loadHDRBackground(path) {
const hdrLoader = new RGBELoader();
hdrLoader.setPath('./libs/textures/').load(path, function (texture) {
texture.mapping = THREE.EquirectangularReflectionMapping;
// Ensure PMREM Generator exists
if (!pmremGenerator) {
console.error("❌ PMREM Generator is not initialized.");
return;
}
const envMap = pmremGenerator.fromEquirectangular(texture).texture;
// Apply to scene background and environment
scene.environment = envMap;
scene.background = envMap;
texture.dispose(); // Free up memory
console.log(`🌄 HDR Background switched to: ${path}`);
}, undefined, function (error) {
console.error('❌ Failed to load HDR background:', error);
});
}
function lightUpButton(note, colorCode) {
if (midiOutput) {
midiOutput.send([0x90, note, colorCode]);
} else {
console.warn("MIDI Output not initialized.");
}
}
function adjustLightIntensity(note) {
// Map buttons 82 (max) to 89 (min) to light intensity between 4.0 and 0.0
const maxIntensity = 20.0;
const minIntensity = 0.0;
// Calculate step size for 8 buttons (82-89)
const step = (maxIntensity - minIntensity) / 7;
// Button 82 → max intensity, 89 → min intensity
const intensity = maxIntensity - ((note - 82) * step);
lightingSettings.intensity = intensity;
updateLighting();
console.log(`💡 Light intensity set to: ${intensity.toFixed(2)}`);
}
// Adjust light color based on pad press
function adjustLightColor(note) {
const row = Math.floor(note / 8);
const col = note % 8;
const hue = (col / 7) * 360;
const saturation = 1 - (row / 3);
const color = new THREE.Color().setHSL(hue / 360, saturation, 0.5);
lightingSettings.color = `#${color.getHexString()}`;
updateLighting();
// 1. Update lighting settings
lightingSettings.color = `#${color.getHexString()}`;
updateLighting();
// 2. Sync with GUI light folder
if (gui) {
gui.__folders['Lighting'].__controllers.forEach(controller => {
if (controller.property === 'color') {
controller.setValue(lightingSettings.color);
}
});
}
// 3. Update ASCII effect text color
if (asciiEffect) {
asciiEffect.domElement.style.color = `#${color.getHexString()}`;
}
console.log(`🎨 Adjusted Light Color: ${lightingSettings.color}`);
}
// ✅ Reset Light Color (When Pad is Released)
function resetLightColor(note) {
lightUpButton(note, 1); // Reset pad color to green
console.log(`🔄 Reset Light Pad ${note}`);
}
function moveLightOnZAxis(note) {
if (!currentLight || !(currentLight instanceof THREE.DirectionalLight)) {
console.warn("⚠️ No Directional Light to move.");
return;
}
const maxZ = 8; // Z-axis maximum position
const minZ = -8; // Z-axis minimum position
// Map buttons 32–39 to Z-axis positions between 8 and -8
const step = (maxZ - minZ) / 7; // 7 steps between 8 buttons
const newZ = maxZ - ((note - 32) * step);
currentLight.position.z = newZ;
console.log(`🔦 Directional Light Z-position set to: ${newZ}`);
}
function handleSliderControl(note, velocity) {
const sliderValue = velocity / 127;
switch (note) {
case 48: // Slider 1 → Camera Zoom
camera.zoom = 0.1 + sliderValue * 10;
camera.updateProjectionMatrix();
updateCameraInfo(); // ✅ Update info box
console.log(`Camera Zoom: ${camera.zoom}`);
break;
case 49: // Slider 2 → DOF Focus
dofSettings.focus = 0.1 + sliderValue * 20;
if (bokehPass && bokehPass.uniforms) {
bokehPass.uniforms.focus.value = dofSettings.focus;
}
updateCameraInfo(); // ✅ Update info box
console.log(`DOF Focus: ${dofSettings.focus}`);
break;
case 50: // Slider 3 → DOF Aperture
dofSettings.aperture = 0.001 + sliderValue * 0.099; // Map slider to range [0.001, 0.1]
if (bokehPass && bokehPass.uniforms) {
bokehPass.uniforms.aperture.value = dofSettings.aperture;
}
updateCameraInfo(); // Update the info box if relevant
console.log(`DOF Aperture: ${dofSettings.aperture}`);
break;
case 51: // Slider 4 → Webcam Zoom
textureSettings.zoom = 0.1 + sliderValue * 5;
updateTextureTransform();
console.log(`Webcam Zoom: ${textureSettings.zoom}`);
break;
case 52: // Slider 5 → Pixelation Level
textureSettings.pixelSize = 1 + sliderValue * 600;
if (pixelationPass) {
pixelationPass.setPixelSize(textureSettings.pixelSize);
}
console.log(`Pixelation Level: ${textureSettings.pixelSize}`);
break;
case 53: // Slider 6 → Inverted Bloom Strength
bloomPass.threshold = (1 - sliderValue) * 3; // Inverted scale
console.log(`Inverted Bloom strength: ${bloomPass.threshold}`);
break;
case 54: // Slider 7 → Object X Position
transformSettings.positionX = (sliderValue * 20) - 10;
updateObjectTransform(); // ✅ Position only, rotation preserved
console.log(`Object X Position: ${transformSettings.positionX}`);
break;
case 55: // Slider 8 → Object Y Position
transformSettings.positionY = (sliderValue * 20) - 10;
updateObjectTransform(); // ✅ Position only, rotation preserved
console.log(`Object Y Position: ${transformSettings.positionY}`);
break;
case 56: // Slider 9 → Object Z Position
transformSettings.positionZ = (sliderValue * 20) - 10;
updateObjectTransform(); // ✅ Position only, rotation preserved
console.log(`Object Z Position: ${transformSettings.positionZ}`);
break;
case 32: // Move Light Z → +8
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = 8;
console.log("🔦 Light moved to Z: +8");
}
break;
case 33:
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = 6;
console.log("🔦 Light moved to Z: +6");
}
break;
case 34:
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = 4;
console.log("🔦 Light moved to Z: +4");
}
break;
case 35:
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = 2;
console.log("🔦 Light moved to Z: +2");
}
break;
case 36: // Center Position
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = 0;
console.log("🔦 Light moved to Z: 0 (Center)");
}
break;
case 37:
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = -2;
console.log("🔦 Light moved to Z: -2");
}
break;
case 38:
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = -4;
console.log("🔦 Light moved to Z: -4");
}
break;
case 39: // Move Light Z → -8
if (currentLight && currentLight instanceof THREE.DirectionalLight) {
currentLight.position.z = -8;
console.log("🔦 Light moved to Z: -8");
}
break;
default:
console.warn(`Unhandled slider: ${note}`);
}
}
// === Initialize MIDI on Load === //
window.addEventListener('load', initMIDI);
initMIDI(); // Existing MIDI setup
setTimeout(setPadColors, 500);
// Renderer setup
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
appContainer.appendChild(renderer.domElement);
// PMREM Generator Initialization
pmremGenerator = new THREE.PMREMGenerator(renderer);
pmremGenerator.compileEquirectangularShader();
// Postprocessing Composer
composer = new EffectComposer(renderer);
const renderPass = new RenderPass(scene, camera);
composer.addPass(renderPass);
// Pixelation Pass
pixelationPass = new RenderPixelatedPass(textureSettings.pixelSize, scene, camera);
composer.addPass(pixelationPass);
// Bloom Pass
bloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight), 1.5, 0.4, 0.85);
composer.addPass(bloomPass);
// Depth of Field (DOF) Pass
bokehPass = new BokehPass(scene, camera, {
focus: dofSettings.focus,
aperture: dofSettings.aperture,
maxblur: dofSettings.maxblur,
});
composer.addPass(bokehPass);
// Glitch Pass
glitchPass = new GlitchPass();
glitchPass.enabled = glitchSettings.enabled;
glitchPass.goWild = glitchSettings.goWild;
composer.addPass(glitchPass);
// Shader Pass (Filters)
filterPass = new ShaderPass(SepiaShader);
filterPass.enabled = false;
composer.addPass(filterPass);
// OrbitControls
const controls = new OrbitControls(camera, renderer.domElement);
controls.minDistance = 2;
controls.maxDistance = 10;
controls.target.set(0, 0, -0.2);
controls.update();
// Webcam Setup
setupWebcam();
// Load Default Model
loadModel(modelPaths[modelSettings.model]);
// Call this function during initialization
loadCustomFonts();
// GUI Setup
setupGUI();
setupAsciiEffect();
filterSettings.filter = 'none';
// Window Resize Handling
window.addEventListener('resize', onWindowResize);
}
function adjustActiveEffect(activeEffect, index) {
// Safeguard: Check if an effect is active
if (!activeEffect || activeEffect === "none") {
console.warn(`No adjustable parameters for the effect: ${activeEffect}`);
return; // Exit early to prevent errors
}
const stepSize = 1.0 / 7; // Divide the range into 8 steps
switch (activeEffect) {
case 'ascii':
// Adjust ASCII Contrast (range 10–100)
asciiSettings.contrast = 10 + index * 12.857; // Map to [10, 100]
updateAsciiEffect();
console.log(`ASCII Contrast set to: ${asciiSettings.contrast}`);
break;
case 'glitch':
// Adjust Glitch Wildness (goWild intensity)
glitchSettings.goWild = index > 3; // Enable wildness for buttons 52–55
glitchPass.goWild = glitchSettings.goWild; // Sync to glitch pass
console.log(`Glitch Wildness: ${glitchSettings.goWild ? 'High' : 'Low'}`);
break;
case 'anaglyph':
// Adjust Anaglyph Layer Separation
if (anaglyphPass && anaglyphPass.uniforms && anaglyphPass.uniforms.separation) {
anaglyphPass.uniforms.separation.value = 0.005 + index * stepSize * 0.02; // Map to [0.005, 0.02]
console.log(`Anaglyph Separation set to: ${anaglyphPass.uniforms.separation.value}`);
} else {
console.warn("Anaglyph pass or its uniforms are not initialized.");
}
break;
case 'halftone':
// Adjust Halftone Scale
if (halftonePass && halftonePass.uniforms && halftonePass.uniforms.scale) {
halftonePass.uniforms.scale.value = 1.0 + index * stepSize * 9.0; // Map to [1.0, 10.0]
console.log(`Halftone Scale set to: ${halftonePass.uniforms.scale.value}`);
} else {
console.warn("Halftone pass or its uniforms are not initialized.");
}
break;
default:
console.warn(`No adjustable parameters for the effect: ${activeEffect}`);
}
}
// Function to setup webcam with brightness adjustment
function setupWebcam() {
const video = document.createElement('video');
video.autoplay = true;
video.muted = true;
video.playsInline = true;
navigator.mediaDevices
.getUserMedia({ video: true })