-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1669 lines (1452 loc) · 58.5 KB
/
app.js
File metadata and controls
1669 lines (1452 loc) · 58.5 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
document.addEventListener("DOMContentLoaded", () => {
// Initialize main app first, then handle ISF separately
console.log("Initializing main app...");
// Declare all variables first
const layersContainer = document.getElementById("layers-container");
const openOutputBtn = document.getElementById("open-output");
const numLayers = 4;
let outputWindow = null;
let audioContext;
let sourceNode;
let delayedAudible;
const layers = [];
const presets = {};
let isfManager = null;
// Built-in ISF shaders
const isfShaders = {
"solid-red.fs": `/*{\n "CREDIT": "Test",\n "CATEGORIES": ["Generator"],\n "DESCRIPTION": "A simple solid red color.",\n "INPUTS": []\n}*/\n\nvoid main() {\n gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n}`,
"simple-anim.fs": `/*{\n "CREDIT": "Test",\n "CATEGORIES": ["Generator"],\n "DESCRIPTION": "A simple animated shader.",\n "INPUTS": []\n}*/\n\nvoid main() {\n vec2 uv = gl_FragCoord.xy / RENDERSIZE.xy;\n float t = TIME * 0.5;\n vec3 color = 0.5 + 0.5 * cos(t + uv.xyx + vec3(0,2,4));\n gl_FragColor = vec4(color, 1.0);\n}`,
"test-green.fs": `/*{\n "CREDIT": "Test",\n "CATEGORIES": ["Generator"],\n "DESCRIPTION": "Ultra simple green shader.",\n "INPUTS": []\n}*/\n\nvoid main() {\n gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n}`,
"Load from file...": "LOAD_FROM_FILE",
"manual-red.fs": `Manual Red Test`
};
// Utility functions
function rgbaToHex(r, g, b) {
const toHex = (c) => Math.round(c * 255).toString(16).padStart(2, '0');
return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}
function hexToRgba(hex) {
const r = parseInt(hex.slice(1, 3), 16) / 255;
const g = parseInt(hex.slice(3, 5), 16) / 255;
const b = parseInt(hex.slice(5, 7), 16) / 255;
return [r, g, b, 1.0];
}
function initAudio() {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
}
function initPresets() {
console.log("window.all:", window.all);
if (window.all && window.all.default) {
Object.assign(presets, window.all.default);
console.log("presets:", presets);
} else {
setTimeout(initPresets, 100);
}
}
function connectAudio(source) {
if (delayedAudible) {
delayedAudible.disconnect();
}
delayedAudible = audioContext.createDelay();
delayedAudible.delayTime.value = 0.26;
source.connect(delayedAudible);
delayedAudible.connect(audioContext.destination);
layers.forEach((layer) => {
if (layer.visualizer) {
layer.visualizer.connectAudio(delayedAudible);
}
});
}
// Async function to load shader files
async function loadShaderFile(filename) {
try {
const response = await fetch(`shaders/${filename}`);
if (!response.ok) {
throw new Error(`Failed to load shader: ${response.status}`);
}
return await response.text();
} catch (error) {
console.error('Error loading shader file:', error);
throw error;
}
}
// === MAIN INITIALIZATION FUNCTIONS ===
function initializeMainApp() {
console.log("Setting up main app UI...");
// Initialize core app functionality that doesn't depend on ISF
initializeAudioControls();
initializeLayers();
initPresets(); // Initialize MilkDrop presets
startAnimationLoop();
console.log("Main app initialized successfully");
}
function initializeAudioControls() {
console.log('Initializing audio controls...');
// Global audio controls
const audioControls = document.createElement("div");
audioControls.innerHTML = `
<label>Audio:</label>
<input type="file" id="audio-file-input" accept="audio/*">
<button id="mic-input-btn">Use Mic</button>
`;
document.getElementById("main-controls").appendChild(audioControls);
const audioFileInput = document.getElementById("audio-file-input");
audioFileInput.addEventListener("change", (e) => {
const file = e.target.files[0];
if (file) {
initAudio();
const audioUrl = URL.createObjectURL(file);
const audio = new Audio(audioUrl);
audio.crossOrigin = "anonymous";
if (sourceNode) {
sourceNode.disconnect();
}
sourceNode = audioContext.createMediaElementSource(audio);
connectAudio(sourceNode);
const playPromise = audio.play();
if (playPromise !== undefined) {
playPromise.catch((error) => {
if (error.name === "AbortError") {
console.log("Audio play() request was aborted.");
} else {
console.error("Audio play() failed:", error);
}
});
}
}
});
const micInputBtn = document.getElementById("mic-input-btn");
micInputBtn.addEventListener("click", () => {
initAudio();
navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
if (sourceNode) {
sourceNode.disconnect();
}
sourceNode = audioContext.createMediaStreamSource(stream);
connectAudio(sourceNode);
});
});
console.log('Audio controls initialized');
}
function initializeLayers() {
console.log('Initializing layers...');
console.log('layersContainer element:', layersContainer);
console.log('numLayers:', numLayers);
for (let i = 0; i < numLayers; i++) {
console.log(`Creating layer ${i + 1}...`);
const layer = {
id: i,
opacity: 1,
file: null,
fileType: null,
element: null,
visualizer: null,
outputVisualizer: null,
renderer: null,
renderFunc: null,
presets: [],
presetKeys: [],
currentPresetIndex: -1,
};
layers.push(layer);
const layerEl = document.createElement("div");
layerEl.classList.add("layer");
layerEl.setAttribute("data-layer", i);
layerEl.innerHTML = `
<h3>Layer ${i + 1}</h3>
<div class="layer-controls">
<label>Opacity:</label>
<input type="range" min="0" max="1" value="1" step="0.01" class="opacity-slider" data-layer="${i}">
<input type="file" class="file-input" data-layer="${i}" accept=".gif,.isf,.fs,.frag,.mp4,.json">
<button class="load-presets-btn" data-layer="${i}">Load MilkDrop Presets</button>
<button class="load-isf-btn" data-layer="${i}">Load ISF</button>
</div>
<div class="layer-preview"></div>
<div class="advanced-controls"></div>
`;
console.log(`Appending layer ${i + 1} element to container:`, layerEl);
layersContainer.appendChild(layerEl);
console.log(`Layer ${i + 1} appended successfully`);
}
console.log('All layers created successfully!');
console.log('Total layers in array:', layers.length);
// Set up layer event listeners
setupLayerEventListeners();
}
function setupLayerEventListeners() {
console.log('Setting up layer event listeners...');
layersContainer.addEventListener("input", (e) => {
if (e.target.classList.contains("opacity-slider")) {
const layerId = parseInt(e.target.dataset.layer, 10);
layers[layerId].opacity = parseFloat(e.target.value);
// renderOutput(); // Will implement later
}
});
layersContainer.addEventListener("change", (e) => {
if (e.target.classList.contains("file-input")) {
const layerId = parseInt(e.target.dataset.layer, 10);
const file = e.target.files[0];
if (file) {
console.log(`File selected for layer ${layerId}:`, file.name);
// handleFile(layerId, file); // Will implement later
}
}
});
layersContainer.addEventListener("click", (e) => {
if (e.target.classList.contains("load-presets-btn")) {
const layerId = parseInt(e.target.dataset.layer, 10);
console.log(`MilkDrop button clicked for layer ${layerId}`);
// handleMilk(layers[layerId]); // Will implement later
} else if (e.target.classList.contains("load-isf-btn")) {
const layerId = parseInt(e.target.dataset.layer, 10);
const layer = layers[layerId];
console.log(`ISF button clicked for layer ${layerId}`);
const advancedControls = document.querySelector(
`.layer[data-layer='${layer.id}'] .advanced-controls`
);
advancedControls.innerHTML = "";
const select = document.createElement("select");
select.innerHTML = `<option>Select ISF Shader</option>`;
// Add built-in shaders
Object.keys(isfShaders).forEach(file => {
select.innerHTML += `<option value="${file}">${file}</option>`;
});
// Add file-based shaders
const fileShaders = ['test-simple.fs', 'rainbow.fs', 'tapestryfract.fs', 'badtv.fs'];
fileShaders.forEach(file => {
select.innerHTML += `<option value="file:${file}">${file} (from file)</option>`;
});
select.addEventListener("change", async (e) => {
const value = e.target.value;
if (value) {
if (value.startsWith('file:')) {
// Load from file
const filename = value.replace('file:', '');
try {
const source = await loadShaderFile(filename);
await handleIsfFromSource(layer, source);
} catch (error) {
console.error('Error loading shader file:', error);
alert('Failed to load shader file: ' + error.message);
}
} else {
// Load built-in shader
const source = isfShaders[value];
await handleIsfFromSource(layer, source);
}
}
});
advancedControls.appendChild(select);
}
});
openOutputBtn.addEventListener("click", () => {
console.log('Output button clicked');
// Output window logic will go here
});
console.log('Layer event listeners set up successfully');
}
function startAnimationLoop() {
console.log('Starting animation loop...');
let frameCount = 0;
function animationLoop() {
frameCount++;
layers.forEach((layer) => {
if (layer.renderFunc) {
// Only log every 60 frames to avoid spam
if (frameCount % 60 === 0) {
console.log("Rendering layer in animationLoop:", layer.id, "Type:", layer.fileType);
}
layer.renderFunc();
}
if (layer.outputRenderer) {
// Handle different types of output renderers
if (typeof layer.outputRenderer === 'function') {
// Direct rendering function (fallback approach)
layer.outputRenderer();
} else if (layer.outputRenderer && layer.outputRenderer.type === 'isfManager') {
// ISF Manager handles this automatically, no action needed
}
}
});
requestAnimationFrame(animationLoop);
}
requestAnimationFrame(animationLoop);
console.log('Animation loop started');
}
// === ISF HANDLING FUNCTIONS ===
async function handleIsfFromSource(layer, source) {
console.log("handleIsfFromSource called for layer:", layer.id, "with source:", source.substring(0, 100));
// Check for manual test mode
if (source === "Manual Red Test") {
console.log("Using manual WebGL rendering fallback...");
handleManualShader(layer);
return;
}
// Check for special file loading option
if (source === "LOAD_FROM_FILE") {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.fs,.isf,.frag';
input.onchange = async (e) => {
const file = e.target.files[0];
if (file) {
try {
const fileContent = await file.text();
await handleIsfFromSource(layer, fileContent);
} catch (error) {
console.error('Error loading file:', error);
alert('Error loading shader file: ' + error.message);
}
}
};
input.click();
return;
}
// Check if ISF Manager is available
if (!isfManager) {
console.error("ISF Manager not initialized! Trying fallback...");
// Try simple WebGL fallback for built-in shaders
if (source.includes('gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0)')) {
handleSimpleRedShader(layer);
return;
} else if (source.includes('gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0)')) {
handleSimpleGreenShader(layer);
return;
}
alert("ISF Manager not available. Please wait for initialization.");
return;
}
const canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 150;
canvas.style.border = "2px solid #00ff00";
canvas.style.display = "block";
canvas.style.width = "200px";
canvas.style.height = "150px";
layer.element = canvas;
layer.fileType = "isf";
console.log("Canvas created with dimensions:", canvas.width, "x", canvas.height);
try {
console.log("Creating ISF renderer using ISF Manager...");
// Use the ISF Manager to create the renderer
const renderer = isfManager.createISFRenderer(layer, source, canvas);
console.log("ISF Renderer created successfully");
layer.renderer = renderer;
layer.shader = source;
layer.startTime = Date.now(); // For TIME uniform in output rendering
// The ISF Manager handles all rendering automatically,
// so we don't need a renderFunc for individual layers anymore
// The animation loop in ISF Manager will handle this
console.log("ISF rendering is now handled by ISF Manager");
// Parse ISF metadata and create controls
const metadata = parseISFMetadata(source);
if (metadata) {
const advancedControls = document.querySelector(
`.layer[data-layer='${layer.id}'] .advanced-controls`
);
createISFControls(layer, renderer, metadata, advancedControls);
}
renderLayer(layer);
console.log("ISF shader loaded successfully for layer", layer.id);
} catch (error) {
console.error("Error initializing ISF:", error);
console.error("Error stack:", error.stack);
alert("Failed to initialize ISF shader: " + error.message);
}
}
function handleSimpleRedShader(layer) {
console.log("Creating simple red shader fallback...");
const canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 150;
canvas.style.border = "2px solid red";
canvas.style.display = "block";
canvas.style.width = "200px";
canvas.style.height = "150px";
layer.element = canvas;
layer.fileType = "simple";
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, canvas.width, canvas.height);
renderLayer(layer);
console.log("Simple red shader created successfully!");
}
function handleSimpleGreenShader(layer) {
console.log("Creating simple green shader fallback...");
const canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 150;
canvas.style.border = "2px solid green";
canvas.style.display = "block";
canvas.style.width = "200px";
canvas.style.height = "150px";
layer.element = canvas;
layer.fileType = "simple";
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, canvas.width, canvas.height);
renderLayer(layer);
console.log("Simple green shader created successfully!");
}
function renderLayer(layer) {
console.log("Rendering layer:", layer.id, "with element:", layer.element);
const previewEl = document.querySelector(
`.layer[data-layer='${layer.id}'] .layer-preview`
);
console.log("Preview element found:", previewEl);
if (!previewEl) {
console.error("Preview element not found for layer", layer.id);
return;
}
previewEl.innerHTML = "";
if (layer.element) {
console.log("Adding element to preview:", layer.element.tagName, layer.element.width + "x" + layer.element.height);
previewEl.appendChild(layer.element);
console.log("Element added to DOM, preview container size:", previewEl.clientWidth + "x" + previewEl.clientHeight);
} else {
console.log("No element to render for layer", layer.id);
}
}
// Helper functions for ISF metadata parsing and controls
function parseISFMetadata(source) {
try {
// Extract JSON metadata from ISF source
const jsonMatch = source.match(/\/\*(\{[\s\S]*?\})\*\//);
if (jsonMatch) {
return JSON.parse(jsonMatch[1]);
}
return null;
} catch (error) {
console.error('Error parsing ISF metadata:', error);
return null;
}
}
function createISFControls(layer, renderer, metadata, container) {
console.log('createISFControls called for layer:', layer.id);
console.log('Metadata:', metadata);
console.log('Container:', container);
if (!metadata || !metadata.INPUTS) {
console.log('No metadata or inputs found');
return;
}
console.log('Found', metadata.INPUTS.length, 'inputs to create controls for');
const controlsDiv = document.createElement('div');
controlsDiv.innerHTML = '<h4>ISF Controls</h4>';
// Function to update both preview and output renderers
function updateParameter(paramName, value) {
console.log(`Updating parameter ${paramName} = ${value} for layer ${layer.id}`);
// Try using ISF Manager's centralized parameter setting first
if (isfManager && isfManager.setParameterForLayer) {
const success = isfManager.setParameterForLayer(layer.id, paramName, value);
if (success) {
console.log('Updated via ISF Manager setParameterForLayer');
} else {
console.log('ISF Manager setParameterForLayer found no renderers');
}
}
// Fallback: Update preview renderer directly (in case ISF Manager doesn't handle it)
if (renderer && renderer.setValue) {
renderer.setValue(paramName, value);
console.log('Updated preview renderer directly');
}
// Fallback: Update output renderer if it exists and wasn't handled by ISF Manager
if (layer.outputRenderer) {
console.log('Output renderer exists:', {
type: typeof layer.outputRenderer,
hasRenderer: !!layer.outputRenderer.renderer,
rendererType: layer.outputRenderer.type,
hasSetValue: !!(layer.outputRenderer.renderer && layer.outputRenderer.renderer.setValue)
});
if (typeof layer.outputRenderer === 'function' && layer.outputRenderer.renderer && layer.outputRenderer.renderer.setValue) {
// Direct rendering approach
layer.outputRenderer.renderer.setValue(paramName, value);
console.log('Updated output renderer (direct)');
} else if (layer.outputRenderer.renderer && layer.outputRenderer.renderer.setValue) {
// ISF Manager approach - but this should be handled by setParameterForLayer now
layer.outputRenderer.renderer.setValue(paramName, value);
console.log('Updated output renderer (ISF Manager fallback)');
} else {
console.log('Output renderer exists but cannot set parameters');
}
} else {
console.log('No output renderer available yet');
}
// Store parameter value on layer for when output window is created/recreated
if (!layer.parameters) {
layer.parameters = {};
}
layer.parameters[paramName] = value;
console.log('Stored parameter on layer');
}
metadata.INPUTS.forEach(input => {
const controlDiv = document.createElement('div');
controlDiv.className = 'isf-control';
const label = document.createElement('label');
label.textContent = input.NAME + ': ';
controlDiv.appendChild(label);
let control;
switch (input.TYPE) {
case 'float':
control = document.createElement('input');
control.type = 'range';
control.min = input.MIN || 0;
control.max = input.MAX || 1;
control.step = 0.01;
control.value = input.DEFAULT || 0.5;
// Initialize the parameter value
console.log('Initializing parameter control for:', input.NAME, 'with value:', parseFloat(control.value));
updateParameter(input.NAME, parseFloat(control.value));
const valueDisplay = document.createElement('span');
valueDisplay.textContent = control.value;
control.addEventListener('input', (e) => {
const value = parseFloat(e.target.value);
valueDisplay.textContent = value.toFixed(2);
console.log('Parameter control moved:', input.NAME, '=', value);
updateParameter(input.NAME, value);
});
console.log('Added event listener for parameter:', input.NAME);
controlDiv.appendChild(control);
controlDiv.appendChild(valueDisplay);
break;
case 'bool':
control = document.createElement('input');
control.type = 'checkbox';
control.checked = input.DEFAULT || false;
// Initialize the parameter value
updateParameter(input.NAME, control.checked);
control.addEventListener('change', (e) => {
updateParameter(input.NAME, e.target.checked);
});
controlDiv.appendChild(control);
break;
case 'color':
control = document.createElement('input');
control.type = 'color';
control.value = input.DEFAULT || '#ffffff';
// Initialize the parameter value
const hex = control.value;
const r = parseInt(hex.slice(1, 3), 16) / 255;
const g = parseInt(hex.slice(3, 5), 16) / 255;
const b = parseInt(hex.slice(5, 7), 16) / 255;
updateParameter(input.NAME, [r, g, b, 1.0]);
control.addEventListener('input', (e) => {
// Convert hex to RGB array
const hex = e.target.value;
const r = parseInt(hex.slice(1, 3), 16) / 255;
const g = parseInt(hex.slice(3, 5), 16) / 255;
const b = parseInt(hex.slice(5, 7), 16) / 255;
updateParameter(input.NAME, [r, g, b, 1.0]);
});
controlDiv.appendChild(control);
break;
}
controlsDiv.appendChild(controlDiv);
});
container.appendChild(controlsDiv);
}
function handleManualShader(layer) {
console.log("Creating manual WebGL shader...");
const canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 150;
canvas.style.border = "3px solid lime";
canvas.style.display = "block";
canvas.style.width = "200px";
canvas.style.height = "150px";
layer.element = canvas;
layer.fileType = "manual";
const gl = canvas.getContext("webgl");
if (!gl) {
console.error("WebGL not supported.");
return;
}
// Create simple vertex shader
const vertexShaderSource = `
attribute vec2 a_position;
void main() {
gl_Position = vec4(a_position, 0.0, 1.0);
}
`;
// Create simple fragment shader that just outputs red
const fragmentShaderSource = `
precision mediump float;
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`;
// Compile shaders
function createShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error('Shader compile error:', gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
// Create program
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
console.error('Program link error:', gl.getProgramInfoLog(program));
return;
}
// Create vertex buffer for full screen quad
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positions = [
-1, -1,
1, -1,
-1, 1,
1, 1,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
// Create render function
layer.renderFunc = () => {
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(program);
const positionLocation = gl.getAttribLocation(program, "a_position");
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.enableVertexAttribArray(positionLocation);
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
};
renderLayer(layer);
console.log("Manual WebGL shader created successfully!");
}
// Initialize main app components immediately
initializeMainApp();
// Then try to initialize ISF (non-blocking)
setTimeout(() => {
console.log("Checking ISF library availability...");
initializeISF();
}, 100);
function initializeISF() {
// Check for different possible ISF library exports
const isfAvailable = (
typeof ISFRenderer !== 'undefined' ||
typeof window.ISFRenderer !== 'undefined' ||
typeof window.interactiveShaderFormat !== 'undefined' ||
(window.InteractiveShaderFormat && window.InteractiveShaderFormat.Renderer)
);
if (isfAvailable) {
// Determine which ISF API is available
if (typeof ISFRenderer !== 'undefined') {
window.ISFRenderer = ISFRenderer;
} else if (typeof window.ISFRenderer !== 'undefined') {
// Already available
} else if (typeof window.interactiveShaderFormat !== 'undefined') {
window.ISFRenderer = window.interactiveShaderFormat.Renderer;
} else if (window.InteractiveShaderFormat && window.InteractiveShaderFormat.Renderer) {
window.ISFRenderer = window.InteractiveShaderFormat.Renderer;
}
console.log("ISFRenderer loaded successfully:", window.ISFRenderer);
// Use EnhancedISFManager if available, otherwise regular ISFManager
const ManagerClass = window.EnhancedISFManager || window.ISFManager || ISFManager;
isfManager = new ManagerClass();
isfManager.startAnimationLoop();
console.log("ISF Manager initialized with:", ManagerClass.name);
} else {
console.error("ISFRenderer not available. Trying fallback...");
console.log("Available globals:", {
ISFRenderer: typeof ISFRenderer,
'window.ISFRenderer': typeof window.ISFRenderer,
'window.interactiveShaderFormat': typeof window.interactiveShaderFormat,
'window.InteractiveShaderFormat': typeof window.InteractiveShaderFormat,
'window.ISFManager': typeof window.ISFManager,
'window.EnhancedISFManager': typeof window.EnhancedISFManager
});
// Try to initialize with fallback anyway
if (typeof window.EnhancedISFManager !== 'undefined') {
console.log('Initializing with EnhancedISFManager (includes fallback)');
isfManager = new window.EnhancedISFManager();
isfManager.startAnimationLoop();
console.log('Fallback ISF Manager initialized');
}
}
}
// Try multiple times to initialize ISF
let isfInitAttempts = 0;
const maxISFAttempts = 10;
function tryInitializeISF() {
isfInitAttempts++;
console.log(`ISF initialization attempt ${isfInitAttempts}/${maxISFAttempts}`);
if (isfManager) {
console.log("ISF already initialized");
return;
}
initializeISF();
if (!isfManager && isfInitAttempts < maxISFAttempts) {
setTimeout(tryInitializeISF, 1000);
}
}
// Start trying to initialize
tryInitializeISF();
function initializeMainApp() {
console.log("Setting up main app UI...");
// Initialize core app functionality that doesn't depend on ISF
initializeAudioControls();
initializeLayers();
initPresets(); // Initialize MilkDrop presets
startAnimationLoop();
console.log("Main app initialized successfully");
}
function initializeAudioControls() {
// Global audio controls
const audioControls = document.createElement("div");
audioControls.innerHTML = `
<label>Audio:</label>
<input type="file" id="audio-file-input" accept="audio/*">
<button id="mic-input-btn">Use Mic</button>
`;
document.getElementById("main-controls").appendChild(audioControls);
const audioFileInput = document.getElementById("audio-file-input");
audioFileInput.addEventListener("change", (e) => {
const file = e.target.files[0];
if (file) {
initAudio();
const audioUrl = URL.createObjectURL(file);
const audio = new Audio(audioUrl);
audio.crossOrigin = "anonymous";
if (sourceNode) {
sourceNode.disconnect();
}
sourceNode = audioContext.createMediaElementSource(audio);
connectAudio(sourceNode);
const playPromise = audio.play();
if (playPromise !== undefined) {
playPromise.catch((error) => {
if (error.name === "AbortError") {
console.log("Audio play() request was aborted.");
} else {
console.error("Audio play() failed:", error);
}
});
}
}
});
const micInputBtn = document.getElementById("mic-input-btn");
micInputBtn.addEventListener("click", () => {
initAudio();
navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
if (sourceNode) {
sourceNode.disconnect();
}
sourceNode = audioContext.createMediaStreamSource(stream);
connectAudio(sourceNode);
});
});
}
function initializeLayers() {
console.log('Initializing layers...');
console.log('layersContainer element:', layersContainer);
console.log('numLayers:', numLayers);
for (let i = 0; i < numLayers; i++) {
console.log(`Creating layer ${i + 1}...`);
const layer = {
id: i,
opacity: 1,
file: null,
fileType: null,
element: null,
visualizer: null,
outputVisualizer: null,
renderer: null,
renderFunc: null,
presets: [],
presetKeys: [],
currentPresetIndex: -1,
};
layers.push(layer);
const layerEl = document.createElement("div");
layerEl.classList.add("layer");
layerEl.setAttribute("data-layer", i);
layerEl.innerHTML = `
<h3>Layer ${i + 1}</h3>
<div class="layer-controls">
<label>Opacity:</label>
<input type="range" min="0" max="1" value="1" step="0.01" class="opacity-slider" data-layer="${i}">
<input type="file" class="file-input" data-layer="${i}" accept=".gif,.isf,.fs,.frag,.mp4,.json">
<button class="load-presets-btn" data-layer="${i}">Load MilkDrop Presets</button>
<button class="load-isf-btn" data-layer="${i}">Load ISF</button>
</div>
<div class="layer-preview"></div>
<div class="advanced-controls"></div>
`;
console.log(`Appending layer ${i + 1} element to container:`, layerEl);
layersContainer.appendChild(layerEl);
console.log(`Layer ${i + 1} appended successfully`);
}
console.log('All layers created successfully!');
console.log('Total layers in array:', layers.length);
// Set up layer event listeners
setupLayerEventListeners();
}
function setupLayerEventListeners() {
layersContainer.addEventListener("input", (e) => {
if (e.target.classList.contains("opacity-slider")) {
const layerId = parseInt(e.target.dataset.layer, 10);
layers[layerId].opacity = parseFloat(e.target.value);
renderOutput();
}
});
layersContainer.addEventListener("change", (e) => {
if (e.target.classList.contains("file-input")) {
const layerId = parseInt(e.target.dataset.layer, 10);
const file = e.target.files[0];
if (file) {
handleFile(layerId, file);
}
}
});
layersContainer.addEventListener("click", (e) => {
if (e.target.classList.contains("load-presets-btn")) {
const layerId = parseInt(e.target.dataset.layer, 10);
handleMilk(layers[layerId]);
} else if (e.target.classList.contains("load-isf-btn")) {
const layerId = parseInt(e.target.dataset.layer, 10);
const layer = layers[layerId];
const advancedControls = document.querySelector(
`.layer[data-layer='${layer.id}'] .advanced-controls`
);
advancedControls.innerHTML = "";
const select = document.createElement("select");
select.innerHTML = `<option>Select ISF Shader</option>`;
// Add built-in shaders
Object.keys(isfShaders).forEach(file => {
select.innerHTML += `<option value="${file}">${file}</option>`;
});
// Add file-based shaders
const fileShaders = ['test-simple.fs', 'rainbow.fs', 'tapestryfract.fs', 'badtv.fs'];
fileShaders.forEach(file => {
select.innerHTML += `<option value="file:${file}">${file} (from file)</option>`;
});
select.addEventListener("change", async (e) => {
const value = e.target.value;
if (value) {
if (value.startsWith('file:')) {
// Load from file
const filename = value.replace('file:', '');
try {
const source = await loadShaderFile(filename);
await handleIsfFromSource(layer, source);
} catch (error) {
console.error('Error loading shader file:', error);
alert('Failed to load shader file: ' + error.message);
}
} else {
// Load built-in shader
const source = isfShaders[value];
await handleIsfFromSource(layer, source);
}
}
});
advancedControls.appendChild(select);
}
});
openOutputBtn.addEventListener("click", () => {
if (outputWindow && !outputWindow.closed) {
outputWindow.focus();
return;
}