@needle-tools/engine 2.40.0-pre → 2.41.0-pre

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 (52) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/needle-engine.d.ts +269 -123
  3. package/dist/needle-engine.js +389 -389
  4. package/dist/needle-engine.js.map +4 -4
  5. package/dist/needle-engine.min.js +41 -41
  6. package/dist/needle-engine.min.js.map +4 -4
  7. package/lib/engine/engine_gizmos.d.ts +1 -0
  8. package/lib/engine/engine_gizmos.js +16 -4
  9. package/lib/engine/engine_gizmos.js.map +1 -1
  10. package/lib/engine/engine_math.d.ts +9 -6
  11. package/lib/engine/engine_math.js +9 -0
  12. package/lib/engine/engine_math.js.map +1 -1
  13. package/lib/engine/engine_physics.js +14 -6
  14. package/lib/engine/engine_physics.js.map +1 -1
  15. package/lib/engine/engine_serialization_core.js +2 -0
  16. package/lib/engine/engine_serialization_core.js.map +1 -1
  17. package/lib/engine/engine_utils.d.ts +1 -0
  18. package/lib/engine/engine_utils.js +3 -0
  19. package/lib/engine/engine_utils.js.map +1 -1
  20. package/lib/engine-components/AnimationCurve.js +20 -5
  21. package/lib/engine-components/AnimationCurve.js.map +1 -1
  22. package/lib/engine-components/Light.d.ts +2 -0
  23. package/lib/engine-components/Light.js +33 -9
  24. package/lib/engine-components/Light.js.map +1 -1
  25. package/lib/engine-components/ParticleSystem.d.ts +15 -26
  26. package/lib/engine-components/ParticleSystem.js +251 -184
  27. package/lib/engine-components/ParticleSystem.js.map +1 -1
  28. package/lib/engine-components/ParticleSystemModules.d.ts +208 -63
  29. package/lib/engine-components/ParticleSystemModules.js +640 -153
  30. package/lib/engine-components/ParticleSystemModules.js.map +1 -1
  31. package/lib/engine-components/WebXR.js +8 -3
  32. package/lib/engine-components/WebXR.js.map +1 -1
  33. package/lib/engine-components/codegen/components.d.ts +6 -0
  34. package/lib/engine-components/codegen/components.js +6 -0
  35. package/lib/engine-components/codegen/components.js.map +1 -1
  36. package/package.json +3 -1
  37. package/src/engine/codegen/register_types.js +24 -0
  38. package/src/engine/engine_gizmos.ts +19 -4
  39. package/src/engine/engine_math.ts +19 -6
  40. package/src/engine/engine_physics.ts +17 -7
  41. package/src/engine/engine_serialization_core.ts +1 -0
  42. package/src/engine/engine_utils.ts +5 -0
  43. package/src/engine-components/AnimationCurve.ts +25 -11
  44. package/src/engine-components/Light.ts +39 -8
  45. package/src/engine-components/ParticleSystem.ts +314 -194
  46. package/src/engine-components/ParticleSystemModules.ts +537 -154
  47. package/src/engine-components/WebXR.ts +11 -8
  48. package/src/engine-components/codegen/components.ts +6 -0
  49. package/src/engine/dist/engine_physics.js +0 -739
  50. package/src/engine/dist/engine_setup.js +0 -777
  51. package/src/engine-components/dist/CharacterController.js +0 -123
  52. package/src/engine-components/dist/RigidBody.js +0 -458
