-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
758 lines (649 loc) · 27.1 KB
/
main.js
File metadata and controls
758 lines (649 loc) · 27.1 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
import * as THREE from 'three';
import { OrbitControls } from './libs/OrbitControls.js';
import * as CANNON from './libs/cannon-es.js';
/**
* @typedef {Object} WorldObject
* @property {THREE.Mesh} mesh
* @property {CANNON.Body} body
* @property {string} type
* @property {Map<WorldObject, CANNON.Constraint>} [stuckObjects]
* @property {number} objectId
*/
let scene, camera, renderer, world, controls, raycaster, mouse;
let objectIdCounter = 1;
/** @type {WorldObject[]} */
let objects = [];
let counts = {
rice: 0,
nori: 0,
fish: 0,
bamboo: 0,
};
let currentMode = 'interact-move';
/** @type {WorldObject[]} */
let heldObjects = [];
let rotatingDir = 0;
/** @type {WorldObject[]} */
let highlightedObjects = [];
let groundPlane;
/** @type {THREE.Vector3[]} */
let dragOffsets = [];
let debugVisualizationEnabled = document.getElementById('debug-toggle').checked;
let constraintBreakThreshold = parseFloat(document.getElementById('constraint-threshold').value);
let riceSize = parseFloat(document.getElementById('rice-size').value);
let liftHeight = parseFloat(document.getElementById('lift-height').value);
let liftDuration = parseFloat(document.getElementById('lift-time').value);
let liftFraction = 0; // for animating lift
let rotationSpeed = 3; // radians per second
const keys = {};
const MAX_CONSTRAINTS_PER_GRAIN = 8;
const RICE_GRAB_RADIUS = 0.2;
const RICE_DELETION_RADIUS = 0.3;
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.getElementById('scene-container').appendChild(renderer.domElement);
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(10, 20, 10);
directionalLight.castShadow = true;
scene.add(directionalLight);
camera.position.set(0, 2, 3);
camera.lookAt(0, 0, 0);
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
world = new CANNON.World();
world.gravity.set(0, -9.82, 0);
const groundShape = new CANNON.Plane();
const groundBody = new CANNON.Body({ mass: 0 });
groundBody.addShape(groundShape);
groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);
world.addBody(groundBody);
const groundSize = 1000;
const groundGeometry = new THREE.PlaneGeometry(groundSize, groundSize);
const groundMaterial = new THREE.MeshStandardMaterial({ color: 0xd2b48c });
const groundMesh = new THREE.Mesh(groundGeometry, groundMaterial);
groundMesh.rotation.x = -Math.PI / 2;
groundMesh.name = 'ground';
groundMesh.receiveShadow = true;
scene.add(groundMesh);
objects.push({ mesh: groundMesh, body: groundBody, type: 'ground' });
groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
// I'm tired, and I'm working within a bad framework decided by the AI
let justClosed = [];
document.addEventListener('pointerdown', (e) => {
if (e.target?.closest('.flyout')) return; // allow clicking within the flyout
justClosed = [...document.querySelectorAll('.flyout.active')];
document.querySelectorAll('.flyout').forEach(flyout => flyout.classList.remove('active'));
});
document.addEventListener('pointerup', (e) => {
// pointerup comes before click, hence the timeout
setTimeout(() => { justClosed = []; }, 0);
});
document.getElementById('settings-menu').addEventListener('click', (e) => {
if (justClosed.some(flyout => flyout === document.getElementById('settings-flyout'))) return; // allow toggling the flyout closed (but for other menus, open immediately)
if (e.target?.closest('#settings-flyout')) return; // because the stupid flyout is within the button
document.getElementById('settings-flyout').classList.toggle('active');
});
document.getElementById('add-menu').addEventListener('click', (e) => {
if (justClosed.some(flyout => flyout === document.getElementById('add-flyout'))) return; // allow toggling the flyout closed (but for other menus, open immediately)
if (e.target?.closest('#add-flyout')) return; // because the stupid flyout is within the button
document.getElementById('add-flyout').classList.toggle('active');
});
document.getElementById('add-rice').addEventListener('click', addRiceBatch);
document.getElementById('add-nori').addEventListener('click', addNori);
document.getElementById('add-fish').addEventListener('click', addFish);
document.getElementById('add-bamboo').addEventListener('click', addBambooMat);
document.querySelectorAll('.toolbar-button').forEach(button => {
button.addEventListener('click', (e) => {
setMode(e.currentTarget.id);
});
});
document.getElementById('debug-toggle').addEventListener('change', (e) => {
debugVisualizationEnabled = e.target.checked;
});
document.getElementById('constraint-threshold').addEventListener('input', (e) => {
constraintBreakThreshold = parseFloat(e.target.value);
});
document.getElementById('rice-size').addEventListener('input', (e) => {
riceSize = parseFloat(e.target.value);
});
document.getElementById('lift-height').addEventListener('input', (e) => {
liftHeight = parseFloat(e.target.value);
});
document.getElementById('lift-time').addEventListener('input', (e) => {
liftDuration = parseFloat(e.target.value);
});
renderer.domElement.addEventListener('pointerdown', onPointerDown);
renderer.domElement.addEventListener('pointermove', onPointerMove);
renderer.domElement.addEventListener('pointerup', onPointerUp);
renderer.domElement.addEventListener('pointercancel', onPointerUp);
document.addEventListener('wheel', (e) => {
if (heldObjects.length > 0) {
// A different useful feature to map to mousewheel would be to adjust the lift height dynamically...
rotateHeldObjects(e.deltaY * 0.001);
} else {
// FIXME: this breaks the perspective once you resize the window / toggle fullscreen
camera.zoom += e.deltaY * 0.001;
}
});
document.addEventListener('keydown', (e) => {
keys[e.code] = true;
});
document.addEventListener('keyup', (e) => {
keys[e.code] = false;
});
// AAAAAAAAAAAAAAAA
// Why is it so hard to implement a continuous effect for a button???
let pointerIdForRotation = null;
document.getElementById('rotate-left').addEventListener('pointerdown', (e) => {
pointerIdForRotation = e.pointerId;
rotatingDir = -1;
});
document.getElementById('rotate-right').addEventListener('pointerdown', (e) => {
pointerIdForRotation = e.pointerId;
rotatingDir = 1;
});
document.getElementById('rotate-left').addEventListener('pointerenter', (e) => {
if (e.pointerId === pointerIdForRotation) {
rotatingDir = -1;
};
});
document.getElementById('rotate-right').addEventListener('pointerenter', (e) => {
if (e.pointerId === pointerIdForRotation) {
rotatingDir = 1;
}
});
// pointerleave and pointerout aren't happening until the pointer is released for some reason
// (do buttons implicitly capture the pointer?? well it doesn't work even if I make them not buttons... some weird multitouch thing I guess!)
document.getElementById('rotate-left').addEventListener('pointerleave', (e) => {
// console.log(`e.pointerId: ${e.pointerId}, pointerIdForRotation: ${pointerIdForRotation}`);
if (e.pointerId === pointerIdForRotation) {
rotatingDir = 0;
}
});
document.getElementById('rotate-right').addEventListener('pointerleave', (e) => {
if (e.pointerId === pointerIdForRotation) {
rotatingDir = 0;
}
});
// so I have to use pointermove to detect leaving the button :(
// still need the above pointerleave or pointerout for when the pointer is released
document.addEventListener('pointermove', (e) => {
// console.log(`pointermove, e.pointerId: ${e.pointerId}, pointerIdForRotation: ${pointerIdForRotation}`);
// console.log(`e.target.className: ${e.target.className}`);
// e.target also doesn't work, it stays as the button when pointer is outside the button
const theElement = document.elementFromPoint(e.clientX, e.clientY);
if (e.pointerId === pointerIdForRotation) {
const leftButton = document.getElementById('rotate-left');
const rightButton = document.getElementById('rotate-right');
// if (!leftButton.contains(theElement) && !rightButton.contains(theElement)) {
// rotatingDir = 0;
// }
rotatingDir = leftButton.contains(theElement) ? -1 : rightButton.contains(theElement) ? 1 : 0;
}
});
// /AAAAAAAAAAAAAAAA
setMode('interact-move');
animate();
// Add initial objects
addBambooMat();
addNori();
addFish();
addRiceBatch();
}
function rotateHeldObjects(angle) {
if (heldObjects.length > 0) {
const center = new THREE.Vector3();
heldObjects.forEach(obj => center.add(obj.mesh.position));
center.divideScalar(heldObjects.length);
const rotationAxis = new THREE.Vector3(0, 1, 0);
const rotationQuaternion = new THREE.Quaternion().setFromAxisAngle(rotationAxis, angle);
heldObjects.forEach(obj => {
const localPos = obj.mesh.position.clone().sub(center);
localPos.applyQuaternion(rotationQuaternion);
obj.mesh.position.copy(localPos.add(center));
obj.mesh.quaternion.premultiply(rotationQuaternion);
// Update physics body
obj.body.position.copy(obj.mesh.position);
obj.body.quaternion.copy(obj.mesh.quaternion);
});
// Update drag offsets
dragOffsets.forEach(offset => offset.applyQuaternion(rotationQuaternion));
}
}
function handleRiceCollision(event) {
const contact = event.contact;
const riceBody = contact.bi;
const otherBody = contact.bj;
const riceObject = objects.find(object => object.body === riceBody);
const otherObject = objects.find(object => object.body === otherBody);
if (riceObject && otherObject) {
if (riceObject.type !== 'rice') {
console.error('contact.bi doesn\'t correspond to a rice grain');
}
// TODO: try limiting to one constraint per PAIR of objects instead of two (one both ways), might make it more stable
if (
!riceObject.stuckObjects.has(otherObject) &&
riceObject.stuckObjects.size < MAX_CONSTRAINTS_PER_GRAIN &&
// Don't stick while dragging (this is paired with explicit unsticking when starting a drag)
heldObjects.every(heldObject => heldObject !== otherObject && heldObject !== riceObject)
) {
const constraint = new CANNON.LockConstraint(riceObject.body, otherObject.body, {
// TODO: tune this value, may be ridiculously high?
// The AI decided on this when first using LockConstraint in https://github.com/1j01/makisu/commit/6b6f0876b569b9a4c175901914c1672aedd37ac9
// Actually apparently it's the default value. I don't know what it does exactly yet. Could still play around with it.
maxForce: 1e6,
});
// console.log('adding constraint');
world.addConstraint(constraint);
riceObject.stuckObjects.set(otherObject, constraint);
}
}
}
function setMode(mode) {
currentMode = mode;
document.querySelectorAll('.toolbar-button').forEach(button => {
button.classList.remove('active');
});
document.getElementById(mode).classList.add('active');
updateCursor();
controls.enableRotate = true;
controls.enablePan = true;
controls.enableZoom = true;
controls.mouseButtons = {
LEFT: THREE.MOUSE.ROTATE,
MIDDLE: THREE.MOUSE.ROTATE,
RIGHT: THREE.MOUSE.PAN
};
controls.touches = {
ONE: THREE.TOUCH.ROTATE,
TWO: THREE.TOUCH.DOLLY_PAN,
};
if (mode === 'camera-pan') {
controls.mouseButtons.LEFT = THREE.MOUSE.PAN;
controls.touches.ONE = THREE.TOUCH.PAN;
} else if (mode === 'camera-zoom') {
controls.mouseButtons.LEFT = THREE.MOUSE.DOLLY;
controls.touches.ONE = null; // there is no THREE.TOUCH.DOLLY, and DOLLY_PAN is not handled for a single touch
// for now, you just have to use multitouch to zoom, and this tool isn't technically useful,
// since you can do it with other tools selected
} else if (mode === 'interact-move' || mode === 'interact-pinch' || mode === 'interact-delete') {
controls.mouseButtons.LEFT = null;
controls.touches.ONE = null;
}
}
function updateHover(event) {
const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
for (const highlightedObject of highlightedObjects) {
// TODO: maybe avoid unnecessary calls to setHex? not sure if it's expensive
highlightedObject.mesh.material.emissive.setHex(0x000000);
}
if (heldObjects.length === 0) {
highlightedObjects = [];
const intersects = raycaster.intersectObjects(objects.filter(object => object.type !== "ground").map(item => item.mesh));
if (intersects.length > 0 && (currentMode === 'interact-move' || currentMode === 'interact-pinch' || currentMode === 'interact-delete')) {
const hoveredObject = objects.find(item => item.mesh === intersects[0].object);
if (currentMode === 'interact-move' || currentMode === 'interact-delete') {
if (hoveredObject.type === 'rice') {
// Target all rice grains within the appropriate radius
const riceSearchRadius = currentMode === 'interact-delete' ? RICE_DELETION_RADIUS : RICE_GRAB_RADIUS;
objects.forEach(object => {
if (object.type === 'rice' && object.mesh.position.distanceTo(hoveredObject.mesh.position) <= riceSearchRadius) {
highlightedObjects.push(object);
}
});
} else {
// For other object types, target all parts of the specific logical object
const objectId = hoveredObject.objectId;
objects.forEach(object => {
if (object.objectId === objectId) {
highlightedObjects.push(object);
}
});
}
} else if (currentMode === 'interact-pinch') {
// Target only the clicked object
highlightedObjects.push(hoveredObject);
}
}
}
for (const highlightedObject of highlightedObjects) {
highlightedObject.mesh.material.emissive.setHex(currentMode === 'interact-delete' ? 0xff0000 : 0x444444);
}
updateCursor();
}
function updateCursor() {
switch (currentMode) {
case 'camera-rotate':
renderer.domElement.style.cursor = 'default';
break;
case 'camera-pan':
renderer.domElement.style.cursor = 'move';
break;
case 'camera-zoom':
renderer.domElement.style.cursor = 'zoom-in';
break;
case 'interact-move':
renderer.domElement.style.cursor = heldObjects.length ? 'grabbing' : (highlightedObjects.length ? 'grab' : 'default');
break;
case 'interact-pinch':
renderer.domElement.style.cursor = heldObjects.length ? 'grabbing' : (highlightedObjects.length ? 'grab' : 'default');
break;
case 'interact-delete':
renderer.domElement.style.cursor = highlightedObjects.length ? 'crosshair' : 'default';
break;
}
}
function onPointerDown(event) {
event.preventDefault();
updateHover(event);
if (highlightedObjects.length > 0) {
if (currentMode === 'interact-move' || currentMode === 'interact-pinch') {
heldObjects = highlightedObjects.slice();
if (heldObjects[0].type === 'rice') {
// Break connections between the dragged rice and other objects
// Connections may be either direction, from the dragged rice to another object, or from another rice to the dragged rice
// So we can't only look at heldObjects' stuckObjects (unless we made it bidirectional)
objects.forEach(object => {
if (object.stuckObjects) {
object.stuckObjects.forEach((constraint, otherObject) => {
if (heldObjects.includes(otherObject) !== heldObjects.includes(object)) {
// console.log('removing constraint due to drag');
world.removeConstraint(constraint);
object.stuckObjects.delete(otherObject);
}
});
}
});
}
controls.enabled = false;
// Store the initial offsets for all grabbed objects
const intersection = new THREE.Vector3();
raycaster.ray.intersectPlane(groundPlane, intersection);
dragOffsets = heldObjects.map(object => {
const offset = new THREE.Vector3().subVectors(object.mesh.position, intersection);
return offset;
});
// Show rotate buttons for touch devices
if ('ontouchstart' in window) {
document.getElementById('toolbar').style.display = 'none';
document.getElementById('rotate-buttons').style.display = '';
}
} else if (currentMode === 'interact-delete') {
deleteObjects(highlightedObjects);
}
}
// Cursor may change from starting a drag or deleting objects after `updateHover` above
updateCursor();
}
function deleteObjects(objectsToDelete) {
// Ugly, I wouldn't do it like this from first principles,
// I'm just fixing the AI's counting bug
// It would probably be better to count everything from the current state every time (when adding and removing)
// Could improve this a bit by defining the group types in one place though
const isGroup = ["nori", "bamboo"].includes(objectsToDelete[0].type);
objectsToDelete.forEach(object => {
scene.remove(object.mesh);
world.removeBody(object.body);
if (!isGroup) {
updateObjectCounter(object.type, -1);
}
});
if (isGroup) {
updateObjectCounter(objectsToDelete[0].type, -1);
}
objects = objects.filter(object => !objectsToDelete.includes(object));
}
function onPointerMove(event) {
updateHover(event);
}
function onPointerUp(event) {
rotatingDir = 0;
heldObjects = [];
dragOffsets = [];
controls.enabled = true;
updateCursor();
// Hide rotate buttons and show toolbar for touch devices
document.getElementById('toolbar').style.display = '';
document.getElementById('rotate-buttons').style.display = 'none';
}
function addRiceBatch() {
for (let i = 0; i < 100; i++) {
setTimeout(() => addRice(), i * 10);
}
}
function addRice() {
const riceGeometry = new THREE.SphereGeometry(riceSize, 8, 8);
const riceMaterial = new THREE.MeshStandardMaterial({ color: 0xfffaf0 });
const riceMesh = new THREE.Mesh(riceGeometry, riceMaterial);
riceMesh.userData.type = 'rice';
riceMesh.castShadow = true;
riceMesh.receiveShadow = true;
const riceShape = new CANNON.Sphere(riceSize);
const riceBody = new CANNON.Body({
mass: 0.01,
shape: riceShape,
position: new CANNON.Vec3(Math.random() * 2 - 1, 5 + Math.random() * 2, Math.random() * 2 - 1)
});
riceBody.material = new CANNON.Material({ friction: 0.5, restitution: 0.1 });
riceBody.addEventListener("collide", handleRiceCollision);
scene.add(riceMesh);
world.addBody(riceBody);
objects.push({ mesh: riceMesh, body: riceBody, type: 'rice', stuckObjects: new Map(), objectId: objectIdCounter++ });
updateObjectCounter('rice', 1);
}
function addNori() {
const noriWidth = 1;
const noriHeight = 0.01;
const noriDepth = 1;
const segments = 10;
const objectId = objectIdCounter++;
for (let i = 0; i < segments; i++) {
const segmentWidth = noriWidth / segments;
const segmentGeometry = new THREE.BoxGeometry(segmentWidth, noriHeight, noriDepth);
const noriMaterial = new THREE.MeshStandardMaterial({ color: 0x1a4c1a });
const noriMesh = new THREE.Mesh(segmentGeometry, noriMaterial);
noriMesh.userData.type = 'nori';
noriMesh.castShadow = true;
noriMesh.receiveShadow = true;
const noriShape = new CANNON.Box(new CANNON.Vec3(segmentWidth / 2, noriHeight / 2, noriDepth / 2));
const noriBody = new CANNON.Body({
mass: 0.05,
shape: noriShape,
position: new CANNON.Vec3((i - segments / 2) * segmentWidth, 5, Math.random() * 2 - 1)
});
if (i > 0) {
const constraint = new CANNON.HingeConstraint(
objects[objects.length - 1].body,
noriBody,
{
pivotA: new CANNON.Vec3(segmentWidth / 2, 0, 0),
pivotB: new CANNON.Vec3(-segmentWidth / 2, 0, 0),
axisA: new CANNON.Vec3(0, 0, 1),
axisB: new CANNON.Vec3(0, 0, 1)
}
);
world.addConstraint(constraint);
}
scene.add(noriMesh);
world.addBody(noriBody);
objects.push({ mesh: noriMesh, body: noriBody, type: 'nori', objectId });
}
updateObjectCounter('nori', 1);
}
function addFish() {
const fishGeometry = new THREE.BoxGeometry(0.4, 0.1, 0.2);
const fishMaterial = new THREE.MeshStandardMaterial({ color: 0xfa8072 });
const fishMesh = new THREE.Mesh(fishGeometry, fishMaterial);
fishMesh.userData.type = 'fish';
fishMesh.castShadow = true;
fishMesh.receiveShadow = true;
const fishShape = new CANNON.Box(new CANNON.Vec3(0.2, 0.05, 0.1));
const fishBody = new CANNON.Body({
mass: 0.3,
shape: fishShape,
position: new CANNON.Vec3(Math.random() * 2 - 1, 5, Math.random() * 2 - 1)
});
scene.add(fishMesh);
world.addBody(fishBody);
objects.push({ mesh: fishMesh, body: fishBody, type: 'fish', objectId: objectIdCounter++ });
updateObjectCounter('fish', 1);
}
function addBambooMat() {
const matWidth = 1.5;
const matHeight = 0.01;
const matDepth = 1;
const segments = 15;
const objectId = objectIdCounter++;
for (let i = 0; i < segments; i++) {
const segmentWidth = matWidth / segments;
const segmentGeometry = new THREE.BoxGeometry(segmentWidth, matHeight, matDepth);
const bambooMaterial = new THREE.MeshStandardMaterial({ color: 0x90EE90 }); // Light green color
const bambooMesh = new THREE.Mesh(segmentGeometry, bambooMaterial);
bambooMesh.userData.type = 'bamboo';
bambooMesh.castShadow = true;
bambooMesh.receiveShadow = true;
const bambooShape = new CANNON.Box(new CANNON.Vec3(segmentWidth / 2, matHeight / 2, matDepth / 2));
const bambooBody = new CANNON.Body({
mass: 0.05,
shape: bambooShape,
position: new CANNON.Vec3((i - segments / 2) * segmentWidth, 5, Math.random() * 2 - 1)
});
if (i > 0) {
const constraint = new CANNON.HingeConstraint(
objects[objects.length - 1].body,
bambooBody,
{
pivotA: new CANNON.Vec3(segmentWidth / 2, 0, 0),
pivotB: new CANNON.Vec3(-segmentWidth / 2, 0, 0),
axisA: new CANNON.Vec3(0, 0, 1),
axisB: new CANNON.Vec3(0, 0, 1)
}
);
world.addConstraint(constraint);
}
scene.add(bambooMesh);
world.addBody(bambooBody);
objects.push({ mesh: bambooMesh, body: bambooBody, type: 'bamboo', objectId });
}
updateObjectCounter('bamboo', 1);
}
function updateObjectCounter(type, change) {
counts[type] += change;
document.getElementById(type + '-count').textContent = counts[type];
}
function step(deltaTime) {
world.step(deltaTime);
objects.forEach(object => {
object.mesh.position.copy(object.body.position);
object.mesh.quaternion.copy(object.body.quaternion);
// Check and break constraints if necessary
if (object.stuckObjects) {
for (let [otherObject, constraint] of object.stuckObjects.entries()) {
if (constraint.equations[0].multiplier > constraintBreakThreshold) {
// console.log('removing constraint due to break threshold');
world.removeConstraint(constraint);
object.stuckObjects.delete(otherObject);
}
}
}
});
if (heldObjects.length > 0) {
liftFraction += deltaTime / liftDuration;
liftFraction = Math.min(liftFraction, 1);
const realRotatingDir = Math.sign(rotatingDir + ((keys['ArrowLeft'] || keys['KeyQ']) ? -1 : 0) + ((keys['ArrowRight'] || keys['KeyE']) ? 1 : 0)); // shush! it's fine!
rotateHeldObjects(realRotatingDir * rotationSpeed * deltaTime);
const intersection = new THREE.Vector3();
raycaster.ray.intersectPlane(groundPlane, intersection);
heldObjects.forEach((object, index) => {
const targetPosition = new THREE.Vector3().addVectors(intersection, dragOffsets[index]);
targetPosition.y += liftHeight * liftFraction;
object.mesh.position.copy(targetPosition);
object.body.position.copy(targetPosition);
object.body.velocity.set(0, 0, 0);
object.body.angularVelocity.set(0, 0, 0);
});
} else {
liftFraction = 0;
}
}
let lastTime = performance.now();
function animate() {
requestAnimationFrame(animate);
const now = performance.now();
let deltaTime = (now - lastTime) / 1000;
// Prevent large time steps when debugging or when the window loses focus or the computer sleeps
deltaTime = Math.min(deltaTime, 0.1);
// Strategy 0:
// Fixed time step; one step per frame.
// Thin objects phase through each other.
// step(1 / 60);
// Strategy 1:
// Real time; one step per frame.
// `deltaTime` often tends towards the limit of 0.1, making this much less stable (and not even realtime) on my computer.
// step(deltaTime);
// Strategy 2:
// Base time step repeated as needed, followed by a smaller remainder time step; variable number of steps per frame.
// Usually smaller time steps make simulations more stable,
// but this seems much less stable if anything!
// ~~Maybe because I'm not running my game logic in each iteration?~~
// No, I created `step` to wrap it and `world.step` and it's still unstable
// Maybe super tiny time steps cause numerical instability?
// const baseTimeStep = 1 / 600;
// let remainingSimTime = deltaTime;
// while (remainingSimTime > 0) {
// const simTimeStep = Math.min(remainingSimTime, baseTimeStep);
// step(simTimeStep);
// remainingSimTime -= simTimeStep;
// }
// Strategy 3:
// Real time divided into fixed number of steps per frame.
// This actually seems more stable
// So maybe it really is just the tiny time steps from the remainder approach
const divisions = 10;
const simTimeStep = deltaTime / divisions;
for (let i = 0; i < divisions; i++) {
step(simTimeStep);
}
// Other strategies:
// All involving af fixed physics time step, with a variable number of steps per frame, and accumulating the remainder time across frames.
// - Simply render the latest physics state.
// This may lead to judder. However, it should be physically stable, since it's only using small, equal time steps.
// - Blend rendering between two physics steps
// (https://gafferongames.com/post/fix_your_timestep/)
// This introduces one frame of rendering latency, since it's blending the last two physics steps, not the current and the next,
// but avoids judder from the physics time steps not aligning with frame boundaries.
// Linear interpolation is not ideal for non-linear motion, but it's usually good enough,
// especially with small enough physics time steps, since that limits the time over which the interpolation is done.
// - Simulate ahead by the remainder for rendering but throw away the result (reset to the last physics step, for reproducible physics)
// This doesn't introduce latency in that way, since it's going forward from the last physics step, not blending between the last two.
// (Also, it's more accurate than blending, for any non-linear motion that's simulated non-linearly.
// But most games simulate gravity by applying it at discrete times, not calculating a parabola.
// Small time steps are enough for a good approximation of the continuous motion.)
// However, if there's inconsistencies that occur from tiny time steps, they could show for a frame.
// Also, major gameplay events like dying are best avoided in this non-authoritative simulation step,
// since they could be undone if the real simulation step doesn't agree, and since it's not meant to be authoritative.
// Like you don't want a game over screen popping up or a sound effect playing due to the rendering-only simulation step.
// (See this video around 2 hour mark: https://youtu.be/fdAOPHgW7qM?t=7658)
controls.update();
renderer.render(scene, camera);
lastTime = now;
}
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
init();