@threenative/physics 0.1.0

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.
@@ -0,0 +1,986 @@
1
+ // src/handles.ts
2
+ function physicsHandle(raw) {
3
+ return { raw };
4
+ }
5
+ function physicsWorldHandle(raw, simulation) {
6
+ return { raw, simulation };
7
+ }
8
+ function physicsBodyHandle(id, raw) {
9
+ return { id, raw };
10
+ }
11
+ function physicsColliderHandle(id, raw) {
12
+ return { id, raw };
13
+ }
14
+
15
+ // src/collision.ts
16
+ function interactionGroups(layer, mask) {
17
+ if (!Number.isInteger(layer) || layer < 0 || layer > 65535)
18
+ throw new Error("interactionGroups: layer must be an integer in 0..0xffff.");
19
+ if (!Number.isInteger(mask) || mask < 0 || mask > 65535)
20
+ throw new Error("interactionGroups: mask must be an integer in 0..0xffff.");
21
+ return (layer << 16 | mask) >>> 0;
22
+ }
23
+
24
+ // src/simulation.ts
25
+ var PHYSICS_TRANSFORM_STRIDE = 8;
26
+ var PHYSICS_COLLISION_EVENT_STRIDE = 4;
27
+ var selectedBackend;
28
+ function installPhysicsSimulationBackend(backend) {
29
+ selectedBackend = backend;
30
+ }
31
+ function physicsSimulationBackend() {
32
+ if (selectedBackend === void 0)
33
+ throw new Error("TN_PHYSICS_BACKEND_MISSING: no PhysicsSimulation backend was selected");
34
+ return selectedBackend;
35
+ }
36
+ function requirePhysicsStepInput(deltaTime, inputSnapshot, bodyExists) {
37
+ if (!Number.isFinite(deltaTime) || deltaTime <= 0)
38
+ throw new Error("PhysicsSimulation.step requires a positive finite deltaTime.");
39
+ if (inputSnapshot === void 0) return;
40
+ if (!(inputSnapshot.kinematicTransforms instanceof Float32Array))
41
+ throw new Error("PhysicsSimulation input must use a Float32Array.");
42
+ if (!Number.isSafeInteger(inputSnapshot.kinematicCount) || inputSnapshot.kinematicCount < 0 || inputSnapshot.kinematicCount > Math.floor(inputSnapshot.kinematicTransforms.length / PHYSICS_TRANSFORM_STRIDE)) {
43
+ throw new Error("PhysicsSimulation input has an invalid kinematic record count.");
44
+ }
45
+ for (let index = 0; index < inputSnapshot.kinematicCount; index += 1) {
46
+ const offset = index * PHYSICS_TRANSFORM_STRIDE;
47
+ for (let scalar = 0; scalar < PHYSICS_TRANSFORM_STRIDE; scalar += 1) {
48
+ if (!Number.isFinite(inputSnapshot.kinematicTransforms[offset + scalar]))
49
+ throw new Error("PhysicsSimulation input contains a non-finite transform.");
50
+ }
51
+ const id = inputSnapshot.kinematicTransforms[offset];
52
+ if (!Number.isInteger(id) || id < 0)
53
+ throw new Error("PhysicsSimulation input contains an invalid body id.");
54
+ if (!bodyExists(id)) throw new Error("PhysicsSimulation input contains an unknown body id.");
55
+ }
56
+ }
57
+ function requirePhysicsRenderBuffer(renderBuffer, bodyCount) {
58
+ if (!(renderBuffer instanceof Float32Array))
59
+ throw new Error("PhysicsSimulation output must use a Float32Array.");
60
+ if (renderBuffer.length < bodyCount * PHYSICS_TRANSFORM_STRIDE)
61
+ throw new Error("PhysicsSimulation output buffer is too small for visible transforms.");
62
+ }
63
+ function requirePhysicsEventBuffer(buffer) {
64
+ if (!(buffer instanceof Uint32Array))
65
+ throw new Error("PhysicsSimulation events must use a Uint32Array.");
66
+ }
67
+ function requirePhysicsSimulation(physics, world) {
68
+ if (physics?.simulation !== void 0) return physics.simulation;
69
+ const candidate = typeof world === "object" && world !== null && "simulation" in world ? world.simulation : world;
70
+ if (typeof candidate === "object" && candidate !== null && "createBody" in candidate && typeof candidate.createBody === "function" && "step" in candidate && typeof candidate.step === "function")
71
+ return candidate;
72
+ const backend = selectedBackend;
73
+ if (world !== void 0 && backend?.simulationForWorld !== void 0)
74
+ return backend.simulationForWorld(candidate);
75
+ throw new Error(
76
+ "Physics nodes require a PhysicsContext. Passing a raw backend world is deprecated and backend-specific."
77
+ );
78
+ }
79
+
80
+ // src/native/host.ts
81
+ function nativePhysicsHost() {
82
+ const host = globalThis.__THREENATIVE_NATIVE__?.physics;
83
+ if (host === void 0 || typeof host.version !== "string" || typeof host.createSimulation !== "function") {
84
+ throw new Error("TN_NATIVE_PHYSICS_MISSING: runtime did not install the physics ABI");
85
+ }
86
+ return host;
87
+ }
88
+ function nativeSimulation(value) {
89
+ if (typeof value !== "object" || value === null || !("configureCharacter" in value) || typeof value.configureCharacter !== "function" || !("createBody" in value) || typeof value.createBody !== "function" || !("dispose" in value) || typeof value.dispose !== "function" || !("drainCollisionEvents" in value) || typeof value.drainCollisionEvents !== "function" || !("removeBody" in value) || typeof value.removeBody !== "function" || !("readVisibleTransforms" in value) || typeof value.readVisibleTransforms !== "function" || !("readCharacterStates" in value) || typeof value.readCharacterStates !== "function" || !("readAreaIntersections" in value) || typeof value.readAreaIntersections !== "function" || !("step" in value) || typeof value.step !== "function") {
90
+ throw new Error("TN_NATIVE_PHYSICS_INVALID: physics world is not a native simulation");
91
+ }
92
+ return value;
93
+ }
94
+ function primitiveShape(shape) {
95
+ if (shape.kind !== "box" && shape.kind !== "sphere" && shape.kind !== "capsule")
96
+ throw new Error(`TN_NATIVE_PHYSICS_SHAPE_UNSUPPORTED: ${shape.kind} remains OPEN on native`);
97
+ return shape;
98
+ }
99
+ function isSmallBufferError(error) {
100
+ return error instanceof Error && /buffer is too small/i.test(error.message);
101
+ }
102
+ function growUint32(buffer, minimum) {
103
+ let length = Math.max(16, buffer.length);
104
+ while (length < minimum) length *= 2;
105
+ return length === buffer.length ? buffer : new Uint32Array(length);
106
+ }
107
+ function createNativePhysicsSimulation(raw, version) {
108
+ const bodyIds = /* @__PURE__ */ new Set();
109
+ const areaIds = /* @__PURE__ */ new Set();
110
+ const characterIds = /* @__PURE__ */ new Set();
111
+ const characterState = /* @__PURE__ */ new Map();
112
+ let characterStates = new Float32Array(48);
113
+ let areaPairs = new Uint32Array(32);
114
+ const areaIntersections = /* @__PURE__ */ new Map();
115
+ let characterStateDirty = true;
116
+ let areaIntersectionsDirty = true;
117
+ const invalidateObservations = () => {
118
+ characterStateDirty = true;
119
+ areaIntersectionsDirty = true;
120
+ };
121
+ const refreshCharacterState = () => {
122
+ if (!characterStateDirty) return;
123
+ const required = Math.max(1, characterIds.size) * 3;
124
+ if (characterStates.length < required) characterStates = new Float32Array(required);
125
+ const stateCount = raw.readCharacterStates(characterStates);
126
+ characterState.clear();
127
+ for (let index = 0; index < stateCount; index += 1) {
128
+ const offset = index * 3;
129
+ const id = characterStates[offset];
130
+ const grounded = characterStates[offset + 1];
131
+ const groundCollider = characterStates[offset + 2];
132
+ if (id === void 0 || grounded === void 0 || groundCollider === void 0)
133
+ throw new Error("TN_NATIVE_PHYSICS_INVALID: malformed character state");
134
+ characterState.set(id, {
135
+ grounded: grounded === 1,
136
+ groundCollider: groundCollider < 0 ? void 0 : groundCollider
137
+ });
138
+ }
139
+ characterStateDirty = false;
140
+ };
141
+ const refreshAreaIntersections = () => {
142
+ if (!areaIntersectionsDirty) return;
143
+ areaPairs = growUint32(areaPairs, bodyIds.size * 2);
144
+ const maximum = Math.max(16, bodyIds.size * bodyIds.size * 2);
145
+ let pairCount;
146
+ for (; ; ) {
147
+ try {
148
+ pairCount = raw.readAreaIntersections(areaPairs);
149
+ break;
150
+ } catch (error) {
151
+ if (!isSmallBufferError(error) || areaPairs.length >= maximum) throw error;
152
+ areaPairs = growUint32(areaPairs, Math.min(maximum, areaPairs.length * 2));
153
+ }
154
+ }
155
+ areaIntersections.clear();
156
+ for (const areaId of areaIds) areaIntersections.set(areaId, /* @__PURE__ */ new Set());
157
+ for (let index = 0; index < pairCount; index += 1) {
158
+ const offset = index * 2;
159
+ const areaId = areaPairs[offset];
160
+ const bodyId = areaPairs[offset + 1];
161
+ if (areaId === void 0 || bodyId === void 0)
162
+ throw new Error("TN_NATIVE_PHYSICS_INVALID: malformed area intersection");
163
+ areaIntersections.get(areaId)?.add(bodyId);
164
+ }
165
+ areaIntersectionsDirty = false;
166
+ };
167
+ const simulation = {
168
+ version,
169
+ rawEventQueue: raw,
170
+ rawWorld: raw,
171
+ createBody: (options) => {
172
+ const shape = primitiveShape(options.shape);
173
+ const id = raw.createBody({
174
+ collisionLayer: shape.collisionLayer,
175
+ collisionMask: shape.collisionMask,
176
+ mass: options.mass,
177
+ position: options.position,
178
+ rotation: options.rotation,
179
+ sensor: options.sensor,
180
+ shape,
181
+ type: options.type
182
+ });
183
+ if (!Number.isInteger(id) || id < 0)
184
+ throw new Error("TN_NATIVE_PHYSICS_INVALID: runtime returned an invalid body id");
185
+ const rawHandle = { backend: "native", id };
186
+ bodyIds.add(id);
187
+ if (options.sensor) areaIds.add(id);
188
+ if (options.type === "character") characterIds.add(id);
189
+ invalidateObservations();
190
+ return {
191
+ body: physicsBodyHandle(id, rawHandle),
192
+ collider: physicsColliderHandle(id, rawHandle),
193
+ controller: options.type === "character" ? physicsHandle(rawHandle) : void 0,
194
+ rawShape: shape
195
+ };
196
+ },
197
+ configureCharacter: (id, options) => {
198
+ raw.configureCharacter(id, options);
199
+ invalidateObservations();
200
+ },
201
+ removeBody: (id) => {
202
+ raw.removeBody(id);
203
+ bodyIds.delete(id);
204
+ areaIds.delete(id);
205
+ characterIds.delete(id);
206
+ characterState.delete(id);
207
+ invalidateObservations();
208
+ },
209
+ setBodyTransform: (id, position) => {
210
+ if (raw.setBodyTransform === void 0)
211
+ throw new Error("TN_NATIVE_PHYSICS_SET_TRANSFORM_MISSING: runtime ABI is too old");
212
+ raw.setBodyTransform(id, position);
213
+ },
214
+ step: (deltaTime, inputSnapshot) => {
215
+ requirePhysicsStepInput(deltaTime, inputSnapshot, (id) => bodyIds.has(id));
216
+ raw.step(deltaTime, inputSnapshot);
217
+ invalidateObservations();
218
+ },
219
+ readVisibleTransforms: (buffer) => {
220
+ requirePhysicsRenderBuffer(buffer, bodyIds.size);
221
+ return raw.readVisibleTransforms(buffer);
222
+ },
223
+ readCharacterState: (id) => {
224
+ refreshCharacterState();
225
+ return characterState.get(id);
226
+ },
227
+ areaIntersections: (id) => {
228
+ refreshAreaIntersections();
229
+ return areaIntersections.get(id) ?? /* @__PURE__ */ new Set();
230
+ },
231
+ drainCollisionEvents: (buffer) => {
232
+ requirePhysicsEventBuffer(buffer);
233
+ return raw.drainCollisionEvents(buffer);
234
+ },
235
+ dispose: () => {
236
+ raw.dispose();
237
+ bodyIds.clear();
238
+ areaIds.clear();
239
+ characterIds.clear();
240
+ characterState.clear();
241
+ areaIntersections.clear();
242
+ characterStateDirty = false;
243
+ areaIntersectionsDirty = false;
244
+ }
245
+ };
246
+ return simulation;
247
+ }
248
+
249
+ // src/native.ts
250
+ var simulations = /* @__PURE__ */ new WeakMap();
251
+ function wrapNativeSimulation(raw, version) {
252
+ const simulation = createNativePhysicsSimulation(raw, version);
253
+ simulations.set(raw, simulation);
254
+ return simulation;
255
+ }
256
+ installPhysicsSimulationBackend({
257
+ initialize: async () => void 0,
258
+ createSimulation: (options = {}) => {
259
+ const host = nativePhysicsHost();
260
+ return wrapNativeSimulation(nativeSimulation(host.createSimulation(options)), host.version);
261
+ },
262
+ simulationForWorld: (world) => {
263
+ if (typeof world !== "object" || world === null)
264
+ throw new Error("TN_NATIVE_PHYSICS_INVALID: native world must be an object");
265
+ const existing = simulations.get(world);
266
+ if (existing !== void 0) return existing;
267
+ const host = nativePhysicsHost();
268
+ return wrapNativeSimulation(nativeSimulation(world), host.version);
269
+ }
270
+ });
271
+
272
+ // src/Area3D.ts
273
+ var MAX_CONTACT_LOG = 1e3;
274
+ function finiteTransform(values, offset) {
275
+ const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
276
+ if (result.some((value) => value === void 0 || !Number.isFinite(value)))
277
+ throw new Error("PhysicsSimulation returned a malformed transform.");
278
+ return result;
279
+ }
280
+ var Area3D = class {
281
+ entity;
282
+ body;
283
+ collider;
284
+ #simulation;
285
+ #physics;
286
+ #position = { x: 0, y: 0, z: 0 };
287
+ #entered = /* @__PURE__ */ new Map();
288
+ #contacts = [];
289
+ #monitoring = true;
290
+ #listeners = {
291
+ bodyEntered: /* @__PURE__ */ new Set(),
292
+ bodyExited: /* @__PURE__ */ new Set()
293
+ };
294
+ #disposed = false;
295
+ constructor(options) {
296
+ this.#simulation = requirePhysicsSimulation(options.physics, options.world);
297
+ this.#physics = options.physics;
298
+ this.entity = options.entity;
299
+ Object.assign(this.#position, options.position ?? { x: 0, y: 0, z: 0 });
300
+ const shape = options.shape.setSensor(true).descriptor;
301
+ if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
302
+ const layer = options.collisionLayer ?? shape.collisionLayer;
303
+ const mask = options.collisionMask ?? shape.collisionMask;
304
+ options.shape.setCollisionGroups(interactionGroups(layer, mask));
305
+ }
306
+ const registration = this.#simulation.createBody({
307
+ mass: 0,
308
+ position: this.#position,
309
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
310
+ sensor: true,
311
+ shape,
312
+ type: "kinematic"
313
+ });
314
+ options.shape.bindRaw(registration.rawShape);
315
+ this.body = registration.body;
316
+ this.collider = registration.collider;
317
+ this.#physics?.addArea(this);
318
+ }
319
+ on(event, handler) {
320
+ this.#listeners[event].add(handler);
321
+ return () => this.#listeners[event].delete(handler);
322
+ }
323
+ /** Mirrors Godot's Area3D.monitoring. When false the area reports no contacts. */
324
+ get monitoring() {
325
+ return this.#monitoring;
326
+ }
327
+ set monitoring(value) {
328
+ if (this.#monitoring === value) return;
329
+ this.#monitoring = value;
330
+ if (!value) this.#entered.clear();
331
+ }
332
+ setPosition(position) {
333
+ if (!this.#disposed) {
334
+ Object.assign(this.#position, position);
335
+ this.#simulation.setBodyTransform(this.body.id, position);
336
+ }
337
+ }
338
+ /** Called by the shared plugin before a bulk step. */
339
+ writeKinematic(buffer, offset) {
340
+ if (this.#disposed) return;
341
+ buffer.set(
342
+ [this.body.id, this.#position.x, this.#position.y, this.#position.z, 0, 0, 0, 1],
343
+ offset
344
+ );
345
+ }
346
+ applyTransform(values, offset) {
347
+ const [, x, y, z] = finiteTransform(values, offset);
348
+ Object.assign(this.#position, { x, y, z });
349
+ }
350
+ handleCollision(body, started) {
351
+ if (this.#disposed || !this.#monitoring) return;
352
+ const handle = body.body.id;
353
+ if (started) {
354
+ if (this.#entered.has(handle)) return;
355
+ this.#entered.set(handle, body);
356
+ this.#contacts.push({ area: this, body, entity: this.entity, started: true });
357
+ if (this.#contacts.length > MAX_CONTACT_LOG) this.#contacts.shift();
358
+ for (const handler of this.#listeners.bodyEntered) handler(body);
359
+ return;
360
+ }
361
+ const entered = this.#entered.get(handle);
362
+ if (entered === void 0) return;
363
+ this.#entered.delete(handle);
364
+ this.#contacts.push({ area: this, body: entered, entity: this.entity, started: false });
365
+ if (this.#contacts.length > MAX_CONTACT_LOG) this.#contacts.shift();
366
+ for (const handler of this.#listeners.bodyExited) handler(entered);
367
+ }
368
+ drainContacts() {
369
+ const contacts = this.#contacts;
370
+ this.#contacts = [];
371
+ return contacts;
372
+ }
373
+ reconcileIntersections(current) {
374
+ for (const body of current.values()) this.handleCollision(body, true);
375
+ for (const [handle, body] of this.#entered) {
376
+ if (!current.has(handle)) this.handleCollision(body, false);
377
+ }
378
+ }
379
+ dispose() {
380
+ if (this.#disposed) return;
381
+ this.#disposed = true;
382
+ this.#physics?.removeArea(this);
383
+ this.#simulation.removeBody(this.body.id);
384
+ this.#entered.clear();
385
+ this.#listeners.bodyEntered.clear();
386
+ this.#listeners.bodyExited.clear();
387
+ }
388
+ };
389
+
390
+ // src/CharacterBody3D.ts
391
+ function finiteTransform2(values, offset) {
392
+ const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
393
+ if (result.some((value) => value === void 0 || !Number.isFinite(value)))
394
+ throw new Error("PhysicsSimulation returned a malformed transform.");
395
+ return result;
396
+ }
397
+ var CharacterBody3D = class {
398
+ body;
399
+ collider;
400
+ controller;
401
+ object;
402
+ velocity;
403
+ gravity;
404
+ maxFallSpeed;
405
+ oneWayLayers;
406
+ grounded = false;
407
+ #simulation;
408
+ #physics;
409
+ #desired = { x: 0, y: 0, z: 0 };
410
+ #sliding = false;
411
+ #groundCollider;
412
+ #beforeY = 0;
413
+ #desiredY = 0;
414
+ #disposed = false;
415
+ constructor(options) {
416
+ this.#simulation = requirePhysicsSimulation(options.physics, options.world);
417
+ this.#physics = options.physics;
418
+ this.object = options.object;
419
+ this.velocity = this.object.position.clone().set(0, 0, 0);
420
+ this.gravity = options.gravity ?? -9.81;
421
+ this.maxFallSpeed = options.maxFallSpeed ?? 50;
422
+ this.oneWayLayers = options.oneWayLayers ?? 0;
423
+ const shape = options.shape.descriptor;
424
+ if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
425
+ const layer = options.collisionLayer ?? shape.collisionLayer;
426
+ const mask = options.collisionMask ?? shape.collisionMask;
427
+ options.shape.setCollisionGroups(interactionGroups(layer, mask));
428
+ }
429
+ const registration = this.#simulation.createBody({
430
+ mass: 0,
431
+ position: this.object.position,
432
+ rotation: this.object.quaternion,
433
+ sensor: false,
434
+ shape,
435
+ type: "character"
436
+ });
437
+ if (registration.controller === void 0) {
438
+ this.#simulation.removeBody(registration.body.id);
439
+ throw new Error("Physics character backend did not provide a controller handle.");
440
+ }
441
+ options.shape.bindRaw(registration.rawShape);
442
+ this.body = registration.body;
443
+ this.collider = registration.collider;
444
+ this.controller = registration.controller;
445
+ const characterOptions = {
446
+ autostep: options.autostep === void 0 ? void 0 : {
447
+ includeDynamicBodies: options.autostep.includeDynamicBodies ?? false,
448
+ maxHeight: options.autostep.maxHeight,
449
+ minWidth: options.autostep.minWidth
450
+ },
451
+ maxSlopeClimbAngle: options.maxSlopeClimbAngle ?? Math.PI / 4,
452
+ offset: options.offset ?? 0.01,
453
+ oneWayLayers: this.oneWayLayers,
454
+ snapToGround: options.snapToGround
455
+ };
456
+ try {
457
+ this.#simulation.configureCharacter(this.body.id, characterOptions);
458
+ } catch (error) {
459
+ this.#simulation.removeBody(this.body.id);
460
+ throw error;
461
+ }
462
+ this.#physics?.add(this);
463
+ }
464
+ move(desiredTranslation) {
465
+ this.#desired = { x: desiredTranslation.x, y: desiredTranslation.y, z: desiredTranslation.z };
466
+ this.#sliding = false;
467
+ }
468
+ moveAndSlide(dt) {
469
+ if (!Number.isFinite(dt) || dt < 0)
470
+ throw new Error("CharacterBody3D.moveAndSlide requires a finite non-negative dt.");
471
+ this.velocity.y = Math.max(this.velocity.y + this.gravity * dt, -this.maxFallSpeed);
472
+ this.#desired = {
473
+ x: this.velocity.x * dt,
474
+ y: this.velocity.y * dt,
475
+ z: this.velocity.z * dt
476
+ };
477
+ this.#sliding = true;
478
+ }
479
+ /** Called by the shared plugin before a bulk step. */
480
+ writeKinematic(buffer, offset) {
481
+ if (this.#disposed) return;
482
+ this.#beforeY = this.object.position.y;
483
+ this.#desiredY = this.#desired.y;
484
+ const carry = this.#sliding && this.grounded && this.velocity.y <= 0 && this.#groundCollider !== void 0 ? this.#physics?.kinematicMotion?.(this.#groundCollider) : void 0;
485
+ buffer.set(
486
+ [
487
+ this.body.id,
488
+ this.object.position.x + this.#desired.x + (carry?.x ?? 0),
489
+ this.object.position.y + this.#desired.y + (carry?.y ?? 0),
490
+ this.object.position.z + this.#desired.z + (carry?.z ?? 0),
491
+ this.object.quaternion.x,
492
+ this.object.quaternion.y,
493
+ this.object.quaternion.z,
494
+ this.object.quaternion.w
495
+ ],
496
+ offset
497
+ );
498
+ }
499
+ syncToPhysics() {
500
+ }
501
+ step() {
502
+ }
503
+ teleport(position) {
504
+ if (this.#disposed) throw new Error("CharacterBody3D.teleport cannot be used after dispose.");
505
+ this.#simulation.setBodyTransform(this.body.id, position);
506
+ this.object.position.set(position.x, position.y, position.z);
507
+ this.velocity.set(0, 0, 0);
508
+ this.#desired = { x: 0, y: 0, z: 0 };
509
+ this.#sliding = false;
510
+ this.#groundCollider = void 0;
511
+ this.grounded = false;
512
+ }
513
+ applyTransform(values, offset) {
514
+ const [, x, y, z, qx, qy, qz, qw] = finiteTransform2(values, offset);
515
+ const state = this.#simulation.readCharacterState?.(this.body.id);
516
+ this.grounded = state?.grounded ?? (this.#sliding && this.#desiredY < 0 && y - this.#beforeY > this.#desiredY + 1e-4);
517
+ this.#groundCollider = state?.groundCollider;
518
+ if (this.#sliding && this.grounded && this.velocity.y < 0) this.velocity.y = 0;
519
+ this.object.position.set(x, y, z);
520
+ this.object.quaternion.set(qx, qy, qz, qw);
521
+ this.#desired = { x: 0, y: 0, z: 0 };
522
+ this.#sliding = false;
523
+ }
524
+ syncFromPhysics() {
525
+ const transform = this.#simulation.readBodyTransform?.(this.body.id);
526
+ if (transform === void 0) return;
527
+ this.object.position.set(transform.position.x, transform.position.y, transform.position.z);
528
+ this.object.quaternion.set(
529
+ transform.rotation.x,
530
+ transform.rotation.y,
531
+ transform.rotation.z,
532
+ transform.rotation.w
533
+ );
534
+ }
535
+ dispose() {
536
+ if (this.#disposed) return;
537
+ this.#disposed = true;
538
+ this.#physics?.remove(this);
539
+ this.#simulation.removeBody(this.body.id);
540
+ }
541
+ };
542
+
543
+ // src/CollisionShape3D.ts
544
+ function geometryVertices(mesh) {
545
+ const position = mesh.geometry.getAttribute("position");
546
+ if (position === void 0)
547
+ throw new Error("CollisionShape3D.fromMesh requires vertex positions.");
548
+ const vertices = new Float32Array(position.count * 3);
549
+ for (let index = 0; index < position.count; index++) {
550
+ vertices[index * 3] = position.getX(index) * mesh.scale.x;
551
+ vertices[index * 3 + 1] = position.getY(index) * mesh.scale.y;
552
+ vertices[index * 3 + 2] = position.getZ(index) * mesh.scale.z;
553
+ }
554
+ return vertices;
555
+ }
556
+ function geometryIndices(mesh) {
557
+ const index = mesh.geometry.getIndex();
558
+ if (index !== null)
559
+ return Uint32Array.from({ length: index.count }, (_, offset) => index.getX(offset));
560
+ const count = mesh.geometry.getAttribute("position")?.count ?? 0;
561
+ if (count === 0 || count % 3 !== 0)
562
+ throw new Error("CollisionShape3D.fromMesh requires triangle indices.");
563
+ return Uint32Array.from({ length: count }, (_, offset) => offset);
564
+ }
565
+ function finitePositive(value, label) {
566
+ if (!Number.isFinite(value) || value <= 0)
567
+ throw new Error(`CollisionShape3D.${label} requires a positive finite value.`);
568
+ return value;
569
+ }
570
+ function applyRaw(raw, method, ...args) {
571
+ if (typeof raw !== "object" || raw === null || !(method in raw)) return;
572
+ const operation = raw[method];
573
+ if (typeof operation === "function") operation.apply(raw, args);
574
+ }
575
+ var CollisionShape3D = class _CollisionShape3D {
576
+ #descriptor;
577
+ #backendRaw;
578
+ constructor(descriptor) {
579
+ this.#descriptor = descriptor;
580
+ }
581
+ /** Backend-neutral data consumed by the selected PhysicsSimulation adapter. */
582
+ get descriptor() {
583
+ return this.#descriptor;
584
+ }
585
+ /** Rapier's descriptor on web, or an opaque native descriptor after registration. */
586
+ get raw() {
587
+ if (this.#backendRaw === void 0) {
588
+ try {
589
+ const createShape = physicsSimulationBackend().createShape;
590
+ if (createShape !== void 0) this.#backendRaw = createShape(this.#descriptor);
591
+ } catch {
592
+ }
593
+ }
594
+ return this.#backendRaw ?? this.#descriptor;
595
+ }
596
+ /** Internal seam: the backend binds its own descriptor when the body is created. */
597
+ bindRaw(raw) {
598
+ this.#backendRaw = raw;
599
+ applyRaw(
600
+ raw,
601
+ "setCollisionGroups",
602
+ interactionGroups(this.#descriptor.collisionLayer, this.#descriptor.collisionMask)
603
+ );
604
+ applyRaw(raw, "setSensor", this.#descriptor.sensor);
605
+ }
606
+ static box(width, height, depth) {
607
+ return new _CollisionShape3D({
608
+ collisionLayer: 1,
609
+ collisionMask: 65535,
610
+ kind: "box",
611
+ sensor: false,
612
+ x: finitePositive(width, "box") / 2,
613
+ y: finitePositive(height, "box") / 2,
614
+ z: finitePositive(depth, "box") / 2
615
+ });
616
+ }
617
+ static sphere(radius) {
618
+ return new _CollisionShape3D({
619
+ collisionLayer: 1,
620
+ collisionMask: 65535,
621
+ kind: "sphere",
622
+ sensor: false,
623
+ x: finitePositive(radius, "sphere"),
624
+ y: 0,
625
+ z: 0
626
+ });
627
+ }
628
+ static capsule(halfHeight, radius) {
629
+ if (!Number.isFinite(halfHeight) || halfHeight < 0)
630
+ throw new Error("CollisionShape3D.capsule requires a finite non-negative halfHeight.");
631
+ return new _CollisionShape3D({
632
+ collisionLayer: 1,
633
+ collisionMask: 65535,
634
+ kind: "capsule",
635
+ sensor: false,
636
+ x: halfHeight,
637
+ y: finitePositive(radius, "capsule"),
638
+ z: 0
639
+ });
640
+ }
641
+ static heightfield(rows, columns, heights, scale) {
642
+ if (!Number.isInteger(rows) || rows < 2)
643
+ throw new Error("CollisionShape3D.heightfield requires at least 2 rows.");
644
+ if (!Number.isInteger(columns) || columns < 2)
645
+ throw new Error("CollisionShape3D.heightfield requires at least 2 columns.");
646
+ if (heights.length !== rows * columns)
647
+ throw new Error(
648
+ `CollisionShape3D.heightfield expected ${rows * columns} heights, received ${heights.length}.`
649
+ );
650
+ return new _CollisionShape3D({
651
+ collisionLayer: 1,
652
+ collisionMask: 65535,
653
+ kind: "heightfield",
654
+ sensor: false,
655
+ x: 0,
656
+ y: 0,
657
+ z: 0,
658
+ rows,
659
+ columns,
660
+ heights,
661
+ shape: { ncols: columns - 1, nrows: rows - 1, scale },
662
+ scale
663
+ });
664
+ }
665
+ static fromMesh(mesh, kind) {
666
+ const geometry = mesh.geometry;
667
+ const inferred = kind ?? (geometry.type.toLowerCase().includes("sphere") ? "sphere" : geometry.type.toLowerCase().includes("capsule") ? "capsule" : "box");
668
+ if (inferred === "trimesh")
669
+ return new _CollisionShape3D({
670
+ collisionLayer: 1,
671
+ collisionMask: 65535,
672
+ kind: inferred,
673
+ sensor: false,
674
+ x: 0,
675
+ y: 0,
676
+ z: 0,
677
+ vertices: geometryVertices(mesh),
678
+ indices: geometryIndices(mesh)
679
+ });
680
+ if (inferred === "convexHull")
681
+ return new _CollisionShape3D({
682
+ collisionLayer: 1,
683
+ collisionMask: 65535,
684
+ kind: inferred,
685
+ sensor: false,
686
+ x: 0,
687
+ y: 0,
688
+ z: 0,
689
+ vertices: geometryVertices(mesh)
690
+ });
691
+ if (inferred === "heightfield")
692
+ throw new Error("CollisionShape3D.fromMesh cannot infer a heightfield.");
693
+ geometry.computeBoundingBox();
694
+ const bounds = geometry.boundingBox;
695
+ if (bounds === null) throw new Error("CollisionShape3D.fromMesh requires a bounding box.");
696
+ const width = (bounds.max.x - bounds.min.x) * Math.abs(mesh.scale.x);
697
+ const height = (bounds.max.y - bounds.min.y) * Math.abs(mesh.scale.y);
698
+ const depth = (bounds.max.z - bounds.min.z) * Math.abs(mesh.scale.z);
699
+ if (inferred === "sphere") {
700
+ geometry.computeBoundingSphere();
701
+ const radius = (geometry.boundingSphere?.radius ?? Math.max(width, height, depth) / 2) * Math.max(Math.abs(mesh.scale.x), Math.abs(mesh.scale.y), Math.abs(mesh.scale.z));
702
+ return _CollisionShape3D.sphere(radius);
703
+ }
704
+ if (inferred === "capsule") {
705
+ const radius = Math.min(width, depth) / 2;
706
+ return _CollisionShape3D.capsule(Math.max(0, height / 2 - radius), radius);
707
+ }
708
+ return _CollisionShape3D.box(width, height, depth);
709
+ }
710
+ setCollisionGroups(groups) {
711
+ const layer = groups >>> 16;
712
+ const mask = groups & 65535;
713
+ interactionGroups(layer, mask);
714
+ this.#descriptor.collisionLayer = layer;
715
+ this.#descriptor.collisionMask = mask;
716
+ applyRaw(this.#backendRaw, "setCollisionGroups", groups);
717
+ return this;
718
+ }
719
+ setSensor(sensor) {
720
+ this.#descriptor.sensor = sensor;
721
+ applyRaw(this.#backendRaw, "setSensor", sensor);
722
+ return this;
723
+ }
724
+ };
725
+
726
+ // src/RigidBody3D.ts
727
+ function finiteTransform3(values, offset) {
728
+ const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
729
+ if (result.some((value) => value === void 0 || !Number.isFinite(value)))
730
+ throw new Error("PhysicsSimulation returned a malformed transform.");
731
+ return result;
732
+ }
733
+ var RigidBody3D = class {
734
+ body;
735
+ collider;
736
+ object;
737
+ type;
738
+ #simulation;
739
+ #physics;
740
+ #lastPosition;
741
+ #disposed = false;
742
+ constructor(options) {
743
+ this.#simulation = requirePhysicsSimulation(options.physics, options.world);
744
+ this.#physics = options.physics;
745
+ this.object = options.object;
746
+ this.type = options.type ?? "dynamic";
747
+ const shape = options.shape.descriptor;
748
+ if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
749
+ const layer = options.collisionLayer ?? shape.collisionLayer;
750
+ const mask = options.collisionMask ?? shape.collisionMask;
751
+ options.shape.setCollisionGroups(interactionGroups(layer, mask));
752
+ }
753
+ const registration = this.#simulation.createBody({
754
+ mass: options.mass ?? 0,
755
+ position: this.object.position,
756
+ rotation: this.object.quaternion,
757
+ sensor: false,
758
+ shape,
759
+ type: this.type
760
+ });
761
+ options.shape.bindRaw(registration.rawShape);
762
+ this.body = registration.body;
763
+ this.collider = registration.collider;
764
+ this.#lastPosition = {
765
+ x: this.object.position.x,
766
+ y: this.object.position.y,
767
+ z: this.object.position.z
768
+ };
769
+ this.#physics?.add(this);
770
+ }
771
+ /** Called by the shared plugin before a bulk step. */
772
+ writeKinematic(buffer, offset) {
773
+ if (this.#disposed) return;
774
+ buffer.set(
775
+ [
776
+ this.body.id,
777
+ this.object.position.x,
778
+ this.object.position.y,
779
+ this.object.position.z,
780
+ this.object.quaternion.x,
781
+ this.object.quaternion.y,
782
+ this.object.quaternion.z,
783
+ this.object.quaternion.w
784
+ ],
785
+ offset
786
+ );
787
+ }
788
+ /** Displacement since the last backend transform, used for moving-platform carry. */
789
+ kinematicMotion() {
790
+ return {
791
+ x: this.object.position.x - this.#lastPosition.x,
792
+ y: this.object.position.y - this.#lastPosition.y,
793
+ z: this.object.position.z - this.#lastPosition.z
794
+ };
795
+ }
796
+ syncToPhysics() {
797
+ }
798
+ syncFromPhysics() {
799
+ const transform = this.#simulation.readBodyTransform?.(this.body.id);
800
+ if (transform === void 0) return;
801
+ this.object.position.set(transform.position.x, transform.position.y, transform.position.z);
802
+ this.object.quaternion.set(
803
+ transform.rotation.x,
804
+ transform.rotation.y,
805
+ transform.rotation.z,
806
+ transform.rotation.w
807
+ );
808
+ this.#lastPosition = { ...transform.position };
809
+ }
810
+ applyTransform(values, offset) {
811
+ const [, x, y, z, qx, qy, qz, qw] = finiteTransform3(values, offset);
812
+ this.object.position.set(x, y, z);
813
+ this.object.quaternion.set(qx, qy, qz, qw);
814
+ this.#lastPosition = { x, y, z };
815
+ }
816
+ dispose() {
817
+ if (this.#disposed) return;
818
+ this.#disposed = true;
819
+ this.#physics?.remove(this);
820
+ this.#simulation.removeBody(this.body.id);
821
+ }
822
+ };
823
+
824
+ // src/plugin.ts
825
+ function growFloat(buffer, records) {
826
+ if (buffer.length >= records * PHYSICS_TRANSFORM_STRIDE) return buffer;
827
+ return new Float32Array(
828
+ Math.max(records, Math.max(1, buffer.length / PHYSICS_TRANSFORM_STRIDE) * 2) * PHYSICS_TRANSFORM_STRIDE
829
+ );
830
+ }
831
+ function growEvents(buffer, bodyCount) {
832
+ const required = Math.max(64, bodyCount * 2 * PHYSICS_COLLISION_EVENT_STRIDE);
833
+ let length = buffer.length;
834
+ while (length < required) length *= 2;
835
+ return length === buffer.length ? buffer : new Uint32Array(length);
836
+ }
837
+ function isSmallBufferError2(error) {
838
+ return error instanceof Error && /buffer is too small/i.test(error.message);
839
+ }
840
+ function visibleId(buffer, offset) {
841
+ const value = buffer[offset];
842
+ if (value === void 0 || !Number.isInteger(value) || value < 0)
843
+ throw new Error("PhysicsSimulation returned an invalid visible body id.");
844
+ return value;
845
+ }
846
+ function rapier(options = {}) {
847
+ const backend = physicsSimulationBackend();
848
+ let simulation;
849
+ let context;
850
+ const bodies = /* @__PURE__ */ new Set();
851
+ const bodiesById = /* @__PURE__ */ new Map();
852
+ const areas = /* @__PURE__ */ new Map();
853
+ const kinematicMotions = /* @__PURE__ */ new Map();
854
+ let kinematic = new Float32Array(PHYSICS_TRANSFORM_STRIDE * 16);
855
+ let visible = new Float32Array(PHYSICS_TRANSFORM_STRIDE * 16);
856
+ let events = new Uint32Array(64);
857
+ return {
858
+ setup: async (ctx, runtime) => {
859
+ await backend.initialize();
860
+ const selected = backend.createSimulation(options);
861
+ simulation = selected;
862
+ if (runtime !== void 0) runtime.rapier = selected.version;
863
+ context = {
864
+ add: (body) => {
865
+ bodies.add(body);
866
+ bodiesById.set(body.body.id, body);
867
+ },
868
+ addArea: (area) => areas.set(area.body.id, area),
869
+ eventQueue: physicsHandle(selected.rawEventQueue),
870
+ kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
871
+ numBodies: () => bodies.size,
872
+ remove: (body) => {
873
+ bodies.delete(body);
874
+ bodiesById.delete(body.body.id);
875
+ },
876
+ removeArea: (area) => areas.delete(area.body.id),
877
+ simulation: selected,
878
+ world: physicsWorldHandle(selected.rawWorld, selected)
879
+ };
880
+ ctx.physics = context;
881
+ return void 0;
882
+ },
883
+ update: (_ctx, dt) => {
884
+ if (simulation === void 0) throw new Error("Physics plugin updated before setup.");
885
+ kinematicMotions.clear();
886
+ let count = 0;
887
+ kinematic = growFloat(kinematic, bodies.size + areas.size);
888
+ for (const body of bodies) {
889
+ if (body instanceof RigidBody3D && body.type === "kinematic") {
890
+ kinematicMotions.set(body.collider.id, body.kinematicMotion());
891
+ body.writeKinematic(kinematic, count * PHYSICS_TRANSFORM_STRIDE);
892
+ count += 1;
893
+ }
894
+ }
895
+ for (const body of bodies) {
896
+ if (body instanceof CharacterBody3D) {
897
+ body.writeKinematic(kinematic, count * PHYSICS_TRANSFORM_STRIDE);
898
+ count += 1;
899
+ }
900
+ }
901
+ for (const area of areas.values()) {
902
+ area.writeKinematic(kinematic, count * PHYSICS_TRANSFORM_STRIDE);
903
+ count += 1;
904
+ }
905
+ const input = {
906
+ kinematicCount: count,
907
+ kinematicTransforms: kinematic
908
+ };
909
+ simulation.step(dt, input);
910
+ visible = growFloat(visible, bodies.size + areas.size);
911
+ const visibleCount = simulation.readVisibleTransforms(visible);
912
+ for (let index = 0; index < visibleCount; index += 1) {
913
+ const offset = index * PHYSICS_TRANSFORM_STRIDE;
914
+ const id = visibleId(visible, offset);
915
+ const body = bodiesById.get(id);
916
+ if (body !== void 0) body.applyTransform(visible, offset);
917
+ else {
918
+ const area = areas.get(id);
919
+ if (area === void 0)
920
+ throw new Error("PhysicsSimulation returned an unknown visible body id.");
921
+ area.applyTransform(visible, offset);
922
+ }
923
+ }
924
+ events = growEvents(events, bodies.size + areas.size);
925
+ const maximumEventValues = Math.max(
926
+ 64,
927
+ (bodies.size + areas.size) ** 2 * PHYSICS_COLLISION_EVENT_STRIDE
928
+ );
929
+ let eventCount;
930
+ for (; ; ) {
931
+ try {
932
+ eventCount = simulation.drainCollisionEvents(events);
933
+ break;
934
+ } catch (error) {
935
+ if (!isSmallBufferError2(error) || events.length >= maximumEventValues) throw error;
936
+ events = new Uint32Array(Math.min(maximumEventValues, events.length * 2));
937
+ }
938
+ }
939
+ for (let index = 0; index < eventCount; index += 1) {
940
+ const offset = index * PHYSICS_COLLISION_EVENT_STRIDE;
941
+ const left = events[offset];
942
+ const right = events[offset + 1];
943
+ const started = events[offset + 2] === 1;
944
+ if (left === void 0 || right === void 0)
945
+ throw new Error("PhysicsSimulation returned a malformed collision event.");
946
+ const leftArea = areas.get(left);
947
+ const rightArea = areas.get(right);
948
+ const leftBody = bodiesById.get(left);
949
+ const rightBody = bodiesById.get(right);
950
+ if (leftArea !== void 0 && rightBody !== void 0)
951
+ leftArea.handleCollision(rightBody, started);
952
+ if (rightArea !== void 0 && leftBody !== void 0)
953
+ rightArea.handleCollision(leftBody, started);
954
+ }
955
+ if (simulation.areaIntersections !== void 0) {
956
+ for (const area of areas.values()) {
957
+ const current = /* @__PURE__ */ new Map();
958
+ for (const bodyId of simulation.areaIntersections(area.body.id)) {
959
+ const body = bodiesById.get(bodyId);
960
+ if (body !== void 0) current.set(bodyId, body);
961
+ }
962
+ area.reconcileIntersections(current);
963
+ }
964
+ }
965
+ kinematicMotions.clear();
966
+ },
967
+ sceneExit: () => {
968
+ for (const area of [...areas.values()]) area.dispose();
969
+ for (const body of [...bodies]) body.dispose();
970
+ kinematicMotions.clear();
971
+ },
972
+ dispose: () => {
973
+ for (const area of [...areas.values()]) area.dispose();
974
+ for (const body of [...bodies]) body.dispose();
975
+ simulation?.dispose();
976
+ simulation = void 0;
977
+ context = void 0;
978
+ areas.clear();
979
+ bodies.clear();
980
+ bodiesById.clear();
981
+ kinematicMotions.clear();
982
+ }
983
+ };
984
+ }
985
+
986
+ export { Area3D, CharacterBody3D, CollisionShape3D, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, RigidBody3D, interactionGroups, rapier };