@needle-tools/engine 3.4.0-alpha → 3.5.0-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/needle-engine.js +59357 -59090
  3. package/dist/needle-engine.min.js +368 -345
  4. package/dist/needle-engine.umd.cjs +386 -363
  5. package/lib/engine/api.d.ts +1 -0
  6. package/lib/engine/api.js +1 -0
  7. package/lib/engine/api.js.map +1 -1
  8. package/lib/engine/engine_context.d.ts +1 -1
  9. package/lib/engine/engine_context.js +21 -15
  10. package/lib/engine/engine_context.js.map +1 -1
  11. package/lib/engine/engine_context_registry.d.ts +5 -3
  12. package/lib/engine/engine_context_registry.js +10 -2
  13. package/lib/engine/engine_context_registry.js.map +1 -1
  14. package/lib/engine/engine_element.js.map +1 -1
  15. package/lib/engine/engine_element_loading.js +2 -3
  16. package/lib/engine/engine_element_loading.js.map +1 -1
  17. package/lib/engine/engine_input.d.ts +2 -2
  18. package/lib/engine/engine_physics.d.ts +20 -93
  19. package/lib/engine/engine_physics.js +20 -892
  20. package/lib/engine/engine_physics.js.map +1 -1
  21. package/lib/engine/engine_physics.types.js.map +1 -1
  22. package/lib/engine/engine_physics_rapier.d.ts +103 -0
  23. package/lib/engine/engine_physics_rapier.js +1003 -0
  24. package/lib/engine/engine_physics_rapier.js.map +1 -0
  25. package/lib/engine/engine_types.d.ts +50 -1
  26. package/lib/engine/engine_types.js +8 -0
  27. package/lib/engine/engine_types.js.map +1 -1
  28. package/lib/engine-components/Collider.js +6 -6
  29. package/lib/engine-components/Collider.js.map +1 -1
  30. package/lib/engine-components/Joints.js +2 -2
  31. package/lib/engine-components/Joints.js.map +1 -1
  32. package/lib/engine-components/RigidBody.d.ts +0 -1
  33. package/lib/engine-components/RigidBody.js +24 -30
  34. package/lib/engine-components/RigidBody.js.map +1 -1
  35. package/lib/engine-components/export/usdz/ThreeUSDZExporter.js +55 -27
  36. package/lib/engine-components/export/usdz/ThreeUSDZExporter.js.map +1 -1
  37. package/lib/engine-components/export/usdz/extensions/behavior/BehaviourComponents.d.ts +8 -2
  38. package/lib/engine-components/export/usdz/extensions/behavior/BehaviourComponents.js +44 -7
  39. package/lib/engine-components/export/usdz/extensions/behavior/BehaviourComponents.js.map +1 -1
  40. package/lib/engine-components/ui/RectTransform.js +3 -1
  41. package/lib/engine-components/ui/RectTransform.js.map +1 -1
  42. package/lib/tsconfig.tsbuildinfo +1 -1
  43. package/package.json +1 -1
  44. package/plugins/vite/config.js +2 -1
  45. package/plugins/vite/defines.js +30 -0
  46. package/plugins/vite/dependency-watcher.js +173 -0
  47. package/plugins/vite/editor-connection.js +37 -39
  48. package/plugins/vite/index.js +5 -1
  49. package/plugins/vite/reload.js +3 -1
  50. package/src/engine/api.ts +1 -0
  51. package/src/engine/codegen/register_types.js +2 -2
  52. package/src/engine/engine_context.ts +32 -23
  53. package/src/engine/engine_context_registry.ts +13 -6
  54. package/src/engine/engine_element.ts +2 -1
  55. package/src/engine/engine_element_loading.ts +2 -3
  56. package/src/engine/engine_input.ts +2 -2
  57. package/src/engine/engine_physics.ts +25 -1020
  58. package/src/engine/engine_physics.types.ts +1 -3
  59. package/src/engine/engine_physics_rapier.ts +1127 -0
  60. package/src/engine/engine_types.ts +66 -4
  61. package/src/engine-components/Collider.ts +6 -6
  62. package/src/engine-components/Joints.ts +2 -2
  63. package/src/engine-components/RigidBody.ts +24 -31
  64. package/src/engine-components/export/usdz/ThreeUSDZExporter.ts +62 -30
  65. package/src/engine-components/export/usdz/extensions/behavior/BehaviourComponents.ts +51 -9
  66. package/src/engine-components/ui/RectTransform.ts +3 -2
