-
Notifications
You must be signed in to change notification settings - Fork 1
/
skirtgospinny_1.html
983 lines (754 loc) · 29.7 KB
/
skirtgospinny_1.html
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
<html lang="en">
<head>
<title>Ammo.js Skirt Go Spinny</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="../style/skirt.css">
<style>
body {
color: #333;
}
</style>
</head>
<body>
<div id="start">
<h1 id="title">start</h1>
</div>
<div id='startblur'>
<div id="info">
Ammo.js physics anchoring soft body to kinematic box demo<br/>
Spin the skirt with your touch input or mouse!
<br>
<div id="stats">
<div>
<h3>Spinny Tracker:</h3>
<h1 id="stat-spins">0</h1>
</div>
<div>
<h3>Twirl Speed:</h3>
<h1 id="stat-speed">0</h1>
</div>
</div>
</div>
<div id="container"></div>
<div id='pause'><p class="title">x</p></div>
<div id='aboutlink'><a href='http://aprilonian.art/?post=2021-06-28-Happy-Pride' target="_blank">@aprilonian</a></div>
</div>
<script src="../examples/js/libs/ammo.wasm.js"></script>
<script type="module">
import * as THREE from '../build/three.module.js';
import Stats from '../examples/jsm/libs/stats.module.js';
import { GUI } from '../examples/jsm/libs/dat.gui.module.js';
import { OrbitControls } from '../examples/jsm/controls/OrbitControls.js';
import { BufferGeometryUtils } from '../examples/jsm/utils/BufferGeometryUtils.js';
import { GLTFLoader } from '../examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from '../examples/jsm/loaders/DRACOLoader.js';
import { MStylizedFabric } from '../materials/MStylizedFabric.js';
// SCENE VARIABLES
let container, gui, stats, params, camera, controls, scene, renderer, mixer, meshScene, skirt, krbRotator;
const clock = new THREE.Clock();
// STAT COUNTERS
let spins = 0;
let statSpins = 0;
let statSpeed = 0;
// MOUSE VARIABLES
let clickRequest = false;
let interactDown = false;
let mouseX, mouseY;
let mTimestamp = null;
let lastMouseX = null;
let lastMouseY = null;
let mSpeedX = 0;
let mSpeedY = 0;
let lastClientX = 0;
let distanceX = 0;
// krbRotator VARIABLES
let r_current_rotY = 0;
let r_momentum_rotY = 0;
let r_momentum_rotY_dir = 0;
let r_momentum_rotY_max = 100.1;
let r_tmp_m_rotY;
let r_tmpTransform, r_ammoTmpPos, r_ammoTmpQuat;
let r_tmpPos = new THREE.Vector3()
let r_tmpQuat = new THREE.Quaternion();
// BALL VARIABLES for testing
const mouseCoords = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
const pos = new THREE.Vector3();
const quat = new THREE.Quaternion();
// PHYSICS VARIABLES
const gravityConstant = -9.8;
let physicsWorld, transformAux1, softBodyHelpers;
const rigidBodies = [];
const softBodies = [];
const margin = 0.05;
const FLAGS = { CF_KINEMATIC_OBJECT: 2 };
const STATE = { DISABLE_DEACTIVATION : 4 }
// MATERIALS
let M_invisible, M_skirt_fresnel, M_skirt_fabric;
Ammo().then( function ( AmmoLib ) {
Ammo = AmmoLib;
init();
// animate(); // normally this would be where we want to start our animate() loop, but we are loading in a custom model
} );
////////////////////
// Initialization //
////////////////////
//#region
function init() {
params = {
opacity: 0,
projectiles: false,
simulate: false,
showVertexColors: false,
};
r_tmpTransform = new Ammo.btTransform();
r_ammoTmpPos = new Ammo.btVector3();
r_ammoTmpQuat = new Ammo.btQuaternion();
initScene();
initPhysics();
initCreateObjects();
initInput();
// initGUI();
initStats();
}
function initScene() {
// CAMERA
camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 0.2, 2000 );
camera.position.set( 0, 2, 10 );
camera.rotation.set(-0.2, 0, 0);
// RENDERER
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMap.enabled = true;
container = document.getElementById( 'container' );
container.oncontextmenu = contextSelect;
function contextSelect(e){e.preventDefault();}
container.appendChild( renderer.domElement );
// CONTROLS
// controls = new OrbitControls( camera, renderer.domElement );
// controls.target.set( 0, 0, 0 );
// controls.update();
// controls.enablePan = false;
// controls.enableDamping = false;
// controls.rotateSpeed = 0;
// // controls.panSpeed = 1.5;
// controls.zoomSpeed = 0;
// DEFINE GROUPS
// grpLines = new THREE.Group();
// SCENE
scene = new THREE.Scene();
scene.background = new THREE.Color(0xF7A8B8);
// DEFINE LIGHTS
const hemisphereLight = new THREE.HemisphereLight( 0xfceafc, 0x000000, .8 );
scene.add( hemisphereLight );
const dirLight = new THREE.DirectionalLight( 0xffffff, .5 );
dirLight.position.set( 150, 75, 150 );
scene.add( dirLight );
const dirLight2 = new THREE.DirectionalLight( 0xffffff, .2 );
dirLight2.position.set( - 150, 75, - 150 );
scene.add( dirLight2 );
const dirLight3 = new THREE.DirectionalLight( 0xffffff, .1 );
dirLight3.position.set( 125, 125, 0 );
scene.add( dirLight3 );
}
function initPhysics() {
// Physics configuration
const collisionConfiguration = new Ammo.btSoftBodyRigidBodyCollisionConfiguration();
const dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
const broadphase = new Ammo.btDbvtBroadphase();
const solver = new Ammo.btSequentialImpulseConstraintSolver();
const softBodySolver = new Ammo.btDefaultSoftBodySolver();
physicsWorld = new Ammo.btSoftRigidDynamicsWorld( dispatcher, broadphase, solver, collisionConfiguration, softBodySolver );
physicsWorld.setGravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
physicsWorld.getWorldInfo().set_m_gravity( new Ammo.btVector3( 0, gravityConstant, 0 ) );
transformAux1 = new Ammo.btTransform();
softBodyHelpers = new Ammo.btSoftBodyHelpers();
}
function initCreateObjects() {
// DEFINE TEXTURES
let fabricPattern = new THREE.TextureLoader().load( "../models/textures/transPattern.jpg");
fabricPattern.wrapS = THREE.RepeatWrapping;
fabricPattern.wrapT = THREE.RepeatWrapping;
fabricPattern.repeat.set( 1,1);
// fabricPattern.offset = new THREE.Vector2( 0.2, 0.5 );
const gradientMap = createGradientMap(4,4);
// DEFINE MATERIALS
M_skirt_fabric = new THREE.MeshToonMaterial( {
// color: new THREE.Color(0xd3678d),
color: new THREE.Color(0xaaaaaa),
map: fabricPattern,
gradientMap: gradientMap,
transparent: true,
opacity: 1,
side: THREE.DoubleSide,
vertexColors: true, // helpful to visualize your vertex colors
} );
M_skirt_fresnel = new THREE.ShaderMaterial( {
uniforms: MStylizedFabric.uniforms,
vertexShader: MStylizedFabric.vertexShader,
fragmentShader: MStylizedFabric.fragmentShader,
// side: THREE.DoubleSide,
} );
M_skirt_fresnel.uniforms[ "baseColor" ].value = fabricPattern;
M_invisible = new THREE.MeshToonMaterial( {
color: new THREE.Color(0xffffff),
gradientMap: gradientMap,
transparent: true,
opacity: params.opacity,
} );
// DEFINE GEOMETRIES
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath( '../examples/js/libs/draco/gltf/' );
// Ground
pos.set( 0, - 2.5, 0 );
quat.set( 0, 0, 0, 1 );
const ground = createRigidBodyBoxShape( 40, 1, 40, 0, pos, quat, M_invisible);
ground.castShadow = true;
ground.receiveShadow = true;
// Create kinematic rigid body called krbRotator
pos.set( 0, 2.2, 0 );
quat.setFromAxisAngle( new THREE.Vector3( 0, 0, 0 ), 0 );
krbRotator = createRigidBodyBoxShape( 4, 1, 4, 1, pos, quat, M_invisible, true);
krbRotator.castShadow = false;
krbRotator.receiveShadow = false;
// ADD LOADER AND GEO
const loader = new GLTFLoader();
loader.setDRACOLoader( dracoLoader );
loader.load( '../models/skirtgospinnyLP.gltf', function ( gltf ) {
// IMPORT THE SCENE
const meshScene = gltf.scene;
meshScene.position.set( - 5, 25, 0 );
// ADD THE SCENE
// scene.add( meshScene );
// ADD SOFTBODIES
meshScene.traverse( c => {
if ( c.isMesh ) {
let mesh = c;
let count = 0;
const volumeMass = 15;
const volumePressure = 0; // 0 for flat open geometries, 1+ for closed geometries
mesh.translate( - 2, 5, 0 );
skirt = createSoftBody( mesh.geometry, volumeMass, volumePressure);
if(params.showVertexColors) {
skirt.material = M_skirt_fabric;
}
else {
skirt.material = M_skirt_fresnel;
}
// VERTEX WEIGHTS from Vertex Colors
let anchors = getVertexWeights(mesh.geometry, 0.05, 0.5); // max influence 0.5 for performance
// Glue the cloth to the arm
count = 0;
let ammoVertAssociation = skirt.geometry.ammoIndexInOrder;
for(let i=0; i < ammoVertAssociation.length; i++) {
for(let j=0; j < anchors.length; j++) {
if(ammoVertAssociation[i] == anchors[j].index) {
let influence = anchors[j].weight;
count++;
skirt.userData.physicsBody.appendAnchor( ammoVertAssociation[i], krbRotator.userData.physicsBody, false, influence);
}
}
}
}
});
// Add an animation mixer to take care of mesh animations
mixer = new THREE.AnimationMixer( meshScene );
let i;
for(i=0; i<gltf.animations.length; i++){
const clip = gltf.animations[i];
if ( clip ) {
const action = mixer.clipAction( clip );
action.play();
}
}
animate();
}, function() {
console.log("LOADED SKIRT!");
}, function ( e ) {
console.error( e );
} );
}
function initInput() {
document.getElementById('start').addEventListener('pointerdown', function ( event ) {
document.getElementById('start').setAttribute('style','display: none;');
document.getElementById('startblur').setAttribute('style','filter: blur(0rem);');
params.simulate = true;
if(gui){
gui.updateDisplay();
}
});
document.getElementById('pause').addEventListener('pointerdown', function ( event ) {
document.getElementById('start').setAttribute('style','display: flex;');
document.getElementById('startblur').setAttribute('style','filter: blur(1.5rem);');
params.simulate = false;
if(gui){
gui.updateDisplay();
}
});
window.addEventListener( 'pointerdown', function ( event ) {
if ( ! clickRequest ) {
mouseCoords.set(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1
);
clickRequest = true;
}
} );
function handleInputDown(e) {
// console.log("down");
interactDown = true;
r_tmp_m_rotY = r_momentum_rotY;
setTimeout(function() {
if(interactDown){
r_momentum_rotY = 0;
}
}, 200);
if(e.touches) {
lastClientX = e.touches[0].clientX;
} else {
lastClientX = e.clientX;
}
}
function handleInputMove(e) {
if(interactDown) {
let maxX = 0;
let maxY = 0;
if (mTimestamp === null) {
mTimestamp = Date.now();
if(e.touches) {
lastMouseX = e.touches[0].screenX;
lastMouseY = e.touches[0].screenY;
} else {
lastMouseX = e.screenX;
lastMouseY = e.screenY;
}
return;
}
let now = Date.now();
let dt = now - mTimestamp;
let dx = 0;
let dy = 0;
if(e.touches) {
maxX = 120;
maxY = maxX;
// console.log("touch moving!");
dx = e.touches[0].screenX - lastMouseX;
dy = e.touches[0].screenY - lastMouseY;
mSpeedX = Math.round( dx / dt * 100 );
mSpeedY = Math.round( dy / dt * 100 );
distanceX = ((Math.abs((e.touches[0].clientX - lastClientX)/dt) + 1)/100);
} else {
maxX = 100;
maxY = maxX;
dx = e.screenX - lastMouseX;
dy = e.screenY - lastMouseY;
mSpeedX = Math.round( dx / dt * 100 );
mSpeedY = Math.round( dy / dt * 100 );
distanceX = (Math.abs((e.clientX - lastClientX)/dt) + 1)/100;
}
// console.log(distanceX);
let tmpCenterX = Math.abs((1-(Math.abs(distanceX*100))));
tmpCenterX = tmpCenterX<=1?1:tmpCenterX;
mSpeedX = mSpeedX * tmpCenterX;
if(Math.abs(mSpeedX) >= maxX || Math.abs(mSpeedX) === Infinity) {
mSpeedX = Math.sign(mSpeedX)*maxX;
}
if(Math.abs(mSpeedY) >= maxY || Math.abs(mSpeedY) === Infinity) {
mSpeedY = Math.sign(mSpeedY)*maxY;
}
if(isNaN(mSpeedX)) {
mSpeedX = 0;
}
if(isNaN(mSpeedY)) {
mSpeedY = 0;
}
// console.log(mSpeedX);
mTimestamp = now;
if(e.touches) {
lastMouseX = e.touches[0].screenX;
lastMouseY = e.touches[0].screenY;
} else {
lastMouseX = e.screenX;
lastMouseY = e.screenY;
}
let angularMomentumY = krbRotator.userData.physicsBody.getAngularVelocity().y();
r_momentum_rotY = (Math.abs(angularMomentumY)+(r_tmp_m_rotY));
r_momentum_rotY_dir = Math.sign(angularMomentumY);
}
// mouseX = ( event.clientX / window.innerWidth ) * 2 - 1;
// mouseY = - ( event.clientY / window.innerHeight ) * 2 + 1;
// console.log("Screen X: "+e.screenX+"\nClient X: "+e.clientX);
}
function handleInputUp(e) {
// console.log("up")
interactDown = false;
mSpeedX = 0;
mSpeedY = 0;
}
window.addEventListener( 'mousedown', handleInputDown);
window.addEventListener( 'mousemove', handleInputMove);
window.addEventListener( 'mouseup', handleInputUp);
window.addEventListener( 'touchstart', function ( e ) { e.preventDefault(); handleInputDown(e);},false );
window.addEventListener( 'touchmove', function ( e ) { e.preventDefault(); handleInputMove(e);},false );
window.addEventListener( 'touchend', function ( e ) { e.preventDefault(); handleInputUp(e);},false );
window.addEventListener( 'resize', onWindowResize );
}
function initGUI() {
gui = new GUI();
// GEO OUTLINE GUI
gui.add( params, 'opacity' ).min( 0.0 ).max( 1.0 ).step( 0.1 ).onChange( function(value)
{
M_invisible.opacity = value;
});
gui.add( params, 'showVertexColors' ).onChange( function(value)
{
skirt.material = value?M_skirt_fabric:M_skirt_fresnel;
});
gui.add( params, 'projectiles');
gui.add( params, 'simulate' );
gui.domElement.setAttribute('style','margin-top: 35px; margin-right: -15px;')
}
function initStats() {
// stats = new Stats();
// stats.domElement.style.position = 'absolute';
// stats.domElement.style.top = '0px';
// container.appendChild( stats.domElement );
statSpins = document.getElementById('stat-spins');
statSpeed = document.getElementById('stat-speed');
}
//#endregion
////////////////////////////
// Utility Ammo Functions //
////////////////////////////
//#region
function processGeometry( bufGeometry ) {
// Ony consider the position values when merging the vertices
const posOnlyBufGeometry = new THREE.BufferGeometry();
posOnlyBufGeometry.setAttribute( 'position', bufGeometry.getAttribute( 'position' ) );
posOnlyBufGeometry.setIndex( bufGeometry.getIndex() );
// Merge the vertices so the triangle soup is converted to indexed triangles
const indexedBufferGeom = BufferGeometryUtils.mergeVertices( posOnlyBufGeometry );
// Create index arrays mapping the indexed vertices to bufGeometry vertices
mapIndices( bufGeometry, indexedBufferGeom );
}
function mapIndices( bufGeometry, indexedBufferGeom ) {
// Creates ammoVertices, ammoIndices and ammoIndexAssociation in bufGeometry
const vertices = bufGeometry.attributes.position.array;
const idxVertices = indexedBufferGeom.attributes.position.array;
const indices = indexedBufferGeom.index.array;
const numIdxVertices = idxVertices.length / 3;
const numVertices = vertices.length / 3;
bufGeometry.ammoVertices = idxVertices;
bufGeometry.ammoIndices = indices;
bufGeometry.ammoIndexAssociation = [];
bufGeometry.ammoIndexInOrder = [];
for ( let i = 0; i < numIdxVertices; i ++ ) {
const association = [];
bufGeometry.ammoIndexAssociation.push( association );
const i3 = i * 3;
for ( let j = 0; j < numVertices; j ++ ) {
const j3 = j * 3;
if ( isEqual( idxVertices[ i3 ], idxVertices[ i3 + 1 ], idxVertices[ i3 + 2 ],
vertices[ j3 ], vertices[ j3 + 1 ], vertices[ j3 + 2 ] ) ) {
association.push( j3 );
bufGeometry.ammoIndexInOrder.push(j);
}
}
}
for( let i = 0; i < bufGeometry.ammoIndexInOrder.length; i++) {
if(bufGeometry.ammoIndexInOrder[i] >= numIdxVertices) {
// console.log(bufGeometry.ammoIndexInOrder[i] +" compare to "+ numIdxVertices);
bufGeometry.ammoIndexInOrder.splice(i,1);
i--;
}
}
}
function isEqual( x1, y1, z1, x2, y2, z2 ) {
const delta = 0.000001;
return Math.abs( x2 - x1 ) < delta &&
Math.abs( y2 - y1 ) < delta &&
Math.abs( z2 - z1 ) < delta;
}
function createSoftBody( bufferGeom, mass, pressure ) {
processGeometry( bufferGeom );
const sbMesh = new THREE.Mesh( bufferGeom, new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) );
sbMesh.castShadow = true;
sbMesh.receiveShadow = true;
sbMesh.frustumCulled = false;
scene.add( sbMesh );
// sbMesh physic object
const volumeSoftBody = softBodyHelpers.CreateFromTriMesh(
physicsWorld.getWorldInfo(),
bufferGeom.ammoVertices,
bufferGeom.ammoIndices,
bufferGeom.ammoIndices.length / 3,
true );
const sbConfig = volumeSoftBody.get_m_cfg();
sbConfig.set_viterations( 40 );
sbConfig.set_piterations( 40 );
// Soft-soft and soft-rigid collisions
sbConfig.set_collisions( 0x11 );
// Friction
sbConfig.set_kDF( 0.1 );
// Damping
sbConfig.set_kDP( 0.01 );
// Pressure
sbConfig.set_kPR( pressure );
// Stiffness
volumeSoftBody.get_m_materials().at( 0 ).set_m_kLST( 0.9 );
volumeSoftBody.get_m_materials().at( 0 ).set_m_kAST( 0.9 );
volumeSoftBody.setTotalMass( mass, false );
Ammo.castObject( volumeSoftBody, Ammo.btCollisionObject ).getCollisionShape().setMargin( margin );
physicsWorld.addSoftBody( volumeSoftBody, 1, - 1 );
sbMesh.userData.physicsBody = volumeSoftBody;
// Disable deactivation
volumeSoftBody.setActivationState( 4 );
softBodies.push( sbMesh );
return sbMesh;
}
function createRigidBody( threeObject, physicsShape, mass, pos, quat, isKinematic=false ) {
threeObject.position.copy( pos );
threeObject.quaternion.copy( quat );
const transform = new Ammo.btTransform();
transform.setIdentity();
transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
transform.setRotation( new Ammo.btQuaternion( quat.x, quat.y, quat.z, quat.w ) );
const motionState = new Ammo.btDefaultMotionState( transform );
const localInertia = new Ammo.btVector3( 0, 0, 0 );
physicsShape.calculateLocalInertia( mass, localInertia );
const rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, physicsShape, localInertia );
const body = new Ammo.btRigidBody( rbInfo );
threeObject.userData.physicsBody = body;
scene.add( threeObject );
if ( mass > 0 ) {
rigidBodies.push( threeObject );
// Disable deactivation
body.setActivationState( 4 );
}
if(isKinematic){
body.setActivationState( STATE.DISABLE_DEACTIVATION );
body.setCollisionFlags( FLAGS.CF_KINEMATIC_OBJECT );
}
physicsWorld.addRigidBody( body );
return threeObject;
}
function getVertexWeights( bufferGeom, toleranceMin = 0.0, toleranceMax = 1.0) {
const m = new THREE.BufferGeometry();
m.setAttribute( 'position', bufferGeom.getAttribute( 'position' ) );
m.setAttribute( 'color', bufferGeom.getAttribute( 'color' ) );
m.setIndex(bufferGeom.getIndex());
const indexedMesh = BufferGeometryUtils.mergeVertices( m );
let vertColors = indexedMesh.attributes.color.array
let weights = [];
let wCount = 0;
for(let i=0; i<(vertColors.length/4); i++) {
if((vertColors[i*4]/65535) >= toleranceMin && (vertColors[i*4]/65535) <= toleranceMax){
// Divide by 65535 (max allowed verts) to get a normalied vertex weight [0.0 - 1.0]
// console.log(vertColors[i*4]/65535);
wCount++;
weights.push({
index: i,
weight: (vertColors[i*4]/65535)
});
}
}
console.log("You painted "+wCount+" weights with more than "+toleranceMin+" and less than "+toleranceMax);
return weights;
}
//#endregion
///////////////////////////////////
// Scene Specific Ammo Functions //
///////////////////////////////////
//#region
function createRigidBodyBoxShape( sx, sy, sz, mass, pos, quat, material, isKinematic=false) {
const threeObject = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), material );
const shape = new Ammo.btBoxShape( new Ammo.btVector3( sx * 0.5, sy * 0.5, sz * 0.5 ) );
shape.setMargin( margin );
createRigidBody( threeObject, shape, mass, pos, quat, isKinematic );
return threeObject;
}
//#endregion
/////////////////////////////
// Utility Three Functions //
/////////////////////////////
//#region
function createGradientMap(grad_width = 4, grad_height = 4, grad_color = new THREE.Color( 0xffffff )) {
const grad_size = grad_width * grad_height;
const grad_data = new Uint8Array(grad_size);
const grad_r = Math.floor( grad_color.r * 255 );
const grad_g = Math.floor( grad_color.g * 255 );
const grad_b = Math.floor( grad_color.b * 255 );
for ( let i = 0; i < grad_size; i ++ ) {
const grad_stride = i * 3;
grad_data[ grad_stride ] = grad_r;
grad_data[ grad_stride + 1 ] = grad_g;
grad_data[ grad_stride + 2 ] = grad_b;
}
let gradientMap = new THREE.DataTexture(grad_data, grad_width, grad_height, THREE.LuminanceFormat );
gradientMap.minFilter = THREE.NearestFilter;
gradientMap.magFilter = THREE.NearestFilter;
gradientMap.generateMipmaps = false;
return gradientMap;
}
//#endregion
/////////////////
// Interaction //
/////////////////
//#region
function testingBall() {
if ( clickRequest ) {
// Cast a ray from the camera to where the mouse is
raycaster.setFromCamera( mouseCoords, camera );
// Create a ball
const ballMass = 3;
const ballRadius = 0.4;
const ball = new THREE.Mesh(
new THREE.SphereGeometry( ballRadius, 18, 16 ),
new THREE.MeshPhongMaterial( { color: 0x55CDFC })
);
ball.castShadow = true;
ball.receiveShadow = true;
// Ammo physics shape to apply physics to
const ballShape = new Ammo.btSphereShape( ballRadius );
ballShape.setMargin( margin );
pos.copy( raycaster.ray.direction );
pos.add( raycaster.ray.origin );
quat.set( 0, 0, 0, 1 );
const ballBody = createRigidBody( ball, ballShape, ballMass, pos, quat ).userData.physicsBody;
ballBody.setFriction( 0.5 );
// Apply a vector in the direction of a the ray we casted at the start here
pos.copy( raycaster.ray.direction );
pos.multiplyScalar( 14 );
ballBody.setLinearVelocity( new Ammo.btVector3( pos.x, pos.y, pos.z ) );
clickRequest = false;
}
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
//#endregion
//////////////////
// UPDATE LOOPS //
//////////////////
//#region
function animate() {
requestAnimationFrame( animate );
render();
if(stats)
stats.update();
}
function render() {
if(params.simulate){
const deltaTime = clock.getDelta();
updatePhysics( deltaTime );
updateRotatorPhysics( deltaTime );
mixer.update( deltaTime );
}
if(params.projectiles){
testingBall();
}
renderer.render( scene, camera );
}
function updatePhysics( deltaTime ) {
// Step world
physicsWorld.stepSimulation( deltaTime, 10 );
// Update soft volumes
for ( let i = 0, il = softBodies.length; i < il; i ++ ) {
const sbMesh = softBodies[ i ];
const geometry = sbMesh.geometry;
const softBody = sbMesh.userData.physicsBody;
const volumePositions = geometry.attributes.position.array;
const volumeNormals = geometry.attributes.normal.array;
const association = geometry.ammoIndexAssociation;
const numVerts = association.length;
const nodes = softBody.get_m_nodes();
for ( let j = 0; j < numVerts; j ++ ) {
const node = nodes.at( j );
const nodePos = node.get_m_x();
const x = nodePos.x();
const y = nodePos.y();
const z = nodePos.z();
const nodeNormal = node.get_m_n();
const nx = nodeNormal.x();
const ny = nodeNormal.y();
const nz = nodeNormal.z();
const assocVertex = association[ j ];
for ( let k = 0, kl = assocVertex.length; k < kl; k ++ ) {
let indexVertex = assocVertex[ k ];
volumePositions[ indexVertex ] = x;
volumeNormals[ indexVertex ] = nx;
indexVertex ++;
volumePositions[ indexVertex ] = y;
volumeNormals[ indexVertex ] = ny;
indexVertex ++;
volumePositions[ indexVertex ] = z;
volumeNormals[ indexVertex ] = nz;
}
}
geometry.attributes.position.needsUpdate = true;
geometry.attributes.normal.needsUpdate = true;
}
// Update rigid bodies
for ( let i = 0, il = rigidBodies.length; i < il; i ++ ) {
const objThree = rigidBodies[ i ];
const objPhys = objThree.userData.physicsBody;
const ms = objPhys.getMotionState();
if ( ms ) {
ms.getWorldTransform( transformAux1 );
const p = transformAux1.getOrigin();
const q = transformAux1.getRotation();
objThree.position.set( p.x(), p.y(), p.z() );
objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() );
}
}
}
// Calculate the physics for Kinematic Rigid Body called krbRotator
function updateRotatorPhysics(deltaTime){
// console.log(r_momentum_rotY)
if(interactDown || r_momentum_rotY >=0)
{
let scalingFactor = 0.0005;
spins += ((Math.abs(mSpeedX)*scalingFactor)+(r_momentum_rotY)*(0.01))/(2*Math.PI);
r_current_rotY += (mSpeedX*scalingFactor)+(r_momentum_rotY*r_momentum_rotY_dir)*(0.01);
if(krbRotator && !isNaN(r_current_rotY)) {
r_tmpPos.set(krbRotator.position.x,krbRotator.position.y,krbRotator.position.z);
let tmpEuler = new THREE.Euler( 0, r_current_rotY, 0, 'XYZ' );
r_tmpQuat.setFromEuler(tmpEuler);
let physicsBody = krbRotator.userData.physicsBody;
let ms = physicsBody.getMotionState();
if(ms) {
r_ammoTmpPos.setValue(r_tmpPos.x, r_tmpPos.y, r_tmpPos.z);
r_ammoTmpQuat.setValue( r_tmpQuat.x, r_tmpQuat.y, r_tmpQuat.z, r_tmpQuat.w);
r_tmpTransform.setIdentity();
r_tmpTransform.setOrigin( r_ammoTmpPos );
r_tmpTransform.setRotation( r_ammoTmpQuat );
ms.setWorldTransform(r_tmpTransform);
}
}
mSpeedX = 0;
mSpeedY = 0;
}
// Prevent momentum from going beyond the max
if(r_momentum_rotY > r_momentum_rotY_max) {
r_momentum_rotY = r_momentum_rotY_max;
}
// Decrease the momentum over time
if(r_momentum_rotY >=0) {
r_momentum_rotY-=Math.sqrt(deltaTime);
}
// If momentum is less than 0.2, set the tmp momentum to 0 to stop spinning
if(Math.abs(krbRotator.userData.physicsBody.getAngularVelocity().y()) <= 0.2 && interactDown) {
r_tmp_m_rotY = 0;
}
// Update the innerHTML for our stats
statSpeed.innerHTML = (Math.abs(Math.round(krbRotator.userData.physicsBody.getAngularVelocity().y()*10)/10)) + "<span class='statsLabel'> twirls/s</span>";
statSpins.innerHTML = Math.trunc(spins) + "<span class='statsLabel'> spinnies</span>";
}
//#endregion
</script>
</body>
</html>