@adatechnology/game-destruction-three 0.26.6 → 0.27.1

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/README.md CHANGED
@@ -268,6 +268,10 @@ in `@adatechnology/game-vfx` (`patchSpriteKinds(SPRITE_KINDS, { dust: { life: [1
268
268
  `DestructionRenderer`: `bind`, `unbind`, `makePiece`, `pieces`, `piece`, `impulse`, `update`, `emit`, `explode(point, energy, radius, { effect?, direction?, visual? })` (`visual: false` keeps only the shove and the sound, for a host that played the effect itself), `clear`, `restore`, `stats`, `dispose`.
269
269
  `clear()` removes fragments, decals, puddles and particles from the scene and restores every bound mesh; `dispose()` also unsubscribes from the world.
270
270
 
271
+ ## Engine hits and ray broad phase
272
+
273
+ Two options, off by default, for a renderer whose pieces are in a `PhysicsLoop`: `contactHits: true` turns the engine's strongest blow on each fixed drawn part into a `blunt` hit of the world (`hitPart`, energy about `impulse × closing speed / 2`, direction the other body was going, at most 32 parts a frame, blows under 30 N s ignored; `{ minImpulse, hitsMax, contactRadius }` to tune): a flying piece into a wall, a slab onto a crate, so a blast's cascade takes the next wall by itself. `rayBroadPhase: true` lets the engine's fixed bodies narrow the objects the world's rays read.
274
+
271
275
  ## Português
272
276
 
273
277
  Renderizador three.js para o `@adatechnology/game-destruction`. O núcleo decide o que cada golpe faz e devolve eventos; este pacote desenha: amassados
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { Fragment, Vec3, DebrisKind, HitResult, DestructionWorld, MaterialId, DestructibleSpec, MaterialDef, DestructionEvent, BlastOptions, DamageType } from '@adatechnology/game-destruction';
1
+ import { Vec3, Fragment, DebrisKind, HitResult, DestructionWorld, MaterialId, DestructibleSpec, MaterialDef, DestructionEvent, BlastOptions, DamageType } from '@adatechnology/game-destruction';
2
2
  export { Quat, Vec3 } from '@adatechnology/game-destruction';
3
3
  import { WorkerCoordinator, KitOrigin, DeferredQueue, DeferredQueueOptions, WarmUpProbes, BlastShoveOptions, TaskKind, Vec3 as Vec3$1 } from '@adatechnology/game-contracts';
4
4
  import { HeightPatch } from '@adatechnology/game-terrain';
5
5
  import { WorkerLike, WorkerScopeLike } from '@adatechnology/game-shapes';
6
6
  import * as THREE_NS from 'three';
7
- import { WorkBudgetOptions, PhysicsLoop, SeamWorld, PhysicsEngine, WorldDesc, Quat } from '@adatechnology/game-physics';
7
+ import { Quat, WorkBudgetOptions, PhysicsLoop, SeamWorld, PhysicsEngine, WorldDesc } from '@adatechnology/game-physics';
8
8
  export { DEFAULT_WORK_BUDGET_MS, isPhysicsLoop, physicsPieceCount } from '@adatechnology/game-physics';
9
9
  import { VfxWorld, SpriteKind } from '@adatechnology/game-vfx';
10
10
  import { LoopRecipe, SoundBank, SoundRecipe, Falloff, AudioEngine, VoiceGroup, SampleDefaults, SfxManifest } from '@adatechnology/game-audio';
@@ -114,6 +114,37 @@ declare const createCoordinatorGroundPort: (workers: WorkerCoordinator) => Groun
114
114
  /** The worker side: each job answered with its tile, every array transferred back (the job's own included, for the main thread's pool). */
115
115
  declare const installGroundWorker: (scope: WorkerScopeLike) => void;
116
116
 
117
+ /** The triangles of a fixed drawn part where no box fits it (world space, three indices a triangle). */
118
+ interface StaticMesh {
119
+ readonly vertices: Float32Array;
120
+ readonly indices: Uint32Array;
121
+ }
122
+ /** A fixed box of what does not move, as it is drawn: centre, half sizes and rotation (world). With `mesh` the part is those triangles, and the box is the one around them. */
123
+ interface StaticSolid {
124
+ readonly center: Vec3;
125
+ readonly half: Vec3;
126
+ readonly rotation: Quat;
127
+ readonly mesh?: StaticMesh;
128
+ /** Names the part across lists (a part measured again is the same part): without it, the place in the list. */
129
+ readonly key?: string;
130
+ /** The Coulomb friction and rolling resistance of the part's material; without it the body has the ground's. */
131
+ readonly friction?: {
132
+ readonly static: number;
133
+ readonly dynamic: number;
134
+ readonly rolling: number;
135
+ readonly rollingDamping?: number;
136
+ };
137
+ }
138
+
139
+ interface EngineImpactsOptions {
140
+ /** Blows under this impulse (N s) do nothing. Default 30. */
141
+ readonly minImpulse?: number;
142
+ /** Most fixed parts hit in a frame, in the order the engine met them. Default 32. */
143
+ readonly hitsMax?: number;
144
+ /** The radius (m) of the blunt contact. Default 0.1. */
145
+ readonly contactRadius?: number;
146
+ }
147
+
117
148
  /** What happens to debris that is far from the player and old (`FarDebrisOptions.action`): it sleeps where it lies, or shrinks away and leaves the scene. Debris at rest is already drawn merged by `settledBatches`. */
118
149
  type FarDebrisAction = 'sleep' | 'fade';
119
150
  interface FarDebrisOptions {
@@ -326,6 +357,10 @@ interface SoundDetail {
326
357
  interface RendererOptions {
327
358
  /** What steps the loose pieces; required, so a host never ends up on the kit's solver by forgetting it. See `PieceSystemOptions.physics`. */
328
359
  physics: PiecePhysics;
360
+ /** The engine's fixed bodies as the broad phase of the world's rays (`DestructionWorld.setRayBroadPhase`): shots, sweeps of the kit and blast sight lines skip objects the engine proves out of the way. Off by default. */
361
+ rayBroadPhase?: boolean;
362
+ /** A blow of the engine on a fixed part of the drawn world (a flying piece into a wall) becomes a `blunt` hit of the world, with the energy of the blow (`engine-impacts.ts`); `true` for the defaults. Needs the pieces in a `PhysicsLoop`. Off by default. */
363
+ contactHits?: boolean | EngineImpactsOptions;
329
364
  /** Scene that receives fragments, loose pieces, decals and particles. */
330
365
  scene: THREE_NS.Scene;
331
366
  world: DestructionWorld;
@@ -882,28 +917,6 @@ type BlastPacer = {
882
917
  */
883
918
  declare function createBlastPacer(options: BlastPacerOptions): BlastPacer;
884
919
 
885
- /** The triangles of a fixed drawn part where no box fits it (world space, three indices a triangle). */
886
- interface StaticMesh {
887
- readonly vertices: Float32Array;
888
- readonly indices: Uint32Array;
889
- }
890
- /** A fixed box of what does not move, as it is drawn: centre, half sizes and rotation (world). With `mesh` the part is those triangles, and the box is the one around them. */
891
- interface StaticSolid {
892
- readonly center: Vec3;
893
- readonly half: Vec3;
894
- readonly rotation: Quat;
895
- readonly mesh?: StaticMesh;
896
- /** Names the part across lists (a part measured again is the same part): without it, the place in the list. */
897
- readonly key?: string;
898
- /** The Coulomb friction and rolling resistance of the part's material; without it the body has the ground's. */
899
- readonly friction?: {
900
- readonly static: number;
901
- readonly dynamic: number;
902
- readonly rolling: number;
903
- readonly rollingDamping?: number;
904
- };
905
- }
906
-
907
920
  /**
908
921
  * One fixed drawn part to measure (`measureStaticPart`): plain arrays, so it crosses to a worker (`destruction.static-colliders`). The main thread reads the vertices,
909
922
  * the triangles and the mesh's world matrix (with three's own `decompose` of it); the measuring is here.
@@ -401,7 +401,8 @@ var GameDestructionThree = (() => {
401
401
  PIECE_BOXES: "destruction.piece-boxes",
402
402
  STATIC_COLLIDERS: "destruction.static-colliders",
403
403
  SHAPES_GENERATE: "shapes.generate",
404
- WORLD_REGION: "world.region"
404
+ WORLD_REGION: "world.region",
405
+ VEHICLE_HULL_PLAN: "vehicles.hull-plan"
405
406
  };
406
407
  var WORKER_KIND_DEFAULTS = {
407
408
  [WORKER_KIND_ID.GROUND_TILES]: { lane: "sim", priority: 300, latencyFrames: 2, late: "sync" },
@@ -409,7 +410,8 @@ var GameDestructionThree = (() => {
409
410
  [WORKER_KIND_ID.PIECE_BOXES]: { lane: "sim", priority: 200, latencyFrames: 2, late: "sync" },
410
411
  [WORKER_KIND_ID.STATIC_COLLIDERS]: { lane: "build", priority: 150, late: "sync" },
411
412
  [WORKER_KIND_ID.SHAPES_GENERATE]: { lane: "build", priority: 100, late: "sync" },
412
- [WORKER_KIND_ID.WORLD_REGION]: { lane: "background", priority: 10, latencyFrames: 10, late: "drop" }
413
+ [WORKER_KIND_ID.WORLD_REGION]: { lane: "background", priority: 10, latencyFrames: 10, late: "drop" },
414
+ [WORKER_KIND_ID.VEHICLE_HULL_PLAN]: { lane: "build", priority: 120, late: "keep-waiting" }
413
415
  };
414
416
  var WORKER_INPUT_LOST = "WorkerTaskInputLost";
415
417
  var isWorkerInputLost = (error) => error instanceof Error && error.name === WORKER_INPUT_LOST;
@@ -10430,6 +10432,73 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
10430
10432
  this.entries = state.map((entry) => ({ ...entry }));
10431
10433
  }
10432
10434
  };
10435
+ var GOLDEN_ANGLE = Math.PI * (1 + Math.sqrt(5));
10436
+ var DEFAULT_BODIES_MAX2 = 64;
10437
+ var createImpactReader = (loop, options) => {
10438
+ const world = loop.world;
10439
+ const capacity = options.bodiesMax ?? DEFAULT_BODIES_MAX2;
10440
+ let size = 4;
10441
+ while (size < capacity * 2) size *= 2;
10442
+ const mask = size - 1;
10443
+ const tableKey = new Int32Array(size);
10444
+ const tableStamp = new Uint32Array(size);
10445
+ const tableSlot = new Int32Array(size);
10446
+ let stamp = 0;
10447
+ let told = 0;
10448
+ const bodies = new Int32Array(capacity);
10449
+ const others = new Int32Array(capacity);
10450
+ const impulses = new Float32Array(capacity);
10451
+ const approaches = new Float32Array(capacity);
10452
+ const points = new Float32Array(capacity * 3);
10453
+ const normals = new Float32Array(capacity * 3);
10454
+ const impact3 = { body: 0, other: 0, impulse: 0, approach: 0, point: [0, 0, 0], normal: [0, 0, 0] };
10455
+ const keep = (c, body, other, row, sign) => {
10456
+ let at3 = Math.imul(body, 2654435761) & mask;
10457
+ while (tableStamp[at3] === stamp && tableKey[at3] !== body) at3 = at3 + 1 & mask;
10458
+ let slot;
10459
+ if (tableStamp[at3] === stamp) slot = tableSlot[at3];
10460
+ else {
10461
+ if (told >= capacity || options.accepts && !options.accepts(body)) return;
10462
+ slot = told++;
10463
+ tableStamp[at3] = stamp;
10464
+ tableKey[at3] = body;
10465
+ tableSlot[at3] = slot;
10466
+ impulses[slot] = 0;
10467
+ bodies[slot] = body;
10468
+ }
10469
+ if (c.impulse[row] <= impulses[slot]) return;
10470
+ others[slot] = other;
10471
+ impulses[slot] = c.impulse[row];
10472
+ approaches[slot] = c.approach[row];
10473
+ for (let k = 0; k < 3; k++) {
10474
+ points[slot * 3 + k] = c.point[row * 3 + k];
10475
+ normals[slot * 3 + k] = c.normal[row * 3 + k] * sign;
10476
+ }
10477
+ };
10478
+ const afterSteps = () => {
10479
+ const c = world.contacts;
10480
+ stamp++;
10481
+ told = 0;
10482
+ for (let row = 0; row < c.count; row++) {
10483
+ if (c.impulse[row] < options.minImpulse) continue;
10484
+ keep(c, c.a[row], c.b[row], row, 1);
10485
+ keep(c, c.b[row], c.a[row], row, -1);
10486
+ }
10487
+ const count = told;
10488
+ for (let slot = 0; slot < count; slot++) {
10489
+ impact3.body = bodies[slot];
10490
+ impact3.other = others[slot];
10491
+ impact3.impulse = impulses[slot];
10492
+ impact3.approach = approaches[slot];
10493
+ for (let k = 0; k < 3; k++) {
10494
+ impact3.point[k] = points[slot * 3 + k];
10495
+ impact3.normal[k] = normals[slot * 3 + k];
10496
+ }
10497
+ if (impact3.impulse > 0) options.onImpact(impact3);
10498
+ }
10499
+ };
10500
+ return loop.add({ afterSteps }, "contacts");
10501
+ };
10433
10502
 
10434
10503
  // src/blast-debris.ts
10435
10504
  var BLAST_DEBRIS_DEFAULTS = {
@@ -13423,6 +13492,11 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
13423
13492
  var sameShape = (a, b) => near(a.center, b.center) && near(a.half, b.half) && near(a.rotation, b.rotation) && sameMesh(a.mesh, b.mesh);
13424
13493
  var sameBox = (a, b) => a === b || sameShape(a, b) && sameFriction(a.friction, b.friction);
13425
13494
  var sameSolids = (a, b) => a.length === b.length && a.every((s, i) => sameBox(s, b[i]));
13495
+ var NONE = /* @__PURE__ */ new Set();
13496
+ var partOfKey = (key) => {
13497
+ const colon = key.lastIndexOf(":");
13498
+ return colon < 0 || !/^\d+$/.test(key.slice(colon + 1)) ? key : key.slice(0, colon);
13499
+ };
13426
13500
  var hasSize = (s) => s.half[0] > 0 && s.half[1] > 0 && s.half[2] > 0;
13427
13501
  var shapeOf = (s) => s.mesh ? { kind: "trimesh", vertices: s.mesh.vertices, indices: s.mesh.indices } : { kind: "box", half: s.half };
13428
13502
  var EngineStatics = class {
@@ -13434,32 +13508,55 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
13434
13508
  __publicField(this, "changed", /* @__PURE__ */ new Set());
13435
13509
  /** Every body it holds now: what a piece made or put is checked against (`EnginePieces.outOfStatics`; the ground has its own rule). */
13436
13510
  __publicField(this, "ids", /* @__PURE__ */ new Set());
13511
+ /** The object each held body is a part of (what a ray that meets the body says about the object). */
13512
+ __publicField(this, "ownerOf", /* @__PURE__ */ new Map());
13513
+ /** The part of the object each held body draws (the key without its mesh number): what a blow on the body hits. */
13514
+ __publicField(this, "partOf", /* @__PURE__ */ new Map());
13515
+ /** Changes whenever an answer of `covers` may have (an object came, went, or was fitted again). */
13516
+ __publicField(this, "coverageRevision", 0);
13517
+ __publicField(this, "unsure", NONE);
13437
13518
  }
13438
13519
  /** Whether the engine has a body for the object's drawn parts (what the kit's sweep need not set a piece back from). */
13439
13520
  has(objectId) {
13440
13521
  const f = this.bodies.get(objectId);
13441
13522
  return f !== void 0 && f.held.size > 0;
13442
13523
  }
13443
- lay(now) {
13524
+ /**
13525
+ * 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
13526
+ * world still tests (a loose or hidden one), is not covered: `lay`'s `unsure`.
13527
+ */
13528
+ covers(objectId) {
13529
+ const f = this.bodies.get(objectId);
13530
+ return f !== void 0 && f.held.size > 0 && f.waiting === 0 && !this.unsure.has(objectId);
13531
+ }
13532
+ /** `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`). */
13533
+ lay(now, unsure = NONE) {
13444
13534
  this.changed.clear();
13535
+ if (unsure.size !== this.unsure.size || [...unsure].some((id) => !this.unsure.has(id))) {
13536
+ this.unsure = new Set(unsure);
13537
+ this.coverageRevision++;
13538
+ }
13445
13539
  for (const [id, f] of this.bodies) {
13446
13540
  if (now.has(id)) continue;
13447
13541
  for (const h of f.held.values()) this.release(h, f.settled);
13448
13542
  this.bodies.delete(id);
13543
+ this.coverageRevision++;
13449
13544
  }
13450
13545
  const budget = { triangles: TRIANGLES_PER_UPDATE };
13451
13546
  for (const [id, solids] of now) {
13452
13547
  const f = this.bodies.get(id);
13453
13548
  if (f?.solids === solids && f.waiting === 0) continue;
13454
- const fixed = f ?? { solids, held: /* @__PURE__ */ new Map(), waiting: 0, settled: false };
13549
+ const fixed = f ?? { objectId: id, solids, held: /* @__PURE__ */ new Map(), waiting: 0, settled: false };
13455
13550
  this.bodies.set(id, fixed);
13456
13551
  fixed.solids = solids;
13552
+ this.coverageRevision++;
13457
13553
  this.fit(fixed, budget);
13458
13554
  }
13459
13555
  }
13460
13556
  clear() {
13461
13557
  for (const f of this.bodies.values()) for (const h of f.held.values()) this.drop(h.id);
13462
13558
  this.bodies.clear();
13559
+ this.coverageRevision++;
13463
13560
  this.changed.clear();
13464
13561
  }
13465
13562
  /** The object's parts of a list by name, the ones with a size only. */
@@ -13507,6 +13604,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
13507
13604
  const id = ids[i];
13508
13605
  f.held.set(x.key, { solid: x.solid, id });
13509
13606
  this.ids.add(id);
13607
+ this.ownerOf.set(id, f.objectId);
13608
+ this.partOf.set(id, partOfKey(x.key));
13510
13609
  this.changed.add(id);
13511
13610
  if (f.settled) this.wakeAround(x.solid);
13512
13611
  });
@@ -13537,6 +13636,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
13537
13636
  }
13538
13637
  drop(id) {
13539
13638
  this.ids.delete(id);
13639
+ this.ownerOf.delete(id);
13640
+ this.partOf.delete(id);
13540
13641
  this.world.removeBody(id);
13541
13642
  }
13542
13643
  wakeAround(s) {
@@ -13865,6 +13966,35 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
13865
13966
  return null;
13866
13967
  }
13867
13968
 
13969
+ // src/engine-impacts.ts
13970
+ var DEFAULT_MIN_IMPULSE = 30;
13971
+ var DEFAULT_HITS_MAX = 32;
13972
+ var DEFAULT_CONTACT_RADIUS = 0.1;
13973
+ var createEngineImpacts = (loop, statics, destruction, options = {}) => {
13974
+ const hitsMax = options.hitsMax ?? DEFAULT_HITS_MAX;
13975
+ const radius = options.contactRadius ?? DEFAULT_CONTACT_RADIUS;
13976
+ return createImpactReader(loop, {
13977
+ minImpulse: options.minImpulse ?? DEFAULT_MIN_IMPULSE,
13978
+ bodiesMax: hitsMax,
13979
+ accepts: (body) => statics.ownerOf.has(body),
13980
+ onImpact: (impact3) => {
13981
+ const object = statics.ownerOf.get(impact3.body);
13982
+ const part = statics.partOf.get(impact3.body);
13983
+ if (object === void 0 || part === void 0 || destruction.part(object, part) === null) return;
13984
+ const hit = {
13985
+ type: "blunt",
13986
+ point: [impact3.point[0], impact3.point[1], impact3.point[2]],
13987
+ direction: [-impact3.normal[0], -impact3.normal[1], -impact3.normal[2]],
13988
+ energy: 0.5 * impact3.impulse * impact3.approach,
13989
+ radius,
13990
+ part,
13991
+ source: "engine"
13992
+ };
13993
+ destruction.hitPart(object, part, hit);
13994
+ }
13995
+ });
13996
+ };
13997
+
13868
13998
  // src/engine-ground-heights.ts
13869
13999
  var changedHeights = (before, after2, size) => {
13870
14000
  let minX = size;
@@ -14031,6 +14161,55 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
14031
14161
  }
14032
14162
  };
14033
14163
 
14164
+ // src/engine-rays.ts
14165
+ var RAY_MARGIN = 0.25;
14166
+ var LONGEST_RAY = 2e3;
14167
+ var FIXED_ONLY = { layers: ["static"] };
14168
+ var createEngineRayBroadPhase = (world, statics) => {
14169
+ const hits = [];
14170
+ const inside = [];
14171
+ const met = /* @__PURE__ */ new Set();
14172
+ const metList = [];
14173
+ const from = [0, 0, 0];
14174
+ const toward2 = [0, 0, 0];
14175
+ return {
14176
+ begin(origin, direction, maxDistance) {
14177
+ if (!(maxDistance <= LONGEST_RAY)) return false;
14178
+ met.clear();
14179
+ metList.length = 0;
14180
+ from[0] = origin[0];
14181
+ from[1] = origin[1];
14182
+ from[2] = origin[2];
14183
+ toward2[0] = direction[0];
14184
+ toward2[1] = direction[1];
14185
+ toward2[2] = direction[2];
14186
+ const count = world.sphereCastAll(from, toward2, maxDistance, RAY_MARGIN, hits, FIXED_ONLY);
14187
+ for (let i = 0; i < count; i++) {
14188
+ const owner = statics.ownerOf.get(hits[i].body);
14189
+ if (owner !== void 0 && !met.has(owner)) {
14190
+ met.add(owner);
14191
+ metList.push(owner);
14192
+ }
14193
+ }
14194
+ const around = world.overlapSphere(from, RAY_MARGIN, inside, FIXED_ONLY);
14195
+ for (let i = 0; i < around; i++) {
14196
+ const owner = statics.ownerOf.get(inside[i]);
14197
+ if (owner !== void 0 && !met.has(owner)) {
14198
+ met.add(owner);
14199
+ metList.push(owner);
14200
+ }
14201
+ }
14202
+ return true;
14203
+ },
14204
+ mayMeet: (objectId) => !statics.covers(objectId) || met.has(objectId),
14205
+ candidates: {
14206
+ met: () => metList,
14207
+ covers: (objectId) => statics.covers(objectId),
14208
+ revision: () => statics.coverageRevision
14209
+ }
14210
+ };
14211
+ };
14212
+
14034
14213
  // src/merge-flush-boxes.ts
14035
14214
  var FLUSH = 1e-4;
14036
14215
  var sameTurn = (a, b) => {
@@ -14207,6 +14386,10 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
14207
14386
  this.schedule = o.groundWorker ? new GroundSchedule(o.groundWorker, Math.max(1, Math.round(o.groundWorkerFrames ?? GROUND_WORKER_FRAMES))) : null;
14208
14387
  if (this.schedule) this.warmGround(this.schedule);
14209
14388
  }
14389
+ /** The fixed bodies as a broad phase for the destruction world's rays (`engine-rays.ts`). */
14390
+ rayBroadPhase() {
14391
+ return createEngineRayBroadPhase(this.world, this.statics);
14392
+ }
14210
14393
  /** 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. */
14211
14394
  warmGround(schedule) {
14212
14395
  const warmGround = (x, z) => 0.3 * x - 0.2 * z + 0.15 * Math.floor(x / 0.37) + 0.05 * Math.sin(3 * z);
@@ -15297,7 +15480,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
15297
15480
  /** The host's fixed boxes, one static body per object (`EngineStatics`). */
15298
15481
  layStatics() {
15299
15482
  const now = this.o.staticSolids?.();
15300
- if (now) this.statics.lay(now);
15483
+ if (now) this.statics.lay(now, this.o.staticUnsure?.());
15301
15484
  }
15302
15485
  keepApart(apart2) {
15303
15486
  for (const key of this.ignored) {
@@ -15737,6 +15920,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
15737
15920
  ...o.blastGroundTiles !== void 0 ? { blastTiles: o.blastGroundTiles } : {},
15738
15921
  gravity: o.gravity,
15739
15922
  staticSolids: o.staticSolids,
15923
+ staticUnsure: o.staticUnsure,
15740
15924
  sweep: o.sweep,
15741
15925
  onSlam: o.onSlam,
15742
15926
  onKnock: o.onKnock,
@@ -15748,6 +15932,14 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
15748
15932
  this.groundWorker = o.groundWorker ?? null;
15749
15933
  if (resolved && !resolved.stepsItself) this.joinLoop(resolved.loop, this.engine);
15750
15934
  }
15935
+ /** 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. */
15936
+ contactHits(destruction, options) {
15937
+ return this.engine && this.loop ? createEngineImpacts(this.loop, this.engine.statics, destruction, options) : null;
15938
+ }
15939
+ /** The engine's fixed bodies as the broad phase of the world's rays, or null when the pieces are not in the engine. */
15940
+ rayBroadPhase() {
15941
+ return this.engine?.rayBroadPhase() ?? null;
15942
+ }
15751
15943
  /**
15752
15944
  * 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
15753
15945
  * 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`).
