forked from joinpursuit/FSW-Personal-Website
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrain-on-glass.js
More file actions
1629 lines (1443 loc) · 67.8 KB
/
rain-on-glass.js
File metadata and controls
1629 lines (1443 loc) · 67.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Canvas2D compositor for rain-on-glass effect integrated with the menu overlay
// Lightweight MVP: capture overlay background on open, render refractive droplets
const DPR_CAP = 2; // performance cap
const urlParams = (typeof window !== 'undefined') ? new URLSearchParams(window.location.search) : new URLSearchParams('');
const TEST_MODE = (typeof navigator !== 'undefined' && (navigator.webdriver === true)) ||
(typeof window !== 'undefined' && (urlParams.has('testMode') || document.documentElement?.dataset?.disableRain === '1'));
class RainOnGlass {
constructor(canvas, options = {}) {
this.canvas = canvas;
this.ctx = this.canvas.getContext('2d', { willReadFrequently: true });
this.dpr = Math.min(window.devicePixelRatio || 1, DPR_CAP);
this.drops = [];
this.micro = [];
this.condensation = []; // Fine condensation droplets for sparkling effect
this.running = false;
this.last = 0;
this.hasBackground = false;
this.testMode = false; // Initialize testMode property
// offscreen buffers for sharp/blurred background
this.bgSharp = document.createElement('canvas');
this.bgBlur = document.createElement('canvas');
this.bgSharpCtx = this.bgSharp.getContext('2d', { willReadFrequently: true });
this.bgBlurCtx = this.bgBlur.getContext('2d', { willReadFrequently: true });
// Multi-pass blur system (inspired by WebGL implementation)
this.blurSteps = []; // Array of canvas buffers for downsampling/upsampling
this.blurIterations = 4; // Number of blur passes
// optional miniature reflection buffer (RainyDay-style)
this.bgMini = document.createElement('canvas');
this.bgMiniCtx = this.bgMini.getContext('2d');
this.miniInverted = true; // 180° inverted by default
// trail buffer for condensation trails and water film
this.trailBuffer = document.createElement('canvas');
this.trailCtx = this.trailBuffer.getContext('2d', { willReadFrequently: true });
const q = urlParams;
// optional collision grid
this.enableCollisions = (q.get('collisions') ?? '') !== '0' && (options.enableCollisions ?? true);
this.collisionCell = Number(q.get('cell')) || options.collisionCell || 40; // px in device space
this.grid = null; // lazily created
// gravity configuration (angle in degrees for ergonomics)
const gravityDeg = Number(q.get('gravityDeg')) || options.gravityDeg || 90; // 90 = down
this.gravityAngleRad = (gravityDeg * Math.PI) / 180;
// Align to rainyday-style options
this.blurPx = Number(q.get('blur')) || options.blur || 8; // background blur strength
this.fps = Number(q.get('fps')) || options.fps || 60;
this.gravityBase = Number(q.get('gravity')) || options.gravity || 0.6; // base scalar (increased for proper fall)
this.gravityVariance = Number(q.get('gravVar')) || options.gravityVariance || 0; // 0..1 small randomness
this.gravityThreshold = Number(q.get('gravityThreshold')) || options.gravityThreshold || 3; // px
// trails configuration
this.enableSmudgeTrail = (q.get('smudge') ?? options.smudge ?? '1') !== '0';
this.trailThresholdPx = Number(q.get('trailStep')) || options.trailStep || 50; // distance to leave smudge
// condensation configuration
this.enableCondensation = (q.get('condensation') ?? options.condensation ?? '1') !== '0';
this.condensationDensity = Number(q.get('condDensity')) || options.condensationDensity || 0.8; // Increased for dense coverage
this.condensationSize = Number(q.get('condSize')) || options.condensationSize || 1.2; // Larger micro-droplets
this.condensationSparkle = Number(q.get('condSparkle')) || options.condensationSparkle || 0.9; // More sparkle
// enhanced physics configuration
this.enableTrails = (q.get('trails') ?? options.enableTrails ?? '1') !== '0';
this.dragCoeff = Number(q.get('drag')) || options.dragCoeff || 0.8; // drag coefficient
this.windX = Number(q.get('windX')) || options.windX || 0; // wind force X
this.windY = Number(q.get('windY')) || options.windY || 0; // wind force Y
this.adhesionBase = Number(q.get('adhesion')) || options.adhesionBase || 0.92; // base adhesion (stickiness)
this.slideThreshold = Number(q.get('slideThreshold')) || options.slideThreshold || 8; // radius threshold for sliding
this.terminalVelocity = Number(q.get('terminalVel')) || options.terminalVelocity || 15; // max fall speed
// control panel properties
this.sizeVariance = Number(q.get('sizeVariance')) || options.sizeVariance || 1.0; // drop size variance multiplier
this.trailIntensity = Number(q.get('trailIntensity')) || options.trailIntensity || 0.5; // trail intensity multiplier
// Advanced physics parameters (inspired by RaindropFX)
this.trailDropDensity = Number(q.get('trailDensity')) || options.trailDropDensity || 0.2; // density of trail droplets
this.trailDistance = [Number(q.get('trailDistMin')) || options.trailDistance?.[0] || 20,
Number(q.get('trailDistMax')) || options.trailDistance?.[1] || 30]; // trail droplet spacing
this.trailDropSize = [Number(q.get('trailSizeMin')) || options.trailDropSize?.[0] || 0.3,
Number(q.get('trailSizeMax')) || options.trailDropSize?.[1] || 0.5]; // trail droplet size range
this.trailSpread = Number(q.get('trailSpread')) || options.trailSpread || 0.6; // trail spread factor
this.velocitySpread = Number(q.get('velocitySpread')) || options.velocitySpread || 0.3; // velocity-based spread
this.evaporate = Number(q.get('evaporate')) || options.evaporate || 10; // evaporation rate
this.shrinkRate = Number(q.get('shrinkRate')) || options.shrinkRate || 0.01; // size shrinking rate
this.xShifting = [Number(q.get('xShiftMin')) || options.xShifting?.[0] || 0,
Number(q.get('xShiftMax')) || options.xShifting?.[1] || 0.1]; // horizontal drift range
this.slipRate = Number(q.get('slipRate')) || options.slipRate || 0.1; // slip rate for random motion
// Advanced rendering parameters - DRAMATICALLY ENHANCED for visible micro-lens effect
this.refractBase = Number(q.get('refractBase')) || options.refractBase || 1.5; // base refraction strength (dramatically increased for visible lens effect)
this.refractScale = Number(q.get('refractScale')) || options.refractScale || 2.0; // refraction scaling (dramatically increased for visible lens effect)
this.raindropLightPos = options.raindropLightPos || [-1, 1, 2, 0]; // light position for highlights
this.raindropDiffuseLight = options.raindropDiffuseLight || [0.2, 0.2, 0.2]; // diffuse lighting
this.raindropShadowOffset = Number(q.get('shadowOffset')) || options.raindropShadowOffset || 0.8; // shadow offset
this.raindropLightBump = Number(q.get('lightBump')) || options.raindropLightBump || 1; // lighting bump factor
// standalone/demo configuration
this.standalone = Boolean(options.standalone);
this.backgroundSource = options.backgroundSource; // 'body' | HTMLElement | selector
this.bgSourceEl = null;
// atmosphere & readability helpers
this.saturation = (typeof options.saturation === 'number') ? options.saturation : (urlParams.has('sat') ? Math.max(0, Math.min(1, Number(urlParams.get('sat')))) : 0.85);
this.fogEnabled = (urlParams.get('fog') ?? (options.fog ?? '1')) !== '0';
this.fogStrength = (typeof options.fogStrength === 'number') ? options.fogStrength : (urlParams.has('fogStrength') ? Math.max(0, Math.min(0.25, Number(urlParams.get('fogStrength')))) : 0.08);
this.avgLuma = 0;
this.overlayEl = this.standalone ? null : document.querySelector('.menu .menu-overlay');
// miniature reflection/refraction options
this.useMiniRefraction = (options.useMiniRefraction !== undefined) ? Boolean(options.useMiniRefraction) : (urlParams.get('mini') !== '0'); // default ON
this.miniBoost = (options.miniBoost !== undefined) ? Boolean(options.miniBoost) : (urlParams.get('miniBoost') !== '0' && urlParams.get('boost') !== '0'); // default ON
this.reflectionScaledownFactor = Number(options.reflectionScaledownFactor) || 2; // lower = higher cost/quality
this.reflectionDropMappingWidth = Number(options.reflectionDropMappingWidth) || 200; // device px
this.reflectionDropMappingHeight = Number(options.reflectionDropMappingHeight) || 200; // device px
this.miniMagnification = Number(options.miniMagnification) || 1.16; // stronger lens when boosted
this.miniOffsetScale = Number(options.miniOffsetScale) || 1.35; // boosts offsetX/offsetY
this.resize = this.resize.bind(this);
this.loop = this.loop.bind(this);
window.addEventListener('resize', this.resize);
this.resize();
// preset-based spawner (min, base, ratePerSecond, count optional)
// Enhanced rates for more drops
this.presets = [
{ min: 1, base: 2.5, rate: 9 }, // micro beads (denser)
{ min: 3, base: 4.5, rate: 7 }, // small
{ min: 6, base: 8.5, rate: 4 }, // medium
{ min: 12, base: 16, rate: 0.8 } // big
];
// accumulators for fractional spawning
this._spawnAcc = this.presets.map(() => 0);
// preset API timer
this._rainTimer = null;
this._resizeTimer = null;
}
async captureBackground() {
// In test mode, skip capturing to keep screenshots deterministic
if (TEST_MODE) {
this.hasBackground = false;
return;
}
if (this.standalone) {
return this.captureBackgroundStandalone();
}
const overlay = document.querySelector('.menu .menu-overlay');
if (!overlay) return;
// Allow layout/transform to apply after menu toggle
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
const rect = overlay.getBoundingClientRect();
if (!rect || rect.width < 2 || rect.height < 2) {
// If overlay rect is not measurable yet, skip capture now
this.hasBackground = false;
return;
}
const w = Math.ceil(rect.width * this.dpr);
const h = Math.ceil(rect.height * this.dpr);
this.bgSharp.width = this.bgBlur.width = w;
this.bgSharp.height = this.bgBlur.height = h;
try {
// use html2canvas to snapshot the viewport region under the overlay
const shot = await html2canvas(document.body, {
x: rect.left,
y: rect.top,
width: rect.width,
height: rect.height,
scale: this.dpr,
backgroundColor: null,
useCORS: true
});
if (shot && shot.width > 0 && shot.height > 0) {
this.bgSharpCtx.drawImage(shot, 0, 0);
if (this.saturation < 1) this.applyDesaturate(this.bgSharpCtx, this.bgSharp.width, this.bgSharp.height, this.saturation);
} else {
// Invalid shot; mark as no background captured
this.hasBackground = false;
return;
}
// Deterministic JS blur: draw sharp → apply box blur into bgBlur
this.bgBlurCtx.clearRect(0, 0, this.bgBlur.width, this.bgBlur.height);
this.bgBlurCtx.drawImage(this.bgSharp, 0, 0);
this.applyBoxBlur(this.bgBlurCtx, this.bgBlur.width, this.bgBlur.height, Math.max(0, Math.floor(this.blurPx)));
this.hasBackground = true;
// compute luminance from downscaled buffer and tune overlay for text readability
this.computeAverageLuminance();
this.applyOverlayTuning();
} catch (e) {
// fallback: clear buffers
this.bgSharpCtx.clearRect(0, 0, this.bgSharp.width, this.bgSharp.height);
this.bgBlurCtx.clearRect(0, 0, this.bgBlur.width, this.bgBlur.height);
// eslint-disable-next-line no-console
console.warn('RainOnGlass background capture failed:', e);
this.hasBackground = false;
}
}
async captureBackgroundStandalone() {
try {
// Determine capture target and dimensions
let targetEl = null;
if (this.backgroundSource === 'body' || !this.backgroundSource) {
targetEl = document.body;
} else if (typeof this.backgroundSource === 'string') {
targetEl = document.querySelector(this.backgroundSource);
} else if (this.backgroundSource instanceof HTMLElement) {
targetEl = this.backgroundSource;
}
if (!targetEl) targetEl = document.body;
// Compute capture rect in CSS pixels
const vw = window.innerWidth;
const vh = window.innerHeight;
const rect = (targetEl === document.body)
? { left: 0, top: 0, width: vw, height: vh }
: targetEl.getBoundingClientRect();
if (!rect || rect.width < 2 || rect.height < 2) {
this.hasBackground = false;
return;
}
const w = Math.ceil(rect.width * this.dpr);
const h = Math.ceil(rect.height * this.dpr);
this.bgSharp.width = this.bgBlur.width = w;
this.bgSharp.height = this.bgBlur.height = h;
this.trailBuffer.width = w;
this.trailBuffer.height = h;
this.bgMini.width = Math.max(1, Math.floor(w / 2));
this.bgMini.height = Math.max(1, Math.floor(h / 2));
// If target is an IMG element and complete, draw directly for speed
if (targetEl.tagName === 'IMG' && targetEl.complete && targetEl.naturalWidth > 0) {
this.bgSharpCtx.drawImage(targetEl, 0, 0, w, h);
if (this.saturation < 1) this.applyDesaturate(this.bgSharpCtx, this.bgSharp.width, this.bgSharp.height, this.saturation);
} else {
const shot = await html2canvas(targetEl, {
x: rect.left,
y: rect.top,
width: rect.width,
height: rect.height,
scale: this.dpr,
backgroundColor: null,
useCORS: true
});
if (!shot || shot.width === 0 || shot.height === 0) {
this.hasBackground = false;
return;
}
this.bgSharpCtx.drawImage(shot, 0, 0);
if (this.saturation < 1) this.applyDesaturate(this.bgSharpCtx, this.bgSharp.width, this.bgSharp.height, this.saturation);
}
// Create blurred buffer using multi-pass blur system
this.bgBlurCtx.clearRect(0, 0, this.bgBlur.width, this.bgBlur.height);
this.bgBlurCtx.drawImage(this.bgSharp, 0, 0);
// Use new multi-pass blur for higher quality
const blurStrength = Math.max(0, Math.floor(this.blurPx));
if (blurStrength > 0) {
this.multiPassBlur(this.bgSharp, this.bgBlur, blurStrength);
} else {
// No blur needed, just copy
this.bgBlurCtx.drawImage(this.bgSharp, 0, 0);
}
// Create miniature inverted buffer for optional higher-contrast refraction feel
try {
const mx = this.bgMiniCtx;
mx.setTransform(1, 0, 0, 1, 0, 0);
mx.clearRect(0, 0, this.bgMini.width, this.bgMini.height);
mx.translate(this.bgMini.width / 2, this.bgMini.height / 2);
if (this.miniInverted) mx.rotate(Math.PI);
mx.drawImage(this.bgSharp, -this.bgMini.width / 2, -this.bgMini.height / 2, this.bgMini.width, this.bgMini.height);
} catch(_) {}
this.hasBackground = true;
// Evaluate luminance for potential overlay tuning (noop in standalone)
this.computeAverageLuminance();
} catch (e) {
this.bgSharpCtx.clearRect(0, 0, this.bgSharp.width, this.bgSharp.height);
this.bgBlurCtx.clearRect(0, 0, this.bgBlur.width, this.bgBlur.height);
// eslint-disable-next-line no-console
console.warn('RainOnGlass standalone capture failed:', e);
this.hasBackground = false;
}
}
// Simple separable box blur (two-pass) for determinism across browsers
applyBoxBlur(ctx, w, h, radius) {
if (radius <= 0) return;
try {
const img = ctx.getImageData(0, 0, w, h);
const data = img.data;
const tmp = new Uint8ClampedArray(data.length);
const pass = (src, dst, r, horizontal) => {
const lenOuter = horizontal ? h : w;
const lenInner = horizontal ? w : h;
const step = 4;
const line = new Float32Array(lenInner * 4);
for (let outer = 0; outer < lenOuter; outer++) {
// collect line
for (let inner = 0; inner < lenInner; inner++) {
const idx = horizontal ? (outer * w + inner) * 4 : (inner * w + outer) * 4;
line[inner * 4 + 0] = src[idx + 0];
line[inner * 4 + 1] = src[idx + 1];
line[inner * 4 + 2] = src[idx + 2];
line[inner * 4 + 3] = src[idx + 3];
}
// box window
const windowSize = r * 2 + 1;
let sumR = 0, sumG = 0, sumB = 0, sumA = 0;
for (let i = -r; i <= r; i++) {
const k = Math.min(lenInner - 1, Math.max(0, i));
sumR += line[k * 4 + 0];
sumG += line[k * 4 + 1];
sumB += line[k * 4 + 2];
sumA += line[k * 4 + 3];
}
for (let inner = 0; inner < lenInner; inner++) {
const outIdx = horizontal ? (outer * w + inner) * 4 : (inner * w + outer) * 4;
dst[outIdx + 0] = sumR / windowSize | 0;
dst[outIdx + 1] = sumG / windowSize | 0;
dst[outIdx + 2] = sumB / windowSize | 0;
dst[outIdx + 3] = sumA / windowSize | 0;
// slide window
const iRemove = inner - r;
const iAdd = inner + r + 1;
const kRemove = Math.min(lenInner - 1, Math.max(0, iRemove));
const kAdd = Math.min(lenInner - 1, Math.max(0, iAdd));
sumR += line[kAdd * 4 + 0] - line[kRemove * 4 + 0];
sumG += line[kAdd * 4 + 1] - line[kRemove * 4 + 1];
sumB += line[kAdd * 4 + 2] - line[kRemove * 4 + 2];
sumA += line[kAdd * 4 + 3] - line[kRemove * 4 + 3];
}
}
};
pass(data, tmp, radius, true);
pass(tmp, data, radius, false);
ctx.putImageData(img, 0, 0);
} catch(_) {
// fallback: leave as-is
}
}
// Apply saturation adjustment using luminance mix method
applyDesaturate(ctx, w, h, saturation) {
try {
// Use CSS filter on a temp canvas to avoid per-pixel JS loop on large frames
const tmp = document.createElement('canvas');
tmp.width = w; tmp.height = h;
const tctx = tmp.getContext('2d');
const satPct = Math.round(Math.max(0, Math.min(1, saturation)) * 100);
tctx.filter = `saturate(${satPct}%)`;
tctx.drawImage(this.bgSharp, 0, 0);
ctx.clearRect(0, 0, w, h);
ctx.drawImage(tmp, 0, 0);
} catch (_) {}
}
start() {
if (TEST_MODE) return; // do not animate in tests
if (this.running) return;
this.running = true;
this.last = performance.now();
// initial population (tunable, with mobile-aware defaults)
const isMobile = (typeof window !== 'undefined') && (window.matchMedia?.('(max-width: 768px)').matches || 'ontouchstart' in window.navigator || /Mobi|Android/i.test(window.navigator.userAgent));
const defaultDensity = isMobile ? 26 : 42; // Denser default population
this.initialDensity = Number(urlParams.get('density')) || defaultDensity;
this.maxDrops = Number(urlParams.get('maxDrops')) || 180; // Higher cap
this.spawnChance = Number(urlParams.get('spawn')) || 0.42; // Higher spawn rate
for (let i = 0; i < this.initialDensity; i++) this.spawn();
requestAnimationFrame(this.loop);
}
stop() {
this.running = false;
this.drops.length = 0;
this.micro.length = 0;
this.clear();
}
pause() {
this.running = false;
// Don't clear drops - keep them frozen in place
}
resume() {
if (this.running) return;
this.running = true;
this.last = performance.now();
requestAnimationFrame(this.loop);
}
resize() {
const vw = window.innerWidth;
const vh = window.innerHeight;
this.canvas.width = vw * this.dpr;
this.canvas.height = vh * this.dpr;
this.canvas.style.width = vw + 'px';
this.canvas.style.height = vh + 'px';
// re-apply overlay tuning on resize
this.applyOverlayTuning();
// In standalone mode, recapture background on resize (debounced)
if (this.standalone && !TEST_MODE) {
if (this._resizeTimer) clearTimeout(this._resizeTimer);
this._resizeTimer = setTimeout(() => { this.captureBackgroundStandalone().then(() => this.render()); }, 120);
}
}
clear() {
// Clear in device pixel space with identity transform
const ctx = this.ctx;
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
computeAverageLuminance() {
try {
if (!this.bgSharp || this.bgSharp.width === 0 || this.bgSharp.height === 0) return 0;
const step = 16; // sample grid step for performance
const w = this.bgSharp.width, h = this.bgSharp.height;
const ctx = this.bgSharpCtx;
const img = ctx.getImageData(0, 0, w, h).data;
let sum = 0, count = 0;
for (let y = 0; y < h; y += step) {
for (let x = 0; x < w; x += step) {
const i = (y * w + x) * 4;
const r = img[i], g = img[i+1], b = img[i+2];
// Rec. 709 luma
const l = 0.2126 * r + 0.7152 * g + 0.0722 * b;
sum += l; count++;
}
}
this.avgLuma = count ? (sum / count) : 0;
return this.avgLuma;
} catch (_) {
return 0;
}
}
applyOverlayTuning() {
if (TEST_MODE) return; // keep tests deterministic
const el = this.overlayEl;
if (!el) return;
const luma = this.avgLuma || 0;
// default CSS values
let blurPx = 7;
let alpha = 0.17;
if (luma > 180) { // very bright background/text -> increase separation
blurPx = 10; alpha = 0.22;
} else if (luma > 120) { // moderately bright
blurPx = 8.5; alpha = 0.19;
}
el.style.backdropFilter = `blur(${blurPx}px)`;
el.style.backgroundColor = `rgba(255,255,255,${alpha})`;
}
spawn(x, y, r) {
// Organic size distribution using natural variations
let radius;
if (r) {
radius = r;
} else {
// Use natural drop size variations
const baseSize = 8; // Base medium drop size
const sizeVariation = 0.4; // 40% variation
radius = window.RainUtils?.naturalDropSize(baseSize, sizeVariation) || (baseSize + Math.random() * baseSize * sizeVariation);
// More random size distribution with higher variation
const sizeCategory = Math.random();
if (sizeCategory < 0.4) {
// Small drops (40%) - 3-10px base with high variation
radius = window.RainUtils?.naturalDropSize(6, 0.6) || (6 + Math.random() * 4);
} else if (sizeCategory < 0.8) {
// Medium drops (40%) - 8-20px base with high variation
radius = window.RainUtils?.naturalDropSize(14, 0.5) || (14 + Math.random() * 6);
} else {
// Large drops (20%) - 15-30px base with high variation
radius = window.RainUtils?.naturalDropSize(22, 0.4) || (22 + Math.random() * 8);
}
radius *= this.dpr * this.sizeVariance; // Apply size variance multiplier
}
// Ensure minimum radius to prevent rendering errors
radius = Math.max(0.5, radius);
// Organic positioning using randomInRect for more natural distribution
let spawnX, spawnY;
if (x !== undefined) {
spawnX = x;
} else {
// Use organic positioning within spawn area
const spawnRect = window.RainUtils ? new window.RainUtils.Rect(radius, 0, this.canvas.width - 2 * radius, 50) : null;
const organicPos = window.RainUtils ? window.RainUtils.randomInRect(spawnRect) : null;
spawnX = organicPos ? organicPos.x : (radius + Math.random() * (this.canvas.width - 2 * radius));
}
if (y !== undefined) {
spawnY = y;
} else {
// Organic Y positioning with natural variation
const baseY = -radius - 50;
const yVariation = window.RainUtils?.randomRange(0, 100) || Math.random() * 100;
spawnY = baseY - yVariation * this.dpr;
}
this.drops.push({
x: spawnX,
y: spawnY,
r: radius,
// More random velocity variations
vx: window.RainUtils?.randomRange(-0.8, 0.8) || ((Math.random() - 0.5) * 0.8),
vy: 0,
stretch: 1,
// More random adhesion with higher variation
stick: window.RainUtils?.randomJittered(new window.RainUtils.JitterOption(this.adhesionBase, 0.15)) || (this.adhesionBase + Math.random() * 0.15),
label: (urlParams.get('debugRain') === '1') && Math.random() < 0.2,
shapePoints: null,
_shapeDirty: false,
// Enhanced physics properties with organic variations
mass: radius * radius, // mass ∝ r²
prevX: spawnX,
prevY: spawnY,
adhesion: this.adhesionBase,
_trailAccumulated: 0,
// Advanced physics properties with natural variations
density: window.RainUtils?.randomJittered(new window.RainUtils.JitterOption(1.0, 0.1)) || 1.0, // Organic density variation
spread: { x: 0, y: 0 }, // Shape deformation
resistance: 0, // Dynamic friction
shifting: 0, // Horizontal drift
lastTrailPos: { x: spawnX, y: spawnY },
// Organic trail spacing with natural variation
nextTrailDistance: window.RainUtils?.randomRange(15, 35) || (20 + Math.random() * 20),
nextRandomTime: 0, // Random motion timing
// Unique seed for organic variations
_organicSeed: Math.floor(Math.random() * 10000)
});
}
// Random motion system inspired by RainDrop class
randomMotion(drop) {
try {
// Calculate maximum resistance based on drop size and slip rate
const maxResistance = (8 + Math.random() * 8) * (1 - this.slipRate) ** 2 * 4;
drop.resistance = Math.random() * this.gravityBase * maxResistance;
drop.shifting = Math.random() * (this.xShifting[0] + Math.random() * (this.xShifting[1] - this.xShifting[0]));
} catch (error) {
console.warn('Error in randomMotion:', error);
}
}
// Multi-pass blur system (inspired by WebGL BlurRenderer)
initBlurSteps(width, height) {
// Initialize blur step canvases if needed
for (let i = 0; i <= this.blurIterations; i++) {
if (!this.blurSteps[i]) {
this.blurSteps[i] = document.createElement('canvas');
this.blurSteps[i].getContext('2d');
}
// Calculate size for this step (downsampling)
const stepWidth = Math.max(1, Math.floor(width / Math.pow(2, i)));
const stepHeight = Math.max(1, Math.floor(height / Math.pow(2, i)));
// Resize if needed
if (this.blurSteps[i].width !== stepWidth || this.blurSteps[i].height !== stepHeight) {
this.blurSteps[i].width = stepWidth;
this.blurSteps[i].height = stepHeight;
}
}
}
downSampleBlur(inputCanvas, iteration) {
const ctx = this.blurSteps[iteration].getContext('2d');
const inputCtx = inputCanvas.getContext('2d');
// Clear the target canvas
ctx.clearRect(0, 0, this.blurSteps[iteration].width, this.blurSteps[iteration].height);
// Draw input at half size (downsampling)
ctx.drawImage(inputCanvas, 0, 0, this.blurSteps[iteration].width, this.blurSteps[iteration].height);
// Apply subtle blur for downsampling
ctx.filter = 'blur(0.5px)';
ctx.drawImage(inputCanvas, 0, 0, this.blurSteps[iteration].width, this.blurSteps[iteration].height);
ctx.filter = 'none';
}
upSampleBlur(inputCanvas, iteration, targetWidth, targetHeight) {
const ctx = this.blurSteps[iteration].getContext('2d');
// Clear the target canvas
ctx.clearRect(0, 0, this.blurSteps[iteration].width, this.blurSteps[iteration].height);
// Draw input at double size (upsampling)
ctx.drawImage(inputCanvas, 0, 0, this.blurSteps[iteration].width, this.blurSteps[iteration].height);
// Apply subtle blur for upsampling
ctx.filter = 'blur(0.5px)';
ctx.drawImage(inputCanvas, 0, 0, this.blurSteps[iteration].width, this.blurSteps[iteration].height);
ctx.filter = 'none';
}
multiPassBlur(sourceCanvas, targetCanvas, blurStrength = 1.0) {
const sourceCtx = sourceCanvas.getContext('2d');
const targetCtx = targetCanvas.getContext('2d');
// Initialize blur steps
this.initBlurSteps(sourceCanvas.width, sourceCanvas.height);
// Step 0: Copy source to first blur step
const step0Ctx = this.blurSteps[0].getContext('2d');
step0Ctx.clearRect(0, 0, this.blurSteps[0].width, this.blurSteps[0].height);
step0Ctx.drawImage(sourceCanvas, 0, 0);
// Downsample: progressively reduce size
let currentInput = this.blurSteps[0];
for (let i = 1; i <= this.blurIterations; i++) {
this.downSampleBlur(currentInput, i);
currentInput = this.blurSteps[i];
}
// Upsample: progressively increase size back
for (let i = this.blurIterations - 1; i >= 0; i--) {
this.upSampleBlur(currentInput, i, this.blurSteps[i].width, this.blurSteps[i].height);
currentInput = this.blurSteps[i];
}
// Final blur pass with configurable strength
targetCtx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
targetCtx.filter = `blur(${blurStrength}px)`;
targetCtx.drawImage(currentInput, 0, 0, targetCanvas.width, targetCanvas.height);
targetCtx.filter = 'none';
}
spawnCondensation() {
if (!this.enableCondensation || this.testMode || this.condensation.length >= 3000) return; // Increased limit
// Spawn dense micro-condensation like the reference implementation
const count = Math.floor(this.condensationDensity * 40 * Math.random()); // Much higher density
for (let i = 0; i < count; i++) {
const x = Math.random() * this.canvas.width;
const y = Math.random() * this.canvas.height;
const size = (0.2 + Math.random() * 1.8) * this.condensationSize * this.dpr; // More size variation
this.condensation.push({
x: x,
y: y,
r: size,
sparkle: Math.random() * this.condensationSparkle,
life: 0.6 + Math.random() * 0.8, // Longer life for dense coverage
age: 0,
twinkle: Math.random() * Math.PI * 2, // for sparkle animation
_isMicroCondensation: true // Mark for special rendering
});
}
}
layTrail(drop, prevX, prevY) {
try {
if (!this.enableTrails || !this.trailCtx) return;
// Enhanced trail parameters using RaindropFX-inspired system
const baseWidth = Math.max(0.8, drop.r * 0.4 * this.trailSpread);
const widthVariation = baseWidth * 0.3;
const w = baseWidth + (Math.random() - 0.5) * widthVariation;
// Enhanced trail visibility for realistic rivulets
const trailSpeed = Math.hypot(drop.vx, drop.vy);
const velocityFactor = Math.min(1, trailSpeed / 8); // Normalize speed
const baseAlpha = Math.min(0.4, 0.1 + drop.r * 0.012 + velocityFactor * 0.15); // More visible trails
const alphaVariation = baseAlpha * 0.3;
const alpha = baseAlpha + (Math.random() - 0.5) * alphaVariation;
// Enhanced horizontal drift using xShifting parameters
const driftRange = this.xShifting[1] - this.xShifting[0];
const drift = this.xShifting[0] + Math.random() * driftRange;
const midX = (prevX + drop.x) / 2 + drift;
const midY = (prevY + drop.y) / 2;
this.trailCtx.save();
// Skip white trail strokes in test mode
if (!this.testMode) {
this.trailCtx.strokeStyle = `rgba(255,255,255,${alpha})`;
this.trailCtx.lineWidth = w;
this.trailCtx.lineCap = 'round';
this.trailCtx.globalCompositeOperation = 'lighter';
// Draw curved trail for more natural water flow
this.trailCtx.beginPath();
this.trailCtx.moveTo(prevX, prevY);
this.trailCtx.quadraticCurveTo(midX, midY, drop.x, drop.y);
this.trailCtx.stroke();
}
this.trailCtx.restore();
// Spawn trail droplets occasionally (inspired by RaindropFX)
if (Math.random() < this.trailDropDensity * 0.1) {
this.spawnTrailDroplet(drop, prevX, prevY);
}
} catch (error) {
console.warn('Error in layTrail:', error);
}
}
spawnTrailDroplet(parentDrop, prevX, prevY) {
try {
if (!this.enableTrails) return;
// Create small trail droplet
const trailSize = this.trailDropSize[0] + Math.random() * (this.trailDropSize[1] - this.trailDropSize[0]);
const trailRadius = Math.max(0.5, parentDrop.r * trailSize); // Ensure minimum radius
// Position along the trail path
const t = Math.random();
const x = prevX + (parentDrop.x - prevX) * t;
const y = prevY + (parentDrop.y - prevY) * t;
// Add some spread
const spreadX = (Math.random() - 0.5) * this.trailSpread * 2;
const spreadY = (Math.random() - 0.5) * this.trailSpread * 2;
this.drops.push({
x: x + spreadX,
y: y + spreadY,
r: trailRadius,
vx: parentDrop.vx * 0.5 + (Math.random() - 0.5) * 0.2,
vy: parentDrop.vy * 0.5 + (Math.random() - 0.5) * 0.2,
stretch: 1,
stick: this.adhesionBase + Math.random() * 0.06,
label: false,
shapePoints: null,
_shapeDirty: false,
mass: trailRadius * trailRadius,
prevX: x + spreadX,
prevY: y + spreadY,
adhesion: this.adhesionBase,
_trailAccumulated: 0,
_isTrailDroplet: true // Mark as trail droplet
});
} catch (error) {
console.warn('Error in spawnTrailDroplet:', error);
}
}
evolveTrails() {
try {
if (!this.enableTrails || !this.trailCtx) return;
// Evaporate: darken alpha a tiny bit (slower evaporation for longer trails)
this.trailCtx.save();
this.trailCtx.globalCompositeOperation = 'destination-out';
this.trailCtx.fillStyle = 'rgba(0,0,0,0.005)'; // Reduced from 0.01 for longer-lasting trails
this.trailCtx.fillRect(0, 0, this.trailBuffer.width, this.trailBuffer.height);
this.trailCtx.restore();
// Diffuse: soft blur to widen rivulets (more subtle blur)
this.trailCtx.save();
this.trailCtx.filter = 'blur(0.8px)'; // Reduced blur for more defined trails
const tmp = this.trailCtx.getImageData(0, 0, this.trailBuffer.width, this.trailBuffer.height);
this.trailCtx.clearRect(0, 0, this.trailBuffer.width, this.trailBuffer.height);
this.trailCtx.putImageData(tmp, 0, 0);
this.trailCtx.restore();
} catch (error) {
console.warn('Error in evolveTrails:', error);
}
}
update(dt) {
try {
const g = this.gravityBase;
for (let i = this.drops.length - 1; i >= 0; i--) {
const d = this.drops[i];
// Validate drop data
if (!d || typeof d.x !== 'number' || typeof d.y !== 'number' || typeof d.r !== 'number') {
console.warn('Invalid drop data at index', i, d);
this.drops.splice(i, 1);
continue;
}
// Store previous position for trail rendering
const prevX = d.x;
const prevY = d.y;
// Advanced physics system inspired by RainDrop class
const dtScale = Math.max(0.016, Math.min(0.1, dt)) * this.fps / 1.0; // normalize to configured fps
// Validate dtScale is finite
if (!isFinite(dtScale) || dtScale <= 0) {
console.warn('Invalid dtScale for drop', i, 'dtScale:', dtScale, 'dt:', dt, 'fps:', this.fps);
continue; // Skip this drop's update
}
// Random motion intervals (inspired by RainDrop class)
if (d.nextRandomTime <= this.last) {
d.nextRandomTime = this.last + (0.1 + Math.random() * 0.4); // motionInterval
this.randomMotion(d);
}
// Evaporation (mass decreases over time) - prevent negative mass (skip for test drops)
if (!d._testDrop) {
d.mass = Math.max(0, d.mass - this.evaporate * dtScale);
if (d.mass <= 0) {
d._dead = true;
}
}
// Skip physics calculations for dead drops
if (d._dead || d.mass <= 0) {
continue;
}
// Initialize resistance and shifting if they don't exist (for backward compatibility)
if (!d.resistance || !isFinite(d.resistance)) {
d.resistance = 0;
}
if (!d.shifting || !isFinite(d.shifting)) {
d.shifting = 0;
}
// Advanced physics calculation with validation
const force = this.gravityBase * d.mass - d.resistance;
const acceleration = force / d.mass;
// Validate physics calculations (skip for test drops)
if (!d._testDrop && (!isFinite(force) || !isFinite(acceleration) || !isFinite(d.mass) || d.mass <= 0)) {
console.warn('Invalid physics values for drop', i, 'force:', force, 'acceleration:', acceleration, 'mass:', d.mass);
d._dead = true; // Mark as dead instead of trying to fix
continue;
}
d.vy += acceleration * dtScale;
if (d.vy < 0) d.vy = 0; // Prevent upward movement
d.vx = Math.abs(d.vy) * d.shifting; // Horizontal drift based on vertical speed
// Validate velocities are finite
if (!isFinite(d.vx) || !isFinite(d.vy)) {
console.warn('Invalid velocities for drop', i, 'vx:', d.vx, 'vy:', d.vy);
d.vx = 0;
d.vy = 0;
}
// Update position with validation
const newX = d.x + d.vx * dtScale;
const newY = d.y + d.vy * dtScale;
// Validate new positions are finite
if (isFinite(newX) && isFinite(newY)) {
d.x = newX;
d.y = newY;
} else {
console.warn('Invalid position update for drop', i, 'newX:', newX, 'newY:', newY, 'vx:', d.vx, 'vy:', d.vy, 'dtScale:', dtScale);
// Reset to safe values
d.x = Math.max(0, Math.min(this.canvas.width, d.x || 0));
d.y = Math.max(0, Math.min(this.canvas.height, d.y || 0));
d.vx = 0;
d.vy = 0;
}
// Add wind effect
d.vx += this.windX * dtScale;
d.vy += this.windY * dtScale;
// Initialize spread if it doesn't exist (for backward compatibility)
if (!d.spread) {
d.spread = { x: 0, y: 0 };
}
// Velocity-based spread (inspired by RainDrop class)
const currentDropSpeed = Math.hypot(d.vx, d.vy);
if (currentDropSpeed > 5 && d.r > 0) {
const spreadByVelocity = this.velocitySpread * 2 * Math.atan(Math.abs(d.vy * 0.005)) / Math.PI;
d.spread.y = Math.max(d.spread.y, spreadByVelocity);
}
// Shrink spread over time
d.spread.x *= Math.pow(this.shrinkRate, dtScale);
d.spread.y *= Math.pow(this.shrinkRate, dtScale);
// Initialize lastTrailPos if it doesn't exist (for backward compatibility)
if (!d.lastTrailPos) {
d.lastTrailPos = { x: d.x, y: d.y };
}
if (!d.nextTrailDistance) {
d.nextTrailDistance = 20 + Math.random() * 20;
}
// Distance-based trail generation (inspired by RainDrop class)
const distanceMoved = Math.hypot(d.x - d.lastTrailPos.x, d.y - d.lastTrailPos.y);
if (distanceMoved > d.nextTrailDistance) {
this.layTrail(d, d.lastTrailPos.x, d.lastTrailPos.y);
d.lastTrailPos.x = d.x;
d.lastTrailPos.y = d.y;
d.nextTrailDistance = 20 + Math.random() * 20; // New random distance
}
// variance (wind jitter)
if (this.gravityVariance) d.vx += (Math.random() * 2 - 1) * this.gravityVariance * dtScale * 0.1;
// Apply drag and adhesion
const vyDamp = Math.pow(d.stick, dtScale);
d.vy *= vyDamp;
d.vx *= Math.pow(0.985, dtScale);
// Update position
d.x += d.vx * dtScale;
d.y += d.vy * dtScale;
// Advanced physics: evaporation and shrinking (inspired by RaindropFX) (skip for test drops)
if (!d._testDrop) {
if (d._isTrailDroplet) {
// Trail droplets evaporate faster
d.r = Math.max(0, d.r - this.evaporate * dtScale * 0.1);
if (d.r <= 0.5) {
d._dead = true;
}
} else {
// Regular droplets shrink slowly
d.r = Math.max(0, d.r - this.shrinkRate * dtScale);
if (d.r <= 1) {
d._dead = true;
}
}
}
// Velocity-based stretch (inspired by RaindropFX)
const stretchSpeed = Math.hypot(d.vx, d.vy);
if (stretchSpeed > 5 && d.r > 0) {
d.stretch = 1 + Math.min(stretchSpeed / (10 * d.r), 1.1) * this.velocitySpread;
} else {
d.stretch = 1;
}
// Lay trail if drop moved significantly
if (Math.abs(d.x - prevX) > 0.5 || Math.abs(d.y - prevY) > 0.5) {
this.layTrail(d, prevX, prevY);
}
// Update previous position
d.prevX = prevX;
d.prevY = prevY;
const alongGravity = d.vx * Math.cos(this.gravityAngleRad) + d.vy * Math.sin(this.gravityAngleRad);
d.stretch = 1 + Math.min(alongGravity / (10 * d.r), 1.1);
// mark shape dirty when speed low or very low acceleration
const speed = Math.hypot(d.vx, d.vy);
d._shapeDirty = speed < 1.5 * this.dpr;
// Position already updated in the new physics system above
// remove only when fully off-screen; allow reach to bottom (skip for test drops)
if (!d._testDrop && d.y - d.r > this.canvas.height + 5) this.drops.splice(i, 1);
// mark for smudge trail if moved enough
if (this.enableSmudgeTrail) {
if (d._trailY === undefined) d._trailY = d.y;
if (Math.abs(d.y - d._trailY) > this.trailThresholdPx) {
d._leaveTrail = true;
d._trailY = d.y;
}
}
// TRAIL_DROPS-like micro-drop trail: probabilistic and size-scaled
if (!TEST_MODE && this.enableSmudgeTrail) {
if (!d._lastTrailSpawnY) d._lastTrailSpawnY = d.y;
const dist = Math.abs(d.y - d._lastTrailSpawnY);
const threshold = Math.max(10 * this.dpr, d.r * 0.6);
if (dist > threshold && Math.random() < 0.25 && this.drops.length < this.maxDrops) {
const microR = Math.max(1.5 * this.dpr, Math.ceil(d.r / 6));
this.spawn(d.x, d.y - d.r - 4 * this.dpr, microR);
d._lastTrailSpawnY = d.y;
}
}
}
// merging (grid-assisted if enabled)
if (this.enableCollisions) {
const cell = this.collisionCell * this.dpr;
const cols = Math.max(1, Math.ceil(this.canvas.width / cell));
const rows = Math.max(1, Math.ceil(this.canvas.height / cell));
if (!this.grid || this.grid.cols !== cols || this.grid.rows !== rows) {
this.grid = { cols, rows, buckets: Array.from({ length: cols * rows }, () => []) };
} else {
for (const b of this.grid.buckets) b.length = 0;
}
// bin drops
for (let i = 0; i < this.drops.length; i++) {