@adatechnology/game-destruction-three 0.26.5 → 0.27.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.
package/dist/index.js CHANGED
@@ -1578,6 +1578,8 @@ var rows = (r) => {
1578
1578
  const [x, y, z, w] = r;
1579
1579
  return [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w), 2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w), 2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)];
1580
1580
  };
1581
+ var HINGE_RELEASE = 40 * Math.PI / 180;
1582
+ var HINGE_SECONDS = 1.5;
1581
1583
  var isTurned = (box) => box.rotation !== void 0 && rows(box.rotation).some((v) => Math.abs(v) > 1e-6 && Math.abs(Math.abs(v) - 1) > 1e-6);
1582
1584
  var squareBoxOf = (box) => {
1583
1585
  const r = box.rotation;
@@ -2753,6 +2755,11 @@ var sameFriction = (a, b) => a === b || a !== void 0 && b !== void 0 && a.static
2753
2755
  var sameShape = (a, b) => near(a.center, b.center) && near(a.half, b.half) && near(a.rotation, b.rotation) && sameMesh(a.mesh, b.mesh);
2754
2756
  var sameBox = (a, b) => a === b || sameShape(a, b) && sameFriction(a.friction, b.friction);
2755
2757
  var sameSolids = (a, b) => a.length === b.length && a.every((s, i) => sameBox(s, b[i]));
2758
+ var NONE = /* @__PURE__ */ new Set();
2759
+ var partOfKey = (key) => {
2760
+ const colon = key.lastIndexOf(":");
2761
+ return colon < 0 || !/^\d+$/.test(key.slice(colon + 1)) ? key : key.slice(0, colon);
2762
+ };
2756
2763
  var hasSize = (s) => s.half[0] > 0 && s.half[1] > 0 && s.half[2] > 0;
2757
2764
  var shapeOf = (s) => s.mesh ? { kind: "trimesh", vertices: s.mesh.vertices, indices: s.mesh.indices } : { kind: "box", half: s.half };
2758
2765
  var EngineStatics = class {
@@ -2764,32 +2771,55 @@ var EngineStatics = class {
2764
2771
  __publicField(this, "changed", /* @__PURE__ */ new Set());
2765
2772
  /** Every body it holds now: what a piece made or put is checked against (`EnginePieces.outOfStatics`; the ground has its own rule). */
2766
2773
  __publicField(this, "ids", /* @__PURE__ */ new Set());
2774
+ /** The object each held body is a part of (what a ray that meets the body says about the object). */
2775
+ __publicField(this, "ownerOf", /* @__PURE__ */ new Map());
2776
+ /** The part of the object each held body draws (the key without its mesh number): what a blow on the body hits. */
2777
+ __publicField(this, "partOf", /* @__PURE__ */ new Map());
2778
+ /** Changes whenever an answer of `covers` may have (an object came, went, or was fitted again). */
2779
+ __publicField(this, "coverageRevision", 0);
2780
+ __publicField(this, "unsure", NONE);
2767
2781
  }
2768
2782
  /** Whether the engine has a body for the object's drawn parts (what the kit's sweep need not set a piece back from). */
2769
2783
  has(objectId) {
2770
2784
  const f = this.bodies.get(objectId);
2771
2785
  return f !== void 0 && f.held.size > 0;
2772
2786
  }
2773
- lay(now) {
2787
+ /**
2788
+ * Whether every part a ray can hit has its body: only then is a ray's miss of its bodies a miss of the object. An object whose list is only partly measured, or leaves out a part the
2789
+ * world still tests (a loose or hidden one), is not covered: `lay`'s `unsure`.
2790
+ */
2791
+ covers(objectId) {
2792
+ const f = this.bodies.get(objectId);
2793
+ return f !== void 0 && f.held.size > 0 && f.waiting === 0 && !this.unsure.has(objectId);
2794
+ }
2795
+ /** `now` is the host's list per object; `unsure` names the objects whose list is not all of what a ray can hit (see `covers`). */
2796
+ lay(now, unsure = NONE) {
2774
2797
  this.changed.clear();
2798
+ if (unsure.size !== this.unsure.size || [...unsure].some((id) => !this.unsure.has(id))) {
2799
+ this.unsure = new Set(unsure);
2800
+ this.coverageRevision++;
2801
+ }
2775
2802
  for (const [id, f] of this.bodies) {
2776
2803
  if (now.has(id)) continue;
2777
2804
  for (const h of f.held.values()) this.release(h, f.settled);
2778
2805
  this.bodies.delete(id);
2806
+ this.coverageRevision++;
2779
2807
  }
2780
2808
  const budget = { triangles: TRIANGLES_PER_UPDATE };
2781
2809
  for (const [id, solids] of now) {
2782
2810
  const f = this.bodies.get(id);
2783
2811
  if (f?.solids === solids && f.waiting === 0) continue;
2784
- const fixed = f ?? { solids, held: /* @__PURE__ */ new Map(), waiting: 0, settled: false };
2812
+ const fixed = f ?? { objectId: id, solids, held: /* @__PURE__ */ new Map(), waiting: 0, settled: false };
2785
2813
  this.bodies.set(id, fixed);
2786
2814
  fixed.solids = solids;
2815
+ this.coverageRevision++;
2787
2816
  this.fit(fixed, budget);
2788
2817
  }
2789
2818
  }
2790
2819
  clear() {
2791
2820
  for (const f of this.bodies.values()) for (const h of f.held.values()) this.drop(h.id);
2792
2821
  this.bodies.clear();
2822
+ this.coverageRevision++;
2793
2823
  this.changed.clear();
2794
2824
  }
2795
2825
  /** The object's parts of a list by name, the ones with a size only. */
@@ -2837,6 +2867,8 @@ var EngineStatics = class {
2837
2867
  const id = ids[i];
2838
2868
  f.held.set(x.key, { solid: x.solid, id });
2839
2869
  this.ids.add(id);
2870
+ this.ownerOf.set(id, f.objectId);
2871
+ this.partOf.set(id, partOfKey(x.key));
2840
2872
  this.changed.add(id);
2841
2873
  if (f.settled) this.wakeAround(x.solid);
2842
2874
  });
@@ -2867,6 +2899,8 @@ var EngineStatics = class {
2867
2899
  }
2868
2900
  drop(id) {
2869
2901
  this.ids.delete(id);
2902
+ this.ownerOf.delete(id);
2903
+ this.partOf.delete(id);
2870
2904
  this.world.removeBody(id);
2871
2905
  }
2872
2906
  wakeAround(s) {
@@ -3195,6 +3229,36 @@ function shapeContact(a, b) {
3195
3229
  return null;
3196
3230
  }
3197
3231
 
3232
+ // src/engine-impacts.ts
3233
+ import { createImpactReader } from "@adatechnology/game-physics";
3234
+ var DEFAULT_MIN_IMPULSE = 30;
3235
+ var DEFAULT_HITS_MAX = 32;
3236
+ var DEFAULT_CONTACT_RADIUS = 0.1;
3237
+ var createEngineImpacts = (loop, statics, destruction, options = {}) => {
3238
+ const hitsMax = options.hitsMax ?? DEFAULT_HITS_MAX;
3239
+ const radius = options.contactRadius ?? DEFAULT_CONTACT_RADIUS;
3240
+ return createImpactReader(loop, {
3241
+ minImpulse: options.minImpulse ?? DEFAULT_MIN_IMPULSE,
3242
+ bodiesMax: hitsMax,
3243
+ accepts: (body) => statics.ownerOf.has(body),
3244
+ onImpact: (impact2) => {
3245
+ const object = statics.ownerOf.get(impact2.body);
3246
+ const part = statics.partOf.get(impact2.body);
3247
+ if (object === void 0 || part === void 0 || destruction.part(object, part) === null) return;
3248
+ const hit = {
3249
+ type: "blunt",
3250
+ point: [impact2.point[0], impact2.point[1], impact2.point[2]],
3251
+ direction: [-impact2.normal[0], -impact2.normal[1], -impact2.normal[2]],
3252
+ energy: 0.5 * impact2.impulse * impact2.approach,
3253
+ radius,
3254
+ part,
3255
+ source: "engine"
3256
+ };
3257
+ destruction.hitPart(object, part, hit);
3258
+ }
3259
+ });
3260
+ };
3261
+
3198
3262
  // src/engine-pieces.ts
3199
3263
  import { samePatch } from "@adatechnology/game-terrain";
3200
3264
 
@@ -3364,6 +3428,96 @@ var GroundSchedule = class {
3364
3428
  }
3365
3429
  };
3366
3430
 
3431
+ // src/engine-rays.ts
3432
+ var RAY_MARGIN = 0.25;
3433
+ var LONGEST_RAY = 2e3;
3434
+ var FIXED_ONLY = { layers: ["static"] };
3435
+ var createEngineRayBroadPhase = (world, statics) => {
3436
+ const hits = [];
3437
+ const inside = [];
3438
+ const met = /* @__PURE__ */ new Set();
3439
+ const metList = [];
3440
+ const from = [0, 0, 0];
3441
+ const toward = [0, 0, 0];
3442
+ return {
3443
+ begin(origin, direction, maxDistance) {
3444
+ if (!(maxDistance <= LONGEST_RAY)) return false;
3445
+ met.clear();
3446
+ metList.length = 0;
3447
+ from[0] = origin[0];
3448
+ from[1] = origin[1];
3449
+ from[2] = origin[2];
3450
+ toward[0] = direction[0];
3451
+ toward[1] = direction[1];
3452
+ toward[2] = direction[2];
3453
+ const count = world.sphereCastAll(from, toward, maxDistance, RAY_MARGIN, hits, FIXED_ONLY);
3454
+ for (let i = 0; i < count; i++) {
3455
+ const owner = statics.ownerOf.get(hits[i].body);
3456
+ if (owner !== void 0 && !met.has(owner)) {
3457
+ met.add(owner);
3458
+ metList.push(owner);
3459
+ }
3460
+ }
3461
+ const around = world.overlapSphere(from, RAY_MARGIN, inside, FIXED_ONLY);
3462
+ for (let i = 0; i < around; i++) {
3463
+ const owner = statics.ownerOf.get(inside[i]);
3464
+ if (owner !== void 0 && !met.has(owner)) {
3465
+ met.add(owner);
3466
+ metList.push(owner);
3467
+ }
3468
+ }
3469
+ return true;
3470
+ },
3471
+ mayMeet: (objectId) => !statics.covers(objectId) || met.has(objectId),
3472
+ candidates: {
3473
+ met: () => metList,
3474
+ covers: (objectId) => statics.covers(objectId),
3475
+ revision: () => statics.coverageRevision
3476
+ }
3477
+ };
3478
+ };
3479
+
3480
+ // src/merge-flush-boxes.ts
3481
+ var FLUSH = 1e-4;
3482
+ var sameTurn = (a, b) => {
3483
+ if (!a.rotation && !b.rotation) return true;
3484
+ if (!a.rotation || !b.rotation) return false;
3485
+ return a.rotation.every((v, i) => Math.abs(v - b.rotation[i]) < FLUSH);
3486
+ };
3487
+ var flushAxis = (a, b) => {
3488
+ if (!sameTurn(a, b)) return -1;
3489
+ let along2 = -1;
3490
+ for (let axis = 0; axis < 3; axis++) {
3491
+ const same2 = Math.abs(a.half[axis] - b.half[axis]) < FLUSH && Math.abs(a.center[axis] - b.center[axis]) < FLUSH;
3492
+ if (same2) continue;
3493
+ if (along2 >= 0) return -1;
3494
+ along2 = axis;
3495
+ }
3496
+ if (along2 < 0) return -1;
3497
+ return Math.abs(Math.abs(a.center[along2] - b.center[along2]) - a.half[along2] - b.half[along2]) < FLUSH ? along2 : -1;
3498
+ };
3499
+ function mergeFlushBoxes(boxes) {
3500
+ const out = [...boxes];
3501
+ for (let i = 0; i < out.length; i++) {
3502
+ for (let j = i + 1; j < out.length; j++) {
3503
+ const a = out[i];
3504
+ const axis = flushAxis(a, out[j]);
3505
+ if (axis < 0) continue;
3506
+ const b = out[j];
3507
+ const low = Math.min(a.center[axis] - a.half[axis], b.center[axis] - b.half[axis]);
3508
+ const high = Math.max(a.center[axis] + a.half[axis], b.center[axis] + b.half[axis]);
3509
+ const center = [a.center[0], a.center[1], a.center[2]];
3510
+ const half = [a.half[0], a.half[1], a.half[2]];
3511
+ center[axis] = (low + high) / 2;
3512
+ half[axis] = (high - low) / 2;
3513
+ out[i] = { center, half, ...a.rotation ? { rotation: a.rotation } : {} };
3514
+ out.splice(j, 1);
3515
+ j = i;
3516
+ }
3517
+ }
3518
+ return out;
3519
+ }
3520
+
3367
3521
  // src/engine-pieces.ts
3368
3522
  var GROUND_WORKER_FRAMES = 2;
3369
3523
  var wasCoarseOf = (tile) => !tile.slab && tile.collision.length < tile.heights.length;
@@ -3401,6 +3555,7 @@ var RING_SEGMENTS = 16;
3401
3555
  var TOPPLE = 3;
3402
3556
  var HOLD_MARGIN = 4;
3403
3557
  var SIDE_DEAD = 0.01;
3558
+ var BOX_FOOT = 0.02;
3404
3559
  var PUSH_SPIN = 0.3;
3405
3560
  var STEADY_TURN = 0.1;
3406
3561
  var STEADY_SECONDS = 1.5;
@@ -3459,6 +3614,8 @@ var EnginePieces = class {
3459
3614
  __publicField(this, "pose", new Float64Array(7));
3460
3615
  __publicField(this, "velocity", new Float64Array(6));
3461
3616
  __publicField(this, "contactXYZ", new Float32Array(48));
3617
+ /** The pieces hung on a hinge: the fixed anchor at the screw and the joint that holds them to it. */
3618
+ __publicField(this, "hung", /* @__PURE__ */ new Map());
3462
3619
  __publicField(this, "outAxis", new Float64Array(3));
3463
3620
  __publicField(this, "wayAxis", new Float64Array(3));
3464
3621
  /** The centre `readBack` reads into (the sweep may move it). */
@@ -3496,6 +3653,10 @@ var EnginePieces = class {
3496
3653
  this.schedule = o.groundWorker ? new GroundSchedule(o.groundWorker, Math.max(1, Math.round(o.groundWorkerFrames ?? GROUND_WORKER_FRAMES))) : null;
3497
3654
  if (this.schedule) this.warmGround(this.schedule);
3498
3655
  }
3656
+ /** The fixed bodies as a broad phase for the destruction world's rays (`engine-rays.ts`). */
3657
+ rayBroadPhase() {
3658
+ return createEngineRayBroadPhase(this.world, this.statics);
3659
+ }
3499
3660
  /** The worker's first job, a sloped tile with steps away from the host's ground (no host call): its code is parsed and hot before the first blast asks for real ones. */
3500
3661
  warmGround(schedule) {
3501
3662
  const warmGround = (x, z) => 0.3 * x - 0.2 * z + 0.15 * Math.floor(x / 0.37) + 0.05 * Math.sin(3 * z);
@@ -3509,6 +3670,8 @@ var EnginePieces = class {
3509
3670
  remove(b, wakeNeighbours = true) {
3510
3671
  const link = this.links.get(b);
3511
3672
  if (!link) return;
3673
+ const held = this.hung.get(b);
3674
+ if (held) this.letGo(b, held);
3512
3675
  this.world.removeBody(link.id);
3513
3676
  if (wakeNeighbours && (b.sleeping || link.sleeping)) this.wakeAround(b, link.pos);
3514
3677
  this.byUser.delete(link.user);
@@ -3649,6 +3812,7 @@ var EnginePieces = class {
3649
3812
  this.applyDueGround();
3650
3813
  this.layBlastGround();
3651
3814
  this.makeBodies(each);
3815
+ each((b) => this.hang(b));
3652
3816
  each((b) => this.sync(b, dt, h));
3653
3817
  if (this.schedule) this.layGroundLater(each, dt);
3654
3818
  else this.layGround(each, dt);
@@ -3682,8 +3846,44 @@ var EnginePieces = class {
3682
3846
  this.readActive(awake);
3683
3847
  awake.walk((b) => this.readBack(b, dt, time, this.active));
3684
3848
  } else for (const b of list) this.readBack(b, dt, time, null);
3849
+ this.wearHinges(dt);
3685
3850
  this.knock(time);
3686
3851
  }
3852
+ /** A piece with a hinge asked for (`PieceSystem.hinge`) gets a fixed anchor at the screw and a hinge joint to it, once its body exists. It swings in the vertical plane through the screw and its centre. */
3853
+ hang(b) {
3854
+ const hinge = b.hinge;
3855
+ const link = this.links.get(b);
3856
+ if (!hinge || !link || this.hung.has(b)) return;
3857
+ const c = this.centre(b);
3858
+ const dx = c.x - hinge.point[0];
3859
+ const dz = c.z - hinge.point[2];
3860
+ const along2 = Math.hypot(dx, dz);
3861
+ const axis = along2 < 1e-3 ? [0, 0, 1] : [dz / along2, 0, -dx / along2];
3862
+ const anchor = this.world.createBody({ shape: { kind: "box", half: [5e-3, 5e-3, 5e-3] }, motion: "static", position: hinge.point, user: 0 });
3863
+ this.world.ignorePair(anchor, link.id, true);
3864
+ const joint = this.world.createJoint({ kind: "hinge", a: anchor, b: link.id, point: hinge.point, axis, normal: [0, 1, 0], min: -Math.PI / 2, max: Math.PI / 2 });
3865
+ this.hung.set(b, { anchor, joint });
3866
+ }
3867
+ /** The screw tears out: past `HINGE_RELEASE` of turn, or after `HINGE_SECONDS`, the piece falls free. */
3868
+ wearHinges(dt) {
3869
+ for (const [b, held] of this.hung) {
3870
+ const hinge = b.hinge;
3871
+ if (hinge) {
3872
+ hinge.seconds -= dt;
3873
+ const [x, y, z, w] = hinge.from;
3874
+ const q = b.root.quaternion;
3875
+ const turned = 2 * Math.acos(Math.min(1, Math.abs(q.x * x + q.y * y + q.z * z + q.w * w)));
3876
+ if (turned < HINGE_RELEASE && hinge.seconds > 0) continue;
3877
+ }
3878
+ this.letGo(b, held);
3879
+ }
3880
+ }
3881
+ letGo(b, held) {
3882
+ this.world.removeJoint(held.joint);
3883
+ this.world.removeBody(held.anchor);
3884
+ this.hung.delete(b);
3885
+ b.hinge = void 0;
3886
+ }
3687
3887
  /** The engine's awake bodies in one crossing: a sleeping piece one of them wakes (a blow) is among the awake pieces from now on, and read back in this same step. */
3688
3888
  readActive(awake) {
3689
3889
  this.active.clear();
@@ -3767,7 +3967,7 @@ var EnginePieces = class {
3767
3967
  return { kind: "compound", children: [{ shape: { kind: "cylinder", halfHeight: b.halfExtents[round.axis], radius: round.radius }, position: [0, 0, 0], rotation }] };
3768
3968
  }
3769
3969
  if (b.partBoxes && b.partBoxes.length > 0) {
3770
- return { kind: "compound", children: b.partBoxes.map((part, i) => ({ shape: { kind: "box", half: part.half }, position: part.center, ...part.rotation ? { rotation: part.rotation } : {}, tag: i })) };
3970
+ return { kind: "compound", children: mergeFlushBoxes(b.partBoxes).map((part, i) => ({ shape: { kind: "box", half: part.half }, position: part.center, ...part.rotation ? { rotation: part.rotation } : {}, tag: i })) };
3771
3971
  }
3772
3972
  return { kind: "box", half: b.halfExtents };
3773
3973
  }
@@ -3833,8 +4033,7 @@ var EnginePieces = class {
3833
4033
  return {
3834
4034
  frictionStatic: b.friction?.static ?? MU_STATIC,
3835
4035
  frictionDynamic: b.friction?.dynamic ?? MU_DYNAMIC,
3836
- // a box lands dead (the kit never bounced them); a round piece bounces by its material
3837
- restitution: b.round ? b.restitution ?? SLAM_BOUNCE : 0,
4036
+ restitution: b.restitution ?? SLAM_BOUNCE,
3838
4037
  rolling: b.friction?.rolling ?? ROLLING_RESISTANCE
3839
4038
  };
3840
4039
  }
@@ -4079,8 +4278,16 @@ var EnginePieces = class {
4079
4278
  this.slip(b, link, false);
4080
4279
  return;
4081
4280
  }
4082
- const c = this.centre(b);
4083
4281
  const q = b.root.quaternion;
4282
+ const c = this.centre(b);
4283
+ let shiftX = 0, shiftY = 0, shiftZ = 0;
4284
+ if (b.massCentre) {
4285
+ this.w.set(b.massCentre[0], b.massCentre[1], b.massCentre[2]).applyQuaternion(q);
4286
+ shiftX = this.w.x;
4287
+ shiftY = this.w.y;
4288
+ shiftZ = this.w.z;
4289
+ c.add(this.w);
4290
+ }
4084
4291
  let low = Infinity;
4085
4292
  for (let i = 0; i < n; i++) low = Math.min(low, this.contactXYZ[i * 3 + 1] - c.y);
4086
4293
  let x0 = Infinity, x1 = -Infinity, z0 = Infinity, z1 = -Infinity;
@@ -4092,6 +4299,23 @@ var EnginePieces = class {
4092
4299
  z0 = Math.min(z0, rz);
4093
4300
  z1 = Math.max(z1, rz);
4094
4301
  }
4302
+ if (!b.contacts && !b.round && !b.apart) {
4303
+ const [hx, hy, hz] = b.halfExtents;
4304
+ const corner = this.w;
4305
+ let lowest = Infinity;
4306
+ for (let k = 0; k < 8; k++) lowest = Math.min(lowest, corner.set(k & 1 ? hx : -hx, k & 2 ? hy : -hy, k & 4 ? hz : -hz).applyQuaternion(q).y - shiftY);
4307
+ if (Math.abs(lowest - low) < BOX_FOOT) {
4308
+ for (let k = 0; k < 8; k++) {
4309
+ corner.set(k & 1 ? hx : -hx, k & 2 ? hy : -hy, k & 4 ? hz : -hz).applyQuaternion(q);
4310
+ if (corner.y - shiftY > lowest + BOX_FOOT) continue;
4311
+ x0 = Math.min(x0, corner.x - shiftX);
4312
+ x1 = Math.max(x1, corner.x - shiftX);
4313
+ z0 = Math.min(z0, corner.z - shiftZ);
4314
+ z1 = Math.max(z1, corner.z - shiftZ);
4315
+ }
4316
+ low = Math.min(low, lowest);
4317
+ }
4318
+ }
4095
4319
  const height = -low;
4096
4320
  const wx = x1 - x0;
4097
4321
  const wz = z1 - z0;
@@ -4493,7 +4717,7 @@ var EnginePieces = class {
4493
4717
  replaceGround(tile, made2, ix, iz, material) {
4494
4718
  if (tile) this.world.removeBody(tile.ground);
4495
4719
  if (made2.level === null) return this.world.createBody({ shape: this.heightField(made2, ix, iz), motion: "static", position: [0, 0, 0], material, user: 0 });
4496
- return this.world.createBody({ shape: { kind: "box", half: [TILE / 2, 0.5, TILE / 2] }, motion: "static", position: [(ix + 0.5) * TILE, made2.level - 0.5, (iz + 0.5) * TILE], material, user: 0 });
4720
+ return this.world.createBody({ shape: { kind: "box", half: [TILE / 2, 0.5, TILE / 2], convexRadius: 0 }, motion: "static", position: [(ix + 0.5) * TILE, made2.level - 0.5, (iz + 0.5) * TILE], material, user: 0 });
4497
4721
  }
4498
4722
  /** The solid under a height field, on its own body, swapped in place when the ground changed; none under a slab. Boxes only: a box costs nothing to make, a hull did (T3.8ag). */
4499
4723
  layVolume(t, tile, material) {
@@ -4517,13 +4741,13 @@ var EnginePieces = class {
4517
4741
  }
4518
4742
  stepBoxes(boxes) {
4519
4743
  const children = [];
4520
- for (let i = 0; i < boxes.length; i += 6) children.push({ shape: { kind: "box", half: [boxes[i + 3], boxes[i + 4], boxes[i + 5]] }, position: [boxes[i], boxes[i + 1], boxes[i + 2]] });
4744
+ for (let i = 0; i < boxes.length; i += 6) children.push({ shape: { kind: "box", half: [boxes[i + 3], boxes[i + 4], boxes[i + 5]], convexRadius: 0 }, position: [boxes[i], boxes[i + 1], boxes[i + 2]] });
4521
4745
  return { kind: "compound", children };
4522
4746
  }
4523
4747
  /** The host's fixed boxes, one static body per object (`EngineStatics`). */
4524
4748
  layStatics() {
4525
4749
  const now = this.o.staticSolids?.();
4526
- if (now) this.statics.lay(now);
4750
+ if (now) this.statics.lay(now, this.o.staticUnsure?.());
4527
4751
  }
4528
4752
  keepApart(apart2) {
4529
4753
  for (const key of this.ignored) {
@@ -4741,6 +4965,10 @@ var MU_DYNAMIC2 = 0.6;
4741
4965
  var SLIP_SPEED = 0.02;
4742
4966
  var ROLLING_RESISTANCE2 = 0.015;
4743
4967
  var ROUND_LYING = Math.SQRT1_2;
4968
+ var MIN_PIECE_HALF = 1e-3;
4969
+ var OWN_MIN_PIECE_HALF = 0.01;
4970
+ var OWN_MIN_MEASURED_HALF = 0.02;
4971
+ var minPieceHalf = (physics) => physics === "own" ? OWN_MIN_MEASURED_HALF : MIN_PIECE_HALF;
4744
4972
  var SLEEP_AFTER = 0.5;
4745
4973
  var STILL_SPEED2 = 0.12;
4746
4974
  var STILL_SPIN2 = 0.45;
@@ -4760,6 +4988,8 @@ var TIP_RISE_AFTER = 0.5;
4760
4988
  var TIP_LYING = 0.25;
4761
4989
  var TIP_SECONDS = 3;
4762
4990
  var STEP = 0.03;
4991
+ var WAKE_SAMPLES = 4;
4992
+ var WAKE_DROP = 0.05;
4763
4993
  var WARM_SLOTS = 8 + 12 * 7;
4764
4994
  var SOLVER_PASSES = 10;
4765
4995
  var SIDE_BOUNCE = 0.1;
@@ -4787,8 +5017,6 @@ var cellKey = (ix, iz) => (ix + 32768) * 65536 + (iz + 32768);
4787
5017
  var MAX_COLLISION_STEPS = 8;
4788
5018
  var MIN_ROUND_RADIUS = 5e-3;
4789
5019
  var BOUNCE_MIN_SPEED = 0.1;
4790
- var HINGE_RELEASE = 40 * Math.PI / 180;
4791
- var HINGE_SECONDS = 1.5;
4792
5020
  var BOX_IMPACT_SPEED = 1.5;
4793
5021
  var KNOCK_FLAT = 0.5;
4794
5022
  var SEPARATE_SPEED = 1.5;
@@ -4854,6 +5082,7 @@ var PieceSystem = class {
4854
5082
  __publicField(this, "m");
4855
5083
  __publicField(this, "hingeM");
4856
5084
  __publicField(this, "ax");
5085
+ __publicField(this, "wakeBox");
4857
5086
  __publicField(this, "solids", []);
4858
5087
  /** The engine stepping the pieces (`PieceSystemOptions.physics`), or null for the kit's own solver. */
4859
5088
  __publicField(this, "engine");
@@ -4944,6 +5173,7 @@ var PieceSystem = class {
4944
5173
  this.m = new THREE.Matrix4();
4945
5174
  this.hingeM = new THREE.Matrix4();
4946
5175
  this.ax = new THREE.Vector3();
5176
+ this.wakeBox = new THREE.Box3();
4947
5177
  const resolved = resolvePhysics(o.physics);
4948
5178
  this.loop = resolved?.loop ?? null;
4949
5179
  this.stepsItself = resolved?.stepsItself ?? false;
@@ -4958,6 +5188,7 @@ var PieceSystem = class {
4958
5188
  ...o.blastGroundTiles !== void 0 ? { blastTiles: o.blastGroundTiles } : {},
4959
5189
  gravity: o.gravity,
4960
5190
  staticSolids: o.staticSolids,
5191
+ staticUnsure: o.staticUnsure,
4961
5192
  sweep: o.sweep,
4962
5193
  onSlam: o.onSlam,
4963
5194
  onKnock: o.onKnock,
@@ -4969,6 +5200,14 @@ var PieceSystem = class {
4969
5200
  this.groundWorker = o.groundWorker ?? null;
4970
5201
  if (resolved && !resolved.stepsItself) this.joinLoop(resolved.loop, this.engine);
4971
5202
  }
5203
+ /** Contact blows on the fixed parts become `blunt` hits of `destruction` (`engine-impacts.ts`); null when the pieces are not in the engine's loop. Returns the way to stop it. */
5204
+ contactHits(destruction, options) {
5205
+ return this.engine && this.loop ? createEngineImpacts(this.loop, this.engine.statics, destruction, options) : null;
5206
+ }
5207
+ /** The engine's fixed bodies as the broad phase of the world's rays, or null when the pieces are not in the engine. */
5208
+ rayBroadPhase() {
5209
+ return this.engine?.rayBroadPhase() ?? null;
5210
+ }
4972
5211
  /**
4973
5212
  * The loop mode: the system's work goes into the loop's phases. `prepare` (sync, kinematic targets, the kit's rules that came before the step) runs in the first fixed step of
4974
5213
  * a frame; a held piece's target again in each later one; the read-back and knock sounds after the steps (`contacts`); the budget and the measure after those (`rules`).
@@ -5108,10 +5347,9 @@ var PieceSystem = class {
5108
5347
  }
5109
5348
  /**
5110
5349
  * Hangs a piece on a hinge at `point` (world): that point of it stays where it is while the rest swings down about it, as a shelf that lost the side at one end swings on
5111
- * the screw at the other and pours what lay on it off its free end. It lets go past `HINGE_RELEASE` or `HINGE_SECONDS`. The kit's own solver only (`physics` swings nothing).
5350
+ * the screw at the other and pours what lay on it off its free end. It lets go past `HINGE_RELEASE` or `HINGE_SECONDS`. On the engine it is a hinge joint to a fixed anchor (`EnginePieces.hang`).
5112
5351
  */
5113
5352
  hinge(body, point) {
5114
- if (this.engine) return;
5115
5353
  const c = this.centerOf(body, this.p);
5116
5354
  const q = body.root.quaternion;
5117
5355
  const local = this.ax.set(point[0] - c.x, point[1] - c.y, point[2] - c.z).applyQuaternion(this.dq.copy(q).invert());
@@ -5130,6 +5368,7 @@ var PieceSystem = class {
5130
5368
  return existing;
5131
5369
  }
5132
5370
  const awake = this.awake;
5371
+ const least = this.engine ? MIN_PIECE_HALF : OWN_MIN_PIECE_HALF;
5133
5372
  let asleep = false;
5134
5373
  let inHand = false;
5135
5374
  const body = {
@@ -5139,7 +5378,7 @@ var PieceSystem = class {
5139
5378
  root,
5140
5379
  velocity: velocity ? [...velocity] : [0, 0, 0],
5141
5380
  angularVelocity: angular ? [...angular] : [0, 0, 0],
5142
- halfExtents: [Math.max(0.01, halfExtents[0]), Math.max(0.01, halfExtents[1]), Math.max(0.01, halfExtents[2])],
5381
+ halfExtents: [Math.max(least, halfExtents[0]), Math.max(least, halfExtents[1]), Math.max(least, halfExtents[2])],
5143
5382
  mass: Math.max(0.05, mass),
5144
5383
  // asleep or held is read and written as a plain flag; waking or taking it in hand puts the piece among the awake ones
5145
5384
  get sleeping() {
@@ -5339,12 +5578,31 @@ var PieceSystem = class {
5339
5578
  wakeRegion(x, z, radius) {
5340
5579
  this.engine?.groundChanged(x, z, radius);
5341
5580
  for (const b of this.list) {
5342
- if (!b.sleeping || b.held || Math.hypot(b.root.position.x - x, b.root.position.z - z) > radius) continue;
5581
+ if (!b.sleeping || b.held) continue;
5582
+ if (Math.hypot(b.root.position.x - x, b.root.position.z - z) > radius && !this.lostGroundIn(b, x, z, radius)) continue;
5343
5583
  b.sleeping = false;
5344
5584
  b.still = 0;
5345
5585
  b.calmAt = null;
5346
5586
  }
5347
5587
  }
5588
+ /**
5589
+ * A piece whose root is elsewhere (cut from a whole object, its root is that object's origin) that lies in the disc, with the ground gone from under part of its footprint:
5590
+ * where it lies is read from its drawn box, and only a support that went down wakes it (a piece the disc only passes over stays asleep).
5591
+ */
5592
+ lostGroundIn(b, x, z, radius) {
5593
+ const center = this.centerOf(b, this.ax);
5594
+ if (Math.hypot(center.x - x, center.z - z) > radius + Math.hypot(b.halfExtents[0], b.halfExtents[2])) return false;
5595
+ const box = this.wakeBox.setFromObject(b.root);
5596
+ for (let i = 0; i <= WAKE_SAMPLES; i++) {
5597
+ for (let k = 0; k <= WAKE_SAMPLES; k++) {
5598
+ const px = box.min.x + (box.max.x - box.min.x) * i / WAKE_SAMPLES, pz = box.min.z + (box.max.z - box.min.z) * k / WAKE_SAMPLES;
5599
+ if (Math.hypot(px - x, pz - z) > radius) continue;
5600
+ const support = Math.max(this.o.groundAt(px, pz), this.o.staticTopAt?.(px, pz, box.min.y, STEP) ?? -Infinity);
5601
+ if (support < box.min.y - WAKE_DROP) return true;
5602
+ }
5603
+ }
5604
+ return false;
5605
+ }
5348
5606
  /** A step is about to move the pieces: the roots go back to the step's pose and the awake ones are recorded as the previous one (`interpolate`). */
5349
5607
  beginTick() {
5350
5608
  const trail = this.trail;
@@ -6139,7 +6397,7 @@ var PieceSystem = class {
6139
6397
  let awake = 0;
6140
6398
  for (const b of this.list) {
6141
6399
  if (b.sleeping || b.held) continue;
6142
- if (b.balancing && this.hasComeToRest(b)) this.sleepByBudget(b);
6400
+ if (this.hasComeToRest(b) && (b.balancing || b.still >= SLEEP_AFTER && !b.hinge && !this.onSteepSupport(b))) this.sleepByBudget(b);
6143
6401
  else awake++;
6144
6402
  }
6145
6403
  for (const b of this.list) {
@@ -6215,7 +6473,9 @@ var PieceSystem = class {
6215
6473
  }
6216
6474
  /** Sleeps sooner than it would by itself, so it answers to every point it lies on (`restPoints`). */
6217
6475
  sleepByBudget(b) {
6476
+ const steady = b.steady;
6218
6477
  this.sleep(b);
6478
+ b.steady = steady;
6219
6479
  b.restPoints = this.restPointsOf(b);
6220
6480
  }
6221
6481
  hasComeToRest(b) {
@@ -8875,7 +9135,6 @@ var CONTACT_MESHES = 12;
8875
9135
  var PART_BOX_MESHES = 64;
8876
9136
  var ROUND_SAMPLES = 400;
8877
9137
  var ROUND_SIDES = 0.12;
8878
- var MIN_PIECE_HALF = 0.02;
8879
9138
  var ROUND_SLACK = 1.12;
8880
9139
  var RIM_POINTS = 12;
8881
9140
  var rimPoints = (round, half) => {
@@ -9055,6 +9314,8 @@ var Renderer = class {
9055
9314
  __publicField(this, "staticBoxes", /* @__PURE__ */ new Map());
9056
9315
  /** `staticSolids` per object, kept until `staticNow` measures the object again for a reason. */
9057
9316
  __publicField(this, "solidCache", /* @__PURE__ */ new Map());
9317
+ /** The objects whose last `staticSolids` list is not all of what a ray can hit: measured in part, or with a loose or hidden part left out. */
9318
+ __publicField(this, "unsureSolids", /* @__PURE__ */ new Set());
9058
9319
  /** The objects `staticNow` measured again for a reason (an event, a moved root, boxes that changed): their `staticSolids` are measured again too. */
9059
9320
  __publicField(this, "solidStale", /* @__PURE__ */ new Set());
9060
9321
  /** The world matrix of each root when `staticNow` last measured it. */
@@ -9185,6 +9446,7 @@ var Renderer = class {
9185
9446
  __publicField(this, "time", 0);
9186
9447
  __publicField(this, "scanTimer", 0);
9187
9448
  __publicField(this, "disposed", false);
9449
+ __publicField(this, "stopContactHits", null);
9188
9450
  __publicField(this, "box");
9189
9451
  __publicField(this, "tmpQ");
9190
9452
  __publicField(this, "v1");
@@ -9260,6 +9522,7 @@ var Renderer = class {
9260
9522
  ...o.blastGroundTiles !== void 0 ? { blastGroundTiles: o.blastGroundTiles } : {},
9261
9523
  staticTopAt: (x, z, y, step) => this.staticTopAt(x, z, y, step),
9262
9524
  staticSolids: () => this.staticSolids(),
9525
+ staticUnsure: () => this.unsureSolids,
9263
9526
  gravity: this.gravity,
9264
9527
  scene: o.scene,
9265
9528
  maxAwake: o.maxAwakePieces ?? Infinity,
@@ -9276,6 +9539,8 @@ var Renderer = class {
9276
9539
  this.landingSound(b.objectId, point, clamp(speed / 10, 0.2, 1));
9277
9540
  }
9278
9541
  });
9542
+ if (o.rayBroadPhase) this.world.setRayBroadPhase(this.pieceSys.rayBroadPhase());
9543
+ if (o.contactHits) this.stopContactHits = this.pieceSys.contactHits(this.world, o.contactHits === true ? void 0 : o.contactHits);
9279
9544
  this.unsubscribe = this.world.on("*", (ev) => {
9280
9545
  if (ev.type === "explode") this.coverWhenWentOff.set(ev, this.coverAround(ev));
9281
9546
  if (this.queue.length < QUEUE_CAP || isStructuralEvent(ev)) this.queue.push(ev);
@@ -9451,7 +9716,8 @@ var Renderer = class {
9451
9716
  }
9452
9717
  if (total.isEmpty()) return { half: [0.25, 0.25, 0.25], center: new this.THREE.Vector3() };
9453
9718
  const size = total.getSize(new this.THREE.Vector3());
9454
- return { half: [Math.max(MIN_PIECE_HALF, size.x / 2), Math.max(MIN_PIECE_HALF, size.y / 2), Math.max(MIN_PIECE_HALF, size.z / 2)], center: total.getCenter(new this.THREE.Vector3()) };
9719
+ const least = minPieceHalf(this.o.physics);
9720
+ return { half: [Math.max(least, size.x / 2), Math.max(least, size.y / 2), Math.max(least, size.z / 2)], center: total.getCenter(new this.THREE.Vector3()) };
9455
9721
  }
9456
9722
  /**
9457
9723
  * A hosted body's boxes (`hostedSolids`: its damage zones) cut to the box of what its root draws, in the root's frame: the zones reach past the drawn body (17 cm each
@@ -10138,6 +10404,10 @@ var Renderer = class {
10138
10404
  const budget = { left: VERTICES_PER_UPDATE, incomplete: false, updated: this.measuredMeshes, workers: this.o.workers ?? null };
10139
10405
  try {
10140
10406
  this.measureEach(now, budget, out);
10407
+ this.unsureSolids.clear();
10408
+ for (const id of out.keys()) {
10409
+ if (this.solidStale.has(id) || this.solidCache.get(id)?.leftOut) this.unsureSolids.add(id);
10410
+ }
10141
10411
  } finally {
10142
10412
  this.measuredMeshes.clear();
10143
10413
  }
@@ -10160,14 +10430,26 @@ var Renderer = class {
10160
10430
  budget.incomplete = false;
10161
10431
  const solids = this.measureSolids(id, budget);
10162
10432
  if (budget.incomplete) this.solidStale.add(id);
10433
+ const leftOut = this.hasUnlistedPart(id);
10163
10434
  if (cached && sameSolids(cached.solids, solids)) {
10435
+ cached.leftOut = leftOut;
10164
10436
  out.set(id, cached.solids);
10165
10437
  continue;
10166
10438
  }
10167
- this.solidCache.set(id, { solids });
10439
+ this.solidCache.set(id, { solids, leftOut });
10168
10440
  out.set(id, solids);
10169
10441
  }
10170
10442
  }
10443
+ /** Whether a part the world still lets a ray hit is not in the object's list: a loose or hidden mesh (a lost part is no hit either). */
10444
+ hasUnlistedPart(id) {
10445
+ const b = this.bounds.get(id);
10446
+ if (!b) return false;
10447
+ for (const pv of b.parts.values()) {
10448
+ if (pv.gone !== "none") continue;
10449
+ if (pv.meshes.some((mv) => mv.loose || !this.visuals.shown(mv))) return true;
10450
+ }
10451
+ return false;
10452
+ }
10171
10453
  /**
10172
10454
  * Every fixed thing the object draws as what it collides as (`drawnSolidsOf`): a box where one fits the part, the triangles where not, a part of a merged mesh by its own
10173
10455
  * vertices, a mesh of any width. What is hidden, broken or loose is not drawn, so it is not here.
@@ -10965,6 +11247,7 @@ var Renderer = class {
10965
11247
  old.halfExtents = half;
10966
11248
  this.pieceSys.setCenter(old, center);
10967
11249
  old.mass = Math.max(MIN_PIECE_MASS_KG, this.massOf(objectId) - (old.massOffset ?? 0));
11250
+ old.apart = true;
10968
11251
  if (old.contacts || old.round) {
10969
11252
  this.fitSurface(b, old);
10970
11253
  if (!old.round) this.setContacts(b, old, this.meshesOf(b).filter((mv) => this.visuals.shown(mv)));
@@ -10972,6 +11255,7 @@ var Renderer = class {
10972
11255
  if (!this.splittingAtLoad) old.sleeping = false;
10973
11256
  } else if (kitOriginOf3(b.root)?.kind === "furniture" && !this.splittingAtLoad) {
10974
11257
  const piece = this.makePiece(objectId);
11258
+ piece.apart = true;
10975
11259
  this.tipIfTopHeavy(b, true);
10976
11260
  this.o.onLoosened?.(objectId, piece, "apart");
10977
11261
  }
@@ -11223,6 +11507,7 @@ var Renderer = class {
11223
11507
  }
11224
11508
  const piece = this.pieceSys.create(newId, group, half, center, this.massOf(newId), vel, ang);
11225
11509
  nb.piece = piece;
11510
+ piece.apart = true;
11226
11511
  this.fitSurface(nb, piece);
11227
11512
  this.fitPartBoxes(nb, piece);
11228
11513
  const resting = this.splittingAtLoad && this.pieceSys.restIfSupported(piece);
@@ -11248,6 +11533,7 @@ var Renderer = class {
11248
11533
  body.halfExtents = half;
11249
11534
  this.pieceSys.setCenter(body, center);
11250
11535
  body.mass = Math.max(MIN_PIECE_MASS_KG, this.massOf(objectId) - (body.massOffset ?? 0));
11536
+ body.apart = true;
11251
11537
  if (!structural) {
11252
11538
  this.fitSurface(b, body);
11253
11539
  if (!body.round) this.setContacts(b, body, left);
@@ -11279,6 +11565,7 @@ var Renderer = class {
11279
11565
  away = hull.length >= 3 ? inside.out : null;
11280
11566
  }
11281
11567
  const piece = this.makePiece(objectId);
11568
+ (b.piece ?? piece).apart = true;
11282
11569
  this.setContacts(b, b.piece ?? piece, left);
11283
11570
  const loose = b.piece;
11284
11571
  if (away && loose) {
@@ -11330,6 +11617,7 @@ var Renderer = class {
11330
11617
  }
11331
11618
  if (!this.standsOn(objectId, wholeBoxes) || this.standsOn(objectId, boxes)) return false;
11332
11619
  const piece = this.makePiece(objectId);
11620
+ (b.piece ?? piece).apart = true;
11333
11621
  this.setContacts(b, b.piece ?? piece, this.meshesOf(b).filter((mv) => this.visuals.shown(mv)));
11334
11622
  this.tipIfTopHeavy(b);
11335
11623
  this.o.onLoosened?.(objectId, piece, "apart");
@@ -11412,6 +11700,38 @@ var Renderer = class {
11412
11700
  }
11413
11701
  body.contacts = points.length > 0 && meshes.length <= CONTACT_MESHES ? points : void 0;
11414
11702
  body.partBoxes = boxes.length > 1 || boxes.length === 1 && isTurned(boxes[0]) ? boxes : void 0;
11703
+ body.massCentre = this.massCentreOf(b, body);
11704
+ }
11705
+ /** Where the weight of what is drawn of `b` is, from the middle of its box (`PieceBody.massCentre`): each part's box centre weighed by the part's mass. */
11706
+ massCentreOf(b, body) {
11707
+ if (b.parts.size < 2) return void 0;
11708
+ const inv = specFrameInverse(this.THREE, b.root);
11709
+ const m4 = new this.THREE.Matrix4();
11710
+ const lb = new this.THREE.Box3();
11711
+ const box = new this.THREE.Box3();
11712
+ const middle = new this.THREE.Vector3();
11713
+ let weight = 0;
11714
+ const sum = [0, 0, 0];
11715
+ for (const [partId, pv] of b.parts) {
11716
+ const mass = pv.gone === "none" ? this.world.part(b.id, partId)?.mass ?? 0 : 0;
11717
+ if (mass <= 0) continue;
11718
+ box.makeEmpty();
11719
+ for (const mv of pv.meshes) {
11720
+ if (!this.visuals.shown(mv)) continue;
11721
+ mv.mesh.updateWorldMatrix(true, false);
11722
+ this.visuals.localBox(mv, lb);
11723
+ if (!lb.isEmpty()) box.union(lb.applyMatrix4(m4.multiplyMatrices(inv, mv.mesh.matrixWorld)));
11724
+ }
11725
+ if (box.isEmpty()) continue;
11726
+ box.getCenter(middle);
11727
+ sum[0] += middle.x * mass;
11728
+ sum[1] += middle.y * mass;
11729
+ sum[2] += middle.z * mass;
11730
+ weight += mass;
11731
+ }
11732
+ if (weight <= 0) return void 0;
11733
+ const [cx, cy, cz] = body.localCenter;
11734
+ return [sum[0] / weight - cx, sum[1] / weight - cy, sum[2] / weight - cz];
11415
11735
  }
11416
11736
  /** `fitOrientedBoxes` of a ranged part's points, taken from what it gave before when the points and the triangles are the very same numbers. */
11417
11737
  fitRanged(mv, points) {
@@ -12156,6 +12476,8 @@ var Renderer = class {
12156
12476
  this.releaseWarmProbes();
12157
12477
  if (this.disposed) return;
12158
12478
  this.unsubscribe();
12479
+ if (this.o.rayBroadPhase) this.world.setRayBroadPhase(null);
12480
+ this.stopContactHits?.();
12159
12481
  this.clear();
12160
12482
  for (const id of [...this.bounds.keys()]) this.unbind(id);
12161
12483
  this.fragments.dispose();