@@ -0,0 +1,1003 @@
1
+ import { BufferAttribute, BufferGeometry, LineBasicMaterial, LineSegments, Matrix4, Quaternion, Vector3 } from 'three';
2
+ import { CircularBuffer, getParam } from "./engine_utils";
3
+ import { getWorldPosition, getWorldQuaternion, getWorldScale, setWorldPositionXYZ, setWorldQuaternionXYZW } from "./engine_three_utils";
4
+ import { Collision, ContactPoint, } from './engine_types';
5
+ import { foreachComponent } from './engine_gameobject';
6
+ import { ActiveCollisionTypes, ActiveEvents, CoefficientCombineRule, Ball, Collider, ColliderDesc, EventQueue, JointData, QueryFilterFlags, RigidBody, RigidBodyType, World, Ray } from '@dimforge/rapier3d-compat';
7
+ import { CollisionDetectionMode, PhysicsMaterialCombine } from '../engine/engine_physics.types';
8
+ import { Gizmos } from './engine_gizmos';
9
+ import { Mathf } from './engine_math';
10
+ import { SphereOverlapResult } from './engine_types';
11
+ import { ContextEvent, ContextRegistry } from './engine_context_registry';
12
+ const debugPhysics = getParam("debugphysics");
13
+ const debugColliderPlacement = getParam("debugphysicscolliders");
14
+ const debugCollisions = getParam("debugcollisions");
15
+ const showColliders = getParam("showcolliders");
16
+ /** on physics body and references the needle component */
17
+ const $componentKey = Symbol("needle component");
18
+ /** on needle component and references physics body */
19
+ const $bodyKey = Symbol("physics body");
20
+ const $colliderRigidbody = Symbol("rigidbody");
21
+ let RAPIER = undefined;
22
+ if (NEEDLE_USE_RAPIER) {
23
+ ContextRegistry.registerCallback(ContextEvent.ContextCreationStart, evt => {
24
+ if (debugPhysics)
25
+ console.log("Register rapier physics backend");
26
+ evt.context.physics.engine = new RapierPhysics();
27
+ // We want the physics engine to be initialized on start so when components start to enable and modify values they don't have delays
28
+ // TODO: should the promise be returned here to make the engine creation wait?
29
+ if (NEEDLE_USE_RAPIER) {
30
+ evt.context.physics.engine.initialize(evt.context);
31
+ }
32
+ });
33
+ }
34
+ export class RapierPhysics {
35
+ removeBody(obj) {
36
+ this.validate();
37
+ const body = obj[$bodyKey];
38
+ obj[$bodyKey] = null;
39
+ if (body && this.world) {
40
+ const index = this.objects.findIndex(o => o === obj);
41
+ if (index >= 0) {
42
+ const body = this.bodies[index];
43
+ this.bodies.splice(index, 1);
44
+ this.objects.splice(index, 1);
45
+ if (body instanceof Collider) {
46
+ const collider = body;
47
+ this.world?.removeCollider(collider, true);
48
+ // remove the rigidbody if it doesnt have colliders anymore
49
+ const rb = collider.parent();
50
+ if (rb && rb.numColliders() <= 0) {
51
+ this.world?.removeRigidBody(rb);
52
+ }
53
+ }
54
+ else if (body instanceof RigidBody) {
55
+ // TODO: running this code below causes a crash in rapier
56
+ // const rb = body as RigidBody;
57
+ // console.log("colliders", rb.numColliders())
58
+ // for (let i = 0; i < rb.numColliders(); i++) {
59
+ // const col = rb.collider(i);
60
+ // this.world?.removeCollider(col, true);
61
+ // }
62
+ // console.log("colliders", rb.numColliders(), rb)
63
+ // console.log(rb.handle, rb.userData);
64
+ // if (rb.userData === undefined)
65
+ // this.world?.removeRigidBody(rb);
66
+ }
67
+ // check if we need to remove the rigidbody too
68
+ // const col = obj as ICollider;
69
+ // if (col.isCollider && col.attachedRigidbody) {
70
+ // const rb = col.attachedRigidbody[$bodyKey] as RigidBody;
71
+ // if (rb && rb.numColliders() <= 0) {
72
+ // // this.world?.removeRigidBody(rb);
73
+ // }
74
+ // }
75
+ }
76
+ }
77
+ }
78
+ updateBody(comp, translation, rotation) {
79
+ this.validate();
80
+ if (!this.enabled)
81
+ return;
82
+ if (comp.destroyed || !comp.gameObject)
83
+ return;
84
+ if (!translation && !rotation)
85
+ return;
86
+ if (comp.isCollider === true) {
87
+ // const collider = comp as ICollider;
88
+ console.warn("TODO: implement updating collider position");
89
+ }
90
+ else {
91
+ const rigidbody = comp;
92
+ const body = rigidbody[$bodyKey];
93
+ if (body) {
94
+ this.syncPhysicsBody(rigidbody.gameObject, body, translation, rotation);
95
+ }
96
+ }
97
+ }
98
+ updateProperties(rigidbody) {
99
+ this.validate();
100
+ const physicsBody = rigidbody[$bodyKey];
101
+ if (physicsBody) {
102
+ this.internalUpdateProperties(rigidbody, physicsBody);
103
+ }
104
+ }
105
+ addForce(rigidbody, force, wakeup) {
106
+ this.validate();
107
+ const body = this.internal_getRigidbody(rigidbody);
108
+ body?.addForce(force, wakeup);
109
+ }
110
+ addImpulse(rigidbody, force, wakeup) {
111
+ this.validate();
112
+ const body = this.internal_getRigidbody(rigidbody);
113
+ body?.applyImpulse(force, wakeup);
114
+ }
115
+ getLinearVelocity(rigidbody) {
116
+ this.validate();
117
+ const body = this.internal_getRigidbody(rigidbody);
118
+ if (body) {
119
+ const vel = body.linvel();
120
+ return vel;
121
+ }
122
+ return null;
123
+ }
124
+ getAngularVelocity(rb) {
125
+ this.validate();
126
+ const body = this.internal_getRigidbody(rb);
127
+ if (body) {
128
+ const vel = body.angvel();
129
+ return vel;
130
+ }
131
+ return null;
132
+ }
133
+ resetForces(rb, wakeup) {
134
+ this.validate();
135
+ const body = this.internal_getRigidbody(rb);
136
+ body?.resetForces(wakeup);
137
+ }
138
+ resetTorques(rb, wakeup) {
139
+ this.validate();
140
+ const body = this.internal_getRigidbody(rb);
141
+ body?.resetTorques(wakeup);
142
+ }
143
+ applyImpulse(rb, vec, wakeup) {
144
+ this.validate();
145
+ const body = this.internal_getRigidbody(rb);
146
+ body?.applyImpulse(vec, wakeup);
147
+ }
148
+ wakeup(rb) {
149
+ this.validate();
150
+ const body = this.internal_getRigidbody(rb);
151
+ body?.wakeUp();
152
+ }
153
+ setAngularVelocity(rb, vec, wakeup) {
154
+ this.validate();
155
+ const body = this.internal_getRigidbody(rb);
156
+ body?.setAngvel(vec, wakeup);
157
+ }
158
+ setLinearVelocity(rb, vec, wakeup) {
159
+ this.validate();
160
+ const body = this.internal_getRigidbody(rb);
161
+ body?.setLinvel(vec, wakeup);
162
+ }
163
+ context;
164
+ _initializePromise;
165
+ _isInitialized = false;
166
+ async initialize(context) {
167
+ this.context = context;
168
+ if (!this._initializePromise)
169
+ this._initializePromise = this.internalInitialization();
170
+ return this._initializePromise;
171
+ }
172
+ async internalInitialization() {
173
+ // NEEDLE_PHYSICS_INIT_START
174
+ // use .env file with VITE_NEEDLE_USE_RAPIER=false to treeshape rapier
175
+ if (import.meta.env.VITE_NEEDLE_USE_RAPIER === "false") {
176
+ return false;
177
+ }
178
+ // Can be transformed during build time to disable rapier
179
+ if (!NEEDLE_USE_RAPIER)
180
+ return false;
181
+ if (this._hasCreatedWorld) {
182
+ console.error("Invalid call to create physics world: world is already created");
183
+ return true;
184
+ }
185
+ this._hasCreatedWorld = true;
186
+ if (RAPIER === undefined) {
187
+ RAPIER = await import("@dimforge/rapier3d-compat");
188
+ await RAPIER.init();
189
+ }
190
+ if (debugPhysics)
191
+ console.log("Physics engine initialized, creating world...");
192
+ this.world = new World(this._gravity);
193
+ this.enabled = true;
194
+ this._isInitialized = true;
195
+ if (debugPhysics)
196
+ console.log("Physics world created");
197
+ return true;
198
+ // NEEDLE_PHYSICS_INIT_END
199
+ }
200
+ /** Check is the physics engine has been initialized and the call can be made */
201
+ validate() {
202
+ if (!this._isInitialized) {
203
+ if (debugPhysics)
204
+ console.warn("Physics engine is not initialized");
205
+ }
206
+ }
207
+ rapierRay = new Ray({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 1 });
208
+ raycastVectorsBuffer = new CircularBuffer(() => new Vector3(), 10);
209
+ /** Fast raycast against physics colliders
210
+ * @param origin ray origin in screen or worldspace
211
+ * @param direction ray direction in worldspace
212
+ * @param maxDistance max distance to raycast
213
+ * @param solid if true it will also hit the collider if origin is already inside it
214
+ */
215
+ raycast(origin, direction = undefined, maxDistance = Infinity, solid = true) {
216
+ const ray = this.getPhysicsRay(this.rapierRay, origin, direction);
217
+ if (!ray)
218
+ return null;
219
+ const hit = this.world?.castRay(ray, maxDistance, solid, undefined, undefined, undefined, undefined, (c) => {
220
+ // ignore objects in the IgnoreRaycast=2 layer
221
+ return !c[$componentKey]?.gameObject.layers.isEnabled(2);
222
+ });
223
+ if (hit) {
224
+ const point = ray.pointAt(hit.toi);
225
+ const vec = this.raycastVectorsBuffer.get();
226
+ vec.set(point.x, point.y, point.z);
227
+ return { point: vec, collider: hit.collider[$componentKey] };
228
+ }
229
+ return null;
230
+ }
231
+ raycastAndGetNormal(origin, direction = undefined, maxDistance = Infinity, solid = true) {
232
+ const ray = this.getPhysicsRay(this.rapierRay, origin, direction);
233
+ if (!ray)
234
+ return null;
235
+ const hit = this.world?.castRayAndGetNormal(ray, maxDistance, solid, undefined, undefined, undefined, undefined, (c) => {
236
+ // ignore objects in the IgnoreRaycast=2 layer
237
+ return !c[$componentKey]?.gameObject.layers.isEnabled(2);
238
+ });
239
+ if (hit) {
240
+ const point = ray.pointAt(hit.toi);
241
+ const normal = hit.normal;
242
+ const vec = this.raycastVectorsBuffer.get();
243
+ const nor = this.raycastVectorsBuffer.get();
244
+ vec.set(point.x, point.y, point.z);
245
+ nor.set(normal.x, normal.y, normal.z);
246
+ return { point: vec, normal: nor, collider: hit.collider[$componentKey] };
247
+ }
248
+ return null;
249
+ }
250
+ getPhysicsRay(ray, origin, direction = undefined) {
251
+ const cam = this.context?.mainCamera;
252
+ // if we get origin in 2d space we need to project it to 3d space
253
+ if (origin["z"] === undefined) {
254
+ if (!cam) {
255
+ console.error("Can not perform raycast from 2d point - no main camera found");
256
+ return null;
257
+ }
258
+ const vec3 = this.raycastVectorsBuffer.get();
259
+ vec3.x = origin.x;
260
+ vec3.y = origin.y;
261
+ vec3.z = 0;
262
+ // if the origin is in screen space we need to convert it to raycaster space
263
+ if (vec3.x > 1 || vec3.y > 1 || vec3.y < -1 || vec3.x < -1) {
264
+ this.context?.input.convertScreenspaceToRaycastSpace(vec3);
265
+ }
266
+ vec3.unproject(cam);
267
+ origin = vec3;
268
+ }
269
+ const o = origin;
270
+ ray.origin.x = o.x;
271
+ ray.origin.y = o.y;
272
+ ray.origin.z = o.z;
273
+ const vec = this.raycastVectorsBuffer.get();
274
+ if (direction)
275
+ vec.set(direction.x, direction.y, direction.z);
276
+ else {
277
+ if (!cam) {
278
+ console.error("Can not perform raycast - no camera found");
279
+ return null;
280
+ }
281
+ vec.set(ray.origin.x, ray.origin.y, ray.origin.z);
282
+ const camPosition = getWorldPosition(cam);
283
+ vec.sub(camPosition);
284
+ }
285
+ // we need to normalize the ray because our input is a max travel length and the direction may be not normalized
286
+ vec.normalize();
287
+ ray.dir.x = vec.x;
288
+ ray.dir.y = vec.y;
289
+ ray.dir.z = vec.z;
290
+ // Gizmos.DrawRay(ray.origin, ray.dir, 0xff0000, Infinity);
291
+ return ray;
292
+ }
293
+ rapierSphere = null;
294
+ rapierColliderArray = [];
295
+ rapierIdentityRotation = { x: 0, y: 0, z: 0, w: 1 };
296
+ rapierForwardVector = { x: 0, y: 0, z: 1 };
297
+ /** Precice sphere overlap detection using rapier against colliders
298
+ * @param point center of the sphere in worldspace
299
+ * @param radius radius of the sphere
300
+ * @returns array of colliders that overlap with the sphere. Note: they currently only contain the collider and the gameobject
301
+ */
302
+ sphereOverlap(point, radius) {
303
+ this.rapierColliderArray.length = 0;
304
+ if (!this.world)
305
+ return this.rapierColliderArray;
306
+ if (!this.rapierSphere)
307
+ this.rapierSphere = new Ball(radius);
308
+ this.rapierSphere.radius = radius;
309
+ this.world.intersectionsWithShape(point, this.rapierIdentityRotation, this.rapierSphere, col => {
310
+ const collider = col[$componentKey];
311
+ // if (collider.gameObject.layers.isEnabled(2)) return true;
312
+ const intersection = new SphereOverlapResult(collider.gameObject, collider);
313
+ this.rapierColliderArray.push(intersection);
314
+ return true; // Return `false` instead if we want to stop searching for other colliders that contain this point.
315
+ }, QueryFilterFlags.EXCLUDE_SENSORS, undefined, undefined, undefined, col => {
316
+ const collider = col[$componentKey];
317
+ return collider.gameObject.layers.isEnabled(2) == false;
318
+ });
319
+ return this.rapierColliderArray;
320
+ // TODO: this only returns one hit
321
+ // let filterGroups = 0xffffffff;
322
+ // filterGroups &= ~(1 << 2);
323
+ // const hit: ShapeColliderTOI | null = this.world.castShape(point,
324
+ // this.rapierIdentityRotation,
325
+ // this.rapierForwardVector,
326
+ // this.rapierSphere,
327
+ // 0,
328
+ // QueryFilterFlags.EXCLUDE_SENSORS,
329
+ // // filterGroups,
330
+ // );
331
+ // // console.log(hit);
332
+ // if (hit) {
333
+ // const collider = hit.collider[$componentKey] as ICollider
334
+ // const intersection = new SphereOverlapResult(collider.gameObject);
335
+ // this.rapierColliderArray.push(intersection);
336
+ // // const localpt = hit.witness2;
337
+ // // // const normal = hit.normal2;
338
+ // // const hitPoint = new Vector3(localpt.x, localpt.y, localpt.z);
339
+ // // // collider.gameObject.localToWorld(hitPoint);
340
+ // // // const normalPt = new Vector3(normal.x, normal.y, normal.z);
341
+ // // // const mat = new Matrix4().setPosition(point).scale(new Vector3(radius, radius, radius));
342
+ // // // hitPoint.applyMatrix4(mat);
343
+ // // console.log(hit.witness2)
344
+ // // // hitPoint.add(point);
345
+ // // const dist = hitPoint.distanceTo(point);
346
+ // }
347
+ // return this.rapierColliderArray;
348
+ }
349
+ // physics simulation
350
+ enabled = false;
351
+ _tempPosition = new Vector3();
352
+ _tempQuaternion = new Quaternion();
353
+ _tempScale = new Vector3();
354
+ _tempMatrix = new Matrix4();
355
+ static _didLoadPhysicsEngine = false;
356
+ _isUpdatingPhysicsWorld = false;
357
+ get isUpdating() { return this._isUpdatingPhysicsWorld; }
358
+ world;
359
+ _hasCreatedWorld = false;
360
+ eventQueue;
361
+ collisionHandler;
362
+ objects = [];
363
+ bodies = [];
364
+ _meshCache = new Map();
365
+ _gravity = { x: 0.0, y: -9.81, z: 0.0 };
366
+ get gravity() {
367
+ return this.world?.gravity ?? this._gravity;
368
+ }
369
+ set gravity(value) {
370
+ if (this.world) {
371
+ this.world.gravity = value;
372
+ }
373
+ else {
374
+ this._gravity = value;
375
+ }
376
+ }
377
+ clearCaches() {
378
+ this._meshCache.clear();
379
+ }
380
+ async addBoxCollider(collider, center, size) {
381
+ if (!this._isInitialized)
382
+ await this.initialize(collider.context);
383
+ if (!collider.activeAndEnabled)
384
+ return;
385
+ if (!this.enabled) {
386
+ if (debugPhysics)
387
+ console.warn("Physics are disabled");
388
+ return;
389
+ }
390
+ const obj = collider.gameObject;
391
+ const scale = getWorldScale(obj, this._tempPosition).multiply(size);
392
+ scale.multiplyScalar(0.5);
393
+ // prevent negative scale
394
+ if (scale.x < 0)
395
+ scale.x = Math.abs(scale.x);
396
+ if (scale.y < 0)
397
+ scale.y = Math.abs(scale.y);
398
+ if (scale.z < 0)
399
+ scale.z = Math.abs(scale.z);
400
+ // prevent zero scale - seems normals are flipped otherwise
401
+ if (scale.x == 0)
402
+ scale.x = 0.0000001;
403
+ if (scale.y == 0)
404
+ scale.y = 0.0000001;
405
+ if (scale.z == 0)
406
+ scale.z = 0.0000001;
407
+ const desc = ColliderDesc.cuboid(scale.x, scale.y, scale.z);
408
+ // const objectLayerMask = collider.gameObject.layers.mask;
409
+ // const mask = objectLayerMask & ~2;
410
+ // TODO: https://rapier.rs/docs/user_guides/javascript/colliders/#collision-groups-and-solver-groups
411
+ // desc.setCollisionGroups(objectLayerMask);
412
+ this.createCollider(collider, desc, center);
413
+ }
414
+ async addSphereCollider(collider, center, radius) {
415
+ if (!this._isInitialized)
416
+ await this.initialize(collider.context);
417
+ if (!collider.activeAndEnabled)
418
+ return;
419
+ if (!this.enabled) {
420
+ if (debugPhysics)
421
+ console.warn("Physics are disabled");
422
+ return;
423
+ }
424
+ const obj = collider.gameObject;
425
+ const scale = getWorldScale(obj, this._tempPosition).multiplyScalar(radius);
426
+ // Prevent negative scales
427
+ scale.x = Math.abs(scale.x);
428
+ const desc = ColliderDesc.ball(scale.x);
429
+ this.createCollider(collider, desc, center);
430
+ }
431
+ async addCapsuleCollider(collider, center, height, radius) {
432
+ if (!this._isInitialized)
433
+ await this.initialize(collider.context);
434
+ if (!collider.activeAndEnabled)
435
+ return;
436
+ if (!this.enabled) {
437
+ if (debugPhysics)
438
+ console.warn("Physics are disabled");
439
+ return;
440
+ }
441
+ const obj = collider.gameObject;
442
+ const scale = getWorldScale(obj, this._tempPosition);
443
+ // Prevent negative scales
444
+ scale.x = Math.abs(scale.x);
445
+ scale.y = Math.abs(scale.y);
446
+ const desc = ColliderDesc.capsule(height * .5 * scale.y - radius, radius * scale.x);
447
+ this.createCollider(collider, desc, center);
448
+ }
449
+ async addMeshCollider(collider, mesh, convex, scale) {
450
+ if (!this._isInitialized)
451
+ await this.initialize(collider.context);
452
+ if (!collider.activeAndEnabled)
453
+ return;
454
+ if (!this.enabled) {
455
+ if (debugPhysics)
456
+ console.warn("Physics are disabled");
457
+ return;
458
+ }
459
+ const geo = mesh.geometry;
460
+ if (!geo) {
461
+ if (debugPhysics)
462
+ console.warn("Missing mesh geometry", mesh.name);
463
+ return;
464
+ }
465
+ let positions = geo.getAttribute("position").array;
466
+ const indices = geo.index?.array;
467
+ // console.log(geo.center())
468
+ // scaling seems not supported yet https://github.com/dimforge/rapier/issues/243
469
+ if (Math.abs(scale.x - 1) > 0.0001 || Math.abs(scale.y - 1) > 0.0001 || Math.abs(scale.z - 1) > 0.0001) {
470
+ const key = geo.uuid + "_" + scale.x + "_" + scale.y + "_" + scale.z + "_" + convex;
471
+ if (this._meshCache.has(key)) {
472
+ positions = this._meshCache.get(key);
473
+ }
474
+ else {
475
+ console.warn("Your model is using scaled mesh colliders which is not optimal for performance", mesh.name, Object.assign({}, scale), mesh);
476
+ // showBalloonWarning("Your model is using scaled mesh colliders which is not optimal for performance: " + mesh.name + ", consider using unscaled objects");
477
+ const scaledPositions = new Float32Array(positions.length);
478
+ for (let i = 0; i < positions.length; i += 3) {
479
+ scaledPositions[i] = positions[i] * scale.x;
480
+ scaledPositions[i + 1] = positions[i + 1] * scale.y;
481
+ scaledPositions[i + 2] = positions[i + 2] * scale.z;
482
+ }
483
+ positions = scaledPositions;
484
+ this._meshCache.set(key, scaledPositions);
485
+ }
486
+ }
487
+ const desc = convex ? ColliderDesc.convexMesh(positions) : ColliderDesc.trimesh(positions, indices);
488
+ if (desc) {
489
+ const col = this.createCollider(collider, desc);
490
+ col.setMassProperties(1, { x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0, w: 1 });
491
+ // rb?.setTranslation({ x: 0, y: 2, z: 0 });
492
+ // col.setTranslationWrtParent(new Vector3(0,2,0));
493
+ }
494
+ }
495
+ createCollider(collider, desc, center) {
496
+ if (!this.world)
497
+ throw new Error("Physics world not initialized");
498
+ const matrix = this._tempMatrix;
499
+ const { rigidBody, useExplicitMassProperties } = this.getRigidbody(collider, this._tempMatrix);
500
+ matrix.decompose(this._tempPosition, this._tempQuaternion, this._tempScale);
501
+ getWorldScale(collider.gameObject, this._tempScale);
502
+ if (center) {
503
+ center.multiply(this._tempScale);
504
+ this._tempPosition.x -= center.x;
505
+ this._tempPosition.y += center.y;
506
+ this._tempPosition.z += center.z;
507
+ }
508
+ desc.setTranslation(this._tempPosition.x, this._tempPosition.y, this._tempPosition.z);
509
+ desc.setRotation(this._tempQuaternion);
510
+ desc.setSensor(collider.isTrigger);
511
+ // TODO: we might want to update this if the material changes
512
+ const physicsMaterial = collider.sharedMaterial;
513
+ if (physicsMaterial) {
514
+ desc.setRestitution(physicsMaterial.bounciness);
515
+ switch (physicsMaterial.bounceCombine) {
516
+ case PhysicsMaterialCombine.Average:
517
+ desc.setRestitutionCombineRule(CoefficientCombineRule.Average);
518
+ break;
519
+ case PhysicsMaterialCombine.Maximum:
520
+ desc.setRestitutionCombineRule(CoefficientCombineRule.Max);
521
+ break;
522
+ case PhysicsMaterialCombine.Minimum:
523
+ desc.setRestitutionCombineRule(CoefficientCombineRule.Min);
524
+ break;
525
+ case PhysicsMaterialCombine.Multiply:
526
+ desc.setRestitutionCombineRule(CoefficientCombineRule.Multiply);
527
+ break;
528
+ }
529
+ desc.setFriction(physicsMaterial.dynamicFriction);
530
+ switch (physicsMaterial.frictionCombine) {
531
+ case PhysicsMaterialCombine.Average:
532
+ desc.setFrictionCombineRule(CoefficientCombineRule.Average);
533
+ break;
534
+ case PhysicsMaterialCombine.Maximum:
535
+ desc.setFrictionCombineRule(CoefficientCombineRule.Max);
536
+ break;
537
+ case PhysicsMaterialCombine.Minimum:
538
+ desc.setFrictionCombineRule(CoefficientCombineRule.Min);
539
+ break;
540
+ case PhysicsMaterialCombine.Multiply:
541
+ desc.setFrictionCombineRule(CoefficientCombineRule.Multiply);
542
+ break;
543
+ }
544
+ }
545
+ // if we want to use explicit mass properties, we need to set the collider density to 0
546
+ // otherwise rapier will compute the mass properties based on the collider shape and density
547
+ // https://rapier.rs/docs/user_guides/javascript/rigid_bodies#mass-properties
548
+ if (useExplicitMassProperties) {
549
+ // desc.setDensity(0);
550
+ }
551
+ const col = this.world.createCollider(desc, rigidBody);
552
+ col[$componentKey] = collider;
553
+ collider[$bodyKey] = col;
554
+ col.setActiveEvents(ActiveEvents.COLLISION_EVENTS);
555
+ // We want to receive collisitons between two triggers too
556
+ col.setActiveCollisionTypes(ActiveCollisionTypes.ALL);
557
+ // const objectLayerMask = collider.gameObject.layers.mask;
558
+ // const mask = objectLayerMask & ~2;
559
+ // col.setCollisionGroups(objectLayerMask);
560
+ this.objects.push(collider);
561
+ this.bodies.push(col);
562
+ return col;
563
+ }
564
+ getRigidbody(collider, _matrix) {
565
+ if (!this.world)
566
+ throw new Error("Physics world not initialized");
567
+ let rigidBody = null;
568
+ let useExplicitMassProperties = false;
569
+ if (collider.attachedRigidbody) {
570
+ const rb = collider.attachedRigidbody;
571
+ rigidBody = rb[$bodyKey];
572
+ useExplicitMassProperties = true;
573
+ if (!rigidBody) {
574
+ const kinematic = rb.isKinematic && !debugColliderPlacement;
575
+ if (debugPhysics)
576
+ console.log("Create rigidbody", kinematic);
577
+ const rigidBodyDesc = kinematic ? RAPIER.RigidBodyDesc.kinematicPositionBased() : RAPIER.RigidBodyDesc.dynamic();
578
+ const pos = getWorldPosition(collider.attachedRigidbody.gameObject);
579
+ rigidBodyDesc.setTranslation(pos.x, pos.y, pos.z);
580
+ rigidBodyDesc.setRotation(getWorldQuaternion(collider.attachedRigidbody.gameObject));
581
+ rigidBody = this.world.createRigidBody(rigidBodyDesc);
582
+ this.bodies.push(rigidBody);
583
+ this.objects.push(rb);
584
+ }
585
+ rigidBody[$componentKey] = rb;
586
+ rb[$bodyKey] = rigidBody;
587
+ this.internalUpdateProperties(rb, rigidBody);
588
+ this.getRigidbodyRelativeMatrix(collider.gameObject, rb.gameObject, _matrix);
589
+ }
590
+ else {
591
+ const rigidBodyDesc = RAPIER.RigidBodyDesc.kinematicPositionBased();
592
+ const pos = getWorldPosition(collider.gameObject);
593
+ rigidBodyDesc.setTranslation(pos.x, pos.y, pos.z);
594
+ rigidBodyDesc.setRotation(getWorldQuaternion(collider.gameObject));
595
+ rigidBody = this.world.createRigidBody(rigidBodyDesc);
596
+ _matrix.identity();
597
+ rigidBody[$componentKey] = null;
598
+ }
599
+ collider[$colliderRigidbody] = rigidBody;
600
+ return { rigidBody: rigidBody, useExplicitMassProperties: useExplicitMassProperties };
601
+ }
602
+ internal_getRigidbody(rb) {
603
+ return rb[$bodyKey];
604
+ }
605
+ internalUpdateProperties(rb, rigidbody) {
606
+ // continuous collision detection
607
+ // https://rapier.rs/docs/user_guides/javascript/rigid_bodies#continuous-collision-detection
608
+ rigidbody.enableCcd(rb.collisionDetectionMode !== CollisionDetectionMode.Discrete);
609
+ rigidbody.setLinearDamping(rb.drag);
610
+ rigidbody.setAngularDamping(rb.angularDrag);
611
+ rigidbody.setGravityScale(rb.useGravity ? rb.gravityScale : 0, true);
612
+ // https://rapier.rs/docs/user_guides/javascript/rigid_bodies#mass-properties
613
+ // rigidbody.setAdditionalMass(rb.mass, true);
614
+ // for (let i = 0; i < rigidbody.numColliders(); i++) {
615
+ // const collider = rigidbody.collider(i);
616
+ // if (collider) {
617
+ // collider.setMass(rb.mass);
618
+ // // const density = rb.mass / collider.shape.computeMassProperties().mass;
619
+ // }
620
+ // }
621
+ // lock rotations
622
+ rigidbody.setEnabledRotations(!rb.lockRotationX, !rb.lockRotationY, !rb.lockRotationZ, true);
623
+ rigidbody.setEnabledTranslations(!rb.lockPositionX, !rb.lockPositionY, !rb.lockPositionZ, true);
624
+ if (rb.isKinematic) {
625
+ rigidbody.setBodyType(RAPIER.RigidBodyType.KinematicPositionBased);
626
+ }
627
+ else {
628
+ rigidbody.setBodyType(RAPIER.RigidBodyType.Dynamic);
629
+ }
630
+ }
631
+ // private _lastStepTime: number | undefined = 0;
632
+ lines;
633
+ step(dt) {
634
+ if (!this.world)
635
+ return;
636
+ if (!this.enabled)
637
+ return;
638
+ this._isUpdatingPhysicsWorld = true;
639
+ if (!this.eventQueue) {
640
+ this.eventQueue = new EventQueue(false);
641
+ }
642
+ if (dt) {
643
+ // if we make to sudden changes to the timestep the physics can get unstable
644
+ // https://rapier.rs/docs/user_guides/javascript/integration_parameters/#dt
645
+ this.world.timestep = Mathf.lerp(this.world.timestep, dt, 0.8);
646
+ }
647
+ this.world.step(this.eventQueue);
648
+ this._isUpdatingPhysicsWorld = false;
649
+ this.updateDebugRendering(this.world);
650
+ }
651
+ updateDebugRendering(world) {
652
+ if (debugPhysics || debugColliderPlacement || showColliders) {
653
+ if (!this.lines) {
654
+ const material = new LineBasicMaterial({
655
+ color: 0x227700,
656
+ // vertexColors: THREE.VertexColors
657
+ });
658
+ const geometry = new BufferGeometry();
659
+ this.lines = new LineSegments(geometry, material);
660
+ this.context?.scene.add(this.lines);
661
+ }
662
+ const buffers = world.debugRender();
663
+ this.lines.geometry.setAttribute('position', new BufferAttribute(buffers.vertices, 3));
664
+ this.lines.geometry.setAttribute('color', new BufferAttribute(buffers.colors, 4));
665
+ }
666
+ }
667
+ postStep() {
668
+ if (!this.world)
669
+ return;
670
+ if (!this.enabled)
671
+ return;
672
+ this._isUpdatingPhysicsWorld = true;
673
+ this.syncObjects();
674
+ this._isUpdatingPhysicsWorld = false;
675
+ if (this.eventQueue && !this.collisionHandler) {
676
+ this.collisionHandler = new PhysicsCollisionHandler(this.world, this.eventQueue);
677
+ }
678
+ if (this.collisionHandler) {
679
+ this.collisionHandler.handleCollisionEvents();
680
+ this.collisionHandler.update();
681
+ }
682
+ }
683
+ /** sync rendered objects with physics world (except for colliders without rigidbody) */
684
+ syncObjects() {
685
+ if (debugColliderPlacement)
686
+ return;
687
+ for (let i = 0; i < this.bodies.length; i++) {
688
+ const obj = this.objects[i];
689
+ const body = this.bodies[i];
690
+ // if the collider is not attached to a rigidbody
691
+ // it means that its kinematic so we need to update its position
692
+ const col = obj;
693
+ if (col?.isCollider === true && !col.attachedRigidbody) {
694
+ const rigidbody = body.parent();
695
+ if (rigidbody)
696
+ this.syncPhysicsBody(obj.gameObject, rigidbody, true, true);
697
+ continue;
698
+ }
699
+ // sync
700
+ const pos = body.translation();
701
+ const rot = body.rotation();
702
+ // make sure to keep the collider offset
703
+ const center = obj["center"];
704
+ if (center && center.isVector3) {
705
+ this._tempQuaternion.set(rot.x, rot.y, rot.z, rot.w);
706
+ const offset = this._tempPosition.copy(center).applyQuaternion(this._tempQuaternion);
707
+ const scale = getWorldScale(obj.gameObject);
708
+ offset.multiply(scale);
709
+ pos.x -= offset.x;
710
+ pos.y -= offset.y;
711
+ pos.z -= offset.z;
712
+ }
713
+ setWorldPositionXYZ(obj.gameObject, pos.x, pos.y, pos.z);
714
+ setWorldQuaternionXYZW(obj.gameObject, rot.x, rot.y, rot.z, rot.w);
715
+ }
716
+ }
717
+ syncPhysicsBody(obj, body, translation, rotation) {
718
+ // const bodyType = body.bodyType();
719
+ // const previous = physicsBody.translation();
720
+ // const vel = physicsBody.linvel();
721
+ const worldPosition = getWorldPosition(obj, this._tempPosition);
722
+ const worldQuaternion = getWorldQuaternion(obj, this._tempQuaternion);
723
+ const type = body.bodyType();
724
+ switch (type) {
725
+ case RigidBodyType.Fixed:
726
+ case RigidBodyType.KinematicPositionBased:
727
+ case RigidBodyType.KinematicVelocityBased:
728
+ if (translation)
729
+ body.setNextKinematicTranslation(worldPosition);
730
+ if (rotation)
731
+ body.setNextKinematicRotation(worldQuaternion);
732
+ break;
733
+ default:
734
+ if (translation)
735
+ body.setTranslation(worldPosition, false);
736
+ if (rotation)
737
+ body.setRotation(worldQuaternion, false);
738
+ break;
739
+ }
740
+ body.wakeUp();
741
+ // physicsBody.setBodyType(RAPIER.RigidBodyType.Fixed);
742
+ // physicsBody.setLinvel(vel, false);
743
+ // update velocity
744
+ // const pos = physicsBody.translation();
745
+ // pos.x -= previous.x;
746
+ // pos.y -= previous.y;
747
+ // pos.z -= previous.z;
748
+ // // threhold
749
+ // const t = 1;
750
+ // const canUpdateVelocity = Math.abs(pos.x) < t && Math.abs(pos.y) < t && Math.abs(pos.z) < t;
751
+ // if (canUpdateVelocity) {
752
+ // const damping = 1 + this.context.time.deltaTime;
753
+ // vel.x *= damping;
754
+ // vel.y *= damping;
755
+ // vel.z *= damping;
756
+ // vel.x += pos.x;
757
+ // vel.y += pos.y;
758
+ // vel.z += pos.z;
759
+ // console.log(vel);
760
+ // physicsBody.setLinvel(vel, true);
761
+ // }
762
+ // else if(debugPhysics) console.warn("Movement exceeded threshold, not updating velocity", pos);
763
+ // body.setBodyType(bodyType);
764
+ }
765
+ static _matricesBuffer = [];
766
+ getRigidbodyRelativeMatrix(comp, rigidbody, mat, matrices) {
767
+ // collect all matrices to the rigidbody and then build the rigidbody relative matrix
768
+ if (matrices === undefined) {
769
+ matrices = RapierPhysics._matricesBuffer;
770
+ matrices.length = 0;
771
+ }
772
+ if (comp === rigidbody) {
773
+ const scale = getWorldScale(comp, this._tempPosition);
774
+ mat.makeScale(scale.x, scale.y, scale.z);
775
+ for (let i = matrices.length - 1; i >= 0; i--) {
776
+ mat.multiply(matrices[i]);
777
+ }
778
+ return mat;
779
+ }
780
+ matrices.push(comp.matrix);
781
+ if (comp.parent) {
782
+ this.getRigidbodyRelativeMatrix(comp.parent, rigidbody, mat, matrices);
783
+ }
784
+ return mat;
785
+ }
786
+ static centerConnectionPos = { x: 0, y: 0, z: 0 };
787
+ static centerConnectionRot = { x: 0, y: 0, z: 0, w: 1 };
788
+ addFixedJoint(body1, body2) {
789
+ if (!this.world) {
790
+ console.error("Physics world not initialized");
791
+ return;
792
+ }
793
+ const b1 = body1[$bodyKey];
794
+ const b2 = body2[$bodyKey];
795
+ this.calculateJointRelativeMatrices(body1.gameObject, body2.gameObject, this._tempMatrix);
796
+ this._tempMatrix.decompose(this._tempPosition, this._tempQuaternion, this._tempScale);
797
+ const params = JointData.fixed(RapierPhysics.centerConnectionPos, RapierPhysics.centerConnectionRot, this._tempPosition, this._tempQuaternion);
798
+ const joint = this.world.createImpulseJoint(params, b1, b2, true);
799
+ if (debugPhysics)
800
+ console.log("ADD FIXED JOINT", joint);
801
+ }
802
+ /** The joint prevents any relative movement between two rigid-bodies, except for relative rotations along one axis. This is typically used to simulate wheels, fans, etc. They are characterized by one local anchor as well as one local axis on each rigid-body. */
803
+ addHingeJoint(body1, body2, anchor, axis) {
804
+ if (!this.world) {
805
+ console.error("Physics world not initialized");
806
+ return;
807
+ }
808
+ const b1 = body1[$bodyKey];
809
+ const b2 = body2[$bodyKey];
810
+ this.calculateJointRelativeMatrices(body1.gameObject, body2.gameObject, this._tempMatrix);
811
+ this._tempMatrix.decompose(this._tempPosition, this._tempQuaternion, this._tempScale);
812
+ let params = RAPIER.JointData.revolute(anchor, this._tempPosition, axis);
813
+ let joint = this.world.createImpulseJoint(params, b1, b2, true);
814
+ if (debugPhysics)
815
+ console.log("ADD HINGE JOINT", joint);
816
+ }
817
+ calculateJointRelativeMatrices(body1, body2, mat) {
818
+ body1.updateWorldMatrix(true, false);
819
+ body2.updateWorldMatrix(true, false);
820
+ const world1 = body1.matrixWorld;
821
+ const world2 = body2.matrixWorld;
822
+ // set scale to 1
823
+ world1.elements[0] = 1;
824
+ world1.elements[5] = 1;
825
+ world1.elements[10] = 1;
826
+ world2.elements[0] = 1;
827
+ world2.elements[5] = 1;
828
+ world2.elements[10] = 1;
829
+ mat.copy(world2).premultiply(world1.invert()).invert();
830
+ }
831
+ }
832
+ /** responsible of processing collision events for the component system */
833
+ class PhysicsCollisionHandler {
834
+ world;
835
+ eventQueue;
836
+ constructor(world, eventQueue) {
837
+ this.world = world;
838
+ this.eventQueue = eventQueue;
839
+ }
840
+ activeCollisions = [];
841
+ activeCollisionsStay = [];
842
+ activeTriggers = [];
843
+ handleCollisionEvents() {
844
+ if (!this.eventQueue)
845
+ return;
846
+ if (!this.world)
847
+ return;
848
+ this.eventQueue.drainCollisionEvents((handle1, handle2, started) => {
849
+ const col1 = this.world.getCollider(handle1);
850
+ const col2 = this.world.getCollider(handle2);
851
+ const colliderComponent1 = col1[$componentKey];
852
+ const colliderComponent2 = col2[$componentKey];
853
+ if (debugCollisions)
854
+ console.log("EVT", colliderComponent1.name, colliderComponent2.name, started, col1, col2);
855
+ if (colliderComponent1 && colliderComponent2) {
856
+ if (started) {
857
+ this.onCollisionStarted(colliderComponent1, col1, colliderComponent2, col2);
858
+ this.onCollisionStarted(colliderComponent2, col2, colliderComponent1, col1);
859
+ }
860
+ else {
861
+ this.onCollisionEnded(colliderComponent1, colliderComponent2);
862
+ this.onCollisionEnded(colliderComponent2, colliderComponent1);
863
+ }
864
+ }
865
+ });
866
+ }
867
+ update() {
868
+ this.onHandleCollisionStay();
869
+ }
870
+ onCollisionStarted(self, selfBody, other, otherBody) {
871
+ let collision = null;
872
+ // if one is a trigger we dont get collisions but want to raise the trigger events
873
+ if (self.isTrigger || other.isTrigger) {
874
+ foreachComponent(self.gameObject, (c) => {
875
+ if (c.onTriggerEnter && !c.destroyed) {
876
+ c.onTriggerEnter(other);
877
+ }
878
+ this.activeTriggers.push({ collider: self, component: c, otherCollider: other });
879
+ });
880
+ }
881
+ else {
882
+ const object = self.gameObject;
883
+ // TODO: we dont respect the flip value here!
884
+ this.world.contactPair(selfBody, otherBody, (manifold, _flipped) => {
885
+ foreachComponent(object, (c) => {
886
+ if (c.destroyed)
887
+ return;
888
+ const hasDeclaredEventMethod = c.onCollisionEnter || c.onCollisionStay || c.onCollisionExit;
889
+ if (hasDeclaredEventMethod || debugCollisions) {
890
+ if (!collision) {
891
+ const contacts = [];
892
+ const normal = manifold.normal();
893
+ for (let i = 0; i < manifold.numSolverContacts(); i++) {
894
+ // solver points are in world space
895
+ // https://rapier.rs/docs/user_guides/javascript/advanced_collision_detection_js#the-contact-graph
896
+ const pt = manifold.solverContactPoint(i);
897
+ const impulse = manifold.contactImpulse(i);
898
+ if (pt) {
899
+ const dist = manifold.contactDist(i);
900
+ const friction = manifold.solverContactFriction(i);
901
+ const contact = new ContactPoint(pt, dist, normal, impulse, friction);
902
+ contacts.push(contact);
903
+ if (debugCollisions) {
904
+ Gizmos.DrawDirection(pt, normal, 0xff0000, 3, true);
905
+ }
906
+ }
907
+ }
908
+ collision = new Collision(object, other, contacts);
909
+ }
910
+ // we only need to keep track if any event exists
911
+ if (hasDeclaredEventMethod) {
912
+ const info = { collider: self, component: c, collision };
913
+ this.activeCollisions.push(info);
914
+ if (c.onCollisionStay) {
915
+ this.activeCollisionsStay.push(info);
916
+ }
917
+ c.onCollisionEnter?.call(c, collision);
918
+ }
919
+ }
920
+ });
921
+ });
922
+ }
923
+ }
924
+ onHandleCollisionStay() {
925
+ for (const active of this.activeCollisionsStay) {
926
+ const c = active.component;
927
+ if (c.destroyed)
928
+ continue;
929
+ if (c.activeAndEnabled && c.onCollisionStay) {
930
+ const arg = active.collision;
931
+ c.onCollisionStay(arg);
932
+ }
933
+ }
934
+ for (const active of this.activeTriggers) {
935
+ const c = active.component;
936
+ if (c.destroyed)
937
+ continue;
938
+ if (c.activeAndEnabled && c.onTriggerStay) {
939
+ const arg = active.otherCollider;
940
+ c.onTriggerStay(arg);
941
+ }
942
+ }
943
+ }
944
+ onCollisionEnded(self, other) {
945
+ if (self.destroyed || other.destroyed)
946
+ return;
947
+ for (let i = 0; i < this.activeCollisions.length; i++) {
948
+ const active = this.activeCollisions[i];
949
+ const collider = active.collider;
950
+ if (collider.destroyed) {
951
+ this.activeCollisions.splice(i, 1);
952
+ i--;
953
+ continue;
954
+ }
955
+ if (collider === self && active.collision.collider === other) {
956
+ const c = active.component;
957
+ this.activeCollisions.splice(i, 1);
958
+ i--;
959
+ if (c.activeAndEnabled && c.onCollisionExit) {
960
+ const collision = active.collision;
961
+ c.onCollisionExit(collision);
962
+ }
963
+ }
964
+ }
965
+ for (let i = 0; i < this.activeCollisionsStay.length; i++) {
966
+ const active = this.activeCollisionsStay[i];
967
+ const collider = active.collider;
968
+ if (collider.destroyed) {
969
+ this.activeCollisionsStay.splice(i, 1);
970
+ i--;
971
+ continue;
972
+ }
973
+ if (collider === self && active.collision.collider === other) {
974
+ const c = active.component;
975
+ this.activeCollisionsStay.splice(i, 1);
976
+ i--;
977
+ if (c.activeAndEnabled && c.onCollisionExit) {
978
+ const collision = active.collision;
979
+ c.onCollisionExit(collision);
980
+ }
981
+ }
982
+ }
983
+ for (let i = 0; i < this.activeTriggers.length; i++) {
984
+ const active = this.activeTriggers[i];
985
+ const collider = active.collider;
986
+ if (collider.destroyed) {
987
+ this.activeTriggers.splice(i, 1);
988
+ i--;
989
+ continue;
990
+ }
991
+ if (collider === self && active.otherCollider === other) {
992
+ const c = active.component;
993
+ this.activeTriggers.splice(i, 1);
994
+ i--;
995
+ if (c.activeAndEnabled && c.onTriggerExit) {
996
+ const collision = active.otherCollider;
997
+ c.onTriggerExit(collision);
998
+ }
999
+ }
1000
+ }
1001
+ }
1002
+ }
1003
+ //# sourceMappingURL=engine_physics_rapier.js.map