@@ -21367,6 +21559,20 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
21367
21559
  let time = 0;
21368
21560
  let counter = 0;
21369
21561
  const objects = /* @__PURE__ */ new Map();
21562
+ const slots = /* @__PURE__ */ new Map();
21563
+ let slotCounter = 0;
21564
+ let objectsRevision = 0;
21565
+ const putObject = (id, object) => {
21566
+ if (!objects.has(id)) slots.set(id, ++slotCounter);
21567
+ objectsRevision++;
21568
+ objects.set(id, object);
21569
+ };
21570
+ const dropObject = (id) => {
21571
+ if (objects.delete(id)) {
21572
+ slots.delete(id);
21573
+ objectsRevision++;
21574
+ }
21575
+ };
21370
21576
  const listeners = /* @__PURE__ */ new Map();
21371
21577
  let cur = [];
21372
21578
  const blasts = [];
@@ -23257,18 +23463,52 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
23257
23463
  if (o.soil?.sets.size) restCarry.soilSets = Object.fromEntries(o.soil.sets);
23258
23464
  const rest = build2(sub3(inOld), o.id, o.soil ? o.base.pos : pos, o.soil ? o.base.rot : rot, restCarry);
23259
23465
  dirtyHosted.delete(o);
23260
- objects.set(o.id, rest);
23261
- for (const [nid, object] of fresh) objects.set(nid, object);
23466
+ putObject(o.id, rest);
23467
+ for (const [nid, object] of fresh) putObject(nid, object);
23262
23468
  return fresh.map(([nid]) => nid);
