-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloth.html
More file actions
677 lines (614 loc) · 25.9 KB
/
Copy pathcloth.html
File metadata and controls
677 lines (614 loc) · 25.9 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cloth Simulation</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: #080810; overflow: hidden; font-family: 'SF Mono', 'Fira Code', monospace; }
canvas { display: block; touch-action: none; cursor: crosshair; }
#ui {
position: fixed; top: 20px; left: 20px;
color: rgba(255,255,255,0.4); font-size: 11px; line-height: 2;
pointer-events: none; user-select: none;
}
#ui b { color: rgba(255,255,255,0.8); font-weight: normal; }
#controls {
position: fixed; top: 20px; right: 20px;
display: flex; flex-direction: column; gap: 7px;
}
button {
background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.12);
color: rgba(255,255,255,0.6); padding: 6px 13px; font-size: 11px;
font-family: inherit; cursor: pointer; border-radius: 5px; transition: all 0.12s;
letter-spacing: 0.04em; min-width: 100px; text-align: left;
-webkit-tap-highlight-color: transparent;
}
button:hover { background: rgba(255,255,255,0.11); color: rgba(255,255,255,0.9); border-color: rgba(255,255,255,0.25); }
button.on { background: rgba(100,160,255,0.13); border-color: rgba(100,160,255,0.35); color: rgba(130,185,255,0.9); }
button.warn { background: rgba(255,100,80,0.1); border-color: rgba(255,100,80,0.3); color: rgba(255,140,120,0.9); }
hr.sep { border: none; border-top: 1px solid rgba(255,255,255,0.08); margin: 2px 0; }
#footer {
position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%);
color: rgba(255,255,255,0.12); font-size: 10px; letter-spacing: 0.25em;
text-transform: uppercase; pointer-events: none;
}
@media (max-width: 768px) {
#ui { display: none; }
button { min-width: 90px; padding: 10px 10px; font-size: 12px; }
}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="ui">
<div><b>drag</b> — grab & pull cloth</div>
<div><b>right-drag</b> — knife cut</div>
<div><b>shift+drag</b> — blow burst</div>
</div>
<div id="controls">
<button id="btnReset">reset</button>
<button id="btnGravity" class="on">gravity</button>
<button id="btnWind">wind</button>
<button id="btnGyro">gyro</button>
<button id="btnColor">mono</button>
<hr class="sep">
<button id="btnMat">linen</button>
<hr class="sep">
<button id="btnCoarse">coarsen −</button>
<button id="btnFine">refine +</button>
<hr class="sep">
<button id="btnTouchMode">✂ cut</button>
</div>
<div id="footer">cloth simulation</div>
<script>
'use strict';
// ─── Canvas ─────────────────────────────────────────────────────────────────
const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d', { alpha: false });
let viewWidth = 1;
let viewHeight = 1;
let dpr = 1;
// ─── Resolution levels: [cols, rows] — physical cloth size stays constant ───
const LEVELS = [
[20, 14],
[30, 21],
[40, 28], // default (matches original)
[56, 38],
];
// ─── Material presets ────────────────────────────────────────────────────────
// grav: gravity per frame, damp: velocity damping, stiff: constraint stiffness
const MATERIALS = [
{ name: 'linen', grav: 0.65, damp: 0.981, stiff: 1.00 },
{ name: 'silk', grav: 0.15, damp: 0.997, stiff: 0.82 },
{ name: 'cotton', grav: 0.45, damp: 0.987, stiff: 0.95 },
{ name: 'polyester', grav: 0.32, damp: 0.993, stiff: 0.98 },
];
// ─── Config ──────────────────────────────────────────────────────────────────
const CUT_R = 20;
const GRAB_R = 50;
const PIN_STEP = 4;
const CLOTH_W = 0.75; // fraction of screen width
const FIXED_DT = 1 / 60;
const MAX_STEPS = 4;
const COLOR_BUCKETS = 24;
// ─── State ───────────────────────────────────────────────────────────────────
let COLS, ROWS, SPACING, ITERS;
let px, py, ppx, ppy, pinned;
let cp1, cp2, clen, cactive;
let nP = 0, nC = 0;
let level = 2; // index into LEVELS
let matIdx = 0; // index into MATERIALS
let gravOn = true;
let windOn = false;
let colorMode = 0;
let touchMode = 0; // 0=grab, 1=cut
let time = 0;
// ─── Gyroscope / motion (mobile tilt-to-tip, shake-to-gust) ──────────────────
let gyroOn = false;
let gyroBaseline = null; // { beta, gamma } captured when gyro is enabled
let gravDirX = 0; // smoothed gravity direction, unit-ish vector
let gravDirY = 1; // default: straight down
let gravTargetX = 0;
let gravTargetY = 1;
let lastAccel = null;
let shakeImpulseX = 0;
let shakeImpulseY = 0;
const GYRO_MAX_TILT = 40; // degrees of tilt for full gravity redirect
const GYRO_SMOOTH = 0.12; // per-frame lerp toward target (damps sensor jitter)
const SHAKE_THRESHOLD = 12; // m/s^2 of jerk that counts as a shake
const SHAKE_GAIN = 2.2; // px of impulse per m/s^2 of jerk
const SHAKE_MAX = 40; // px, impulse cap
const SHAKE_DECAY = 0.85; // per physics step
// ─── Mouse / touch ───────────────────────────────────────────────────────────
const mouse = { x: 0, y: 0, lx: 0, ly: 0, down: false, right: false, shift: false };
let grabbed = -1;
let grabPrevX = 0;
let grabPrevY = 0;
let activePointer = -1;
let multiTouch = false;
const pointers = new Map();
// ─── Build cloth ─────────────────────────────────────────────────────────────
function buildCloth() {
[COLS, ROWS] = LEVELS[level];
const maxWidthByHeight = viewHeight * 0.82 * (COLS - 1) / (ROWS - 1);
const clothPx = Math.min(viewWidth * CLOTH_W, maxWidthByHeight, 820);
SPACING = clothPx / (COLS - 1);
// Enough passes for tension propagation without overspending on dense meshes.
ITERS = Math.max(16, Math.ceil(ROWS * 0.8));
const startX = (viewWidth - (COLS - 1) * SPACING) / 2;
const startY = Math.max(18, viewHeight * 0.07);
const pinStep = Math.max(1, Math.round(PIN_STEP * (COLS - 1) / (LEVELS[2][0] - 1)));
nP = COLS * ROWS;
px = new Float32Array(nP);
py = new Float32Array(nP);
ppx = new Float32Array(nP);
ppy = new Float32Array(nP);
pinned = new Uint8Array(nP);
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const i = r * COLS + c;
px[i] = ppx[i] = startX + c * SPACING;
py[i] = ppy[i] = startY + r * SPACING;
pinned[i] = (r === 0 && (c % pinStep === 0 || c === COLS - 1)) ? 1 : 0;
}
}
const maxC = (COLS - 1) * ROWS + COLS * (ROWS - 1);
cp1 = new Int32Array(maxC);
cp2 = new Int32Array(maxC);
clen = new Float32Array(maxC);
cactive = new Uint8Array(maxC);
nC = 0;
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const i = r * COLS + c;
if (c < COLS - 1) { cp1[nC]=i; cp2[nC]=i+1; clen[nC]=SPACING; cactive[nC]=1; nC++; }
if (r < ROWS - 1) { cp1[nC]=i; cp2[nC]=i+COLS; clen[nC]=SPACING; cactive[nC]=1; nC++; }
}
}
grabbed = -1;
}
// ─── Physics update ───────────────────────────────────────────────────────────
function update(dt) {
time += dt;
const mat = MATERIALS[matIdx];
const stepScale = dt / FIXED_DT;
const grav = gravOn ? mat.grav * stepScale * stepScale : 0;
const damp = Math.pow(mat.damp, stepScale);
// Preset stiffness describes one complete solve, not every iteration.
const stiff = mat.stiff >= 1 ? 1 : 1 - Math.pow(1 - mat.stiff, 1 / ITERS);
const held = grabbed >= 0 && mouse.down && !mouse.right && !mouse.shift ? grabbed : -1;
// Wind
let wx = 0;
if (windOn) {
const W = 1.6;
wx = (Math.sin(time*0.42)*W + Math.sin(time*0.78)*W*0.4 +
Math.sin(time*1.86)*W*0.15) * stepScale * stepScale;
}
// Smooth the sensor-driven gravity direction to damp raw sensor jitter.
gravDirX += (gravTargetX - gravDirX) * GYRO_SMOOTH;
gravDirY += (gravTargetY - gravDirY) * GYRO_SMOOTH;
// Shake impulse (devicemotion) decays each physics step after a spike.
const shakeX = shakeImpulseX * stepScale;
const shakeY = shakeImpulseY * stepScale;
shakeImpulseX *= SHAKE_DECAY;
shakeImpulseY *= SHAKE_DECAY;
// 1. Verlet integrate
for (let i = 0; i < nP; i++) {
if (pinned[i] || i === held) continue;
const vx = (px[i] - ppx[i]) * damp;
const vy = (py[i] - ppy[i]) * damp;
ppx[i] = px[i];
ppy[i] = py[i];
px[i] += vx + wx + grav * gravDirX + shakeX;
py[i] += vy + grav * gravDirY + shakeY;
}
// 2. Pin the grabbed particle before solving so its pull propagates now.
if (held >= 0) {
px[held] = mouse.x;
py[held] = mouse.y;
ppx[held] = grabPrevX;
ppy[held] = grabPrevY;
grabPrevX = mouse.x;
grabPrevY = mouse.y;
}
// 3. Blow burst (shift+drag)
if (mouse.down && mouse.shift && !mouse.right) {
const R = 90;
for (let i = 0; i < nP; i++) {
if (pinned[i]) continue;
const dx = px[i] - mouse.x, dy = py[i] - mouse.y;
const d2 = dx*dx + dy*dy;
if (d2 < R*R && d2 > 0.01) {
const d = Math.sqrt(d2), f = (1 - d/R) * 3.5 * stepScale;
px[i] += dx/d * f; py[i] += dy/d * f;
}
}
}
// 4. Satisfy constraints
for (let iter = 0; iter < ITERS; iter++) {
for (let k = 0; k < nC; k++) {
if (!cactive[k]) continue;
const a = cp1[k], b = cp2[k];
const wa = pinned[a] || a === held ? 0 : 1;
const wb = pinned[b] || b === held ? 0 : 1;
const wsum = wa + wb;
if (wsum === 0) continue;
const dx = px[b] - px[a];
const dy = py[b] - py[a];
const d2 = dx*dx + dy*dy;
if (d2 < 1e-8) continue;
const d = Math.sqrt(d2);
const diff = (d - clen[k]) / d * stiff / wsum;
const ox = dx * diff, oy = dy * diff;
if (wa) { px[a] += ox; py[a] += oy; }
if (wb) { px[b] -= ox; py[b] -= oy; }
}
}
// 5. Constraints can push particles outside, so collide after the solve.
const maxX = viewWidth;
const maxY = viewHeight - 1;
for (let i = 0; i < nP; i++) {
if (pinned[i] || i === held) continue;
const vx = px[i] - ppx[i];
const vy = py[i] - ppy[i];
if (px[i] < 0) { px[i] = 0; ppx[i] = px[i] + vx * 0.3; }
if (px[i] > maxX) { px[i] = maxX; ppx[i] = px[i] + vx * 0.3; }
if (py[i] < 0) { py[i] = 0; ppy[i] = py[i] + vy * 0.3; }
if (py[i] > maxY) { py[i] = maxY; ppy[i] = py[i] + vy * 0.3; }
}
}
function pointSegmentDist2(px0, py0, ax, ay, bx, by) {
const dx = bx - ax, dy = by - ay;
const len2 = dx*dx + dy*dy;
if (len2 < 1e-8) {
const ex = px0 - ax, ey = py0 - ay;
return ex*ex + ey*ey;
}
const t = Math.max(0, Math.min(1, ((px0-ax)*dx + (py0-ay)*dy) / len2));
const ex = px0 - (ax + t*dx), ey = py0 - (ay + t*dy);
return ex*ex + ey*ey;
}
function segmentDist2(ax, ay, bx, by, cx, cy, dx, dy) {
const rx = bx - ax, ry = by - ay;
const sx = dx - cx, sy = dy - cy;
const den = rx*sy - ry*sx;
if (Math.abs(den) > 1e-8) {
const qx = cx - ax, qy = cy - ay;
const t = (qx*sy - qy*sx) / den;
const u = (qx*ry - qy*rx) / den;
if (t >= 0 && t <= 1 && u >= 0 && u <= 1) return 0;
}
return Math.min(
pointSegmentDist2(ax, ay, cx, cy, dx, dy),
pointSegmentDist2(bx, by, cx, cy, dx, dy),
pointSegmentDist2(cx, cy, ax, ay, bx, by),
pointSegmentDist2(dx, dy, ax, ay, bx, by)
);
}
function cutAlongPath(ax, ay, bx, by) {
for (let k = 0; k < nC; k++) {
if (!cactive[k]) continue;
const a = cp1[k], b = cp2[k];
if (segmentDist2(ax, ay, bx, by, px[a], py[a], px[b], py[b]) < CUT_R*CUT_R) {
cactive[k] = 0;
}
}
}
// ─── Grab helpers ─────────────────────────────────────────────────────────────
function findNearest(mx, my) {
let best = -1, bestD2 = GRAB_R * GRAB_R;
for (let i = 0; i < nP; i++) {
if (pinned[i]) continue;
const dx = px[i]-mx, dy = py[i]-my;
const d2 = dx*dx + dy*dy;
if (d2 < bestD2) { bestD2 = d2; best = i; }
}
return best;
}
// ─── Rendering ────────────────────────────────────────────────────────────────
function stressColor(s) {
return `rgb(${Math.round(60+s*195)},${Math.round(150-s*130)},${Math.round(220-s*120)})`;
}
function depthColor(t) {
return `rgb(${Math.round(80+t*160)},${Math.round(60+Math.sin(t*Math.PI)*170)},${Math.round(230-t*130)})`;
}
function draw() {
ctx.fillStyle = '#080810';
ctx.fillRect(0, 0, viewWidth, viewHeight);
if (colorMode === 0) {
ctx.beginPath();
for (let k = 0; k < nC; k++) {
if (!cactive[k]) continue;
ctx.moveTo(px[cp1[k]], py[cp1[k]]);
ctx.lineTo(px[cp2[k]], py[cp2[k]]);
}
ctx.strokeStyle = 'rgba(210,218,240,0.5)';
ctx.lineWidth = 1;
ctx.stroke();
} else {
ctx.lineWidth = 1;
const buckets = Array.from({ length: COLOR_BUCKETS }, () => new Path2D());
for (let k = 0; k < nC; k++) {
if (!cactive[k]) continue;
const a = cp1[k], b = cp2[k];
let t;
if (colorMode === 1) {
const dx = px[b]-px[a], dy = py[b]-py[a];
const d = Math.sqrt(dx*dx + dy*dy);
t = Math.min(1, Math.max(0, (d - clen[k]) / (clen[k] * 0.6)));
} else {
t = Math.min(1, Math.max(0, ((py[a]+py[b]) * 0.5) / viewHeight));
}
const bucket = Math.min(COLOR_BUCKETS - 1, Math.floor(t * COLOR_BUCKETS));
buckets[bucket].moveTo(px[a], py[a]);
buckets[bucket].lineTo(px[b], py[b]);
}
for (let i = 0; i < COLOR_BUCKETS; i++) {
const t = (i + 0.5) / COLOR_BUCKETS;
ctx.strokeStyle = colorMode === 1 ? stressColor(t) : depthColor(t);
ctx.stroke(buckets[i]);
}
}
// Pinned anchors
ctx.fillStyle = 'rgba(110,175,255,0.75)';
for (let i = 0; i < nP; i++) {
if (!pinned[i]) continue;
ctx.beginPath();
ctx.arc(px[i], py[i], 3.5, 0, Math.PI*2);
ctx.fill();
}
// Grabbed particle highlight
if (grabbed >= 0 && mouse.down && !mouse.right && !mouse.shift) {
ctx.beginPath();
ctx.arc(px[grabbed], py[grabbed], 6, 0, Math.PI*2);
ctx.fillStyle = 'rgba(255,255,255,0.9)';
ctx.fill();
}
// Cursor indicator
const R = mouse.right ? 14 : mouse.shift ? 80 : 40;
const alpha = mouse.down ? 0.18 : 0.07;
const col = mouse.right ? `rgba(255,70,70,${alpha})` :
mouse.shift ? `rgba(60,210,255,${alpha})` :
`rgba(180,200,255,${alpha})`;
ctx.beginPath();
ctx.arc(mouse.x, mouse.y, R, 0, Math.PI*2);
ctx.fillStyle = col;
ctx.fill();
ctx.strokeStyle = col.replace(/[\d.]+\)$/, '0.4)');
ctx.lineWidth = 1;
ctx.stroke();
}
// ─── Loop ─────────────────────────────────────────────────────────────────────
let lastFrame = null;
let accumulator = 0;
function loop(now) {
if (lastFrame === null) lastFrame = now;
const elapsed = Math.min((now - lastFrame) / 1000, FIXED_DT * MAX_STEPS);
lastFrame = now;
accumulator = Math.min(accumulator + elapsed, FIXED_DT * MAX_STEPS);
while (accumulator >= FIXED_DT) {
update(FIXED_DT);
accumulator -= FIXED_DT;
}
draw();
requestAnimationFrame(loop);
}
// ─── Resize ───────────────────────────────────────────────────────────────────
function resize() {
viewWidth = window.innerWidth;
viewHeight = window.innerHeight;
dpr = Math.min(window.devicePixelRatio || 1, 2);
canvas.style.width = `${viewWidth}px`;
canvas.style.height = `${viewHeight}px`;
canvas.width = Math.round(viewWidth * dpr);
canvas.height = Math.round(viewHeight * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
buildCloth();
}
// ─── Input ────────────────────────────────────────────────────────────────────
function updateMousePos(x, y) {
mouse.lx = mouse.x;
mouse.ly = mouse.y;
mouse.x = Math.max(0, Math.min(viewWidth, x));
mouse.y = Math.max(0, Math.min(viewHeight, y));
}
function resetPointerState() {
pointers.clear();
activePointer = -1;
multiTouch = false;
mouse.down = false;
mouse.right = false;
mouse.shift = false;
grabbed = -1;
}
function touchCentroid() {
const touches = [...pointers.values()].filter(p => p.type === 'touch').slice(0, 2);
if (touches.length < 2) return null;
return {
x: (touches[0].x + touches[1].x) * 0.5,
y: (touches[0].y + touches[1].y) * 0.5,
};
}
canvas.addEventListener('pointerdown', e => {
e.preventDefault();
canvas.setPointerCapture(e.pointerId);
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY, type: e.pointerType });
const center = touchCentroid();
if (center) {
multiTouch = true;
grabbed = -1;
updateMousePos(center.x, center.y);
mouse.down = true;
mouse.right = false;
mouse.shift = true;
return;
}
if (activePointer !== -1 || multiTouch) return;
activePointer = e.pointerId;
updateMousePos(e.clientX, e.clientY);
mouse.down = true;
mouse.right = e.pointerType === 'touch' ? touchMode === 1 : e.button === 2;
mouse.shift = !mouse.right && e.shiftKey;
if (!mouse.right && !mouse.shift) {
grabbed = findNearest(mouse.x, mouse.y);
grabPrevX = mouse.x;
grabPrevY = mouse.y;
}
if (mouse.right) cutAlongPath(mouse.x, mouse.y, mouse.x, mouse.y);
});
canvas.addEventListener('pointermove', e => {
if (pointers.has(e.pointerId)) {
pointers.set(e.pointerId, { x: e.clientX, y: e.clientY, type: e.pointerType });
}
const center = touchCentroid();
if (center) {
updateMousePos(center.x, center.y);
return;
}
if (e.pointerId !== activePointer) {
if (!mouse.down && e.pointerType !== 'touch') {
updateMousePos(e.clientX, e.clientY);
mouse.shift = e.shiftKey;
}
return;
}
updateMousePos(e.clientX, e.clientY);
mouse.shift = !mouse.right && e.shiftKey;
if (mouse.down && mouse.right) cutAlongPath(mouse.lx, mouse.ly, mouse.x, mouse.y);
});
function endPointer(e) {
pointers.delete(e.pointerId);
if (multiTouch) {
const center = touchCentroid();
if (center) {
updateMousePos(center.x, center.y);
mouse.down = true;
mouse.right = false;
mouse.shift = true;
return;
}
// Do not unexpectedly switch from a two-finger burst to a one-finger grab.
if (pointers.size === 0) resetPointerState();
else {
mouse.down = false;
mouse.shift = false;
grabbed = -1;
}
return;
}
if (e.pointerId === activePointer) resetPointerState();
}
canvas.addEventListener('pointerup', endPointer);
canvas.addEventListener('pointercancel', endPointer);
canvas.addEventListener('contextmenu', e => e.preventDefault());
window.addEventListener('blur', resetPointerState);
// ─── Buttons ──────────────────────────────────────────────────────────────────
document.getElementById('btnReset').addEventListener('click', buildCloth);
document.getElementById('btnGravity').addEventListener('click', function() {
gravOn = !gravOn; this.classList.toggle('on', gravOn);
});
document.getElementById('btnWind').addEventListener('click', function() {
windOn = !windOn; this.classList.toggle('on', windOn);
});
const colorLabels = ['mono', 'stress', 'depth'];
document.getElementById('btnColor').addEventListener('click', function() {
colorMode = (colorMode + 1) % 3; this.textContent = colorLabels[colorMode];
});
document.getElementById('btnMat').addEventListener('click', function() {
matIdx = (matIdx + 1) % MATERIALS.length;
this.textContent = MATERIALS[matIdx].name;
buildCloth();
});
document.getElementById('btnCoarse').addEventListener('click', function() {
if (level <= 0) { this.classList.add('warn'); setTimeout(() => this.classList.remove('warn'), 300); return; }
level--;
buildCloth();
document.getElementById('btnFine').classList.remove('warn');
});
document.getElementById('btnFine').addEventListener('click', function() {
if (level >= LEVELS.length - 1) { this.classList.add('warn'); setTimeout(() => this.classList.remove('warn'), 300); return; }
level++;
buildCloth();
document.getElementById('btnCoarse').classList.remove('warn');
});
document.getElementById('btnTouchMode').addEventListener('click', function() {
touchMode = (touchMode + 1) % 2;
this.textContent = touchMode === 0 ? '✂ cut' : '✋ grab';
this.classList.toggle('warn', touchMode === 1);
mouse.down = false; grabbed = -1;
});
// ─── Gyroscope / motion ───────────────────────────────────────────────────────
function flashWarn(el) {
el.classList.add('warn');
setTimeout(() => el.classList.remove('warn'), 300);
}
function onDeviceOrientation(e) {
if (e.beta === null || e.gamma === null) return;
if (!gyroBaseline) gyroBaseline = { beta: e.beta, gamma: e.gamma };
const dGamma = e.gamma - gyroBaseline.gamma;
const dBeta = e.beta - gyroBaseline.beta;
const gx = dGamma / GYRO_MAX_TILT;
const gy = 1 - dBeta / GYRO_MAX_TILT;
const len = Math.sqrt(gx*gx + gy*gy) || 1;
gravTargetX = gx / len;
gravTargetY = gy / len;
}
function onDeviceMotion(e) {
const acc = e.accelerationIncludingGravity;
if (!acc || acc.x === null) return;
if (lastAccel) {
const dx = acc.x - lastAccel.x;
const dy = acc.y - lastAccel.y;
const dz = acc.z - lastAccel.z;
const jerk = Math.sqrt(dx*dx + dy*dy + dz*dz);
if (jerk > SHAKE_THRESHOLD) {
shakeImpulseX = Math.max(-SHAKE_MAX, Math.min(SHAKE_MAX, shakeImpulseX - dx * SHAKE_GAIN));
shakeImpulseY = Math.max(-SHAKE_MAX, Math.min(SHAKE_MAX, shakeImpulseY + dy * SHAKE_GAIN));
}
}
lastAccel = { x: acc.x, y: acc.y, z: acc.z };
}
const btnGyro = document.getElementById('btnGyro');
async function enableGyro() {
const hasOrientation = typeof DeviceOrientationEvent !== 'undefined';
const hasMotion = typeof DeviceMotionEvent !== 'undefined';
if (!hasOrientation && !hasMotion) { flashWarn(btnGyro); return; }
try {
if (hasOrientation && typeof DeviceOrientationEvent.requestPermission === 'function') {
if (await DeviceOrientationEvent.requestPermission() !== 'granted') { flashWarn(btnGyro); return; }
}
if (hasMotion && typeof DeviceMotionEvent.requestPermission === 'function') {
if (await DeviceMotionEvent.requestPermission() !== 'granted') { flashWarn(btnGyro); return; }
}
} catch (err) {
flashWarn(btnGyro);
return;
}
gyroOn = true;
gyroBaseline = null;
lastAccel = null;
shakeImpulseX = 0; shakeImpulseY = 0;
window.addEventListener('deviceorientation', onDeviceOrientation);
window.addEventListener('devicemotion', onDeviceMotion);
btnGyro.classList.add('on');
btnGyro.textContent = 'gyro on';
}
function disableGyro() {
gyroOn = false;
gravTargetX = 0; gravTargetY = 1;
shakeImpulseX = 0; shakeImpulseY = 0;
window.removeEventListener('deviceorientation', onDeviceOrientation);
window.removeEventListener('devicemotion', onDeviceMotion);
btnGyro.classList.remove('on');
btnGyro.textContent = 'gyro';
}
btnGyro.addEventListener('click', () => { gyroOn ? disableGyro() : enableGyro(); });
// ─── Boot ─────────────────────────────────────────────────────────────────────
window.addEventListener('resize', resize);
resize();
requestAnimationFrame(loop);
</script>
</body>
</html>