@adatechnology/game-crowd 0.7.1 → 0.8.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/README.md CHANGED
@@ -125,6 +125,12 @@ crowd.stats.physics // falls by cause, fallsBeyondBlast, climbers, moundMax, thr
125
125
  - **Far band (R1):** no pairs. Every 12th step a coarse grid of 2 m counts the standing walkers of band R1 per cell; above 4 bodies the wanted speed is `4 / bodies` and the field is `(bodies − 4) · 150` N, which the same balance rule reads (`physics.density`, needs `balance`). A body that falls there lies without entering the mound, and joins it when it comes into R0.
126
126
  - **Player pressure:** `playerPressure` reports the pressure of the horde on the target through `knock` and `hurt` (off in the package; a game turns it on).
127
127
 
128
+ ### The crowd in the physics engine
129
+
130
+ `createAgentBodies(loop, crowd, { radius })` gives each agent of the store a kinematic capsule on the `agent` layer, moved in the loop's `crowd` phase before every fixed step: game-crowd moves, the engine only lets the agents push what they meet (a door leaf, a prop, debris); agents meet neither each other nor the ground (`LAYER_PAIRS`). Capsule `i` follows agent `i`, also after a removal moved the last agent into `i`. Nothing the engine does is written back into the store, so `state-hash` and the team goldens are the same with or without it.
131
+ `createDoorBodies(loop, doors, { leafMass, breakImpulse })` hangs each closed door on a hinge: a dynamic leaf on the `prop` layer with a `breakImpulse`; when the agents tear the hinge off, the crowd's door is `broken` through `doors.hit` (grid opened, events fired). A door that opens or breaks by another cause loses its leaf, and one shut again or added gets one. The corpses go through `createCorpseBodies` of `game-physics` (`onSettled` → `relocateCorpse`).
132
+ Cost (spec 008, 1 000 agents and a door, `pnpm --filter @adatechnology/game-crowd test:cost`): median 0.34 ms, p99 0.5 ms per fixed step.
133
+
128
134
  ### The contact and the pressure in a worker
129
135
 
130
136
  `physics.worker` is `'off'` by default (the step runs where it always did). `'auto'` moves the contact and the pressure to a worker when one can be made and stays in the step when it cannot; `'on'` throws instead of staying.