23263
23469
  };
23470
+ let rayBroad = null;
23471
+ let uncovered = [];
23472
+ let uncoveredFor = { hook: null, coverage: -1, objects: -1 };
23473
+ const metObjects = [];
23474
+ const rayObjects = [];
23475
+ const candidatesOf = (hook) => {
23476
+ const asked = hook.candidates;
23477
+ if (!asked) return null;
23478
+ const coverage = asked.revision();
23479
+ if (uncoveredFor.hook !== hook || uncoveredFor.coverage !== coverage || uncoveredFor.objects !== objectsRevision) {
23480
+ uncovered = [];
23481
+ for (const o of objects.values()) if (!asked.covers(o.id)) uncovered.push(o);
23482
+ uncoveredFor = { hook, coverage, objects: objectsRevision };
23483
+ }
23484
+ if (uncovered.length * 2 > objects.size) return null;
23485
+ metObjects.length = 0;
23486
+ for (const id of asked.met()) {
23487
+ const o = objects.get(id);
23488
+ if (o && asked.covers(id)) metObjects.push(o);
23489
+ }
23490
+ metObjects.sort((a, b) => slots.get(a.id) - slots.get(b.id));
23491
+ rayObjects.length = 0;
23492
+ let m = 0;
23493
+ let u = 0;
23494
+ while (m < metObjects.length || u < uncovered.length) {
23495
+ const takeMet = u >= uncovered.length || m < metObjects.length && slots.get(metObjects[m].id) < slots.get(uncovered[u].id);
23496
+ rayObjects.push(takeMet ? metObjects[m++] : uncovered[u++]);
23497
+ }
23498
+ return rayObjects;
23499
+ };
23264
23500
  const raycastInternal = (origin, dir, maxDist, ignore, worldOnly = false, precise = false, skip = {}, scope) => {
23265
23501
  const d = vec.normalize(dir);
23502
+ const asked = rayBroad && !scope && rayBroad.begin(origin, d, maxDist) ? rayBroad : null;
23503
+ const candidates = asked ? candidatesOf(asked) : null;
23504
+ const outside = candidates ? null : asked;
23266
23505
  const minRadius = skip.minObjectRadius ?? 0;
23267
23506
  let best = null;
23268
23507
  const counts = sweepCounts;
23269
- for (const o of scope ? scope.objects : objects.values()) {
23508
+ for (const o of scope ? scope.objects : candidates ?? objects.values()) {
23270
23509
  if (counts) counts.objectVisits++;
23271
23510
  if (skip.skipLoose && o.loose || o.br < minRadius) continue;
23511
+ if (outside && !outside.mayMeet(o.id)) continue;
23272
23512
  if (raySphereMiss(origin, d, worldCentreOf(o), o.br, best ? Math.min(maxDist, best.distance) : maxDist)) continue;
23273
23513
  const qi = quat.conjugate(o.st.rotation);
23274
23514
  const lo = rotateVec(qi, vec.sub(origin, o.st.position));
@@ -26021,7 +26261,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
26021
26261
  finishExplosions();
26022
26262
  const id = opts.id ?? nextId();
26023
26263
  if (taken(id)) throw new Error(`object "${id}" already exists`);
26024
- objects.set(id, build2(resolveSpec(spec), id, opts.position ?? [0, 0, 0], opts.rotation ?? [0, 0, 0, 1]));
26264
+ putObject(id, build2(resolveSpec(spec), id, opts.position ?? [0, 0, 0], opts.rotation ?? [0, 0, 0, 1]));
26025
26265
  return id;
26026
26266
  },
26027
26267
  register(impl, opts = {}) {
@@ -26056,7 +26296,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
26056
26296
  impls.get(id)?.impl.dispose?.();
26057
26297
  const existing = objects.get(id);
26058
26298
  if (existing) dirtyHosted.delete(existing);
26059
- objects.delete(id);
26299
+ dropObject(id);
26060
26300
  impls.delete(id);
26061
26301
  },
26062
26302
  has: (id) => taken(id),
@@ -26175,6 +26415,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
26175
26415
  },
26176
26416
  beginExplosion,
26177
26417
  cancelExplosions,
26418
+ setRayBroadPhase(broadPhase2) {
26419
+ rayBroad = broadPhase2;
26420
+ },
26178
26421
  groundLoss(loss) {
26179
26422
  if (!(loss.radius > 0) || !(loss.depth > 0) || !Number.isFinite(loss.x) || !Number.isFinite(loss.z)) return;
26180
26423
  pendingLosses.push({ ...loss });
@@ -26429,7 +26672,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
26429
26672
  }
26430
26673
  const o = getObj(id);
26431
26674
  dirtyHosted.delete(o);
26432
- objects.set(id, build2(o.spec, id, o.base.pos, o.base.rot));
26675
+ putObject(id, build2(o.spec, id, o.base.pos, o.base.rot));
26433
26676
  },