@@ -1,739 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (_) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- exports.__esModule = true;
39
- exports.Physics = exports.SphereIntersection = exports.RaycastOptions = void 0;
40
- var three_1 = require("three");
41
- var engine_utils_1 = require("./engine_utils");
42
- var engine_three_utils_1 = require("./engine_three_utils");
43
- var engine_types_1 = require("./engine_types");
44
- var engine_gameobject_1 = require("./engine_gameobject");
45
- var rapier3d_compat_1 = require("@dimforge/rapier3d-compat");
46
- var engine_physics_types_1 = require("../engine/engine_physics.types");
47
- var debugPhysics = engine_utils_1.getParam("debugphysics");
48
- var debugColliderPlacement = engine_utils_1.getParam("debugphysicscolliders");
49
- var debugCollisions = engine_utils_1.getParam("debugcollisions");
50
- var $componentKey = Symbol("needle component");
51
- var $bodyKey = Symbol("physics body");
52
- var $colliderRigidbody = Symbol("rigidbody");
53
- // const $removed = Symbol("removed");
54
- var RaycastOptions = /** @class */ (function () {
55
- function RaycastOptions() {
56
- this.ray = undefined;
57
- this.cam = undefined;
58
- this.screenPoint = undefined;
59
- this.raycaster = undefined;
60
- this.results = undefined;
61
- this.targets = undefined;
62
- this.recursive = true;
63
- this.minDistance = undefined;
64
- this.maxDistance = undefined;
65
- this.lineThreshold = undefined;
66
- this.layerMask = undefined;
67
- this.ignore = undefined;
68
- }
69
- RaycastOptions.prototype.screenPointFromOffset = function (ox, oy) {
70
- if (this.screenPoint === undefined)
71
- this.screenPoint = new three_1.Vector2();
72
- this.screenPoint.x = ox / window.innerWidth * 2 - 1;
73
- this.screenPoint.y = -(oy / window.innerHeight) * 2 + 1;
74
- };
75
- RaycastOptions.prototype.setMask = function (mask) {
76
- if (!this.layerMask)
77
- this.layerMask = new three_1.Layers();
78
- var lm = this.layerMask;
79
- if (lm)
80
- lm.mask = mask;
81
- else
82
- this.layerMask = mask;
83
- };
84
- RaycastOptions.AllLayers = 0xFFFFFFFF;
85
- return RaycastOptions;
86
- }());
87
- exports.RaycastOptions = RaycastOptions;
88
- var SphereIntersection = /** @class */ (function () {
89
- function SphereIntersection(object, distance, point) {
90
- this.object = object;
91
- this.distance = distance;
92
- this.point = point;
93
- }
94
- return SphereIntersection;
95
- }());
96
- exports.SphereIntersection = SphereIntersection;
97
- var Physics = /** @class */ (function () {
98
- // private rigidbodiesLookup: Map<IRigidbody, RigidBody> = new Map<IRigidbody, RigidBody>();
99
- // private kinematicColliders: Array<IComponent> = [];
100
- // private rigidbodyLookup: Map<IRigidbody, IComponent[]> = new Map<IRigidbody, IComponent[]>();
101
- // private objectLookup: Map<Object3D, IRigidbody> = new Map<Object3D, IRigidbody>();
102
- function Physics(context) {
103
- // raycasting
104
- this.raycaster = new three_1.Raycaster();
105
- this.defaultRaycastOptions = new RaycastOptions();
106
- this.targetBuffer = new Array(1);
107
- this.defaultThresholds = {
108
- Mesh: {},
109
- Line: { threshold: 0 },
110
- LOD: {},
111
- Points: { threshold: 0 },
112
- Sprite: {}
113
- };
114
- this.sphereResults = new Array();
115
- this.sphereMask = new three_1.Layers();
116
- this.tempBoundingBox = new three_1.Box3();
117
- // physics simulation
118
- this._tempPosition = new three_1.Vector3();
119
- this._tempQuaternion = new three_1.Quaternion();
120
- this._tempScale = new three_1.Vector3();
121
- this._tempMatrix = new three_1.Matrix4();
122
- this._isUpdatingPhysicsWorld = false;
123
- this._hasCreatedWorld = false;
124
- // private rigidbodies: Array<IRigidbody | null> = [];
125
- this.objects = [];
126
- this.bodies = [];
127
- this.context = context;
128
- }
129
- Physics.prototype.sphereOverlap = function (spherePos, radius, traverseChildsAfterHit) {
130
- if (traverseChildsAfterHit === void 0) { traverseChildsAfterHit = true; }
131
- this.sphereResults.length = 0;
132
- if (!this.context.scene)
133
- return this.sphereResults;
134
- var sphere = new three_1.Sphere(spherePos, radius);
135
- var mask = this.sphereMask;
136
- mask.enableAll();
137
- mask.disable(2);
138
- for (var _i = 0, _a = this.context.scene.children; _i < _a.length; _i++) {
139
- var ch = _a[_i];
140
- this.onSphereOverlap(ch, sphere, mask, this.sphereResults, traverseChildsAfterHit);
141
- }
142
- return this.sphereResults.sort(function (a, b) { return a.distance - b.distance; });
143
- };
144
- Physics.prototype.onSphereOverlap = function (obj, sp, mask, results, traverseChildsAfterHit) {
145
- if (obj.type === "Mesh" && obj.layers.test(mask)) {
146
- var mesh = obj;
147
- var geo = mesh.geometry;
148
- if (!geo.boundingBox)
149
- geo.computeBoundingBox();
150
- if (geo.boundingBox) {
151
- if (mesh.matrixWorldNeedsUpdate)
152
- mesh.updateMatrixWorld();
153
- var test = this.tempBoundingBox.copy(geo.boundingBox).applyMatrix4(mesh.matrixWorld);
154
- if (sp.intersectsBox(test)) {
155
- // console.log(obj, obj.layers.test(mask), obj.layers.mask, mask.mask);
156
- var wp = engine_three_utils_1.getWorldPosition(obj);
157
- var dist = wp.distanceTo(sp.center);
158
- var int = new SphereIntersection(obj, dist, sp.center.clone());
159
- results.push(int);
160
- if (!traverseChildsAfterHit)
161
- return;
162
- }
163
- }
164
- }
165
- if (obj.children) {
166
- for (var _i = 0, _a = obj.children; _i < _a.length; _i++) {
167
- var ch = _a[_i];
168
- var len = results.length;
169
- this.onSphereOverlap(ch, sp, mask, results, traverseChildsAfterHit);
170
- if (len != results.length && !traverseChildsAfterHit)
171
- return;
172
- }
173
- }
174
- };
175
- Physics.prototype.raycastFromRay = function (ray, options) {
176
- if (options === void 0) { options = null; }
177
- var opts = options !== null && options !== void 0 ? options : this.defaultRaycastOptions;
178
- opts.ray = ray;
179
- return this.raycast(opts);
180
- };
181
- Physics.prototype.raycast = function (options) {
182
- var _a, _b, _c, _d, _e, _f;
183
- if (options === void 0) { options = null; }
184
- if (!options)
185
- options = this.defaultRaycastOptions;
186
- var mp = (_a = options.screenPoint) !== null && _a !== void 0 ? _a : this.context.input.mousePositionRC;
187
- var rc = (_b = options.raycaster) !== null && _b !== void 0 ? _b : this.raycaster;
188
- rc.near = (_c = options.minDistance) !== null && _c !== void 0 ? _c : 0;
189
- rc.far = (_d = options.maxDistance) !== null && _d !== void 0 ? _d : Infinity;
190
- rc.params = this.defaultThresholds;
191
- if (options.lineThreshold)
192
- rc.params.Line = { threshold: options.lineThreshold };
193
- else
194
- rc.params.Line = { threshold: 0 };
195
- if (options.ray) {
196
- rc.ray.copy(options.ray);
197
- }
198
- else {
199
- var cam = (_e = options.cam) !== null && _e !== void 0 ? _e : this.context.mainCamera;
200
- if (!cam) {
201
- console.error("Can not perform raycast - no main camera found");
202
- if (this.defaultRaycastOptions.results)
203
- this.defaultRaycastOptions.results.length = 0;
204
- return (_f = this.defaultRaycastOptions.results) !== null && _f !== void 0 ? _f : [];
205
- }
206
- rc.setFromCamera(mp, cam);
207
- }
208
- var targets = options.targets;
209
- if (!targets) {
210
- targets = this.targetBuffer;
211
- targets[0] = this.context.scene;
212
- }
213
- var results = options.results;
214
- if (!results) {
215
- if (!this.defaultRaycastOptions.results)
216
- this.defaultRaycastOptions.results = new Array();
217
- results = this.defaultRaycastOptions.results;
218
- }
219
- // layermask
220
- // https://github.com/mrdoob/js/blob/master/src/core/Layers.js
221
- if (options.layerMask !== undefined) {
222
- if (options.layerMask instanceof three_1.Layers)
223
- rc.layers.mask = options.layerMask.mask;
224
- else
225
- rc.layers.mask = options.layerMask;
226
- }
227
- else {
228
- rc.layers.enableAll();
229
- rc.layers.disable(2);
230
- }
231
- // console.log(rc)
232
- // console.log(targets);
233
- // shoot
234
- results.length = 0;
235
- rc.intersectObjects(targets, options.recursive, results);
236
- var ignorelist = options.ignore;
237
- if (ignorelist !== undefined && ignorelist.length > 0) {
238
- results = results.filter(function (r) { return !ignorelist.includes(r.object); });
239
- }
240
- return results;
241
- };
242
- Object.defineProperty(Physics.prototype, "isUpdating", {
243
- get: function () { return this._isUpdatingPhysicsWorld; },
244
- enumerable: false,
245
- configurable: true
246
- });
247
- Physics.prototype.createWorld = function () {
248
- return __awaiter(this, void 0, void 0, function () {
249
- var gravity;
250
- return __generator(this, function (_a) {
251
- switch (_a.label) {
252
- case 0:
253
- if (this._hasCreatedWorld) {
254
- console.error("Invalid call to create physics world: world is already created");
255
- return [2 /*return*/];
256
- }
257
- this._hasCreatedWorld = true;
258
- if (!!Physics._didLoadPhysicsEngine) return [3 /*break*/, 2];
259
- return [4 /*yield*/, rapier3d_compat_1["default"].init().then(function () { return rapier3d_compat_1["default"]; })];
260
- case 1:
261
- _a.sent();
262
- Physics._didLoadPhysicsEngine = true;
263
- _a.label = 2;
264
- case 2:
265
- gravity = { x: 0.0, y: -9.81, z: 0.0 };
266
- this.world = new rapier3d_compat_1.World(gravity);
267
- return [2 /*return*/];
268
- }
269
- });
270
- });
271
- };
272
- Physics.prototype.addBoxCollider = function (collider, center, size) {
273
- var obj = collider.gameObject;
274
- var scale = engine_three_utils_1.getWorldScale(obj, this._tempPosition).multiply(size);
275
- scale.multiplyScalar(0.5);
276
- var desc = rapier3d_compat_1.ColliderDesc.cuboid(scale.x, scale.y, scale.z);
277
- this.createCollider(collider, desc, center);
278
- };
279
- Physics.prototype.addSphereCollider = function (collider, center, radius) {
280
- var obj = collider.gameObject;
281
- var scale = engine_three_utils_1.getWorldScale(obj, this._tempPosition).multiplyScalar(radius);
282
- var desc = rapier3d_compat_1.ColliderDesc.ball(scale.x);
283
- this.createCollider(collider, desc, center);
284
- };
285
- Physics.prototype.addCapsuleCollider = function (collider, center, height, radius) {
286
- var obj = collider.gameObject;
287
- var scale = engine_three_utils_1.getWorldScale(obj, this._tempPosition);
288
- if (debugPhysics)
289
- console.log("capsule scale", scale, height, radius);
290
- var desc = rapier3d_compat_1.ColliderDesc.capsule(height * .5 * scale.y - radius, radius * scale.x);
291
- this.createCollider(collider, desc, center);
292
- };
293
- Physics.prototype.addMeshCollider = function (collider, mesh, convex) {
294
- var _a;
295
- var geo = mesh.geometry;
296
- if (!geo) {
297
- if (debugPhysics)
298
- console.warn("Missing mesh geometry", mesh.name);
299
- return;
300
- }
301
- var positions = geo.getAttribute("position").array;
302
- var indices = (_a = geo.index) === null || _a === void 0 ? void 0 : _a.array;
303
- // console.log(geo.center())
304
- // scaling seems not supported yet https://github.com/dimforge/rapier/issues/243
305
- var scale = engine_three_utils_1.getWorldScale(mesh, this._tempPosition);
306
- if (Math.abs(scale.x - 1) > 0.0001 || Math.abs(scale.y - 1) > 0.0001 || Math.abs(scale.z - 1) > 0.0001) {
307
- console.warn("Your model is using scaled mesh colliders which is not optimal for performance", mesh.name, Object.assign({}, scale), mesh);
308
- // showBalloonWarning("Your model is using scaled mesh colliders which is not optimal for performance: " + mesh.name + ", consider using unscaled objects");
309
- var scaledPositions = new Float32Array(positions.length);
310
- for (var i = 0; i < positions.length; i += 3) {
311
- scaledPositions[i] = positions[i] * scale.x;
312
- scaledPositions[i + 1] = positions[i + 1] * scale.y;
313
- scaledPositions[i + 2] = positions[i + 2] * scale.z;
314
- }
315
- positions = scaledPositions;
316
- }
317
- var desc = convex ? rapier3d_compat_1.ColliderDesc.convexMesh(positions) : rapier3d_compat_1.ColliderDesc.trimesh(positions, indices);
318
- if (desc) {
319
- this.createCollider(collider, desc);
320
- // col.setTranslationWrtParent(new Vector3(0,2,0));
321
- }
322
- };
323
- Physics.prototype.createCollider = function (collider, desc, center) {
324
- if (!this.world)
325
- throw new Error("Physics world not initialized");
326
- var matrix = this._tempMatrix;
327
- var _a = this.getRigidbody(collider, this._tempMatrix), rigidBody = _a.rigidBody, useExplicitMassProperties = _a.useExplicitMassProperties;
328
- matrix.decompose(this._tempPosition, this._tempQuaternion, this._tempScale);
329
- if (center)
330
- this._tempPosition.add(center).multiply(this._tempScale);
331
- desc.setTranslation(this._tempPosition.x, this._tempPosition.y, this._tempPosition.z);
332
- desc.setRotation(this._tempQuaternion);
333
- desc.setSensor(collider.isTrigger);
334
- // if we want to use explicit mass properties, we need to set the collider density to 0
335
- // otherwise rapier will compute the mass properties based on the collider shape and density
336
- // https://rapier.rs/docs/user_guides/javascript/rigid_bodies#mass-properties
337
- if (useExplicitMassProperties) {
338
- // desc.setDensity(0);
339
- }
340
- var col = this.world.createCollider(desc, rigidBody);
341
- col[$componentKey] = collider;
342
- collider[$bodyKey] = col;
343
- col.setActiveEvents(rapier3d_compat_1.ActiveEvents.COLLISION_EVENTS);
344
- this.objects.push(collider);
345
- this.bodies.push(col);
346
- return col;
347
- };
348
- Physics.prototype.getRigidbody = function (collider, _matrix) {
349
- if (!this.world)
350
- throw new Error("Physics world not initialized");
351
- var rigidBody = null;
352
- var useExplicitMassProperties = false;
353
- if (collider.attachedRigidbody) {
354
- var rb = collider.attachedRigidbody;
355
- rigidBody = rb[$bodyKey];
356
- useExplicitMassProperties = true;
357
- if (!rigidBody) {
358
- var kinematic = rb.isKinematic && !debugColliderPlacement;
359
- if (debugPhysics)
360
- console.log("Create rigidbody", kinematic);
361
- var rigidBodyDesc = kinematic ? rapier3d_compat_1["default"].RigidBodyDesc.kinematicPositionBased() : rapier3d_compat_1["default"].RigidBodyDesc.dynamic();
362
- var pos = engine_three_utils_1.getWorldPosition(collider.attachedRigidbody.gameObject);
363
- rigidBodyDesc.setTranslation(pos.x, pos.y, pos.z);
364
- rigidBodyDesc.setRotation(engine_three_utils_1.getWorldQuaternion(collider.attachedRigidbody.gameObject));
365
- rigidBody = this.world.createRigidBody(rigidBodyDesc);
366
- this.bodies.push(rigidBody);
367
- this.objects.push(rb);
368
- }
369
- rigidBody[$componentKey] = rb;
370
- rb[$bodyKey] = rigidBody;
371
- this.internalUpdateProperties(rb, rigidBody);
372
- this.getRigidbodyRelativeMatrix(collider.gameObject, rb.gameObject, _matrix);
373
- }
374
- else {
375
- var rigidBodyDesc = rapier3d_compat_1["default"].RigidBodyDesc.kinematicPositionBased();
376
- var pos = engine_three_utils_1.getWorldPosition(collider.gameObject);
377
- rigidBodyDesc.setTranslation(pos.x, pos.y, pos.z);
378
- rigidBodyDesc.setRotation(engine_three_utils_1.getWorldQuaternion(collider.gameObject));
379
- rigidBody = this.world.createRigidBody(rigidBodyDesc);
380
- _matrix.identity();
381
- rigidBody[$componentKey] = null;
382
- }
383
- collider[$colliderRigidbody] = rigidBody;
384
- return { rigidBody: rigidBody, useExplicitMassProperties: useExplicitMassProperties };
385
- };
386
- Physics.prototype.removeBody = function (obj) {
387
- var _a, _b;
388
- var body = obj[$bodyKey];
389
- obj[$bodyKey] = null;
390
- if (body && this.world) {
391
- var index = this.objects.findIndex(function (o) { return o === obj; });
392
- if (index >= 0) {
393
- var body_1 = this.bodies[index];
394
- this.bodies.splice(index, 1);
395
- this.objects.splice(index, 1);
396
- if (body_1 instanceof rapier3d_compat_1.Collider) {
397
- var collider = body_1;
398
- (_a = this.world) === null || _a === void 0 ? void 0 : _a.removeCollider(collider, true);
399
- // remove the rigidbody if it doesnt have colliders anymore
400
- var rb = collider.parent();
401
- if (rb && rb.numColliders() <= 0) {
402
- (_b = this.world) === null || _b === void 0 ? void 0 : _b.removeRigidBody(rb);
403
- }
404
- }
405
- else if (body_1 instanceof rapier3d_compat_1.RigidBody) {
406
- // TODO: running this code below causes a crash in rapier
407
- // const rb = body as RigidBody;
408
- // console.log("colliders", rb.numColliders())
409
- // for (let i = 0; i < rb.numColliders(); i++) {
410
- // const col = rb.collider(i);
411
- // this.world?.removeCollider(col, true);
412
- // }
413
- // console.log("colliders", rb.numColliders(), rb)
414
- // console.log(rb.handle, rb.userData);
415
- // if (rb.userData === undefined)
416
- // this.world?.removeRigidBody(rb);
417
- }
418
- // check if we need to remove the rigidbody too
419
- var col = obj;
420
- if (col.isCollider && col.attachedRigidbody) {
421
- var rb = col.attachedRigidbody[$bodyKey];
422
- if (rb && rb.numColliders() <= 0) {
423
- // this.world?.removeRigidBody(rb);
424
- }
425
- }
426
- }
427
- }
428
- };
429
- Physics.prototype.updateBody = function (comp, translation, rotation) {
430
- if (comp.destroyed || !comp.gameObject)
431
- return;
432
- if (!translation && !rotation)
433
- return;
434
- if (comp.isCollider === true) {
435
- // const collider = comp as ICollider;
436
- console.warn("TODO: implement updating collider position");
437
- }
438
- else {
439
- var rigidbody = comp;
440
- var body = rigidbody[$bodyKey];
441
- if (body) {
442
- this.syncPhysicsBody(rigidbody.gameObject, body, translation, rotation);
443
- }
444
- }
445
- };
446
- Physics.prototype.updateProperties = function (rigidbody) {
447
- var physicsBody = rigidbody[$bodyKey];
448
- if (physicsBody) {
449
- this.internalUpdateProperties(rigidbody, physicsBody);
450
- }
451
- };
452
- Physics.prototype.internal_getRigidbody = function (rb) {
453
- return rb[$bodyKey];
454
- };
455
- Physics.prototype.internalUpdateProperties = function (rb, rigidbody) {
456
- // continuous collision detection
457
- // https://rapier.rs/docs/user_guides/javascript/rigid_bodies#continuous-collision-detection
458
- rigidbody.enableCcd(rb.collisionDetectionMode !== engine_physics_types_1.CollisionDetectionMode.Discrete);
459
- rigidbody.setLinearDamping(rb.drag);
460
- rigidbody.setAngularDamping(rb.angularDrag);
461
- rigidbody.setGravityScale(rb.useGravity ? 1 : 0, true);
462
- // https://rapier.rs/docs/user_guides/javascript/rigid_bodies#mass-properties
463
- // rigidbody.setAdditionalMass(rb.mass, true);
464
- // for (let i = 0; i < rigidbody.numColliders(); i++) {
465
- // const collider = rigidbody.collider(i);
466
- // if (collider) {
467
- // collider.setMass(rb.mass);
468
- // // const density = rb.mass / collider.shape.computeMassProperties().mass;
469
- // }
470
- // }
471
- // lock rotations
472
- rigidbody.setEnabledRotations(!rb.lockRotationX, !rb.lockRotationY, !rb.lockRotationZ, true);
473
- rigidbody.setEnabledTranslations(!rb.lockPositionX, !rb.lockPositionY, !rb.lockPositionZ, true);
474
- if (rb.isKinematic) {
475
- rigidbody.setBodyType(rapier3d_compat_1["default"].RigidBodyType.KinematicPositionBased);
476
- }
477
- else {
478
- rigidbody.setBodyType(rapier3d_compat_1["default"].RigidBodyType.Dynamic);
479
- }
480
- };
481
- Physics.prototype.step = function (_deltaTime) {
482
- if (!this.world)
483
- return;
484
- this._isUpdatingPhysicsWorld = true;
485
- if (!this.eventQueue) {
486
- this.eventQueue = new rapier3d_compat_1.EventQueue(false);
487
- }
488
- this.world.step(this.eventQueue);
489
- this._isUpdatingPhysicsWorld = false;
490
- this.updateDebugRendering(this.world);
491
- };
492
- Physics.prototype.updateDebugRendering = function (world) {
493
- if (debugPhysics || debugColliderPlacement) {
494
- if (!this.lines) {
495
- var material = new three_1.LineBasicMaterial({
496
- color: 0xffffff
497
- });
498
- var geometry = new three_1.BufferGeometry();
499
- this.lines = new three_1.LineSegments(geometry, material);
500
- this.context.scene.add(this.lines);
501
- }
502
- var buffers = world.debugRender();
503
- this.lines.geometry.setAttribute('position', new three_1.BufferAttribute(buffers.vertices, 3));
504
- this.lines.geometry.setAttribute('color', new three_1.BufferAttribute(buffers.colors, 4));
505
- }
506
- };
507
- Physics.prototype.postStep = function () {
508
- if (!this.world)
509
- return;
510
- this._isUpdatingPhysicsWorld = true;
511
- this.syncObjects();
512
- this._isUpdatingPhysicsWorld = false;
513
- if (this.eventQueue && !this.collisionHandler) {
514
- this.collisionHandler = new PhysicsCollisionHandler(this.world, this.eventQueue);
515
- }
516
- if (this.collisionHandler) {
517
- this.collisionHandler.handleCollisionEvents();
518
- this.collisionHandler.update();
519
- }
520
- };
521
- /** sync rendered objects with physics world (except for colliders without rigidbody) */
522
- Physics.prototype.syncObjects = function () {
523
- if (debugColliderPlacement)
524
- return;
525
- for (var i = 0; i < this.bodies.length; i++) {
526
- var obj = this.objects[i];
527
- var body = this.bodies[i];
528
- // if the collider is not attached to a rigidbody
529
- // it means that its kinematic so we need to update its position
530
- var col = obj;
531
- if ((col === null || col === void 0 ? void 0 : col.isCollider) === true && !col.attachedRigidbody) {
532
- var rigidbody = body.parent();
533
- if (rigidbody)
534
- this.syncPhysicsBody(obj.gameObject, rigidbody, true, true);
535
- continue;
536
- }
537
- // sync
538
- var pos = body.translation();
539
- var rot = body.rotation();
540
- // make sure to keep the collider offset
541
- var center = obj["center"];
542
- if (center && center.isVector3) {
543
- this._tempQuaternion.set(rot.x, rot.y, rot.z, rot.w);
544
- var offset = this._tempPosition.copy(center).applyQuaternion(this._tempQuaternion);
545
- var scale = engine_three_utils_1.getWorldScale(obj.gameObject);
546
- offset.multiply(scale);
547
- pos.x -= offset.x;
548
- pos.y -= offset.y;
549
- pos.z -= offset.z;
550
- }
551
- engine_three_utils_1.setWorldPositionXYZ(obj.gameObject, pos.x, pos.y, pos.z);
552
- engine_three_utils_1.setWorldQuaternionXYZW(obj.gameObject, rot.x, rot.y, rot.z, rot.w);
553
- }
554
- };
555
- Physics.prototype.syncPhysicsBody = function (obj, body, translation, rotation) {
556
- // const bodyType = body.bodyType();
557
- // const previous = physicsBody.translation();
558
- // const vel = physicsBody.linvel();
559
- // const debug = obj.name === "Char" && debugPhysics;
560
- var worldPosition = engine_three_utils_1.getWorldPosition(obj, this._tempPosition);
561
- var worldQuaternion = engine_three_utils_1.getWorldQuaternion(obj, this._tempQuaternion);
562
- // if (debug)
563
- // console.log(this._tempPosition.x);
564
- // physicsBody.setBodyType(RAPIER.RigidBodyType.Fixed);
565
- if (translation)
566
- body.setTranslation(worldPosition, false);
567
- if (rotation)
568
- body.setRotation(worldQuaternion, false);
569
- // physicsBody.setLinvel(vel, false);
570
- body.wakeUp();
571
- // update velocity
572
- // const pos = physicsBody.translation();
573
- // pos.x -= previous.x;
574
- // pos.y -= previous.y;
575
- // pos.z -= previous.z;
576
- // // threhold
577
- // const t = 1;
578
- // const canUpdateVelocity = Math.abs(pos.x) < t && Math.abs(pos.y) < t && Math.abs(pos.z) < t;
579
- // if (canUpdateVelocity) {
580
- // const damping = 1 + this.context.time.deltaTime;
581
- // vel.x *= damping;
582
- // vel.y *= damping;
583
- // vel.z *= damping;
584
- // vel.x += pos.x;
585
- // vel.y += pos.y;
586
- // vel.z += pos.z;
587
- // console.log(vel);
588
- // physicsBody.setLinvel(vel, true);
589
- // }
590
- // else if(debugPhysics) console.warn("Movement exceeded threshold, not updating velocity", pos);
591
- // body.setBodyType(bodyType);
592
- };
593
- Physics.prototype.getRigidbodyRelativeMatrix = function (comp, rigidbody, mat, matrices) {
594
- // collect all matrices to the rigidbody and then build the rigidbody relative matrix
595
- if (matrices === undefined) {
596
- matrices = Physics._matricesBuffer;
597
- matrices.length = 0;
598
- }
599
- if (comp === rigidbody) {
600
- var scale = engine_three_utils_1.getWorldScale(comp, this._tempPosition);
601
- mat.makeScale(scale.x, scale.y, scale.z);
602
- for (var i = matrices.length - 1; i >= 0; i--) {
603
- mat.multiply(matrices[i]);
604
- }
605
- return mat;
606
- }
607
- matrices.push(comp.matrix);
608
- if (comp.parent) {
609
- this.getRigidbodyRelativeMatrix(comp.parent, rigidbody, mat, matrices);
610
- }
611
- return mat;
612
- };
613
- Physics._didLoadPhysicsEngine = false;
614
- Physics._matricesBuffer = [];
615
- return Physics;
616
- }());
617
- exports.Physics = Physics;
618
- /** responsible of processing collision events for the component system */
619
- var PhysicsCollisionHandler = /** @class */ (function () {
620
- function PhysicsCollisionHandler(world, eventQueue) {
621
- this.activeCollisions = [];
622
- this.activeTriggers = [];
623
- this.world = world;
624
- this.eventQueue = eventQueue;
625
- }
626
- PhysicsCollisionHandler.prototype.handleCollisionEvents = function () {
627
- var _this = this;
628
- if (!this.eventQueue)
629
- return;
630
- if (!this.world)
631
- return;
632
- this.eventQueue.drainCollisionEvents(function (handle1, handle2, started) {
633
- var col1 = _this.world.getCollider(handle1);
634
- var col2 = _this.world.getCollider(handle2);
635
- var colliderComponent1 = col1[$componentKey];
636
- var colliderComponent2 = col2[$componentKey];
637
- if (debugCollisions)
638
- console.log("EVT", colliderComponent1.name, colliderComponent2.name, started, col1, col2);
639
- if (colliderComponent1 && colliderComponent2) {
640
- if (started) {
641
- _this.onCollisionStarted(colliderComponent1, col1, colliderComponent2, col2);
642
- _this.onCollisionStarted(colliderComponent2, col2, colliderComponent1, col1);
643
- }
644
- else {
645
- _this.onCollisionEnded(colliderComponent1, colliderComponent2);
646
- _this.onCollisionEnded(colliderComponent2, colliderComponent1);
647
- }
648
- }
649
- });
650
- };
651
- PhysicsCollisionHandler.prototype.update = function () {
652
- this.onHandleCollisionStay();
653
- };
654
- PhysicsCollisionHandler.prototype.onCollisionStarted = function (self, selfBody, other, otherBody) {
655
- var _this = this;
656
- var collision = null;
657
- // if one is a trigger we dont get collisions but want to raise the trigger events
658
- if (self.isTrigger || other.isTrigger) {
659
- engine_gameobject_1.foreachComponent(self.gameObject, function (c) {
660
- if (c.onTriggerEnter) {
661
- c.onTriggerEnter(other);
662
- }
663
- _this.activeTriggers.push({ collider: self, component: c, otherCollider: other });
664
- });
665
- }
666
- else {
667
- var object_1 = self.gameObject;
668
- // TODO: we dont respect the flip value here!
669
- this.world.contactPair(selfBody, otherBody, function (manifold, _flipped) {
670
- engine_gameobject_1.foreachComponent(object_1, function (c) {
671
- if (c.onCollisionEnter) {
672
- if (!collision) {
673
- var contacts = [];
674
- var normal = manifold.normal();
675
- for (var i = 0; i < manifold.numContacts(); i++) {
676
- var pt1 = manifold.localContactPoint1(i);
677
- var dist = manifold.contactDist(i);
678
- if (pt1) {
679
- var contact = new engine_types_1.ContactPoint(pt1, dist, normal);
680
- contacts.push(contact);
681
- }
682
- }
683
- collision = new engine_types_1.Collision(object_1, other, contacts);
684
- }
685
- c.onCollisionEnter.call(c, collision);
686
- _this.activeCollisions.push({ collider: self, component: c, collision: collision });
687
- }
688
- });
689
- });
690
- }
691
- };
692
- PhysicsCollisionHandler.prototype.onHandleCollisionStay = function () {
693
- for (var _i = 0, _a = this.activeCollisions; _i < _a.length; _i++) {
694
- var active = _a[_i];
695
- var c = active.component;
696
- if (c.activeAndEnabled && c.onCollisionStay) {
697
- var arg = active.collision;
698
- c.onCollisionStay(arg);
699
- }
700
- }
701
- for (var _b = 0, _c = this.activeTriggers; _b < _c.length; _b++) {
702
- var active = _c[_b];
703
- var c = active.component;
704
- if (c.activeAndEnabled && c.onTriggerStay) {
705
- var arg = active.collider;
706
- c.onTriggerStay(arg);
707
- }
708
- }
709
- };
710
- PhysicsCollisionHandler.prototype.onCollisionEnded = function (self, other) {
711
- for (var i = 0; i < this.activeCollisions.length; i++) {
712
- var active = this.activeCollisions[i];
713
- var collider = active.collider;
714
- if (collider === self && active.collision.collider === other) {
715
- var c = active.component;
716
- this.activeCollisions.splice(i, 1);
717
- i--;
718
- if (c.activeAndEnabled && c.onCollisionExit) {
719
- var collision = active.collision;
720
- c.onCollisionExit(collision);
721
- }
722
- }
723
- }
724
- for (var i = 0; i < this.activeTriggers.length; i++) {
725
- var active = this.activeTriggers[i];
726
- var collider = active.collider;
727
- if (collider === self && active.otherCollider === other) {
728
- var c = active.component;
729
- this.activeTriggers.splice(i, 1);
730
- i--;
731
- if (c.activeAndEnabled && c.onTriggerExit) {
732
- var collision = active.otherCollider;
733
- c.onTriggerExit(collision);
734
- }
735
- }
736
- }
737
- };
738
- return PhysicsCollisionHandler;
739
- }());