-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
11467 lines (9718 loc) Β· 412 KB
/
Copy pathscript.js
File metadata and controls
11467 lines (9718 loc) Β· 412 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
/*
MIT License
Copyright (c) 2017 Pavel Dobryakov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
// Mobile promo section - removed for modern UI
// Simulation section
let canvas = document.getElementById('fluidCanvas') || document.getElementsByTagName('canvas')[0];
// Mobile debugging for canvas initialization
if (isMobile()) {
console.log('π MOBILE DEBUG: Canvas initialization at script load');
console.log('π Canvas found:', !!canvas);
console.log('π Canvas ID:', canvas ? canvas.id : 'none');
console.log('π Total canvas elements:', document.getElementsByTagName('canvas').length);
console.log('π All canvas IDs:', Array.from(document.getElementsByTagName('canvas')).map(c => c.id));
}
// Ensure we have a canvas before proceeding
if (canvas) {
resizeCanvas();
} else if (isMobile()) {
console.log('π MOBILE DEBUG: No canvas found at script load - will retry after DOM ready');
}
// Slider handle padding to prevent clipping at edges
const SLIDER_HANDLE_PADDING = 0.035; // 3.5% padding on each side
// Device-specific configuration presets
const desktopConfig = {
SIM_RESOLUTION: 128, // High-quality simulation for desktop
DYE_RESOLUTION: 1024, // High quality
CAPTURE_RESOLUTION: 512,
DENSITY_DISSIPATION: 1.0, // Increased fade rate
VELOCITY_DISSIPATION: 0.6,
PRESSURE: 0.37,
PRESSURE_ITERATIONS: 20,
CURL: 4, // Swirl intensity
SPLAT_RADIUS: 0.3, // Increased brush size
SPLAT_FORCE: 6000,
SHADING: true, // Enable 3D lighting effects for desktop
COLORFUL: false,
COLOR_UPDATE_SPEED: 10,
PAUSED: false,
BACK_COLOR: { r: 0, g: 0, b: 0 },
STATIC_COLOR: { r: 0, g: 0.831, b: 1 },
TRANSPARENT: false,
BLOOM: true, // Enable bloom for desktop
BLOOM_ITERATIONS: 8,
BLOOM_RESOLUTION: 256,
BLOOM_INTENSITY: 0.4,
BLOOM_THRESHOLD: 0.6,
BLOOM_SOFT_KNEE: 0.7,
SUNRAYS: true, // Enable sunrays for desktop
SUNRAYS_RESOLUTION: 196,
SUNRAYS_WEIGHT: 0.4,
VELOCITY_DRAWING: false, // Velocity-based drawing intensity
FORCE_CLICK: true // Click burst effects (MOUSE ONLY - never affects OSC)
};
const mobileConfig = {
SIM_RESOLUTION: 64, // Lower resolution for mobile
DYE_RESOLUTION: 512, // Reduced quality for performance
CAPTURE_RESOLUTION: 512,
DENSITY_DISSIPATION: 1.0, // Increased fade rate
VELOCITY_DISSIPATION: 0.6,
PRESSURE: 0.37,
PRESSURE_ITERATIONS: 20,
CURL: 4, // Swirl intensity
SPLAT_RADIUS: 0.3, // Increased brush size
SPLAT_FORCE: 6000,
SHADING: false, // Disable 3D lighting effects for mobile
COLORFUL: false,
COLOR_UPDATE_SPEED: 10,
PAUSED: false,
BACK_COLOR: { r: 0, g: 0, b: 0 },
STATIC_COLOR: { r: 0, g: 0.831, b: 1 },
TRANSPARENT: false,
BLOOM: false, // Disable bloom for mobile
BLOOM_ITERATIONS: 8,
BLOOM_RESOLUTION: 128, // Lower bloom resolution for mobile
BLOOM_INTENSITY: 0.4,
BLOOM_THRESHOLD: 0.6,
BLOOM_SOFT_KNEE: 0.7,
SUNRAYS: false, // Disable sunrays for mobile
SUNRAYS_RESOLUTION: 96, // Lower sunrays resolution for mobile
SUNRAYS_WEIGHT: 0.4,
VELOCITY_DRAWING: false, // Velocity-based drawing intensity
FORCE_CLICK: true // Click burst effects (MOUSE ONLY - never affects OSC)
};
// Initialize config based on device type
// Add common parameters to both configs
const commonParams = {
// StreamDiffusion parameters
INFERENCE_STEPS: 50,
SEED: 42,
CONTROLNET_POSE_SCALE: 0.65, // Balanced preset default
CONTROLNET_HED_SCALE: 0.41, // Balanced preset default
CONTROLNET_CANNY_SCALE: 0.00, // Balanced preset default
CONTROLNET_DEPTH_SCALE: 0.21, // Balanced preset default
CONTROLNET_COLOR_SCALE: 0.26, // Balanced preset default
GUIDANCE_SCALE: 7.5,
DELTA: 0.5,
// Denoise controls
DENOISE_X: 3,
DENOISE_Y: 6,
DENOISE_Z: 6,
// Animation Parameters
ANIMATE: true,
LIVELINESS: 0.62,
CHAOS: 0.73,
BREATHING: 0.5,
COLOR_LIFE: 0.22,
ANIMATION_INTERVAL: 0.1,
// Media Parameters
FLUID_CAMERA_SCALE: 1.0, // Fluid background camera scale
FLUID_MEDIA_SCALE: 1.0, // Fluid background media scale
MEDIA_SCALE: 1.0, // Media overlay scale
BACKGROUND_IMAGE_SCALE: 1.0, // Background image scale
// Audio Parameters
AUDIO_REACTIVITY: 2.0,
AUDIO_DELAY: 0,
AUDIO_OPACITY: 0.8,
AUDIO_COLORFUL: 0.3,
AUDIO_EDGE_SOFTNESS: 0.25,
// Debug Parameters
DEBUG_MODE: false,
// Telegram Parameters
TELEGRAM_RECEIVE: true,
TELEGRAM_WAITLIST_INTERVAL: 1,
// OSC Multi-splat channels REMOVED - replaced by OSC velocity drawing system
HIDE_CURSOR: false,
};
// Initialize config based on device type with common parameters
let config = {
...(isMobile() ? mobileConfig : desktopConfig),
...commonParams
};
// Global State Variables (declared early to avoid initialization order issues)
let streamState = {
isStreaming: false,
streamId: null,
playbackId: null,
whipUrl: null,
peerConnection: null,
mediaStream: null,
popupWindow: null,
popupCheckInterval: null,
promptUpdateInterval: null,
lastParameterUpdate: 0,
isUpdatingParameters: false
};
// Simple Camera System
let cameraState = {
active: false,
stream: null,
video: null,
canvas: null,
ctx: null,
animationId: null
};
// Media System
let mediaState = {
active: false,
canvas: null,
ctx: null,
animationId: null,
mediaElement: null, // Could be image, video, etc.
mediaType: null, // 'image' or 'video'
mediaName: null, // filename
scale: 1.0 // media scale factor (will be synced with config.MEDIA_SCALE)
};
// Fluid Background Media System
let fluidBackgroundMedia = {
loaded: false,
texture: null,
width: 0,
height: 0,
type: null, // 'image' or 'video'
element: null, // img or video element
scale: 1.0
};
// Fluid Background Camera System (separate from main camera input mode)
let fluidBackgroundCamera = {
active: false,
stream: null,
video: null,
texture: null,
width: 0,
height: 0,
scale: 1.0
};
// Audio Blob System
let audioBlobState = {
active: false,
audioContext: null,
analyser: null,
microphone: null,
dataArray: null,
frequencyData: null,
canvas: null,
gl: null,
animationId: null,
// Visual properties
color: { r: 0, g: 0.831, b: 1 }, // Default cyan
baseColor: { r: 0, g: 0.831, b: 1 }, // Store original color for cycling
// Control properties
reactivity: 2.0, // 0.1-3.0 range - How much audio affects the blob
delay: 0, // 0-500ms range - Audio delay in milliseconds
opacity: 0.8, // 0-1 range - Blob opacity
colorful: 0.3, // 0-1 range - Color cycling intensity
edgeSoftness: 0.25, // 0-1 range - Blob edge softness
// Audio processing nodes
delayNode: null, // DelayNode for audio delay
previewGain: null, // GainNode for audio preview (muted by default)
// Shader program
shaderProgram: null,
uniforms: {}
};
// Idle Animation System
let idleAnimationEnabled = true;
let lastActivityTime = Date.now();
let idleAnimationTimer = null;
const IDLE_TIMEOUT = 5000; // 5 seconds
const IDLE_SPARK_MIN_INTERVAL = 1500; // 1.5 seconds
const IDLE_SPARK_MAX_INTERVAL = 4000; // 4 seconds
function pointerPrototype () {
this.id = -1;
this.texcoordX = 0;
this.texcoordY = 0;
this.prevTexcoordX = 0;
this.prevTexcoordY = 0;
this.deltaX = 0;
this.deltaY = 0;
this.down = false;
this.moved = false;
this.color = [30, 0, 300];
}
let pointers = [];
let splatStack = [];
pointers.push(new pointerPrototype());
const { gl, ext } = getWebGLContext(canvas);
if (isMobile()) {
config.DYE_RESOLUTION = 512;
}
if (!ext.supportLinearFiltering) {
config.DYE_RESOLUTION = 512;
config.SHADING = false;
config.BLOOM = false;
config.SUNRAYS = false;
}
// Wait for DOM to be ready before initializing UI
document.addEventListener('DOMContentLoaded', () => {
startGUI();
initializeCursorIndicator();
// Start idle animation immediately on page load
setTimeout(() => {
if (Date.now() - lastActivityTime >= IDLE_TIMEOUT) {
startIdleAnimation();
}
}, IDLE_TIMEOUT);
});
function getWebGLContext (canvas) {
const params = { alpha: true, depth: false, stencil: false, antialias: false, preserveDrawingBuffer: false };
let gl = canvas.getContext('webgl2', params);
const isWebGL2 = !!gl;
if (!isWebGL2)
gl = canvas.getContext('webgl', params) || canvas.getContext('experimental-webgl', params);
let halfFloat;
let supportLinearFiltering;
if (isWebGL2) {
gl.getExtension('EXT_color_buffer_float');
supportLinearFiltering = gl.getExtension('OES_texture_float_linear');
} else {
halfFloat = gl.getExtension('OES_texture_half_float');
supportLinearFiltering = gl.getExtension('OES_texture_half_float_linear');
}
gl.clearColor(0.0, 0.0, 0.0, 1.0);
const halfFloatTexType = isWebGL2 ? gl.HALF_FLOAT : halfFloat.HALF_FLOAT_OES;
let formatRGBA;
let formatRG;
let formatR;
if (isWebGL2)
{
formatRGBA = getSupportedFormat(gl, gl.RGBA16F, gl.RGBA, halfFloatTexType);
formatRG = getSupportedFormat(gl, gl.RG16F, gl.RG, halfFloatTexType);
formatR = getSupportedFormat(gl, gl.R16F, gl.RED, halfFloatTexType);
}
else
{
formatRGBA = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType);
formatRG = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType);
formatR = getSupportedFormat(gl, gl.RGBA, gl.RGBA, halfFloatTexType);
}
ga('send', 'event', isWebGL2 ? 'webgl2' : 'webgl', formatRGBA == null ? 'not supported' : 'supported');
return {
gl,
ext: {
formatRGBA,
formatRG,
formatR,
halfFloatTexType,
supportLinearFiltering
}
};
}
function getSupportedFormat (gl, internalFormat, format, type)
{
if (!supportRenderTextureFormat(gl, internalFormat, format, type))
{
switch (internalFormat)
{
case gl.R16F:
return getSupportedFormat(gl, gl.RG16F, gl.RG, type);
case gl.RG16F:
return getSupportedFormat(gl, gl.RGBA16F, gl.RGBA, type);
default:
return null;
}
}
return {
internalFormat,
format
}
}
function supportRenderTextureFormat (gl, internalFormat, format, type) {
let texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, 4, 4, 0, format, type, null);
let fbo = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
return status == gl.FRAMEBUFFER_COMPLETE;
}
// Modern UI Control System - No external dependencies
function startGUI () {
// Core quality settings - hidden, fixed at high quality
// DYE_RESOLUTION is fixed at 1024 (high quality) for optimal visuals
// SIM_RESOLUTION is fixed at 256 for optimal performance
// SHADING is always enabled for 3D lighting effects
// Initialize modern UI handlers
initializeModernUI();
// Mobile performance optimizations
if (isMobile()) {
config.DYE_RESOLUTION = 512; // Default to medium quality on mobile
config.BLOOM_ITERATIONS = 4; // Reduce bloom iterations for mobile
}
}
// Modern UI Event Handlers
function initializeModernUI() {
// Add slider drag functionality
addSliderDragHandlers();
// Initialize toggle states
updateToggleStates();
// Initialize slider positions
updateSliderPositions();
}
function addSliderDragHandlers() {
const sliders = ['density', 'velocity', 'pressure', 'vorticity', 'splat', 'bloomIntensity', 'sunray', 'denoiseX', 'denoiseY', 'denoiseZ', 'inferenceSteps', 'seed', 'controlnetPose', 'controlnetHed', 'controlnetCanny', 'controlnetDepth', 'controlnetColor', 'guidanceScale', 'delta', 'animationInterval', 'chaos', 'breathing', 'colorLife', 'backgroundImageScale', 'mediaScale', 'fluidMediaScale', 'fluidCameraScale', 'streamOpacity', 'audioReactivity', 'audioDelay', 'audioOpacity', 'audioColorful', 'audioEdgeSoftness', 'telegramWaitlistInterval'];
sliders.forEach(slider => {
const handle = document.getElementById(slider + 'Handle');
const container = document.getElementById(slider + 'Fill');
const sliderContainer = container ? container.parentElement : null;
if (handle && container && sliderContainer) {
let isDragging = false;
handle.addEventListener('mousedown', (e) => {
isDragging = true;
e.preventDefault();
// Immediately update slider position on mouse down
updateSliderFromMouse(e, slider);
});
document.addEventListener('mousemove', (e) => {
if (isDragging) {
updateSliderFromMouse(e, slider);
}
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
// Touch support for handle
handle.addEventListener('touchstart', (e) => {
isDragging = true;
e.preventDefault();
e.stopPropagation(); // Prevent event bubbling
// Immediately update slider position on touch start
updateSliderFromTouch(e, slider);
}, { passive: false }); // Need preventDefault for slider
// Global touch move and end handlers
document.addEventListener('touchmove', (e) => {
if (isDragging) {
e.preventDefault(); // Prevent scrolling while dragging
updateSliderFromTouch(e, slider);
}
}, { passive: false }); // Need preventDefault to stop scrolling
document.addEventListener('touchend', (e) => {
if (isDragging) {
isDragging = false;
e.preventDefault();
}
}, { passive: false });
// Add immediate response on container click/touch
sliderContainer.addEventListener('mousedown', (e) => {
if (e.target === sliderContainer || e.target === container) {
isDragging = true;
e.preventDefault();
e.stopPropagation();
updateSliderFromMouse(e, slider);
}
});
sliderContainer.addEventListener('touchstart', (e) => {
if (e.target === sliderContainer || e.target === container) {
isDragging = true;
e.preventDefault();
e.stopPropagation(); // Prevent event bubbling
updateSliderFromTouch(e, slider);
}
}, { passive: false }); // Need preventDefault for slider
}
});
}
function updateSliderFromMouse(e, sliderName) {
const fillElement = document.getElementById(sliderName + 'Fill');
if (!fillElement) return;
const container = fillElement.parentElement;
const rect = container.getBoundingClientRect();
const x = e.clientX - rect.left;
const rawPercentage = Math.max(0, Math.min(1, x / rect.width));
// Convert visual percentage back to actual percentage, accounting for handle padding
const percentage = Math.max(0, Math.min(1, (rawPercentage - SLIDER_HANDLE_PADDING) / (1 - 2 * SLIDER_HANDLE_PADDING)));
updateSliderValue(sliderName, percentage);
}
function updateSliderFromTouch(e, sliderName) {
const fillElement = document.getElementById(sliderName + 'Fill');
if (!fillElement) return;
const container = fillElement.parentElement;
const rect = container.getBoundingClientRect();
const x = e.touches[0].clientX - rect.left;
const rawPercentage = Math.max(0, Math.min(1, x / rect.width));
// Convert visual percentage back to actual percentage, accounting for handle padding
const percentage = Math.max(0, Math.min(1, (rawPercentage - SLIDER_HANDLE_PADDING) / (1 - 2 * SLIDER_HANDLE_PADDING)));
updateSliderValue(sliderName, percentage);
}
function handleSliderClick(event, sliderName, min, max) {
if (isMobile()) {
console.log('π MOBILE DEBUG: Slider click for', sliderName, 'event type:', event.type);
console.log('π Event target:', event.target.className, event.currentTarget.className);
}
event.stopPropagation(); // Prevent event bubbling
event.preventDefault(); // Prevent default behavior
const rect = event.currentTarget.getBoundingClientRect();
let x;
// Handle both mouse and touch events
if (event.touches && event.touches.length > 0) {
x = event.touches[0].clientX - rect.left;
} else if (event.changedTouches && event.changedTouches.length > 0) {
x = event.changedTouches[0].clientX - rect.left;
} else {
x = event.clientX - rect.left;
}
const rawPercentage = Math.max(0, Math.min(1, x / rect.width));
// Convert visual percentage back to actual percentage, accounting for handle padding
const percentage = Math.max(0, Math.min(1, (rawPercentage - SLIDER_HANDLE_PADDING) / (1 - 2 * SLIDER_HANDLE_PADDING)));
updateSliderValue(sliderName, percentage);
}
function updateSliderValue(sliderName, percentage, skipSave = false, updateInput = true) {
// Ensure percentage is between 0 and 1
percentage = Math.min(1, Math.max(0, percentage));
const sliderMap = {
'density': { min: 0, max: 4, prop: 'DENSITY_DISSIPATION', decimals: 2 },
'velocity': { min: 0, max: 4, prop: 'VELOCITY_DISSIPATION', decimals: 2 },
'pressure': { min: 0, max: 1, prop: 'PRESSURE', decimals: 2 },
'vorticity': { min: 0, max: 50, prop: 'CURL', decimals: 0 },
'splat': { min: 0.01, max: 1, prop: 'SPLAT_RADIUS', decimals: 2 },
'bloomIntensity': { min: 0.1, max: 2, prop: 'BLOOM_INTENSITY', decimals: 2 },
'sunray': { min: 0.3, max: 1, prop: 'SUNRAYS_WEIGHT', decimals: 2 },
'denoiseX': { min: 0, max: 45, prop: 'DENOISE_X', decimals: 0 },
'denoiseY': { min: 0, max: 45, prop: 'DENOISE_Y', decimals: 0 },
'denoiseZ': { min: 0, max: 45, prop: 'DENOISE_Z', decimals: 0 },
'inferenceSteps': { min: 1, max: 100, prop: 'INFERENCE_STEPS', decimals: 0 },
'seed': { min: 0, max: 1000, prop: 'SEED', decimals: 0 },
'controlnetPose': { min: 0, max: 1, prop: 'CONTROLNET_POSE_SCALE', decimals: 2 },
'controlnetHed': { min: 0, max: 1, prop: 'CONTROLNET_HED_SCALE', decimals: 2 },
'controlnetCanny': { min: 0, max: 1, prop: 'CONTROLNET_CANNY_SCALE', decimals: 2 },
'controlnetDepth': { min: 0, max: 1, prop: 'CONTROLNET_DEPTH_SCALE', decimals: 2 },
'controlnetColor': { min: 0, max: 1, prop: 'CONTROLNET_COLOR_SCALE', decimals: 2 },
'guidanceScale': { min: 1, max: 20, prop: 'GUIDANCE_SCALE', decimals: 1 },
'delta': { min: 0, max: 1, prop: 'DELTA', decimals: 2 },
'liveliness': { min: 0, max: 1, prop: 'LIVELINESS', decimals: 2 },
'chaos': { min: 0, max: 1, prop: 'CHAOS', decimals: 2 },
'breathing': { min: 0, max: 1, prop: 'BREATHING', decimals: 2 },
'colorLife': { min: 0, max: 1, prop: 'COLOR_LIFE', decimals: 2 },
'animationInterval': { min: 0, max: 1, prop: 'ANIMATION_INTERVAL', decimals: 2 },
'backgroundImageScale': { min: 0.1, max: 2.0, prop: 'BACKGROUND_IMAGE_SCALE', decimals: 2 },
'mediaScale': { min: 0.1, max: 2.0, prop: 'MEDIA_SCALE', decimals: 2, handler: updateMediaScale },
'fluidMediaScale': { min: 0.1, max: 2.0, prop: 'FLUID_MEDIA_SCALE', decimals: 2, handler: updateFluidMediaScale },
'fluidCameraScale': { min: 0.1, max: 2.0, prop: 'FLUID_CAMERA_SCALE', decimals: 2, handler: updateFluidCameraScale },
'tIndexList': { min: 0, max: 50, prop: 'T_INDEX_LIST', decimals: 0, isArray: true },
'audioReactivity': { min: 0.1, max: 3.0, prop: 'AUDIO_REACTIVITY', decimals: 1, handler: updateAudioReactivity },
'audioDelay': { min: 0, max: 500, prop: 'AUDIO_DELAY', decimals: 0, handler: updateAudioDelay },
'audioOpacity': { min: 0, max: 1, prop: 'AUDIO_OPACITY', decimals: 2, handler: updateAudioOpacity },
'audioColorful': { min: 0, max: 1, prop: 'AUDIO_COLORFUL', decimals: 1, handler: updateAudioColorful },
'audioEdgeSoftness': { min: 0, max: 1, prop: 'AUDIO_EDGE_SOFTNESS', decimals: 2, handler: updateAudioEdgeSoftness },
'streamOpacity': { min: 0, max: 1, prop: 'STREAM_OPACITY', decimals: 2, handler: updateStreamOpacity },
'telegramWaitlistInterval': { min: 1, max: 30, prop: 'TELEGRAM_WAITLIST_INTERVAL', decimals: 0, handler: updateTelegramWaitlistInterval }
};
const slider = sliderMap[sliderName];
if (!slider) return;
const value = slider.min + (slider.max - slider.min) * percentage;
// Handle special array case for T_INDEX_LIST
if (slider.isArray && slider.prop === 'T_INDEX_LIST') {
// Generate array based on slider value (middle index)
const middleIndex = Math.round(value);
const step = Math.max(1, Math.floor(middleIndex / 3));
config[slider.prop] = [0, middleIndex, Math.min(middleIndex * 2, 50)];
} else {
config[slider.prop] = value;
}
// Call custom handler if defined (for audio controls)
if (slider.handler && typeof slider.handler === 'function') {
slider.handler(value);
}
// Special handling for background media scale
if (sliderName === 'backgroundImageScale' && backgroundMedia.loaded) {
if (backgroundMedia.type === 'image' && backgroundMedia.originalDataURL) {
// Regenerate the entire image with the new scale
loadBackgroundImage(backgroundMedia.originalDataURL);
}
// For videos, scaling is handled in the shader via uniforms - no action needed here
}
// Update UI
const fill = document.getElementById(sliderName + 'Fill');
const valueDisplay = document.getElementById(sliderName + 'Value');
if (fill) {
// Convert percentage (0-1) to percentage display (0-100) and adjust for handle padding
const displayPercentage = SLIDER_HANDLE_PADDING * 100 + (percentage * (100 - 2 * SLIDER_HANDLE_PADDING * 100));
fill.style.width = displayPercentage + '%';
}
if (valueDisplay && updateInput) {
if (slider.isArray && slider.prop === 'T_INDEX_LIST') {
valueDisplay.value = '[' + config[slider.prop].join(',') + ']';
} else {
valueDisplay.value = value.toFixed(slider.decimals);
}
}
// Save to localStorage only if not loading from storage
if (!skipSave) {
saveConfig();
}
}
function updateSliderPositions() {
const sliderMap = {
'density': { prop: 'DENSITY_DISSIPATION', min: 0, max: 4 },
'velocity': { prop: 'VELOCITY_DISSIPATION', min: 0, max: 4 },
'pressure': { prop: 'PRESSURE', min: 0, max: 1 },
'vorticity': { prop: 'CURL', min: 0, max: 50 },
'splat': { prop: 'SPLAT_RADIUS', min: 0.01, max: 1 },
'bloomIntensity': { prop: 'BLOOM_INTENSITY', min: 0.1, max: 2 },
'sunray': { prop: 'SUNRAYS_WEIGHT', min: 0.3, max: 1 },
'denoiseX': { prop: 'DENOISE_X', min: 0, max: 45 },
'denoiseY': { prop: 'DENOISE_Y', min: 0, max: 45 },
'denoiseZ': { prop: 'DENOISE_Z', min: 0, max: 45 },
'inferenceSteps': { prop: 'INFERENCE_STEPS', min: 1, max: 100 },
'seed': { prop: 'SEED', min: 0, max: 1000 },
'controlnetPose': { prop: 'CONTROLNET_POSE_SCALE', min: 0, max: 1 },
'controlnetHed': { prop: 'CONTROLNET_HED_SCALE', min: 0, max: 1 },
'controlnetCanny': { prop: 'CONTROLNET_CANNY_SCALE', min: 0, max: 1 },
'controlnetDepth': { prop: 'CONTROLNET_DEPTH_SCALE', min: 0, max: 1 },
'controlnetColor': { prop: 'CONTROLNET_COLOR_SCALE', min: 0, max: 1 },
'guidanceScale': { prop: 'GUIDANCE_SCALE', min: 1, max: 20 },
'delta': { prop: 'DELTA', min: 0, max: 1 },
'liveliness': { prop: 'LIVELINESS', min: 0, max: 1 },
'chaos': { prop: 'CHAOS', min: 0, max: 1 },
'breathing': { prop: 'BREATHING', min: 0, max: 1 },
'colorLife': { prop: 'COLOR_LIFE', min: 0, max: 1 },
'animationInterval': { prop: 'ANIMATION_INTERVAL', min: 0, max: 1 },
'backgroundImageScale': { prop: 'BACKGROUND_IMAGE_SCALE', min: 0.1, max: 2.0 },
'mediaScale': { prop: 'MEDIA_SCALE', min: 0.1, max: 2.0 },
'fluidMediaScale': { prop: 'FLUID_MEDIA_SCALE', min: 0.1, max: 2.0 },
'fluidCameraScale': { prop: 'FLUID_CAMERA_SCALE', min: 0.1, max: 2.0 },
'tIndexList': { prop: 'T_INDEX_LIST', min: 0, max: 50, isArray: true },
'audioReactivity': { prop: 'AUDIO_REACTIVITY', min: 0.1, max: 3.0 },
'audioDelay': { prop: 'AUDIO_DELAY', min: 0, max: 500 },
'audioOpacity': { prop: 'AUDIO_OPACITY', min: 0, max: 1 },
'audioColorful': { prop: 'AUDIO_COLORFUL', min: 0, max: 1 },
'audioEdgeSoftness': { prop: 'AUDIO_EDGE_SOFTNESS', min: 0, max: 1 },
'telegramWaitlistInterval': { prop: 'TELEGRAM_WAITLIST_INTERVAL', min: 1, max: 30 }
};
Object.keys(sliderMap).forEach(sliderName => {
const slider = sliderMap[sliderName];
let percentage;
if (slider.isArray && slider.prop === 'T_INDEX_LIST') {
// For T_INDEX_LIST, use the middle value to determine percentage
const middleValue = Array.isArray(config[slider.prop]) ? config[slider.prop][1] || 8 : 8;
percentage = (middleValue - slider.min) / (slider.max - slider.min);
} else {
// Handle undefined config values gracefully
const configValue = config[slider.prop];
if (configValue === undefined || configValue === null || isNaN(configValue)) {
// Use default value (middle of range) for undefined properties
const defaultValue = slider.min + (slider.max - slider.min) * 0.5;
config[slider.prop] = defaultValue;
percentage = 0.5;
console.warn(`Config property ${slider.prop} was undefined, using default value: ${defaultValue}`);
} else {
percentage = (configValue - slider.min) / (slider.max - slider.min);
}
}
updateSliderValue(sliderName, percentage, true); // Skip saving when loading
});
}
function updateToggleStates() {
updateToggle('colorfulToggle', config.COLORFUL);
updateToggle('pausedToggle', config.PAUSED);
updateToggle('animateToggle', config.ANIMATE);
updateToggle('hideCursorToggle', config.HIDE_CURSOR);
updateToggle('bloomToggle', config.BLOOM);
updateToggle('sunraysToggle', config.SUNRAYS);
updateToggle('velocityDrawingToggle', config.VELOCITY_DRAWING);
updateToggle('forceClickToggle', config.FORCE_CLICK);
updateToggle('debugToggle', config.DEBUG_MODE);
// Apply cursor hiding CSS class if needed
if (config.HIDE_CURSOR) {
document.body.classList.add('hide-cursor');
} else {
document.body.classList.remove('hide-cursor');
}
// Update cursor indicator visibility
if (cursorIndicator) {
cursorIndicator.style.display = config.HIDE_CURSOR ? 'block' : 'none';
}
}
function updateToggle(toggleId, state) {
const toggle = document.getElementById(toggleId);
if (toggle) {
if (state) {
toggle.classList.add('active');
} else {
toggle.classList.remove('active');
}
}
}
// Toggle Functions
function togglePanel() {
const panel = document.getElementById('controlPanel');
panel.classList.toggle('collapsed');
// Close color picker when panel is collapsed (especially important on tablets)
if (panel.classList.contains('collapsed') && typeof Coloris !== 'undefined') {
Coloris.close();
}
}
function togglePanelVisibility() {
const panel = document.getElementById('controlPanel');
if (panel.style.display === 'none') {
panel.style.display = 'block';
} else {
panel.style.display = 'none';
// Close color picker when panel is hidden (especially important on tablets)
if (typeof Coloris !== 'undefined') {
Coloris.close();
}
}
}
function toggleFullscreen() {
const doc = document.documentElement;
const isFullscreen = document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement;
if (!isFullscreen) {
// Enter fullscreen
if (doc.requestFullscreen) {
doc.requestFullscreen().catch(err => {
console.log('Fullscreen request failed:', err);
showFullscreenFeedback('Fullscreen not supported');
});
} else if (doc.webkitRequestFullscreen) {
// Safari
doc.webkitRequestFullscreen().catch(err => {
console.log('Webkit fullscreen request failed:', err);
showFullscreenFeedback('Fullscreen not supported on this device');
});
} else if (doc.mozRequestFullScreen) {
// Firefox
doc.mozRequestFullScreen().catch(err => {
console.log('Mozilla fullscreen request failed:', err);
showFullscreenFeedback('Fullscreen not supported');
});
} else if (doc.msRequestFullscreen) {
// IE/Edge
doc.msRequestFullscreen().catch(err => {
console.log('MS fullscreen request failed:', err);
showFullscreenFeedback('Fullscreen not supported');
});
} else {
// Fallback for unsupported browsers
showFullscreenFeedback('Fullscreen not supported on this device');
}
} else {
// Exit fullscreen
if (document.exitFullscreen) {
document.exitFullscreen().catch(err => {
console.log('Exit fullscreen failed:', err);
});
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen().catch(err => {
console.log('Webkit exit fullscreen failed:', err);
});
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen().catch(err => {
console.log('Mozilla exit fullscreen failed:', err);
});
} else if (document.msExitFullscreen) {
document.msExitFullscreen().catch(err => {
console.log('MS exit fullscreen failed:', err);
});
}
}
}
function showFullscreenFeedback(message) {
// Show a temporary message to the user
const button = document.getElementById('fullscreenToggleButton');
if (button) {
const originalTooltip = button.querySelector('.tooltiptext').textContent;
button.querySelector('.tooltiptext').textContent = message;
// Reset tooltip after 2 seconds
setTimeout(() => {
button.querySelector('.tooltiptext').textContent = originalTooltip;
}, 2000);
}
}
function updateFullscreenButton() {
const icon = document.getElementById('fullscreenIcon');
const tooltip = document.getElementById('fullscreenTooltip');
if (!icon || !tooltip) return;
const isFullscreen = document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement;
if (isFullscreen) {
icon.className = 'fas fa-compress';
tooltip.textContent = 'Exit Fullscreen';
} else {
icon.className = 'fas fa-expand';
tooltip.textContent = 'Enter Fullscreen';
}
}
// Safe wrapper functions for mobile compatibility
function safeTogglePanel(event) {
try {
if (event) {
event.preventDefault();
event.stopPropagation();
}
if (isMobile()) {
console.log('π MOBILE DEBUG: Panel toggle called');
}
togglePanel();
} catch (error) {
console.error('Error in safeTogglePanel:', error);
}
}
function safeToggleStream(event) {
try {
if (event) {
event.preventDefault();
event.stopPropagation();
}
if (isMobile()) {
console.log('π MOBILE DEBUG: Stream toggle called');
}
toggleStream();
} catch (error) {
console.error('Error in safeToggleStream:', error);
}
}
function safeToggleNegativePrompt(event) {
try {
if (event) {
event.preventDefault();
event.stopPropagation();
}
if (isMobile()) {
console.log('π MOBILE DEBUG: Negative prompt toggle called');
}
toggleNegativePrompt();
} catch (error) {
console.error('Error in safeToggleNegativePrompt:', error);
}
}
function safeToggleFluidDrawing(event) {
try {
if (event) {
event.preventDefault();
event.stopPropagation();
}
if (isMobile()) {
console.log('π MOBILE DEBUG: Fluid drawing toggle called');
}
toggleFluidDrawing();
} catch (error) {
console.error('Error in safeToggleFluidDrawing:', error);
}
}
function safeToggleAudioBlob(event) {
try {
if (event) {
event.preventDefault();
event.stopPropagation();
}
if (isMobile()) {
console.log('π MOBILE DEBUG: Audio blob toggle called');
}
toggleAudioBlob();
} catch (error) {
console.error('Error in safeToggleAudioBlob:', error);
}
}
// Ensure global availability of safe functions for mobile
window.safeTogglePanel = safeTogglePanel;
window.safeToggleStream = safeToggleStream;
window.safeToggleNegativePrompt = safeToggleNegativePrompt;
window.safeToggleFluidDrawing = safeToggleFluidDrawing;
window.safeToggleAudioBlob = safeToggleAudioBlob;
// Also ensure toggle functions are globally available
window.toggleDebug = toggleDebug;
// Ensure original functions are globally available as fallback (deferred)
function ensureGlobalFunctions() {
if (typeof toggleStream !== 'undefined') window.toggleStream = toggleStream;
if (typeof toggleNegativePrompt !== 'undefined') window.toggleNegativePrompt = toggleNegativePrompt;
if (typeof toggleFluidDrawing !== 'undefined') window.toggleFluidDrawing = toggleFluidDrawing;
if (typeof toggleAudioBlob !== 'undefined') window.toggleAudioBlob = toggleAudioBlob;
}
// Make togglePanel available immediately since it's defined above
window.togglePanel = togglePanel;
// Mobile debugging - log function availability
if (isMobile()) {
console.log('π MOBILE DEBUG: Function availability check:');
console.log('π safeTogglePanel:', typeof window.safeTogglePanel);
console.log('π safeToggleStream:', typeof window.safeToggleStream);
console.log('π safeToggleFluidDrawing:', typeof window.safeToggleFluidDrawing);
console.log('π safeToggleAudioBlob:', typeof window.safeToggleAudioBlob);
}
// Mobile pull-down gesture to close control panel
function initializeMobilePanelGestures() {
// Skip if not mobile or already initialized
if (!isMobile()) return;
console.log('π MOBILE DEBUG: Initializing mobile panel gestures');
try {
const panel = document.getElementById('controlPanel');
const panelHeader = document.querySelector('.panel-header');
const panelContent = document.querySelector('.panel-content');
console.log('π MOBILE DEBUG: Panel elements found:', {
panel: !!panel,
panelHeader: !!panelHeader,
panelContent: !!panelContent,
panelCollapsed: panel ? panel.classList.contains('collapsed') : 'N/A'
});
if (!panel || !panelHeader) {
console.log('π MOBILE DEBUG: Missing panel elements, aborting gesture setup');
return;
}