26434
26677
  on(type, fn) {
26435
26678
  const known = listeners.get(type) ?? [];
@@ -26458,17 +26701,19 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
26458
26701
  finishExplosions();
26459
26702
  const existing = objects.get(id);
26460
26703
  if (existing) dirtyHosted.delete(existing);
26461
- objects.set(id, buildFromEntry(entry, id));
26704
+ putObject(id, buildFromEntry(entry, id));
26462
26705
  },
26463
26706
  load(snap) {
26464
26707
  cancelExplosions();
26465
26708
  if (snap.version !== 1) throw new Error(`unsupported snapshot version ${String(snap.version)}`);
26466
26709
  dirtyHosted.clear();
26467
26710
  objects.clear();
26711
+ slots.clear();
26712
+ objectsRevision++;
26468
26713
  time = snap.time;
26469
26714
  rng.set(snap.rng);
26470
26715
  counter = snap.counter ?? 0;
26471
- for (const e of snap.objects) objects.set(e.id, buildFromEntry(e, e.id));
26716
+ for (const e of snap.objects) putObject(e.id, buildFromEntry(e, e.id));
26472
26717
  for (const e of snap.impls ?? []) {
26473
26718
  const im = impls.get(e.id);
26474
26719
  if (!im) continue;
@@ -29048,6 +29293,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29048
29293
  __publicField(this, "staticBoxes", /* @__PURE__ */ new Map());
29049
29294
  /** `staticSolids` per object, kept until `staticNow` measures the object again for a reason. */
29050
29295
  __publicField(this, "solidCache", /* @__PURE__ */ new Map());
29296
+ /** 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. */
29297
+ __publicField(this, "unsureSolids", /* @__PURE__ */ new Set());
29051
29298
  /** The objects `staticNow` measured again for a reason (an event, a moved root, boxes that changed): their `staticSolids` are measured again too. */
29052
29299
  __publicField(this, "solidStale", /* @__PURE__ */ new Set());
29053
29300
  /** The world matrix of each root when `staticNow` last measured it. */
@@ -29178,6 +29425,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29178
29425
  __publicField(this, "time", 0);
29179
29426
  __publicField(this, "scanTimer", 0);
29180
29427
  __publicField(this, "disposed", false);
29428
+ __publicField(this, "stopContactHits", null);
29181
29429
  __publicField(this, "box");
29182
29430
  __publicField(this, "tmpQ");
29183
29431
  __publicField(this, "v1");
@@ -29253,6 +29501,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29253
29501
  ...o.blastGroundTiles !== void 0 ? { blastGroundTiles: o.blastGroundTiles } : {},
29254
29502
  staticTopAt: (x, z, y, step) => this.staticTopAt(x, z, y, step),
29255
29503
  staticSolids: () => this.staticSolids(),
29504
+ staticUnsure: () => this.unsureSolids,
29256
29505
  gravity: this.gravity,
29257
29506
  scene: o.scene,
29258
29507
  maxAwake: o.maxAwakePieces ?? Infinity,
@@ -29269,6 +29518,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29269
29518
  this.landingSound(b.objectId, point, clamp6(speed / 10, 0.2, 1));
29270
29519
  }
29271
29520
  });