@@ -150,3 +156,7 @@ Measured with `bench/dense-update.mjs` (node, 2000 agents pressed against a wall
150
156
 
151
157
  The drawing and the test area are in `@adatechnology/game-crowd-three`. The game's multi-floor houses (`ANDARES`) and the roof (`ROOF`) are not ported: the crowd walks one
152
158
  ground grid (`floor` is kept on each agent for a game that adds floors).
159
+
160
+ ## Knock down by a car (`knockDown`, spec 008 T6.26)
161
+
162
+ `crowd.knockDown(i, { x, z })` shoves only agent `i` and asks the balance to make it fall (cause `SHOVE`): it lies, slides with the push and gets up in the `game-crowd` time. Without `physics.balance` it falls back to a one-second stun. It is not the area `blast`. `createRunOver` (`game-vehicles-driving`) calls it in the knock band.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { CorpseLedger } from '@adatechnology/game-characters';
2
2
  import { BlastShoveOptions, WorkerCoordinator, NavObstacleSource, ResidentKind, SimModule } from '@adatechnology/game-contracts';
3
+ import { BodyId, PhysicsLoop } from '@adatechnology/game-physics';
3
4
 
4
5
  var numbers = {
5
6
  capacity: 6000,
@@ -1148,6 +1149,11 @@ type Crowd = {
1148
1149
  readonly thrown: ThrownPool;
1149
1150
  /** A blast: queued, and resolved at the start of the next step in one pass over the agents. Without `physics` it only hurts, kills and stuns. */
1150
1151
  blast(blast: CrowdBlast): void;
1152
+ /** Knocks agent `i` alone down at `velocity` m/s (no area): `BALANCE.FALLEN`, slides on the push, gets up; stunned without balance. */
1153
+ knockDown(i: number, velocity: {
1154
+ readonly x: number;
1155
+ readonly z: number;
1156
+ }): void;
1151
1157
  /** How many agents are steps of a pile now. */
1152
1158
  pileCount(): number;
1153
1159
  readonly trail: {
@@ -1205,6 +1211,17 @@ type Crowd = {
1205
1211
  */
1206
1212
  declare function createCrowd(options: CrowdOptions): Crowd;
1207
1213
 
1214
+ /**
1215
+ * A corpse lies elsewhere than where it died (a blast pushed it): the ledger takes the new place and so does the mound, which is made again from it every fixed step, so
1216
+ * the horde climbs it where the body is drawn and where the engine has it. Call it inside the fixed step (the physics applier's `onSettled`); false when no corpse has that id.
1217
+ */
1218
+ declare const relocateCorpse: (crowd: Pick<Crowd, "corpses">, move: {
1219
+ readonly id: number;
1220
+ readonly x: number;
1221
+ readonly z: number;
1222
+ readonly yaw: number;
1223
+ }) => boolean;
1224
+
1208
1225
  type NavObstacleBindingOptions = {
1209
1226
  /** Height (m) from which a box is a solid instead of a low wall (default 1.2). */
1210
1227
  readonly lowWallMaxHeight?: number;
@@ -1788,4 +1805,49 @@ type WorkerPort = {
1788
1805
  */
1789
1806
  declare function attachPhysicsWorker(port: WorkerPort): void;
1790
1807
 
1791
- export { AGENT_FIELDS, BALANCE, CELL, CIVILIAN_DEFAULTS, CROWD_DEFAULTS, CROWD_PHYSICS_DEFAULTS, type Civilian, type CivilianBuilding, type CivilianEventMap, type CivilianEventName, type CivilianNumbers, type CivilianOptions, type CivilianSpec, type CivilianState, type Civilians, type ContactParams, type ContactResult, type ContactView, type Corpse, type Crowd, type CrowdAge, type CrowdBalanceOptions, type CrowdBalanceTraits, type CrowdBand, type CrowdBlast, type CrowdBlastOptions, type CrowdCaliber, type CrowdContactOptions, type CrowdDamageResult, type CrowdDensityOptions, type CrowdEffectId, type CrowdEventMap, type CrowdEventName, type CrowdHit, type CrowdMessageId, type CrowdMoundOptions, type CrowdMovable, type CrowdNumbers, type CrowdOptions, type CrowdOutfit, type CrowdPack, type CrowdPersonalityOptions, type CrowdPhysicsInit, type CrowdPhysicsOptions, type CrowdPlayerPressureOptions, type CrowdPlugin, type CrowdPressureOptions, type CrowdShove, type CrowdSoundId, type CrowdStore, type CrowdTarget, type CrowdThrownOptions, type CrowdTraits, type CrowdType, type CrowdUpdateContext, type CrowdView, DOOR_DEFAULTS, type Door, type DoorEventMap, type DoorEventName, type DoorNumbers, type Doors, FALL_CAUSE, type Flock, type FlockBird, type FlockMode, type FlockOptions, HERD_DEFAULTS, HERD_ROLES, HORDE_COMMAND, HORDE_SIM_ID, type Herd, type HerdAnimal, type HerdAnimalSpec, type HerdEventMap, type HerdEventName, type HerdNumbers, type HerdOptions, type HerdRole, type HordeSimInit, type HordeThreadLike, type InfectionBinding, type InfectionBindingOptions, type InfectionModelLike, MISSING, type MigrationOptions, type MovableContacts, type MovableHit, type NavGrid, type NavGridOptions, type NavObstacleBinding, type NavObstacleBindingOptions, type OffloadTransport, type PhysicsStats, type PhysicsWorkerFactory, type PhysicsWorkerHandle, type PlayerCrowdLike, type Region, type ResolvedPhysics, STATE, type ThrownPool, type WorkerPort, attachPhysicsWorker, bindInfection, bindNavObstacles, carrionCenter, contactStep, createCivilians, createContactView, createCoordinatorRunner, createCrowd, createDoors, createFlock, createHerd, createHordeCrowd, createMovableContacts, createNavGrid, createRng, createStore, crowdPhysicsKind, hordeSimModule, hordeSnapshotBytes, hordeSnapshotLayout, identityOf, mix32, readHordeSnapshot, resolvePhysics, unit, walksInto, writeHordeSnapshot };
1808
+ type AgentBodiesOptions = {
1809
+ /** Radius (m) of the capsule every agent gets. Default 0.25. */
1810
+ readonly radius?: number;
1811
+ /** Height (m) of an agent whose `store.height` is 0. Default 1.7. */
1812
+ readonly fallbackHeight?: number;
1813
+ };
1814
+ type AgentBodies = {
1815
+ /** Kinematic capsules alive in the engine: one per agent in the store. */
1816
+ readonly count: number;
1817
+ /** The capsule of agent `i`, or undefined past the store's `n`. */
1818
+ bodyOf(i: number): BodyId | undefined;
1819
+ /** Takes the capsules out of the world and the phase out of the loop. */
1820
+ dispose(): void;
1821
+ };
1822
+ /**
1823
+ * Every agent of the crowd as a kinematic capsule on the `agent` layer: game-crowd moves them, the engine only lets them push what they meet (a door leaf, a prop, debris).
1824
+ * Capsule `i` follows agent `i` of the store, whichever agent that is after a removal moved the last one into its place; it moves in the loop's `crowd` phase, before each fixed step.
1825
+ * An agent that takes a vacancy (a removal's last agent, a spawn) is placed there with `setPose`: a kinematic move across the world would push whatever is on the way.
1826
+ */
1827
+ declare const createAgentBodies: (loop: PhysicsLoop, crowd: Pick<Crowd, "on"> & {
1828
+ readonly store: CrowdStore;
1829
+ }, options?: AgentBodiesOptions) => AgentBodies;
1830
+
1831
+ type DoorBodiesOptions = {
1832
+ /** Mass (kg) of a leaf. Default 40. */
1833
+ readonly leafMass?: number;
1834
+ /** The impulse (N s) in one step that tears the hinge off: past it the door gives way. Default 40. */
1835
+ readonly breakImpulse?: number;
1836
+ /** Height (m) of a leaf. Default `DOOR_DEFAULTS.height`. */
1837
+ readonly height?: number;
1838
+ };
1839
+ type DoorBodies = {
1840
+ /** The leaf of the door, while it is closed and on its hinge. */
1841
+ leafOf(index: number): BodyId | undefined;
1842
+ /** Takes the phase out of the loop and the frames and leaves out of the world. */
1843
+ dispose(): void;
1844
+ };
1845
+ /**
1846
+ * A closed door as a leaf on a hinge that gives way: a dynamic box on the `prop` layer on a frame post, the hinge limited to a hair of play and with a `breakImpulse`.
1847
+ * The agents (kinematic capsules) press on it; when the hinge breaks the door is `broken` for the crowd (`doors.hit` with all its hit points: the grid opens, the events fire).
1848
+ * A door that opens or breaks by another cause (`doors.set`, the pressure of the field) loses its leaf at the next frame, and one shut again or added gets a leaf.
1849
+ * A leaf torn off by a hinge that broke stays in the world as a prop until that door hangs a new leaf, or until `dispose`.
1850
+ */
1851
+ declare const createDoorBodies: (loop: PhysicsLoop, doors: Doors, options?: DoorBodiesOptions) => DoorBodies;
1852
+
1853
+ export { AGENT_FIELDS, type AgentBodies, type AgentBodiesOptions, BALANCE, CELL, CIVILIAN_DEFAULTS, CROWD_DEFAULTS, CROWD_PHYSICS_DEFAULTS, type Civilian, type CivilianBuilding, type CivilianEventMap, type CivilianEventName, type CivilianNumbers, type CivilianOptions, type CivilianSpec, type CivilianState, type Civilians, type ContactParams, type ContactResult, type ContactView, type Corpse, type Crowd, type CrowdAge, type CrowdBalanceOptions, type CrowdBalanceTraits, type CrowdBand, type CrowdBlast, type CrowdBlastOptions, type CrowdCaliber, type CrowdContactOptions, type CrowdDamageResult, type CrowdDensityOptions, type CrowdEffectId, type CrowdEventMap, type CrowdEventName, type CrowdHit, type CrowdMessageId, type CrowdMoundOptions, type CrowdMovable, type CrowdNumbers, type CrowdOptions, type CrowdOutfit, type CrowdPack, type CrowdPersonalityOptions, type CrowdPhysicsInit, type CrowdPhysicsOptions, type CrowdPlayerPressureOptions, type CrowdPlugin, type CrowdPressureOptions, type CrowdShove, type CrowdSoundId, type CrowdStore, type CrowdTarget, type CrowdThrownOptions, type CrowdTraits, type CrowdType, type CrowdUpdateContext, type CrowdView, DOOR_DEFAULTS, type Door, type DoorBodies, type DoorBodiesOptions, type DoorEventMap, type DoorEventName, type DoorNumbers, type Doors, FALL_CAUSE, type Flock, type FlockBird, type FlockMode, type FlockOptions, HERD_DEFAULTS, HERD_ROLES, HORDE_COMMAND, HORDE_SIM_ID, type Herd, type HerdAnimal, type HerdAnimalSpec, type HerdEventMap, type HerdEventName, type HerdNumbers, type HerdOptions, type HerdRole, type HordeSimInit, type HordeThreadLike, type InfectionBinding, type InfectionBindingOptions, type InfectionModelLike, MISSING, type MigrationOptions, type MovableContacts, type MovableHit, type NavGrid, type NavGridOptions, type NavObstacleBinding, type NavObstacleBindingOptions, type OffloadTransport, type PhysicsStats, type PhysicsWorkerFactory, type PhysicsWorkerHandle, type PlayerCrowdLike, type Region, type ResolvedPhysics, STATE, type ThrownPool, type WorkerPort, attachPhysicsWorker, bindInfection, bindNavObstacles, carrionCenter, contactStep, createAgentBodies, createCivilians, createContactView, createCoordinatorRunner, createCrowd, createDoorBodies, createDoors, createFlock, createHerd, createHordeCrowd, createMovableContacts, createNavGrid, createRng, createStore, crowdPhysicsKind, hordeSimModule, hordeSnapshotBytes, hordeSnapshotLayout, identityOf, mix32, readHordeSnapshot, relocateCorpse, resolvePhysics, unit, walksInto, writeHordeSnapshot };
@@ -40,10 +40,12 @@ var GameCrowd = (() => {
40
40
  bindNavObstacles: () => bindNavObstacles,
41
41
  carrionCenter: () => carrionCenter,
42
42
  contactStep: () => contactStep,
43
+ createAgentBodies: () => createAgentBodies,
43
44
  createCivilians: () => createCivilians,
44
45
  createContactView: () => createContactView,
45
46
  createCoordinatorRunner: () => createCoordinatorRunner,
46
47
  createCrowd: () => createCrowd,
48
+ createDoorBodies: () => createDoorBodies,
47
49
  createDoors: () => createDoors,
48
50
  createFlock: () => createFlock,
49
51
  createHerd: () => createHerd,
@@ -59,6 +61,7 @@ var GameCrowd = (() => {
59
61
  identityOf: () => identityOf,
60
62
  mix32: () => mix32,
61
63
  readHordeSnapshot: () => readHordeSnapshot,
64
+ relocateCorpse: () => relocateCorpse,
62
65
  resolvePhysics: () => resolvePhysics,
63
66
  unit: () => unit,
64
67
  walksInto: () => walksInto,
@@ -190,7 +193,8 @@ var GameCrowd = (() => {
190
193
  PIECE_BOXES: "destruction.piece-boxes",
191
194
  STATIC_COLLIDERS: "destruction.static-colliders",
192
195
  SHAPES_GENERATE: "shapes.generate",
193
- WORLD_REGION: "world.region"
196
+ WORLD_REGION: "world.region",
197
+ VEHICLE_HULL_PLAN: "vehicles.hull-plan"
194
198
  };
195
199
  var WORKER_KIND_DEFAULTS = {
196
200
  [WORKER_KIND_ID.GROUND_TILES]: { lane: "sim", priority: 300, latencyFrames: 2, late: "sync" },
@@ -198,7 +202,8 @@ var GameCrowd = (() => {
198
202
  [WORKER_KIND_ID.PIECE_BOXES]: { lane: "sim", priority: 200, latencyFrames: 2, late: "sync" },
199
203
  [WORKER_KIND_ID.STATIC_COLLIDERS]: { lane: "build", priority: 150, late: "sync" },
200
204
  [WORKER_KIND_ID.SHAPES_GENERATE]: { lane: "build", priority: 100, late: "sync" },
201
- [WORKER_KIND_ID.WORLD_REGION]: { lane: "background", priority: 10, latencyFrames: 10, late: "drop" }
205
+ [WORKER_KIND_ID.WORLD_REGION]: { lane: "background", priority: 10, latencyFrames: 10, late: "drop" },
206
+ [WORKER_KIND_ID.VEHICLE_HULL_PLAN]: { lane: "build", priority: 120, late: "keep-waiting" }
202
207
  };
203
208
 
204
209
  // ../game-characters/dist/index.js
@@ -378,6 +383,14 @@ var GameCrowd = (() => {
378
383
  };
379
384
  var createCorpseLedger = (options) => {
380
385
  const entries = [];
386
+ const listeners = /* @__PURE__ */ new Set();
387
+ let nextId = 1;
388
+ const announceAdded = (entry) => {
389
+ for (const listener of listeners) listener.added?.(entry);
390
+ };
391
+ const announceRemoved = (entry, reason) => {
392
+ for (const listener of listeners) listener.removed?.(entry, reason);
393
+ };
381
394
  return {
382
395
  entries,
383
396
  get count() {
@@ -385,14 +398,19 @@ var GameCrowd = (() => {
385
398
  },
386
399
  add(data) {
387
400
  if (entries.length < options.max) {
388
- entries.push({ age: 0, data });
401
+ const added2 = { id: nextId++, age: 0, data };
402
+ entries.push(added2);
403
+ announceAdded(added2);
389
404
  return void 0;
390
405
  }
391
406
  let oldest = 0;
392
407
  for (let index = 1; index < entries.length; index++) if (entries[index].age > entries[oldest].age) oldest = index;
393
- const replaced = entries[oldest].data;
394
- entries[oldest] = { age: 0, data };
395
- return replaced;
408
+ const evicted = entries[oldest];
409
+ const added = { id: nextId++, age: 0, data };
410
+ entries[oldest] = added;
411
+ announceRemoved(evicted, "replaced");
412
+ announceAdded(added);
413
+ return evicted.data;
396
414
  },
397
415
  update(dt) {
398
416
  const removed = [];
@@ -403,6 +421,7 @@ var GameCrowd = (() => {
403
421
  removed.push(entry.data);
404
422
  entries[index] = entries[entries.length - 1];
405
423
  entries.pop();
424
+ announceRemoved(entry, "expired");
406
425
  index--;
407
426
  }
408
427
  return removed;
@@ -412,10 +431,22 @@ var GameCrowd = (() => {
412
431
  if (!entry) return void 0;
413
432
  entries[index] = entries[entries.length - 1];
414
433
  entries.pop();
434
+ announceRemoved(entry, "taken");
415
435
  return entry.data;
416
436
  },
417
437
  clear() {
418
- entries.length = 0;
438
+ const gone = entries.splice(0);
439
+ for (const entry of gone) announceRemoved(entry, "cleared");
440
+ },
441
+ replace(id, data) {
442
+ const index = entries.findIndex((entry) => entry.id === id);
443
+ if (index < 0) return false;
444
+ entries[index] = { ...entries[index], data };
445
+ return true;
446
+ },
447
+ subscribe(listener) {
448
+ listeners.add(listener);
449
+ return () => void listeners.delete(listener);
419
450
  }
420
451
  };
421
452
  };
@@ -908,6 +939,13 @@ var GameCrowd = (() => {
908
939
  thighLengthRatio: body_default.anthropometry.thighLengthRatio,
909
940
  shinLengthRatio: body_default.anthropometry.shinLengthRatio
910
941
  };
942
+ var R1_HEAD = ["head", "jaw"];
943
+ var R1_LEGS = SEGMENT_TREE.filter((node) => node.region === "legL" || node.region === "legR").map((node) => node.id);
944
+ var R1_TRUNK = SEGMENT_IDS.filter((id) => !R1_HEAD.includes(id) && !R1_LEGS.includes(id));
945
+ var SEGMENTS_OF = {
946
+ R0: SEGMENT_IDS.map((id) => [id]),
947
+ R1: [R1_TRUNK, R1_HEAD, R1_LEGS]
948
+ };
911
949
  var gait_default = {
912
950
  cascade: {
913
951
  hip: 16,
@@ -3411,6 +3449,7 @@ var GameCrowd = (() => {
3411
3449
  var GRAVITY_FORCE2 = 9.8;
3412
3450
  var EXTRA_BODIES = 500;
3413
3451
  var PAIRS_PER_AGENT3 = 12;
3452
+ var KNOCK_STUN_SECONDS = 1;
3414
3453
  function createPhysics(base, options, stats = createPhysicsStats()) {
3415
3454
  const moundOn = options.mound !== null;
3416
3455
  const ctx = { ...base, options, stats, step: -1, h: 0, centre: { x: 0, z: 0 }, lastBlastStep: -1e3, moundAt: (cell) => moundOn ? base.moundHeight[cell] : 0, weightOn: () => 0 };
@@ -3548,6 +3587,20 @@ var GameCrowd = (() => {
3548
3587
  balance,
3549
3588
  beginStep,
3550
3589
  endStep,
3590
+ knockDown: (i, vx, vz) => {
3591
+ if (i < 0 || i >= store.n || store.hp[i] <= 0) return;
3592
+ if (!balance) {
3593
+ store.state[i] = STATE.STUNNED;
3594
+ store.stateTimer[i] = KNOCK_STUN_SECONDS;
3595
+ store.vx[i] = vx;
3596
+ store.vz[i] = vz;
3597
+ return;
3598
+ }
3599
+ if (store.balance[i] !== BALANCE.STANDING && store.balance[i] !== BALANCE.STAGGERING) return;
3600
+ store.pushX[i] += vx;
3601
+ store.pushZ[i] += vz;
3602
+ balance.requestFall(i, FALL_CAUSE.SHOVE, Math.hypot(vx, vz) / options.balance.shoveFall);
3603
+ },
3551
3604
  remap: (removed, moved) => {
3552
3605
  thrown?.remap(removed, moved);
3553
3606
  offload?.remap(removed, moved);
@@ -5240,6 +5293,7 @@ var GameCrowd = (() => {
5240
5293
  mound: moundHeight,
5241
5294
  thrown: engine.thrown,
5242
5295
  blast: (blast) => engine.blasts.enqueue(blast),
5296
+ knockDown: (i, velocity) => engine.knockDown(i, velocity.x, velocity.z),
5243
5297
  pileCount: () => pileN,
5244
5298
  trail,
5245
5299
  variantsOf,
@@ -5312,6 +5366,12 @@ var GameCrowd = (() => {
5312
5366
  return crowd;
5313
5367
  }
5314
5368
 
5369
+ // src/corpse-relocate.ts
5370
+ var relocateCorpse = (crowd, move) => {
5371
+ const entry = crowd.corpses.entries.find((candidate) => candidate.id === move.id);
5372
+ return entry !== void 0 && crowd.corpses.replace(move.id, { ...entry.data, x: move.x, z: move.z, yaw: move.yaw });
5373
+ };
5374
+
5315
5375
  // src/obstacles.ts
5316
5376
  var LOW_WALL_MAX_HEIGHT = 1.2;
5317
5377
  var rangeOf = (grid, rect) => [
@@ -6258,6 +6318,187 @@ var GameCrowd = (() => {
6258
6318
  function hordeSnapshotBytes(capacity) {
6259
6319
  return hordeSnapshotLayout(createStore(capacity)).bytes;
6260
6320
  }
6321
+
6322
+ // src/engine-agents.ts
6323
+ var STILL = [0, 0, 0];
6324
+ var DEFAULT_RADIUS = 0.25;
6325
+ var DEFAULT_HEIGHT = 1.7;
6326
+ var createAgentBodies = (loop, crowd, options = {}) => {
6327
+ const { store } = crowd;
6328
+ const world = loop.world;
6329
+ const radius = options.radius ?? DEFAULT_RADIUS;
6330
+ const fallbackHeight = options.fallbackHeight ?? DEFAULT_HEIGHT;
6331
+ const bodies = [];
6332
+ const centreHeight = new Float32Array(store.capacity);
6333
+ const target = [0, 0, 0];
6334
+ const rotation = [0, 0, 0, 1];
6335
+ const shouldTeleport = new Uint8Array(store.capacity);
6336
+ const delivered = new Float64Array(store.capacity * 4);
6337
+ const isSettled = new Uint8Array(store.capacity);
6338
+ const stopTakingVacancies = [
6339
+ crowd.on("remove", (event) => {
6340
+ if (event.moved >= 0) shouldTeleport[event.agent] = 1;
6341
+ }),
6342
+ crowd.on("spawn", (event) => {
6343
+ shouldTeleport[event.agent] = 1;
6344
+ })
6345
+ ];
6346
+ const create = (i) => {
6347
+ const height = store.height[i] > 0 ? store.height[i] : fallbackHeight;
6348
+ const halfHeight = Math.max(0, height / 2 - radius);
6349
+ centreHeight[i] = halfHeight + radius;
6350
+ return world.createBody({
6351
+ shape: { kind: "capsule", halfHeight, radius },
6352
+ motion: "kinematic",
6353
+ position: [store.x[i], store.y[i] + centreHeight[i], store.z[i]],
6354
+ layer: "agent",
6355
+ user: i
6356
+ });
6357
+ };
6358
+ const beforeStep = (h) => {
6359
+ const count = store.n;
6360
+ while (bodies.length > count) world.removeBody(bodies.pop());
6361
+ for (let i = 0; i < count; i++) {
6362
+ const body = bodies[i];
6363
+ if (body === void 0) {
6364
+ bodies.push(create(i));
6365
+ shouldTeleport[i] = 0;
6366
+ isSettled[i] = 0;
6367
+ delivered[i * 4] = Number.NaN;
6368
+ continue;
6369
+ }
6370
+ const x = store.x[i];
6371
+ const y = store.y[i] + centreHeight[i];
6372
+ const z = store.z[i];
6373
+ const yaw = store.yaw[i];
6374
+ const at = i * 4;
6375
+ const isSamePose = delivered[at] === x && delivered[at + 1] === y && delivered[at + 2] === z && delivered[at + 3] === yaw;
6376
+ if (isSamePose && isSettled[i] && !shouldTeleport[i]) continue;
6377
+ const half = yaw / 2;
6378
+ target[0] = x;
6379
+ target[1] = y;
6380
+ target[2] = z;
6381
+ rotation[1] = Math.sin(half);
6382
+ rotation[3] = Math.cos(half);
6383
+ delivered[at] = x;
6384
+ delivered[at + 1] = y;
6385
+ delivered[at + 2] = z;
6386
+ delivered[at + 3] = yaw;
6387
+ isSettled[i] = isSamePose ? 1 : 0;
6388
+ if (shouldTeleport[i]) {
6389
+ shouldTeleport[i] = 0;
6390
+ world.setPose(body, target, rotation, true);
6391
+ world.setVelocity(body, STILL, STILL);
6392
+ isSettled[i] = 1;
6393
+ } else world.moveKinematic(body, target, rotation, h);
6394
+ }
6395
+ };
6396
+ const removePhase = loop.add({ beforeStep }, "crowd");
6397
+ return {
6398
+ get count() {
6399
+ return bodies.length;
6400
+ },
6401
+ bodyOf: (i) => bodies[i],
6402
+ dispose: () => {
6403
+ removePhase();
6404
+ for (const stop of stopTakingVacancies) stop();
6405
+ for (const body of bodies) if (world.has(body)) world.removeBody(body);
6406
+ bodies.length = 0;
6407
+ }
6408
+ };
6409
+ };
6410
+
6411
+ // src/engine-doors.ts
6412
+ var DEFAULT_LEAF_MASS = 40;
6413
+ var DEFAULT_BREAK_IMPULSE = 40;
6414
+ var LEAF_HALF_THICKNESS = 0.03;
6415
+ var HINGE_PLAY = 0.05;
6416
+ var createDoorBodies = (loop, doors, options = {}) => {
6417
+ const world = loop.world;
6418
+ const leafMass = options.leafMass ?? DEFAULT_LEAF_MASS;
6419
+ const breakImpulse = options.breakImpulse ?? DEFAULT_BREAK_IMPULSE;
6420
+ const height = options.height ?? DOOR_DEFAULTS.height;
6421
+ const hung = /* @__PURE__ */ new Map();
6422
+ const doorOfHinge = /* @__PURE__ */ new Map();
6423
+ const tornLeaves = /* @__PURE__ */ new Map();
6424
+ const removeTornLeaf = (index) => {
6425
+ const leaf = tornLeaves.get(index);
6426
+ if (leaf === void 0) return;
6427
+ tornLeaves.delete(index);
6428
+ if (world.has(leaf)) world.removeBody(leaf);
6429
+ };
6430
+ const hang = (index) => {
6431
+ const door = doors.list[index];
6432
+ if (!door || door.open || door.broken || hung.has(index)) return;
6433
+ removeTornLeaf(index);
6434
+ const alongX = door.axis === "x";
6435
+ const half = door.width / 2;
6436
+ const hingeAt = alongX ? [door.x - half, height / 2, door.z] : [door.x, height / 2, door.z - half];
6437
+ const frame = world.createBody({
6438
+ shape: { kind: "box", half: [0.05, height / 2, 0.05] },
6439
+ motion: "static",
6440
+ position: hingeAt,
6441
+ user: -1
6442
+ });
6443
+ const leaf = world.createBody({
6444
+ shape: { kind: "box", half: alongX ? [half - 0.02, height / 2 - 0.02, LEAF_HALF_THICKNESS] : [LEAF_HALF_THICKNESS, height / 2 - 0.02, half - 0.02] },
6445
+ motion: "dynamic",
6446
+ mass: leafMass,
6447
+ position: [door.x, height / 2, door.z],
6448
+ layer: "prop",
6449
+ user: -2 - index
6450
+ });
6451
+ const hinge = world.createJoint({
6452
+ kind: "hinge",
6453
+ a: frame,
6454
+ b: leaf,
6455
+ point: hingeAt,
6456
+ axis: [0, 1, 0],
6457
+ normal: alongX ? [1, 0, 0] : [0, 0, 1],
6458
+ min: -HINGE_PLAY,
6459
+ max: HINGE_PLAY,
6460
+ breakImpulse
6461
+ });
6462
+ hung.set(index, { door: index, frame, leaf, hinge });
6463
+ doorOfHinge.set(hinge, index);
6464
+ };
6465
+ const drop = (entry, keepLeaf) => {
6466
+ doorOfHinge.delete(entry.hinge);
6467
+ hung.delete(entry.door);
6468
+ if (world.jointExists(entry.hinge)) world.removeJoint(entry.hinge);
6469
+ if (world.has(entry.frame)) world.removeBody(entry.frame);
6470
+ if (!keepLeaf && world.has(entry.leaf)) world.removeBody(entry.leaf);
6471
+ };
6472
+ const afterSteps = () => {
6473
+ for (const joint of world.brokenJoints) {
6474
+ const index = doorOfHinge.get(joint);
6475
+ const entry = index === void 0 ? void 0 : hung.get(index);
6476
+ if (!entry) continue;
6477
+ drop(entry, true);
6478
+ removeTornLeaf(entry.door);
6479
+ tornLeaves.set(entry.door, entry.leaf);
6480
+ doors.hit(entry.door, doors.list[entry.door].hp);
6481
+ }
6482
+ sync();
6483
+ };
6484
+ const sync = () => {
6485
+ for (const entry of hung.values()) {
6486
+ const door = doors.list[entry.door];
6487
+ if (door.open || door.broken) drop(entry, false);
6488
+ }
6489
+ for (let index = 0; index < doors.list.length; index++) hang(index);
6490
+ };
6491
+ const removePhase = loop.add({ afterSteps }, "contacts");
6492
+ sync();
6493
+ return {
6494
+ leafOf: (index) => hung.get(index)?.leaf,
6495
+ dispose: () => {
6496
+ removePhase();
6497
+ for (const entry of [...hung.values()]) drop(entry, false);
6498
+ for (const index of [...tornLeaves.keys()]) removeTornLeaf(index);
6499
+ }
6500
+ };
6501
+ };
6261
6502
  return __toCommonJS(index_exports);
6262
6503
  })();
6263
6504
  //# sourceMappingURL=index.global.js.map