-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreveal copy.html
More file actions
1005 lines (843 loc) · 39.2 KB
/
reveal copy.html
File metadata and controls
1005 lines (843 loc) · 39.2 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
<!--
Portfolio Reveal - Click to release cloth, revealing portfolio
Based on cloth physics by Matthias Müller - Ten Minute Physics
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0">
<title>Guccione - Portfolio Reveal</title>
<!-- Portfolio styles -->
<link rel="stylesheet" type="text/css" href="./portfolio/css/desktop.css" />
<link rel="stylesheet" type="text/css" href="./portfolio/css/fonts.css" />
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body {
overflow: hidden;
height: 100vh;
width: 100vw;
}
/* Portfolio layer - sits behind the cloth */
#portfolio-layer {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 1;
background: #fff;
}
/* Portfolio content styling */
#homeScreen {
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: #fff;
}
#scrollIndicator { display: none; }
#searchItemsWrapper {
display: flex;
flex-direction: column;
align-items: center;
}
/* Cloth canvas layer - overlay */
#cloth-layer {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 10;
pointer-events: auto;
cursor: grab;
}
#cloth-layer:active {
cursor: grabbing;
}
</style>
</head>
<body>
<!-- LAYER 1: Portfolio landing page (revealed when cloth falls away) -->
<div id="portfolio-layer">
<div id="homeScreen" class="hero-wrapper">
<div id="homeScreenNav" class="home-nav">
<a href="#" class="navOption selectedNavOption">Work</a>
<a href="#" class="navOption">Images</a>
<a href="#" class="navOption">About</a>
</div>
<div id="searchItemsWrapper">
<div id="title">
<img src="./portfolio/assets/guccione-logo-3.svg" id="homeLogo" alt="Guccione">
</div>
<div id="homeScreenSearchContainer">
<input id="searchInput" placeholder="" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false">
<div id="btnContainer">
<button id="searchBtn">Search Work</button>
<button id="luckyBtn">I'm Feeling Lucky</button>
</div>
</div>
</div>
<div id="homeScreenInfo">
<a href="mailto:fabrizio.guccione@gmail.com?subject=Advertising%20Space%20Opportunities">Contact me for Advertising Space Opportunities</a>
<p>
<font size=-2>©2025 - <a href="#">Privacy</a></font>
</p>
</div>
</div>
</div>
<!-- LAYER 2: Cloth simulation canvas -->
<div id="cloth-layer"></div>
<!-- Three.js -->
<script src="https://unpkg.com/three@0.139.2/build/three.min.js"></script>
<script src="https://unpkg.com/three@0.139.2/examples/js/controls/OrbitControls.js"></script>
<script>
// ----- Vector math (exactly as original Ten Minute Physics) -----
function vecSetZero(a,anr) {
anr *= 3;
a[anr++] = 0.0;
a[anr++] = 0.0;
a[anr] = 0.0;
}
function vecScale(a,anr, scale) {
anr *= 3;
a[anr++] *= scale;
a[anr++] *= scale;
a[anr] *= scale;
}
function vecCopy(a,anr, b,bnr) {
anr *= 3; bnr *= 3;
a[anr++] = b[bnr++];
a[anr++] = b[bnr++];
a[anr] = b[bnr];
}
function vecAdd(a,anr, b,bnr, scale = 1.0) {
anr *= 3; bnr *= 3;
a[anr++] += b[bnr++] * scale;
a[anr++] += b[bnr++] * scale;
a[anr] += b[bnr] * scale;
}
function vecSetDiff(dst,dnr, a,anr, b,bnr, scale = 1.0) {
dnr *= 3; anr *= 3; bnr *= 3;
dst[dnr++] = (a[anr++] - b[bnr++]) * scale;
dst[dnr++] = (a[anr++] - b[bnr++]) * scale;
dst[dnr] = (a[anr] - b[bnr]) * scale;
}
function vecLengthSquared(a,anr) {
anr *= 3;
let a0 = a[anr], a1 = a[anr + 1], a2 = a[anr + 2];
return a0 * a0 + a1 * a1 + a2 * a2;
}
function vecDistSquared(a,anr, b,bnr) {
anr *= 3; bnr *= 3;
let a0 = a[anr] - b[bnr], a1 = a[anr + 1] - b[bnr + 1], a2 = a[anr + 2] - b[bnr + 2];
return a0 * a0 + a1 * a1 + a2 * a2;
}
function vecSetCross(a,anr, b,bnr, c,cnr) {
anr *= 3; bnr *= 3; cnr *= 3;
a[anr++] = b[bnr + 1] * c[cnr + 2] - b[bnr + 2] * c[cnr + 1];
a[anr++] = b[bnr + 2] * c[cnr + 0] - b[bnr + 0] * c[cnr + 2];
a[anr] = b[bnr + 0] * c[cnr + 1] - b[bnr + 1] * c[cnr + 0];
}
function vecDot(a,anr, b,bnr) {
anr *= 3; bnr *= 3;
return a[anr] * b[bnr] + a[anr + 1] * b[bnr + 1] + a[anr + 2] * b[bnr + 2];
}
function vecSetSum(dst,dnr, a,anr, b,bnr, scale = 1.0) {
dnr *= 3; anr *= 3; bnr *= 3;
dst[dnr++] = (a[anr++] + b[bnr++]) * scale;
dst[dnr++] = (a[anr++] + b[bnr++]) * scale;
dst[dnr] = (a[anr] + b[bnr]) * scale;
}
// ----- Scene globals -----
var gThreeScene;
var gRenderer;
var gCamera;
var gGrabber;
var gCloth = null;
var gTextureLoader = new THREE.TextureLoader();
var gClothTexture = null;
var gSimulationStarted = false;
var gPhysicsScene = {
gravity: [0.0, -10.0, 0.0],
dt: 1.0 / 60.0,
numSubsteps: 15,
paused: true, // START PAUSED
thickness: 0.02 // Cloth thickness for collisions
};
// ----- Hash class for spatial collision detection (from Ten Minute Physics) -----
class Hash {
constructor(spacing, maxNumObjects) {
this.spacing = spacing;
this.tableSize = 5 * maxNumObjects;
this.cellStart = new Int32Array(this.tableSize + 1);
this.cellEntries = new Int32Array(maxNumObjects);
this.queryIds = new Int32Array(maxNumObjects);
this.querySize = 0;
this.maxNumObjects = maxNumObjects;
this.firstAdjId = new Int32Array(maxNumObjects + 1);
this.adjIds = new Int32Array(10 * maxNumObjects);
}
hashCoords(xi, yi, zi) {
var h = (xi * 92837111) ^ (yi * 689287499) ^ (zi * 283923481);
return Math.abs(h) % this.tableSize;
}
intCoord(coord) {
return Math.floor(coord / this.spacing);
}
hashPos(pos, nr) {
return this.hashCoords(
this.intCoord(pos[3 * nr]),
this.intCoord(pos[3 * nr + 1]),
this.intCoord(pos[3 * nr + 2]));
}
create(pos) {
var numObjects = Math.min(pos.length / 3, this.cellEntries.length);
this.cellStart.fill(0);
this.cellEntries.fill(0);
for (var i = 0; i < numObjects; i++) {
var h = this.hashPos(pos, i);
this.cellStart[h]++;
}
var start = 0;
for (var i = 0; i < this.tableSize; i++) {
start += this.cellStart[i];
this.cellStart[i] = start;
}
this.cellStart[this.tableSize] = start;
for (var i = 0; i < numObjects; i++) {
var h = this.hashPos(pos, i);
this.cellStart[h]--;
this.cellEntries[this.cellStart[h]] = i;
}
}
query(pos, nr, maxDist) {
var x0 = this.intCoord(pos[3 * nr] - maxDist);
var y0 = this.intCoord(pos[3 * nr + 1] - maxDist);
var z0 = this.intCoord(pos[3 * nr + 2] - maxDist);
var x1 = this.intCoord(pos[3 * nr] + maxDist);
var y1 = this.intCoord(pos[3 * nr + 1] + maxDist);
var z1 = this.intCoord(pos[3 * nr + 2] + maxDist);
this.querySize = 0;
for (var xi = x0; xi <= x1; xi++) {
for (var yi = y0; yi <= y1; yi++) {
for (var zi = z0; zi <= z1; zi++) {
var h = this.hashCoords(xi, yi, zi);
var start = this.cellStart[h];
var end = this.cellStart[h + 1];
for (var i = start; i < end; i++) {
this.queryIds[this.querySize] = this.cellEntries[i];
this.querySize++;
}
}
}
}
}
queryAll(pos, maxDist) {
var num = 0;
var maxDist2 = maxDist * maxDist;
for (var i = 0; i < this.maxNumObjects; i++) {
var id0 = i;
this.firstAdjId[id0] = num;
this.query(pos, id0, maxDist);
for (var j = 0; j < this.querySize; j++) {
var id1 = this.queryIds[j];
if (id1 >= id0) continue;
var dist2 = vecDistSquared(pos, id0, pos, id1);
if (dist2 > maxDist2) continue;
if (num >= this.adjIds.length) {
var newIds = new Int32Array(2 * num);
newIds.set(this.adjIds);
this.adjIds = newIds;
}
this.adjIds[num++] = id1;
}
}
this.firstAdjId[this.maxNumObjects] = num;
}
}
// ----- Cloth class (matching Ten Minute Physics structure) -----
class Cloth {
constructor(mesh, scene) {
// Particles - DIRECTLY copy mesh vertices (no flattening!)
this.numParticles = mesh.verts.length / 3;
this.pos = new Float32Array(mesh.verts);
this.prevPos = new Float32Array(mesh.verts);
this.restPos = new Float32Array(mesh.verts); // ADDED: Rest positions for collision reference
this.vel = new Float32Array(3 * this.numParticles);
this.invMass = new Float32Array(this.numParticles);
// Collision handling (from Ten Minute Physics)
this.thickness = gPhysicsScene.thickness;
this.handleCollisions = true;
this.hash = new Hash(this.thickness, this.numParticles);
this.vecs = new Float32Array(4 * 3); // Temp vectors for collision calculations
// Constraints
this.stretchingIds = mesh.stretchingIds;
this.stretchingLengths = new Float32Array(this.stretchingIds.length / 2);
this.stretchingCompliance = 0.0;
this.bendingIds = mesh.bendingIds;
this.bendingLengths = new Float32Array(this.bendingIds.length / 4);
this.bendingCompliance = 1.0;
this.grads = new Float32Array(4 * 3);
this.grabId = -1;
this.grabInvMass = 0.0;
// Initialize physics (calculates masses and constraint lengths from this.pos)
this.initPhysics(mesh.faceTriIds);
// Visual edge mesh (hidden)
var geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(this.pos, 3));
geometry.setIndex(mesh.stretchingIds);
this.edgeMesh = new THREE.LineSegments(geometry, new THREE.LineBasicMaterial({color: 0xff0000}));
this.edgeMesh.visible = false;
scene.add(this.edgeMesh);
// Visual triangle mesh
geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(this.pos, 3));
geometry.setIndex(mesh.faceTriIds);
// UV coordinates
var minX = Infinity, maxX = -Infinity;
var minY = Infinity, maxY = -Infinity;
for (var i = 0; i < this.numParticles; i++) {
var x = this.pos[3 * i];
var y = this.pos[3 * i + 1];
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minY = Math.min(minY, y);
maxY = Math.max(maxY, y);
}
var textureAspect = 3024 / 1722;
var viewportAspect = window.innerWidth / window.innerHeight;
this.uvs = new Float32Array(2 * this.numParticles);
for (var i = 0; i < this.numParticles; i++) {
var x = this.pos[3 * i];
var y = this.pos[3 * i + 1];
var u = (x - minX) / (maxX - minX);
var v = (y - minY) / (maxY - minY);
if (viewportAspect > textureAspect) {
var scale = textureAspect / viewportAspect;
var offset = (1 - scale) / 2;
v = offset + v * scale;
} else {
var scale = viewportAspect / textureAspect;
var offset = (1 - scale) / 2;
u = offset + u * scale;
}
this.uvs[2 * i] = u;
this.uvs[2 * i + 1] = v;
}
geometry.setAttribute('uv', new THREE.BufferAttribute(this.uvs, 2));
// Material
var visMaterial = gClothTexture
? new THREE.MeshBasicMaterial({ map: gClothTexture, side: THREE.DoubleSide })
: new THREE.MeshBasicMaterial({ color: 0xcccccc, side: THREE.DoubleSide });
this.triMesh = new THREE.Mesh(geometry, visMaterial);
this.triMesh.userData = this;
// Scale to fill viewport
var clothWidth = maxX - minX;
var clothHeight = maxY - minY;
var visibleHeight = 2.5 * 2 * Math.tan(25 * Math.PI / 180);
var visibleWidth = visibleHeight * viewportAspect;
var scaleY = visibleHeight / clothHeight * 1.15;
var scaleX = visibleWidth / clothWidth * 1.15;
// Validate scales to prevent division issues
if (!isFinite(scaleX) || scaleX <= 0.001) {
console.warn("Invalid scaleX:", scaleX, "- using default");
scaleX = 1.0;
}
if (!isFinite(scaleY) || scaleY <= 0.001) {
console.warn("Invalid scaleY:", scaleY, "- using default");
scaleY = 1.0;
}
this.triMesh.scale.set(scaleX, scaleY, 1);
var clothCenterY = (minY + maxY) / 2;
var meshOffsetY = -clothCenterY * scaleY;
this.triMesh.position.set(0, meshOffsetY, 0);
this.clothScale = { x: scaleX, y: scaleY };
this.meshOffset = { x: 0, y: meshOffsetY };
this.triMesh.layers.enable(1);
scene.add(this.triMesh);
geometry.computeVertexNormals();
this.updateMeshes();
}
initPhysics(triIds) {
// Calculate mass from triangle areas (using this.pos)
this.invMass.fill(0.0);
var numTris = triIds.length / 3;
var e0 = [0.0, 0.0, 0.0];
var e1 = [0.0, 0.0, 0.0];
var c = [0.0, 0.0, 0.0];
for (var i = 0; i < numTris; i++) {
var id0 = triIds[3 * i];
var id1 = triIds[3 * i + 1];
var id2 = triIds[3 * i + 2];
vecSetDiff(e0, 0, this.pos, id1, this.pos, id0);
vecSetDiff(e1, 0, this.pos, id2, this.pos, id0);
vecSetCross(c, 0, e0, 0, e1, 0);
var A = 0.5 * Math.sqrt(vecLengthSquared(c, 0));
var pInvMass = A > 0.0 ? 1.0 / A / 3.0 : 0.0;
this.invMass[id0] += pInvMass;
this.invMass[id1] += pInvMass;
this.invMass[id2] += pInvMass;
}
// Stretching constraint rest lengths (from this.pos)
for (var i = 0; i < this.stretchingLengths.length; i++) {
var id0 = this.stretchingIds[2 * i];
var id1 = this.stretchingIds[2 * i + 1];
// Bounds check
if (id0 < 0 || id0 >= this.numParticles || id1 < 0 || id1 >= this.numParticles) {
console.error("Invalid stretching constraint:", i, id0, id1);
this.stretchingLengths[i] = 0.01;
continue;
}
this.stretchingLengths[i] = Math.sqrt(vecDistSquared(this.pos, id0, this.pos, id1));
// Validate and fix zero/NaN lengths
if (!isFinite(this.stretchingLengths[i]) || this.stretchingLengths[i] <= 0) {
console.warn("Invalid stretching length at", i, ":", this.stretchingLengths[i]);
this.stretchingLengths[i] = 0.01;
}
}
// Bending constraint rest lengths (from this.pos)
for (var i = 0; i < this.bendingLengths.length; i++) {
var id0 = this.bendingIds[4 * i + 2];
var id1 = this.bendingIds[4 * i + 3];
// Bounds check
if (id0 < 0 || id0 >= this.numParticles || id1 < 0 || id1 >= this.numParticles) {
console.error("Invalid bending constraint:", i, id0, id1);
this.bendingLengths[i] = 0.01;
continue;
}
this.bendingLengths[i] = Math.sqrt(vecDistSquared(this.pos, id0, this.pos, id1));
// Validate and fix zero/NaN lengths
if (!isFinite(this.bendingLengths[i]) || this.bendingLengths[i] <= 0) {
console.warn("Invalid bending length at", i, ":", this.bendingLengths[i]);
this.bendingLengths[i] = 0.01;
}
}
// NO corner pins - user wanted only mouse to anchor
}
preSolve(dt, gravity) {
var maxVelocity = 0.2 * this.thickness / dt; // ADDED: Velocity clamping
for (var i = 0; i < this.numParticles; i++) {
if (this.invMass[i] == 0.0) continue;
// Apply gravity
vecAdd(this.vel, i, gravity, 0, dt);
// ADDED: Clamp velocity to prevent numerical explosion
var v = Math.sqrt(vecLengthSquared(this.vel, i));
if (v > maxVelocity) {
vecScale(this.vel, i, maxVelocity / v);
}
vecCopy(this.prevPos, i, this.pos, i);
vecAdd(this.pos, i, this.vel, i, dt);
}
}
solve(dt) {
this.solveStretching(this.stretchingCompliance, dt);
this.solveBending(this.bendingCompliance, dt);
}
postSolve(dt) {
for (var i = 0; i < this.numParticles; i++) {
if (this.invMass[i] == 0.0) continue;
vecSetDiff(this.vel, i, this.pos, i, this.prevPos, i, 1.0 / dt);
}
}
solveStretching(compliance, dt) {
var alpha = compliance / dt / dt;
for (var i = 0; i < this.stretchingLengths.length; i++) {
var id0 = this.stretchingIds[2 * i];
var id1 = this.stretchingIds[2 * i + 1];
var w0 = this.invMass[id0];
var w1 = this.invMass[id1];
var w = w0 + w1;
if (w == 0.0) continue;
vecSetDiff(this.grads, 0, this.pos, id0, this.pos, id1);
var len = Math.sqrt(vecLengthSquared(this.grads, 0));
if (len < 0.0001) continue; // Skip degenerate constraints
vecScale(this.grads, 0, 1.0 / len);
var restLen = this.stretchingLengths[i];
var C = len - restLen;
var s = -C / (w + alpha);
// Clamp correction to prevent explosion
var maxCorrection = 0.1;
if (Math.abs(s) > maxCorrection) s = Math.sign(s) * maxCorrection;
vecAdd(this.pos, id0, this.grads, 0, s * w0);
vecAdd(this.pos, id1, this.grads, 0, -s * w1);
}
}
solveBending(compliance, dt) {
var alpha = compliance / dt / dt;
for (var i = 0; i < this.bendingLengths.length; i++) {
var id0 = this.bendingIds[4 * i + 2];
var id1 = this.bendingIds[4 * i + 3];
var w0 = this.invMass[id0];
var w1 = this.invMass[id1];
var w = w0 + w1;
if (w == 0.0) continue;
vecSetDiff(this.grads, 0, this.pos, id0, this.pos, id1);
var len = Math.sqrt(vecLengthSquared(this.grads, 0));
if (len < 0.0001) continue; // Skip degenerate constraints
vecScale(this.grads, 0, 1.0 / len);
var restLen = this.bendingLengths[i];
var C = len - restLen;
var s = -C / (w + alpha);
// Clamp correction to prevent explosion
var maxCorrection = 0.1;
if (Math.abs(s) > maxCorrection) s = Math.sign(s) * maxCorrection;
vecAdd(this.pos, id0, this.grads, 0, s * w0);
vecAdd(this.pos, id1, this.grads, 0, -s * w1);
}
}
// ADDED: Self-collision handling from Ten Minute Physics
solveCollisions(dt) {
var thickness2 = this.thickness * this.thickness;
for (var i = 0; i < this.numParticles; i++) {
if (this.invMass[i] == 0.0) continue;
var id0 = i;
var first = this.hash.firstAdjId[i];
var last = this.hash.firstAdjId[i + 1];
for (var j = first; j < last; j++) {
var id1 = this.hash.adjIds[j];
if (this.invMass[id1] == 0.0) continue;
vecSetDiff(this.vecs, 0, this.pos, id1, this.pos, id0);
var dist2 = vecLengthSquared(this.vecs, 0);
if (dist2 > thickness2 || dist2 == 0.0) continue;
var restDist2 = vecDistSquared(this.restPos, id0, this.restPos, id1);
var minDist = this.thickness;
if (dist2 > restDist2) continue;
if (restDist2 < thickness2) minDist = Math.sqrt(restDist2);
// Position correction
var dist = Math.sqrt(dist2);
vecScale(this.vecs, 0, (minDist - dist) / dist);
vecAdd(this.pos, id0, this.vecs, 0, -0.5);
vecAdd(this.pos, id1, this.vecs, 0, 0.5);
// Velocity averaging for friction
vecSetDiff(this.vecs, 0, this.pos, id0, this.prevPos, id0);
vecSetDiff(this.vecs, 1, this.pos, id1, this.prevPos, id1);
vecSetSum(this.vecs, 2, this.vecs, 0, this.vecs, 1, 0.5);
vecSetDiff(this.vecs, 0, this.vecs, 2, this.vecs, 0);
vecSetDiff(this.vecs, 1, this.vecs, 2, this.vecs, 1);
var friction = 0.0;
vecAdd(this.pos, id0, this.vecs, 0, friction);
vecAdd(this.pos, id1, this.vecs, 1, friction);
}
}
}
updateMeshes() {
// Check for NaN in position buffer and recover if needed
var hasNaN = false;
for (var i = 0; i < this.pos.length; i++) {
if (!isFinite(this.pos[i])) {
hasNaN = true;
break;
}
}
if (hasNaN) {
console.error("NaN detected in position buffer! Resetting to rest positions.");
this.pos.set(this.restPos);
this.prevPos.set(this.restPos);
this.vel.fill(0);
}
this.triMesh.geometry.attributes.position.needsUpdate = true;
this.triMesh.geometry.computeVertexNormals();
this.triMesh.geometry.computeBoundingSphere();
this.edgeMesh.geometry.attributes.position.needsUpdate = true;
}
startGrab(pos) {
var p = [pos.x, pos.y, pos.z];
// Validate input position
if (!isFinite(p[0]) || !isFinite(p[1]) || !isFinite(p[2])) {
console.error("startGrab: Invalid position", p);
return;
}
var minD2 = Number.MAX_VALUE;
this.grabId = -1;
for (var i = 0; i < this.numParticles; i++) {
var d2 = vecDistSquared(p, 0, this.pos, i);
if (d2 < minD2) {
minD2 = d2;
this.grabId = i;
}
}
if (this.grabId >= 0) {
this.grabInvMass = this.invMass[this.grabId];
this.invMass[this.grabId] = 0.0;
vecCopy(this.pos, this.grabId, p, 0);
vecCopy(this.prevPos, this.grabId, p, 0); // CRITICAL: Sync prevPos to avoid velocity spike
}
}
moveGrabbed(pos) {
if (this.grabId >= 0) {
var p = [pos.x, pos.y, pos.z];
// Validate input position
if (!isFinite(p[0]) || !isFinite(p[1]) || !isFinite(p[2])) {
console.error("moveGrabbed: Invalid position", p);
return;
}
vecCopy(this.pos, this.grabId, p, 0);
vecCopy(this.prevPos, this.grabId, p, 0); // CRITICAL: Sync prevPos to avoid velocity spike
}
}
endGrab(vel) {
if (this.grabId >= 0) {
this.invMass[this.grabId] = this.grabInvMass;
// Validate velocity and clamp if needed
var v = [vel.x, vel.y, vel.z];
if (!isFinite(v[0]) || !isFinite(v[1]) || !isFinite(v[2])) {
v = [0, 0, 0]; // Safe fallback
}
// Clamp release velocity to prevent explosion
var maxReleaseVel = 5.0;
var vMag = Math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
if (vMag > maxReleaseVel) {
var scale = maxReleaseVel / vMag;
v[0] *= scale;
v[1] *= scale;
v[2] *= scale;
}
vecCopy(this.vel, this.grabId, v, 0);
}
this.grabId = -1;
}
}
// ----- Grabber class -----
class Grabber {
constructor() {
this.raycaster = new THREE.Raycaster();
this.raycaster.layers.set(1);
this.physicsObject = null;
this.distance = 0.0;
this.prevPos = new THREE.Vector3();
this.vel = new THREE.Vector3();
this.time = 0.0;
}
increaseTime(dt) { this.time += dt; }
updateRaycaster(x, y) {
var rect = gRenderer.domElement.getBoundingClientRect();
var mousePos = new THREE.Vector2(
((x - rect.left) / rect.width) * 2 - 1,
-((y - rect.top) / rect.height) * 2 + 1
);
this.raycaster.setFromCamera(mousePos, gCamera);
}
start(x, y) {
this.physicsObject = null;
this.updateRaycaster(x, y);
var intersects = this.raycaster.intersectObjects(gThreeScene.children);
if (intersects.length > 0) {
var obj = intersects[0].object.userData;
if (obj) {
this.physicsObject = obj;
this.distance = intersects[0].distance;
var pos = this.raycaster.ray.origin.clone();
pos.addScaledVector(this.raycaster.ray.direction, this.distance);
// Transform world position to local physics space using THREE.js
if (obj.triMesh) {
pos = obj.triMesh.worldToLocal(pos.clone());
}
// Validate position to prevent NaN propagation
if (!isFinite(pos.x) || !isFinite(pos.y) || !isFinite(pos.z)) {
console.error("Invalid grab position:", pos);
this.physicsObject = null;
return;
}
this.physicsObject.startGrab(pos);
this.prevPos.copy(pos);
this.vel.set(0, 0, 0);
this.time = 0.0;
}
}
}
move(x, y) {
if (this.physicsObject) {
this.updateRaycaster(x, y);
var pos = this.raycaster.ray.origin.clone();
pos.addScaledVector(this.raycaster.ray.direction, this.distance);
// Transform world position to local physics space using THREE.js
if (this.physicsObject.triMesh) {
pos = this.physicsObject.triMesh.worldToLocal(pos.clone());
}
// Validate position to prevent NaN propagation
if (!isFinite(pos.x) || !isFinite(pos.y) || !isFinite(pos.z)) {
console.error("Invalid move position:", pos);
return;
}
this.vel.copy(pos).sub(this.prevPos);
if (this.time > 0.0) this.vel.divideScalar(this.time);
else this.vel.set(0, 0, 0);
this.prevPos.copy(pos);
this.time = 0.0;
this.physicsObject.moveGrabbed(pos);
}
}
end() {
if (this.physicsObject) {
this.physicsObject.endGrab(this.vel);
this.physicsObject = null;
}
}
}
// ----- Event handlers -----
function onPointer(evt) {
evt.preventDefault();
if (evt.type == "pointerdown") {
// First click starts the simulation
if (!gSimulationStarted) {
gSimulationStarted = true;
gPhysicsScene.paused = false;
}
gGrabber.start(evt.clientX, evt.clientY);
}
else if (evt.type == "pointermove" && gGrabber.physicsObject) {
gGrabber.move(evt.clientX, evt.clientY);
}
else if (evt.type == "pointerup") {
gGrabber.end();
}
}
function onWindowResize() {
gCamera.aspect = window.innerWidth / window.innerHeight;
gCamera.updateProjectionMatrix();
gRenderer.setSize(window.innerWidth, window.innerHeight);
}
// ----- Scene setup -----
function initThreeScene() {
gThreeScene = new THREE.Scene();
var container = document.getElementById('cloth-layer');
// Load texture
gClothTexture = gTextureLoader.load('./assets/realFullGoogleScreenshot.png');
gClothTexture.wrapS = THREE.ClampToEdgeWrapping;
gClothTexture.wrapT = THREE.ClampToEdgeWrapping;
// Lighting
gThreeScene.add(new THREE.AmbientLight(0xffffff, 0.8));
var dirLight = new THREE.DirectionalLight(0xffffff, 0.4);
dirLight.position.set(0, 2, 2);
gThreeScene.add(dirLight);
// Transparent renderer
gRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
gRenderer.setClearColor(0x000000, 0);
gRenderer.setPixelRatio(window.devicePixelRatio);
gRenderer.setSize(window.innerWidth, window.innerHeight);
window.addEventListener('resize', onWindowResize);
container.appendChild(gRenderer.domElement);
// Camera
gCamera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.01, 100);
gCamera.position.set(0, 0, 2.5);
gThreeScene.add(gCamera);
// Grabber
gGrabber = new Grabber();
container.addEventListener('pointerdown', onPointer);
container.addEventListener('pointermove', onPointer);
container.addEventListener('pointerup', onPointer);
}
// ----- Animation loop -----
function update() {
if (!gPhysicsScene.paused && gCloth) {
var sdt = gPhysicsScene.dt / gPhysicsScene.numSubsteps;
var maxVelocity = 0.2 * gCloth.thickness / sdt;
// Build collision hash ONCE per frame (not per substep!)
if (gCloth.handleCollisions) {
gCloth.hash.create(gCloth.pos);
var maxTravelDist = maxVelocity * gPhysicsScene.dt;
gCloth.hash.queryAll(gCloth.pos, maxTravelDist);
}
for (var step = 0; step < gPhysicsScene.numSubsteps; step++) {
gCloth.preSolve(sdt, gPhysicsScene.gravity);
gCloth.solve(sdt);
// Solve collisions during each substep
if (gCloth.handleCollisions) {
gCloth.solveCollisions(sdt);
}
gCloth.postSolve(sdt);
}
gCloth.updateMeshes();
gGrabber.increaseTime(gPhysicsScene.dt);
}
gRenderer.render(gThreeScene, gCamera);
requestAnimationFrame(update);
}
// ----- Generate cloth mesh dynamically (like Ten Minute Physics) -----
function generateClothMesh(numX, numY, spacing) {
var numParticles = numX * numY;
var verts = [];
var faceTriIds = [];
var stretchingIds = [];
var bendingIds = [];
// Generate vertices (flat grid in XY plane, centered at origin)
var halfWidth = (numX - 1) * spacing * 0.5;
var halfHeight = (numY - 1) * spacing * 0.5;
for (var i = 0; i < numX; i++) {
for (var j = 0; j < numY; j++) {
var x = -halfWidth + i * spacing;
var y = -halfHeight + j * spacing;
var z = 0;
verts.push(x, y, z);
}
}
// Generate triangle indices
for (var i = 0; i < numX - 1; i++) {
for (var j = 0; j < numY - 1; j++) {
var id = i * numY + j;
// Two triangles per quad
faceTriIds.push(id, id + numY, id + 1);
faceTriIds.push(id + 1, id + numY, id + numY + 1);
}
}
// Generate stretching constraints (edges)
// Horizontal edges
for (var i = 0; i < numX - 1; i++) {
for (var j = 0; j < numY; j++) {
stretchingIds.push(i * numY + j, (i + 1) * numY + j);
}
}
// Vertical edges
for (var i = 0; i < numX; i++) {
for (var j = 0; j < numY - 1; j++) {
stretchingIds.push(i * numY + j, i * numY + j + 1);
}
}
// Generate bending constraints (skip-one neighbors)
// The solver reads indices 2 and 3 from each constraint [_,_,id0,id1]
// Horizontal bending: connect vertices that skip one horizontally
for (var i = 0; i < numX - 2; i++) {
for (var j = 0; j < numY; j++) {
var idLeft = i * numY + j;
var idRight = (i + 2) * numY + j;
// Format: [unused, unused, vertex0, vertex1]
bendingIds.push(0, 0, idLeft, idRight);
}
}
// Vertical bending: connect vertices that skip one vertically
for (var i = 0; i < numX; i++) {
for (var j = 0; j < numY - 2; j++) {
var idTop = i * numY + j;
var idBottom = i * numY + j + 2;
bendingIds.push(0, 0, idTop, idBottom);
}
}
console.log("Generated mesh: " + numX + "x" + numY + " = " + numParticles + " particles");
console.log(" verts: " + verts.length + " (" + (verts.length/3) + " vertices)");
console.log(" faces: " + faceTriIds.length/3 + " triangles");
console.log(" stretching: " + stretchingIds.length/2 + " constraints");
console.log(" bending: " + bendingIds.length/4 + " constraints");
return {
verts: verts,
faceTriIds: faceTriIds,
stretchingIds: stretchingIds,
bendingIds: bendingIds
};
}
// Generate a 20x30 cloth grid (600 particles) - good balance of detail and performance
var clothMesh = generateClothMesh(20, 30, 0.02);
// ----- Start -----
function start() {
initThreeScene();
setTimeout(function() {
gCloth = new Cloth(clothMesh, gThreeScene);
update();
}, 100);
}