29521
+ if (o.rayBroadPhase) this.world.setRayBroadPhase(this.pieceSys.rayBroadPhase());
29522
+ if (o.contactHits) this.stopContactHits = this.pieceSys.contactHits(this.world, o.contactHits === true ? void 0 : o.contactHits);
29272
29523
  this.unsubscribe = this.world.on("*", (ev) => {
29273
29524
  if (ev.type === "explode") this.coverWhenWentOff.set(ev, this.coverAround(ev));
29274
29525
  if (this.queue.length < QUEUE_CAP || isStructuralEvent(ev)) this.queue.push(ev);
@@ -30132,6 +30383,10 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
30132
30383
  const budget = { left: VERTICES_PER_UPDATE, incomplete: false, updated: this.measuredMeshes, workers: this.o.workers ?? null };
30133
30384
  try {
30134
30385
  this.measureEach(now, budget, out);
30386
+ this.unsureSolids.clear();
30387
+ for (const id of out.keys()) {
30388
+ if (this.solidStale.has(id) || this.solidCache.get(id)?.leftOut) this.unsureSolids.add(id);
30389
+ }
30135
30390
  } finally {
30136
30391
  this.measuredMeshes.clear();
30137
30392
  }
@@ -30154,14 +30409,26 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
30154
30409
  budget.incomplete = false;
30155
30410
  const solids = this.measureSolids(id, budget);
30156
30411
  if (budget.incomplete) this.solidStale.add(id);
30412
+ const leftOut = this.hasUnlistedPart(id);
30157
30413
  if (cached && sameSolids(cached.solids, solids)) {
30414
+ cached.leftOut = leftOut;
30158
30415
  out.set(id, cached.solids);
30159
30416
  continue;
30160
30417
  }
30161
- this.solidCache.set(id, { solids });
30418
+ this.solidCache.set(id, { solids, leftOut });
30162
30419
  out.set(id, solids);
30163
30420
  }
30164
30421
  }
30422
+ /** 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). */
30423
+ hasUnlistedPart(id) {
30424
+ const b = this.bounds.get(id);
30425
+ if (!b) return false;
30426
+ for (const pv of b.parts.values()) {
30427
+ if (pv.gone !== "none") continue;
30428
+ if (pv.meshes.some((mv) => mv.loose || !this.visuals.shown(mv))) return true;
30429
+ }
30430
+ return false;
30431
+ }
30165
30432
  /**
30166
30433
  * 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
30167
30434
  * vertices, a mesh of any width. What is hidden, broken or loose is not drawn, so it is not here.
@@ -32188,6 +32455,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
32188
32455
  this.releaseWarmProbes();
32189
32456
  if (this.disposed) return;
32190
32457
  this.unsubscribe();
32458
+ if (this.o.rayBroadPhase) this.world.setRayBroadPhase(null);
32459
+ this.stopContactHits?.();
32191
32460
  this.clear();
32192
32461
  for (const id of [...this.bounds.keys()]) this.unbind(id);
32193
32462
  this.fragments.dispose();