-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRapierPhysics.js
More file actions
439 lines (285 loc) · 10.5 KB
/
RapierPhysics.js
File metadata and controls
439 lines (285 loc) · 10.5 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
import { Clock, Vector3, Quaternion, Matrix4 } from 'three';
const RAPIER_PATH = 'https://cdn.skypack.dev/@dimforge/rapier3d-compat@0.17.3';
const frameRate = 60;
const _scale = new Vector3( 1, 1, 1 );
const ZERO = new Vector3();
let RAPIER = null;
function getShape( geometry ) {
const parameters = geometry.parameters;
// TODO change type to is*
if ( geometry.type === 'RoundedBoxGeometry' ) {
const sx = parameters.width !== undefined ? parameters.width / 2 : 0.5;
const sy = parameters.height !== undefined ? parameters.height / 2 : 0.5;
const sz = parameters.depth !== undefined ? parameters.depth / 2 : 0.5;
const radius = parameters.radius !== undefined ? parameters.radius : 0.1;
return RAPIER.ColliderDesc.roundCuboid( sx - radius, sy - radius, sz - radius, radius );
} else if ( geometry.type === 'BoxGeometry' ) {
const sx = parameters.width !== undefined ? parameters.width / 2 : 0.5;
const sy = parameters.height !== undefined ? parameters.height / 2 : 0.5;
const sz = parameters.depth !== undefined ? parameters.depth / 2 : 0.5;
return RAPIER.ColliderDesc.cuboid( sx, sy, sz );
} else if ( geometry.type === 'SphereGeometry' || geometry.type === 'IcosahedronGeometry' ) {
const radius = parameters.radius !== undefined ? parameters.radius : 1;
return RAPIER.ColliderDesc.ball( radius );
} else if ( geometry.type === 'CylinderGeometry' ) {
const radius = parameters.radiusBottom !== undefined ? parameters.radiusBottom : 0.5;
const length = parameters.height !== undefined ? parameters.height : 0.5;
return RAPIER.ColliderDesc.cylinder( length / 2, radius );
} else if ( geometry.type === 'CapsuleGeometry' ) {
const radius = parameters.radius !== undefined ? parameters.radius : 0.5;
const length = parameters.height !== undefined ? parameters.height : 0.5;
return RAPIER.ColliderDesc.capsule( length / 2, radius );
} else if ( geometry.type === 'BufferGeometry' ) {
const vertices = [];
const vertex = new Vector3();
const position = geometry.getAttribute( 'position' );
for ( let i = 0; i < position.count; i ++ ) {
vertex.fromBufferAttribute( position, i );
vertices.push( vertex.x, vertex.y, vertex.z );
}
// if the buffer is non-indexed, generate an index buffer
const indices = geometry.getIndex() === null
? Uint32Array.from( Array( parseInt( vertices.length / 3 ) ).keys() )
: geometry.getIndex().array;
return RAPIER.ColliderDesc.trimesh( vertices, indices );
}
return null;
}
/**
* @classdesc Can be used to include Rapier as a Physics engine into
* `three.js` apps. The API can be initialized via:
* ```js
* const physics = await RapierPhysics();
* ```
* The component automatically imports Rapier from a CDN so make sure
* to use the component with an active Internet connection.
*
* @name RapierPhysics
* @class
* @hideconstructor
* @three_import import { RapierPhysics } from 'three/addons/physics/RapierPhysics.js';
*/
async function RapierPhysics() {
if ( RAPIER === null ) {
RAPIER = await import( `${RAPIER_PATH}` );
await RAPIER.init();
}
// Docs: https://rapier.rs/docs/api/javascript/JavaScript3D/
const gravity = new Vector3( 0.0, - 9.81, 0.0 );
const world = new RAPIER.World( gravity );
const meshes = [];
const meshMap = new WeakMap();
const _vector = new Vector3();
const _quaternion = new Quaternion();
const _matrix = new Matrix4();
function addScene( scene ) {
scene.traverse( function ( child ) {
if ( child.isMesh ) {
const physics = child.userData.physics;
if ( physics ) {
addMesh( child, physics.mass, physics.restitution );
}
}
} );
}
function addMesh( mesh, mass = 0, restitution = 0 ) {
const shape = getShape( mesh.geometry );
if ( shape === null ) return;
shape.setMass( mass );
shape.setRestitution( restitution );
const { body, collider } = mesh.isInstancedMesh
? createInstancedBody( mesh, mass, shape )
: createBody( mesh.position, mesh.quaternion, mass, shape );
if ( ! mesh.userData.physics ) mesh.userData.physics = {};
mesh.userData.physics.body = body;
mesh.userData.physics.collider = collider;
if ( mass > 0 ) {
meshes.push( mesh );
meshMap.set( mesh, { body, collider } );
}
}
function removeMesh( mesh ) {
const index = meshes.indexOf( mesh );
if ( index !== - 1 ) {
meshes.splice( index, 1 );
meshMap.delete( mesh );
if ( ! mesh.userData.physics ) return;
const body = mesh.userData.physics.body;
const collider = mesh.userData.physics.collider;
if ( body ) removeBody( body );
if ( collider ) removeCollider( collider );
}
}
function createInstancedBody( mesh, mass, shape ) {
const matrixx = new Matrix4();
const positionn = new Vector3();
const quaternionn = new Quaternion();
const scalee = new Vector3();
const array = mesh.instanceMatrix.array;
const bodies = [];
const colliders = [];
for ( let i = 0; i < mesh.count; i ++ ) {
matrixx.fromArray(array, i * 16);
// const position = _vector.fromArray( array, i * 16 + 12 );
matrixx.decompose(positionn, quaternionn, scalee);
const { body, collider } = createBody( positionn, quaternionn, mass, shape );
bodies.push( body );
colliders.push( collider );
}
return { body: bodies, collider: colliders };
}
function createBody( position, quaternion, mass, shape ) {
const desc = mass > 0 ? RAPIER.RigidBodyDesc.dynamic() : RAPIER.RigidBodyDesc.fixed();
desc.setTranslation( ...position );
if ( quaternion !== null ) desc.setRotation( quaternion );
const body = world.createRigidBody( desc );
const collider = world.createCollider( shape, body );
return { body, collider };
}
function removeBody( body ) {
if ( Array.isArray( body ) ) {
for ( let i = 0; i < body.length; i ++ ) {
world.removeRigidBody( body[ i ] );
}
} else {
world.removeRigidBody( body );
}
}
function removeCollider( collider ) {
if ( Array.isArray( collider ) ) {
for ( let i = 0; i < collider.length; i ++ ) {
world.removeCollider( collider[ i ] );
}
} else {
world.removeCollider( collider );
}
}
function setMeshPosition( mesh, position, index = 0 ) {
let { body } = meshMap.get( mesh );
if ( mesh.isInstancedMesh ) {
body = body[ index ];
}
body.setAngvel( ZERO );
body.setLinvel( ZERO );
body.setTranslation( position );
}
function setMeshVelocity( mesh, velocity, index = 0 ) {
let { body } = meshMap.get( mesh );
if ( mesh.isInstancedMesh ) {
body = body[ index ];
}
body.setLinvel( velocity );
}
function addHeightfield( mesh, width, depth, heights, scale ) {
const shape = RAPIER.ColliderDesc.heightfield( width, depth, heights, scale );
const bodyDesc = RAPIER.RigidBodyDesc.fixed();
bodyDesc.setTranslation( mesh.position.x, mesh.position.y, mesh.position.z );
bodyDesc.setRotation( mesh.quaternion );
const body = world.createRigidBody( bodyDesc );
world.createCollider( shape, body );
if ( ! mesh.userData.physics ) mesh.userData.physics = {};
mesh.userData.physics.body = body;
return body;
}
//
const clock = new Clock();
function step() {
world.timestep = clock.getDelta();
world.step();
//
for ( let i = 0, l = meshes.length; i < l; i ++ ) {
const mesh = meshes[ i ];
if ( mesh.isInstancedMesh ) {
const array = mesh.instanceMatrix.array;
const { body: bodies } = meshMap.get( mesh );
for ( let j = 0; j < bodies.length; j ++ ) {
const body = bodies[ j ];
const position = body.translation();
_quaternion.copy( body.rotation() );
_matrix.compose( position, _quaternion, _scale ).toArray( array, j * 16 );
}
mesh.instanceMatrix.needsUpdate = true;
mesh.computeBoundingSphere();
} else {
const { body } = meshMap.get( mesh );
mesh.position.copy( body.translation() );
mesh.quaternion.copy( body.rotation() );
}
}
}
// animate
setInterval( step, 1000 / frameRate );
return {
RAPIER,
world,
/**
* Adds the given scene to this physics simulation. Only meshes with a
* `physics` object in their {@link Object3D#userData} field will be honored.
* The object can be used to store the mass and restitution of the mesh. E.g.:
* ```js
* box.userData.physics = { mass: 1, restitution: 0 };
* ```
*
* @method
* @name RapierPhysics#addScene
* @param {Object3D} scene The scene or any type of 3D object to add.
*/
addScene: addScene,
/**
* Adds the given mesh to this physics simulation.
*
* @method
* @name RapierPhysics#addMesh
* @param {Mesh} mesh The mesh to add.
* @param {number} [mass=0] The mass in kg of the mesh.
* @param {number} [restitution=0] The restitution/friction of the mesh.
*/
addMesh: addMesh,
/**
* Removes the given mesh from this physics simulation.
*
* @method
* @name RapierPhysics#removeMesh
* @param {Mesh} mesh The mesh to remove.
*/
removeMesh: removeMesh,
/**
* Set the position of the given mesh which is part of the physics simulation. Calling this
* method will reset the current simulated velocity of the mesh.
*
* @method
* @name RapierPhysics#setMeshPosition
* @param {Mesh} mesh The mesh to update the position for.
* @param {Vector3} position - The new position.
* @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
*/
setMeshPosition: setMeshPosition,
/**
* Set the velocity of the given mesh which is part of the physics simulation.
*
* @method
* @name RapierPhysics#setMeshVelocity
* @param {Mesh} mesh The mesh to update the velocity for.
* @param {Vector3} velocity - The new velocity.
* @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
*/
setMeshVelocity: setMeshVelocity,
/**
* Adds a heightfield terrain to the physics simulation.
*
* @method
* @name RapierPhysics#addHeightfield
* @param {Mesh} mesh - The Three.js mesh representing the terrain.
* @param {number} width - The number of vertices along the width (x-axis) of the heightfield.
* @param {number} depth - The number of vertices along the depth (z-axis) of the heightfield.
* @param {Float32Array} heights - Array of height values for each vertex in the heightfield.
* @param {Object} scale - Scale factors for the heightfield dimensions.
* @param {number} scale.x - Scale factor for width.
* @param {number} scale.y - Scale factor for height.
* @param {number} scale.z - Scale factor for depth.
* @returns {RigidBody} The created Rapier rigid body for the heightfield.
*/
addHeightfield: addHeightfield
};
}
export { RapierPhysics };