@adatechnology/game-destruction-three 0.24.3 → 0.25.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
@@ -294,6 +294,8 @@ var FRAGMENT_SEED = 1374496523;
294
294
  var SUPPORT_CHECKS = 32;
295
295
  var SUPPORT_GAP = 0.02;
296
296
  var SHARD_SHAPES = 6;
297
+ var SETTLE_SECONDS = 0.4;
298
+ var isSlow = (f) => f.vel.lengthSq() < 0.012 && f.ang.lengthSq() < 0.2;
297
299
  var isBig = (size) => {
298
300
  const [, middle, longest] = [...size].sort((a, b) => a - b);
299
301
  return longest >= BIG_LENGTH && middle >= BIG_WIDTH;
@@ -334,6 +336,10 @@ var FragmentSystem = class {
334
336
  meshes() {
335
337
  return this.list.map((f) => f.mesh);
336
338
  }
339
+ /** Meshes of the fragments asleep in the scene, without marks on them (a mark is a mesh of its own on the fragment). */
340
+ restingMeshes() {
341
+ return this.list.filter((f) => f.asleep && !f.dying && f.mesh.children.length === 0 && f.mesh.parent === this.o.scene).map((f) => f.mesh);
342
+ }
337
343
  /** One shared material per source material id + colour (+ transparency). */
338
344
  materialFor(materialId, color, transparent, opacity = 0.5) {
339
345
  const key = `${materialId}:${color}:${transparent ? 1 : 0}`;
@@ -483,6 +489,7 @@ var FragmentSystem = class {
483
489
  baseScale: sc,
484
490
  still: 0,
485
491
  asleep: false,
492
+ contact: false,
486
493
  rest: 0,
487
494
  fade: 1,
488
495
  dying: false,
@@ -576,6 +583,28 @@ var FragmentSystem = class {
576
583
  }
577
584
  this.step(f, dt, g);
578
585
  }
586
+ this.keepBudget();
587
+ }
588
+ /** Over `maxAwake` fragments moving, the oldest at rest on what is under them sleep where they lie (`FragmentSystemOptions.maxAwake`). */
589
+ keepBudget() {
590
+ const most = this.o.maxAwake;
591
+ if (most === void 0 || !Number.isFinite(most)) return;
592
+ let awake = 0;
593
+ for (const f of this.list) if (!f.asleep && !f.dying) awake++;
594
+ for (const f of this.list) {
595
+ if (awake <= most) return;
596
+ if (f.asleep || f.dying || !f.contact || !isSlow(f)) continue;
597
+ this.sleep(f);
598
+ awake--;
599
+ }
600
+ }
601
+ /** The fragment stops where it lies, and its matrix is no longer recomputed every frame. */
602
+ sleep(f) {
603
+ f.asleep = true;
604
+ f.mesh.updateMatrix();
605
+ f.mesh.matrixAutoUpdate = false;
606
+ f.vel.set(0, 0, 0);
607
+ f.ang.set(0, 0, 0);
579
608
  }
580
609
  /** A few fragments asleep each update (`SUPPORT_CHECKS`, in turn) look at the ground under them again: one left over air falls. */
581
610
  wakeUnsupported() {
@@ -638,16 +667,10 @@ var FragmentSystem = class {
638
667
  if (f.air > 0) this.flutter(f, dt);
639
668
  }
640
669
  if (contact && f.vel.lengthSq() < 4) this.settle(f, dt);
641
- const slow = f.vel.lengthSq() < 0.012 && f.ang.lengthSq() < 0.2;
642
- if (contact && slow) {
670
+ f.contact = contact;
671
+ if (contact && isSlow(f)) {
643
672
  f.still += dt;
644
- if (f.still > 0.4) {
645
- f.asleep = true;
646
- f.mesh.updateMatrix();
647
- f.mesh.matrixAutoUpdate = false;
648
- f.vel.set(0, 0, 0);
649
- f.ang.set(0, 0, 0);
650
- }
673
+ if (f.still > SETTLE_SECONDS) this.sleep(f);
651
674
  } else {
652
675
  f.still = 0;
653
676
  }
@@ -911,9 +934,13 @@ var SLIP_SPEED = 0.02;
911
934
  var ROLLING_RESISTANCE = 0.015;
912
935
  var ROUND_LYING = Math.SQRT1_2;
913
936
  var SLEEP_AFTER = 0.5;
937
+ var STILL_SPEED = 0.12;
938
+ var STILL_SPIN = 0.45;
914
939
  var CALM_DRIFT = 0.01;
915
940
  var CALM_TURN = 0.05;
916
941
  var CALM_SLEEP_AFTER = 1.5;
942
+ var STEADY_TURN = 0.1;
943
+ var STEADY_SECONDS = 1.5;
917
944
  var HARD_LANDING = 3;
918
945
  var SLOP = 2e-3;
919
946
  var NARROW = 0.3;
@@ -974,6 +1001,7 @@ var pairFriction = (a, b) => ({
974
1001
  rolling: Math.max(a?.rolling ?? 0, b?.rolling ?? ROLLING_RESISTANCE)
975
1002
  });
976
1003
  var pairRestitution = (a, b) => Math.sqrt((a ?? SLAM_BOUNCE) * (b ?? SLAM_BOUNCE));
1004
+ var turnBetween = (a, q) => 2 * Math.acos(Math.min(1, Math.abs(a[0] * q.x + a[1] * q.y + a[2] * q.z + a[3] * q.w)));
977
1005
  var PieceSystem = class {
978
1006
  constructor(THREE, o) {
979
1007
  __publicField(this, "THREE", THREE);
@@ -1305,6 +1333,7 @@ var PieceSystem = class {
1305
1333
  if (Math.hypot(v[0], v[1], v[2]) > WAKE_ABOVE_SPEED || Math.hypot(w[0], w[1], w[2]) > WAKE_ABOVE_SPIN) this.wakeAbove(b);
1306
1334
  }
1307
1335
  this.collide(dt, only?.meets);
1336
+ this.keepBudget();
1308
1337
  }
1309
1338
  /** A few sleeping pieces each update (`SUPPORT_CHECKS`, in turn) look under them again: one whose table broke, or whose shelf fell over, falls. */
1310
1339
  wakeUnsupported() {
@@ -1312,10 +1341,13 @@ var PieceSystem = class {
1312
1341
  for (let k = 0; k < Math.min(SUPPORT_CHECKS2, n); k++) {
1313
1342
  this.supportTurn = (this.supportTurn + 1) % n;
1314
1343
  const b = this.list[this.supportTurn];
1315
- if (!b.sleeping || b.held || this.supported(b, false) || this.supported(b, true)) continue;
1344
+ if (!b.sleeping || b.held) continue;
1345
+ const rest = b.restPoints;
1346
+ if (rest && rest.length > 0 ? rest.every((point) => this.supportsPoint(b, point)) : this.supported(b, false) || this.supported(b, true)) continue;
1316
1347
  b.sleeping = false;
1317
1348
  b.still = 0;
1318
1349
  b.calmAt = null;
1350
+ b.restPoints = void 0;
1319
1351
  }
1320
1352
  }
1321
1353
  /**
@@ -1721,20 +1753,80 @@ var PieceSystem = class {
1721
1753
  b.lastHit = this.time;
1722
1754
  this.o.onHardLanding(b, landPoint, landing);
1723
1755
  }
1724
- const still = touched && !unstable && Math.hypot(v[0], v[1], v[2]) < 0.12 && Math.hypot(w[0], w[1], w[2]) < 0.45;
1756
+ const still = touched && !unstable && Math.hypot(v[0], v[1], v[2]) < STILL_SPEED && Math.hypot(w[0], w[1], w[2]) < STILL_SPIN;
1725
1757
  if (still) b.still += dt;
1726
1758
  else b.still = 0;
1727
- if (b.still >= SLEEP_AFTER || this.staysInPlace(b, touched && !b.tipping, pos, q, dt)) {
1728
- b.sleeping = true;
1729
- b.calmAt = null;
1730
- v[0] = v[1] = v[2] = 0;
1731
- w[0] = w[1] = w[2] = 0;
1759
+ b.balancing = unstable;
1760
+ this.keepsTilt(b, q, dt);
1761
+ if (b.still >= SLEEP_AFTER || this.staysInPlace(b, touched && !b.tipping, pos, q, dt)) this.sleep(b);
1762
+ }
1763
+ /** The piece sleeps where it lies: its speeds are dropped, nothing moves it. */
1764
+ sleep(b) {
1765
+ b.restPoints = void 0;
1766
+ b.sleeping = true;
1767
+ b.calmAt = null;
1768
+ b.steady = null;
1769
+ b.velocity[0] = b.velocity[1] = b.velocity[2] = 0;
1770
+ b.angularVelocity[0] = b.angularVelocity[1] = b.angularVelocity[2] = 0;
1771
+ }
1772
+ /** How long the piece has kept its tilt (within `STEADY_TURN`): one going over leaves it within a moment, one held up at an angle keeps it. */
1773
+ keepsTilt(b, q, dt) {
1774
+ const at = b.steady;
1775
+ if (at && turnBetween(at.quaternion, q) <= STEADY_TURN) {
1776
+ at.seconds += dt;
1777
+ return;
1732
1778
  }
1779
+ b.steady = { quaternion: [q.x, q.y, q.z, q.w], seconds: 0 };
1780
+ }
1781
+ /**
1782
+ * Over `maxAwake` pieces awake, the oldest that have come to rest sleep where they lie: on the ground, slower than `STILL_SPEED` and `STILL_SPIN`, not falling over (`tip`),
1783
+ * and one held up at an angle (a board leaning on a seat) only once it kept its tilt for `STEADY_SECONDS`; that one sleeps then under the budget too, since nothing else puts
1784
+ * it to sleep. It keeps the points it lies on (`restPoints`) and wakes when any of them loses its support (`wakeUnsupported`): put to sleep sooner than it would have slept by
1785
+ * itself, it answers to every point that holds it.
1786
+ */
1787
+ keepBudget() {
1788
+ const most = this.o.maxAwake;
1789
+ if (most === void 0 || !Number.isFinite(most)) return;
1790
+ let awake = 0;
1791
+ for (const b of this.list) {
1792
+ if (b.sleeping || b.held) continue;
1793
+ if (b.balancing && this.hasComeToRest(b)) this.sleepByBudget(b);
1794
+ else awake++;
1795
+ }
1796
+ for (const b of this.list) {
1797
+ if (awake <= most) return;
1798
+ if (b.sleeping || b.held || !this.hasComeToRest(b)) continue;
1799
+ this.sleepByBudget(b);
1800
+ awake--;
1801
+ }
1802
+ }
1803
+ /** Sleeps sooner than it would by itself, so it answers to every point it lies on (`restPoints`). */
1804
+ sleepByBudget(b) {
1805
+ this.sleep(b);
1806
+ b.restPoints = this.restPointsOf(b);
1807
+ }
1808
+ hasComeToRest(b) {
1809
+ const v = b.velocity;
1810
+ const w = b.angularVelocity;
1811
+ if (!b.onGround || b.tipping || Math.hypot(v[0], v[1], v[2]) >= STILL_SPEED || Math.hypot(w[0], w[1], w[2]) >= STILL_SPIN) return false;
1812
+ return !b.balancing || (b.steady?.seconds ?? 0) >= STEADY_SECONDS;
1813
+ }
1814
+ /** The corners of `b` (its own frame, or its own `contacts`) that have the ground, a piece or a fixed top within `SUPPORT_GAP` under them now; the points along its edges when no corner has. */
1815
+ restPointsOf(b) {
1816
+ const corners = this.samples(b, false).filter((point) => this.supportsPoint(b, point));
1817
+ return corners.length > 0 ? corners : this.samples(b, true).filter((point) => this.supportsPoint(b, point));
1818
+ }
1819
+ /** Whether the point of `b` (its own frame) has the ground, a piece or a fixed top within `SUPPORT_GAP` under it. */
1820
+ supportsPoint(b, [sx, sy, sz]) {
1821
+ const c = this.centerOf(b, this.p);
1822
+ const e = this.m.makeRotationFromQuaternion(b.root.quaternion).elements;
1823
+ const y = c.y + e[1] * sx + e[5] * sy + e[9] * sz;
1824
+ return this.supportAt(b, c.x + e[0] * sx + e[4] * sy + e[8] * sz, y, c.z + e[2] * sx + e[6] * sy + e[10] * sz, STEP) >= y - SUPPORT_GAP2;
1733
1825
  }
1734
1826
  /** Whether the piece has kept to the same spot on the ground for `CALM_SLEEP_AFTER` (see `CALM_DRIFT`). */
1735
1827
  staysInPlace(b, touched, center, q, dt) {
1736
1828
  const at = b.calmAt;
1737
- const turned = at ? 2 * Math.acos(Math.min(1, Math.abs(at.quaternion[0] * q.x + at.quaternion[1] * q.y + at.quaternion[2] * q.z + at.quaternion[3] * q.w))) : Infinity;
1829
+ const turned = at ? turnBetween(at.quaternion, q) : Infinity;
1738
1830
  if (!touched || !at || Math.hypot(center[0] - at.center[0], center[1] - at.center[1], center[2] - at.center[2]) > CALM_DRIFT || turned > CALM_TURN) {
1739
1831
  b.calmAt = touched ? { center: [center[0], center[1], center[2]], quaternion: [q.x, q.y, q.z, q.w] } : null;
1740
1832
  b.calm = 0;
@@ -2298,7 +2390,7 @@ function surfaceOf(materialId, def) {
2298
2390
  }
2299
2391
 
2300
2392
  // src/renderer.ts
2301
- import { kitOriginOf } from "@adatechnology/game-contracts";
2393
+ import { kitOriginOf as kitOriginOf2 } from "@adatechnology/game-contracts";
2302
2394
  import { debrisColor as debrisColor2, debrisLook, fragmentTone } from "@adatechnology/game-destruction";
2303
2395
 
2304
2396
  // src/debris-events.ts
@@ -3524,7 +3616,7 @@ var Visuals = class {
3524
3616
 
3525
3617
  // src/settlement.ts
3526
3618
  import { settlementAt } from "@adatechnology/game-destruction";
3527
- var SETTLE_SECONDS = 1.2;
3619
+ var SETTLE_SECONDS2 = 1.2;
3528
3620
  var SETTLE_REDRAW = 0.1;
3529
3621
  var dropOf = (line, point) => line ? settlementAt(line, point) : 0;
3530
3622
  var sameLine = (a, b) => !!a && a.drop.length === b.drop.length && a.drop.every((v, k) => v === b.drop[k]) && a.from.every((v, k) => v === b.from[k]) && a.to.every((v, k) => v === b.to[k]);
@@ -3551,10 +3643,10 @@ var SettlementView = class {
3551
3643
  update(dt) {
3552
3644
  for (const s of this.moving.values()) {
3553
3645
  s.elapsed += dt;
3554
- const done = s.elapsed >= SETTLE_SECONDS;
3646
+ const done = s.elapsed >= SETTLE_SECONDS2;
3555
3647
  if (!done && s.elapsed - s.lastDrawn < SETTLE_REDRAW) continue;
3556
3648
  s.lastDrawn = s.elapsed;
3557
- const t = Math.min(1, s.elapsed / SETTLE_SECONDS);
3649
+ const t = Math.min(1, s.elapsed / SETTLE_SECONDS2);
3558
3650
  this.draw(s, t * t * (3 - 2 * t));
3559
3651
  if (done) {
3560
3652
  s.pv.settled = s.target;
@@ -3594,6 +3686,115 @@ var SettlementView = class {
3594
3686
  }
3595
3687
  };
3596
3688
 
3689
+ // src/settled-batches.ts
3690
+ import { kitOriginOf, markKitOrigin as markKitOrigin2 } from "@adatechnology/game-contracts";
3691
+ import { BATCHED_LAYER, createStaticBatcher } from "@adatechnology/game-render-three";
3692
+ var SETTLED_BATCH_DEFAULTS = { enabled: true, minMeshes: 16, intervalSeconds: 1, budgetMs: 2, maxVertices: 4e3 };
3693
+ var IDENTITY_KEYS = /* @__PURE__ */ new Set(["uuid", "id", "name", "version", "userData", "_listeners"]);
3694
+ var settingText = (value) => {
3695
+ if (value === null || typeof value === "number" || typeof value === "boolean" || typeof value === "string") return String(value);
3696
+ if (typeof value !== "object") return void 0;
3697
+ const described = value;
3698
+ if (described.isColor === true) return described.getHexString?.();
3699
+ if (described.isTexture === true) return described.uuid;
3700
+ if (described.isVector2 === true) return `${described.x},${described.y}`;
3701
+ if (Object.getPrototypeOf(value) === Object.prototype) {
3702
+ try {
3703
+ return JSON.stringify(value);
3704
+ } catch {
3705
+ return void 0;
3706
+ }
3707
+ }
3708
+ return void 0;
3709
+ };
3710
+ var materialKey = (material) => {
3711
+ const record = material;
3712
+ const settings = [material.type];
3713
+ for (const key of Object.keys(record).sort()) {
3714
+ if (key === "userData" && Object.keys(material.userData).length > 0) return material.uuid;
3715
+ if (IDENTITY_KEYS.has(key)) continue;
3716
+ const text = settingText(record[key]);
3717
+ if (text === void 0) return material.uuid;
3718
+ settings.push(`${key}=${text}`);
3719
+ }
3720
+ return settings.join("|");
3721
+ };
3722
+ var SETTLED_BATCH_ORIGIN = { owner: "game-destruction-three", kind: "debris" };
3723
+ var commonOrigin = (meshes) => {
3724
+ const first = kitOriginOf(meshes[0]);
3725
+ if (!first) return null;
3726
+ for (const mesh of meshes) {
3727
+ const origin = kitOriginOf(mesh);
3728
+ if (!origin || origin.owner !== first.owner || origin.kind !== first.kind || origin.id !== first.id) return null;
3729
+ }
3730
+ return first;
3731
+ };
3732
+ var markBatch = (batch, meshes) => {
3733
+ const origin = commonOrigin(meshes);
3734
+ if (origin) markKitOrigin2(batch, origin);
3735
+ };
3736
+ var isBatchableDebris = (mesh, maxVertices) => {
3737
+ const material = mesh.material;
3738
+ if (Array.isArray(material) || material.transparent) return false;
3739
+ if (mesh.layers.isEnabled(BATCHED_LAYER)) return false;
3740
+ return (mesh.geometry.attributes.position?.count ?? Infinity) <= maxVertices;
3741
+ };
3742
+ var SettledBatches = class {
3743
+ constructor(THREE, scene2, options = {}) {
3744
+ __publicField(this, "THREE", THREE);
3745
+ __publicField(this, "scene", scene2);
3746
+ __publicField(this, "options");
3747
+ __publicField(this, "batcher", null);
3748
+ /** The meshes given to the batcher when it was made. */
3749
+ __publicField(this, "members", /* @__PURE__ */ new Set());
3750
+ __publicField(this, "sinceMade", Infinity);
3751
+ this.options = { ...SETTLED_BATCH_DEFAULTS, ...options };
3752
+ }
3753
+ /** Gives back to its own draw whatever changed, and makes the batches again when `atRest` (the debris meshes at rest) has enough outside them. Once per frame, after the bodies moved. */
3754
+ update(dt, atRest) {
3755
+ this.batcher?.update();
3756
+ this.sinceMade += dt;
3757
+ if (!this.options.enabled || this.sinceMade < this.options.intervalSeconds) return;
3758
+ const meshes = atRest().filter((mesh) => isBatchableDebris(mesh, this.options.maxVertices) || this.batched(mesh));
3759
+ const outside = meshes.length - (this.batcher?.stats().batched ?? 0);
3760
+ if (outside < this.options.minMeshes) return;
3761
+ this.make(meshes);
3762
+ }
3763
+ stats() {
3764
+ const stats = this.batcher?.stats();
3765
+ return { batches: this.batcher ? this.batcher.group.children.filter((child) => child.visible).length : 0, batched: stats?.batched ?? 0 };
3766
+ }
3767
+ /**
3768
+ * Something happened to one of `meshes` (a blow, fire, char): if any is drawn by a batch, every mesh draws on its own again at once and the batches are made again after
3769
+ * `intervalSeconds`. A change the batcher cannot see (a colour written in place) never shows late.
3770
+ */
3771
+ release(meshes) {
3772
+ if (this.members.size === 0 || !meshes.some((mesh) => this.batched(mesh))) return;
3773
+ this.clear();
3774
+ this.sinceMade = 0;
3775
+ }
3776
+ /** Every debris mesh draws on its own again and the batches are disposed. */
3777
+ clear() {
3778
+ this.batcher?.dispose();
3779
+ this.batcher = null;
3780
+ this.members = /* @__PURE__ */ new Set();
3781
+ this.sinceMade = Infinity;
3782
+ }
3783
+ /** Drawn by one of these batches now (given to it, and not given back). */
3784
+ batched(mesh) {
3785
+ return this.members.has(mesh) && mesh.layers.isEnabled(BATCHED_LAYER);
3786
+ }
3787
+ make(meshes) {
3788
+ this.batcher?.dispose();
3789
+ const take = new Set(meshes);
3790
+ this.members = take;
3791
+ this.batcher = createStaticBatcher(this.THREE, this.scene, { include: (mesh) => take.has(mesh), budgetMs: this.options.budgetMs, materialKey, onBatch: markBatch });
3792
+ this.batcher.group.name = "settled-debris-batches";
3793
+ markKitOrigin2(this.batcher.group, SETTLED_BATCH_ORIGIN);
3794
+ this.sinceMade = 0;
3795
+ }
3796
+ };
3797
+
3597
3798
  // src/emitter-anchor.ts
3598
3799
  function anchorOnMesh(THREE, mv, point, normal) {
3599
3800
  mv.mesh.updateWorldMatrix(true, false);
@@ -3616,8 +3817,32 @@ function anchorWorld(anchor, shown, point, normal) {
3616
3817
  return true;
3617
3818
  }
3618
3819
 
3820
+ // src/vfx-source.ts
3821
+ function stampSource(vfx, current) {
3822
+ const stamped = Object.create(vfx);
3823
+ stamped.burst = (kind, point, normal, count, speed, options) => {
3824
+ const source = current();
3825
+ vfx.burst(kind, point, normal, count, speed, source === void 0 || options?.source !== void 0 ? options : { ...options, source });
3826
+ };
3827
+ stamped.spawn = (kind, point, velocity, options) => {
3828
+ const source = current();
3829
+ vfx.spawn(kind, point, velocity, source === void 0 || options?.source !== void 0 ? options : { ...options, source });
3830
+ };
3831
+ stamped.explosion = (id, point, options) => {
3832
+ const source = current();
3833
+ return vfx.explosion(id, point, source === void 0 || options?.source !== void 0 ? options : { ...options, source });
3834
+ };
3835
+ stamped.fire = (options) => {
3836
+ const source = current();
3837
+ return vfx.fire(source === void 0 || options.source !== void 0 ? options : { ...options, source });
3838
+ };
3839
+ return stamped;
3840
+ }
3841
+
3619
3842
  // src/renderer.ts
3620
3843
  var rendererCount = 0;
3844
+ var SUGGESTED_MAX_AWAKE_PIECES = 24;
3845
+ var SUGGESTED_MAX_AWAKE_FRAGMENTS = 64;
3621
3846
  var COLLAPSE_CLOUD_KG = 1e3;
3622
3847
  var REBAR_COLOR = 7628380;
3623
3848
  var STEEL_DENSITY = 7850;
@@ -3851,6 +4076,8 @@ var Renderer = class {
3851
4076
  __publicField(this, "ground");
3852
4077
  __publicField(this, "pieceSys");
3853
4078
  __publicField(this, "cages");
4079
+ /** The debris at rest drawn in batches. */
4080
+ __publicField(this, "settledBatches");
3854
4081
  __publicField(this, "hitPoints", new HitPoints());
3855
4082
  __publicField(this, "active", /* @__PURE__ */ new Map());
3856
4083
  __publicField(this, "fires", /* @__PURE__ */ new Map());
@@ -3863,6 +4090,8 @@ var Renderer = class {
3863
4090
  __publicField(this, "throttles", /* @__PURE__ */ new Map());
3864
4091
  __publicField(this, "rng", createRng(RNG_SEED));
3865
4092
  __publicField(this, "vfx");
4093
+ /** The object whose event is being applied: what the effects world is given while it is set is that object's (`stampSource`). */
4094
+ __publicField(this, "emitting");
3866
4095
  /** Names this renderer to the world's drips, so a shared world tells each renderer where its own landed. */
3867
4096
  __publicField(this, "owner", `destruction-${++rendererCount}`);
3868
4097
  __publicField(this, "stopLanding");
@@ -3895,7 +4124,7 @@ var Renderer = class {
3895
4124
  this.settlement = new SettlementView(THREE, this.visuals);
3896
4125
  this.ground = new GroundSpots(THREE, o.scene, this.groundAt, 48);
3897
4126
  if (!o.vfx) warnOnce("game-destruction-three.own-effects-world", "game-destruction-three made an effects world of its own because the host lent none (options.vfx); pass the host effects so the effects share one budget");
3898
- this.vfx = o.vfx ?? createVfx({ profile: this.quality, gravity: this.gravity, groundAt: this.groundAt, sprites: { capacity: maxParticles, density: this.low ? 0.6 : 1 } });
4127
+ this.vfx = stampSource(o.vfx ?? createVfx({ profile: this.quality, gravity: this.gravity, groundAt: this.groundAt, sprites: { capacity: maxParticles, density: this.low ? 0.6 : 1 } }), () => this.emitting);
3899
4128
  this.ownVfx = o.vfx ? void 0 : createVfxRenderer(THREE, { scene: o.scene, camera: o.camera ?? new THREE.PerspectiveCamera(), vfx: this.vfx, pointScale: o.pointScale ?? 700 });
3900
4129
  this.stopLanding = this.vfx.onLand(this.owner, (x, _y, z, color, tag) => {
3901
4130
  const home = this.homeTags[tag - 1] ?? "";
@@ -3910,14 +4139,17 @@ var Renderer = class {
3910
4139
  formOf: (id) => this.world.materials.get(id)?.splitForm,
3911
4140
  crumbles: (id) => this.world.materials.get(id)?.fracture === "crumble",
3912
4141
  // rubble lands on what is still built (a slab, a wall's top, a floor), not only on the terrain under it
3913
- surfaceAt: (x, y, z) => this.surfaceAt(x, y, z)
4142
+ surfaceAt: (x, y, z) => this.surfaceAt(x, y, z),
4143
+ maxAwake: o.maxAwakeFragments ?? Infinity
3914
4144
  });
3915
4145
  this.cages = new RebarCages(THREE, o.scene);
4146
+ this.settledBatches = new SettledBatches(THREE, o.scene, o.settledBatches ?? { enabled: false });
3916
4147
  this.pieceSys = new PieceSystem(THREE, {
3917
4148
  groundAt: this.groundAt,
3918
4149
  staticTopAt: (x, z, y, step) => this.staticTopAt(x, z, y, step),
3919
4150
  gravity: this.gravity,
3920
4151
  scene: o.scene,
4152
+ maxAwake: o.maxAwakePieces ?? Infinity,
3921
4153
  onHardLanding: (p, point, speed) => this.hardLanding(p, point, speed),
3922
4154
  sweep: (p, from, to) => this.sweepPiece(p, from, to),
3923
4155
  onSlam: (p, hit, speed) => this.slam(p, hit, speed),
@@ -4315,6 +4547,30 @@ var Renderer = class {
4315
4547
  this.ground.update(dt);
4316
4548
  this.ownVfx?.update(dt);
4317
4549
  this.syncTransforms();
4550
+ this.settledBatches.update(dt, () => this.restingDebris());
4551
+ }
4552
+ /** An event of the object (a blow, fire, char): its meshes leave the batches before it is drawn (`SettledBatches.release`). */
4553
+ releaseBatched(objectId) {
4554
+ const b = this.bounds.get(objectId);
4555
+ if (b) this.settledBatches.release(this.meshesOf(b).map((mv) => mv.mesh));
4556
+ }
4557
+ /**
4558
+ * The meshes of the debris at rest: the fragments asleep (without marks on them) and the meshes of their own of the pieces asleep, but for an object with a part burning,
4559
+ * hot or still charring (`active`): its colours change in place.
4560
+ */
4561
+ restingDebris() {
4562
+ const meshes = new Set(this.fragments.restingMeshes());
4563
+ const changing = /* @__PURE__ */ new Set();
4564
+ for (const a of this.active.values()) changing.add(a.object);
4565
+ for (const piece of this.pieceSys.list) {
4566
+ const b = piece.sleeping && !piece.held && !changing.has(piece.objectId) ? this.bounds.get(piece.objectId) : void 0;
4567
+ if (!b) continue;
4568
+ for (const mv of this.meshesOf(b)) if ((!mv.host || mv.loose) && !mv.hidden && this.visuals.shown(mv)) meshes.add(mv.mesh);
4569
+ }
4570
+ return [...meshes];
4571
+ }
4572
+ settledBatchStats() {
4573
+ return this.settledBatches.stats();
4318
4574
  }
4319
4575
  deferredQueue() {
4320
4576
  return this.eventQueue;
@@ -4519,7 +4775,17 @@ var Renderer = class {
4519
4775
  return found;
4520
4776
  }
4521
4777
  apply(ev) {
4778
+ const outer = this.emitting;
4779
+ this.emitting = ev.object || void 0;
4780
+ try {
4781
+ this.applyEvent(ev);
4782
+ } finally {
4783
+ this.emitting = outer;
4784
+ }
4785
+ }
4786
+ applyEvent(ev) {
4522
4787
  this.staticDirty.add(ev.object);
4788
+ this.releaseBatched(ev.object);
4523
4789
  this.hitPoints.note(ev, this.time);
4524
4790
  if (ev.type === "fracture" || ev.type === "detach" || ev.type === "collapse" || ev.type === "burnout" || ev.type === "destroyed") this.broken.add(ev.object);
4525
4791
  switch (ev.type) {
@@ -4562,7 +4828,7 @@ var Renderer = class {
4562
4828
  break;
4563
4829
  case "collapse": {
4564
4830
  const root = this.bounds.get(ev.object)?.root;
4565
- const furniture = !!root && kitOriginOf(root)?.kind === "furniture";
4831
+ const furniture = !!root && kitOriginOf2(root)?.kind === "furniture";
4566
4832
  for (const part of ev.parts) {
4567
4833
  const pv = this.partVis(ev.object, part);
4568
4834
  if (pv) this.settlement.finish(pv);
@@ -4745,7 +5011,7 @@ var Renderer = class {
4745
5011
  if ((kind === "dust" || kind === "chips") && def?.visual?.innerColor !== void 0) return { color: def.visual.innerColor };
4746
5012
  if (kind === "fibers" || kind === "leaves") {
4747
5013
  if (def?.visual?.innerColor !== void 0) return { color: def.visual.innerColor };
4748
- const c = pv ? this.visuals.baseColorHex(pv.meshes[0] ?? {}) : -1;
5014
+ const c = pv && pv.meshes[0] ? this.visuals.baseColorHex(pv.meshes[0]) : -1;
4749
5015
  return c >= 0 ? { color: c } : void 0;
4750
5016
  }
4751
5017
  if (kind === "dust" || kind === "chips") {
@@ -4890,7 +5156,7 @@ var Renderer = class {
4890
5156
  if (this.trickles.length >= TRICKLE_MAX) this.trickles.shift();
4891
5157
  const total = TRICKLE_SECONDS[0] + (TRICKLE_SECONDS[1] - TRICKLE_SECONDS[0]) * this.rng();
4892
5158
  const anchor = mv ? anchorOnMesh(this.THREE, mv, point, normal) : null;
4893
- this.trickles.push({ point: [point[0], point[1], point[2]], normal, anchor, color, left: total, total, next: TRICKLE_EVERY });
5159
+ this.trickles.push({ point: [point[0], point[1], point[2]], normal, anchor, color, left: total, total, next: TRICKLE_EVERY, source: this.emitting ?? mv?.home });
4894
5160
  }
4895
5161
  updateTrickles(dt) {
4896
5162
  for (let i = this.trickles.length - 1; i >= 0; i--) {
@@ -4913,7 +5179,7 @@ var Renderer = class {
4913
5179
  const share = t.left / t.total;
4914
5180
  t.next = TRICKLE_EVERY / Math.max(share, 0.25);
4915
5181
  const out = [t.normal[0] * 0.2, -1, t.normal[2] * 0.2];
4916
- const options = t.color !== void 0 ? { color: t.color } : void 0;
5182
+ const options = { ...t.color !== void 0 ? { color: t.color } : {}, ...t.source !== void 0 ? { source: t.source } : {} };
4917
5183
  this.vfx.burst("chips", t.point, out, this.low ? 1 : 2, 0.3, options);
4918
5184
  if (this.rng() < 0.5) this.vfx.burst("dust", t.point, out, 1, 0.2, options);
4919
5185
  }
@@ -5131,7 +5397,7 @@ var Renderer = class {
5131
5397
  if (!old.round) this.setContacts(b, old, this.meshesOf(b).filter((mv) => this.visuals.shown(mv)));
5132
5398
  } else if (old.partBoxes) this.fitPartBoxes(b, old);
5133
5399
  old.sleeping = false;
5134
- } else if (kitOriginOf(b.root)?.kind === "furniture") {
5400
+ } else if (kitOriginOf2(b.root)?.kind === "furniture") {
5135
5401
  const piece = this.makePiece(objectId);
5136
5402
  this.tipIfTopHeavy(b);
5137
5403
  this.o.onLoosened?.(objectId, piece, "apart");
@@ -5185,7 +5451,7 @@ var Renderer = class {
5185
5451
  const piece = this.pieceSys.create(newId, group, half, center, this.massOf(newId), vel, ang);
5186
5452
  nb.piece = piece;
5187
5453
  this.fitSurface(nb, piece);
5188
- if (kitOriginOf(from.root)?.kind === "furniture") this.tipIfTopHeavy(nb);
5454
+ if (kitOriginOf2(from.root)?.kind === "furniture") this.tipIfTopHeavy(nb);
5189
5455
  this.o.onPiece?.(piece);
5190
5456
  }
5191
5457
  /**
@@ -5300,7 +5566,7 @@ var Renderer = class {
5300
5566
  /** The kind of kit piece a bound object is, by the mark on its root or the nearest one above it (a house binds a group inside its marked root); '' when unmarked. */
5301
5567
  kindOf(b) {
5302
5568
  for (let o = b.root; o; o = o.parent) {
5303
- const kind = kitOriginOf(o)?.kind;
5569
+ const kind = kitOriginOf2(o)?.kind;
5304
5570
  if (kind) return kind;
5305
5571
  }
5306
5572
  return "";
@@ -5551,7 +5817,7 @@ var Renderer = class {
5551
5817
  this.ground.add("puddle", c.x, c.z, clamp(footprint * 0.55, 0.05, 1), this.partColor(pv, def) ?? fallbackColor(def), objectId);
5552
5818
  } else {
5553
5819
  this.ground.add("ash", c.x, c.z, clamp(footprint * 0.35, 0.04, 0.5), 1907224, objectId);
5554
- this.vfx.burst("ash", [c.x, bb.max.y, c.z], [0, 1, 0], 10, 0.8);
5820
+ this.vfx.burst("ash", [c.x, bb.max.y, c.z], [0, 1, 0], 10, 0.8, { source: objectId });
5555
5821
  }
5556
5822
  }
5557
5823
  emitFire(f, pv, def) {
@@ -5559,17 +5825,20 @@ var Renderer = class {
5559
5825
  bb.makeEmpty();
5560
5826
  const tmp = new this.THREE.Box3();
5561
5827
  for (const mv of pv.meshes) if (this.visuals.shown(mv)) bb.union(this.visuals.worldBox(mv, tmp));
5562
- if (!bb.isEmpty()) {
5563
- const c = bb.getCenter(this.v1);
5564
- f.follow.x = c.x;
5565
- f.follow.y = bb.min.y;
5566
- f.follow.z = c.z;
5828
+ if (bb.isEmpty()) {
5829
+ if (f.handle !== void 0) this.vfx.stop(f.handle);
5830
+ delete f.handle;
5831
+ return;
5567
5832
  }
5833
+ const c = bb.getCenter(this.v1);
5834
+ f.follow.x = c.x;
5835
+ f.follow.y = bb.min.y;
5836
+ f.follow.z = c.z;
5568
5837
  if (f.handle !== void 0) return;
5569
- const size = bb.isEmpty() ? this.v2.set(0.2, 0.2, 0.2) : bb.getSize(this.v2);
5838
+ const size = bb.getSize(this.v2);
5570
5839
  const radius = clamp(Math.max(size.x, size.z) * 0.5, 0.12, 1.2);
5571
5840
  const smokeColor = SMOKE_TONES[def?.thermal.smoke ?? "grey"];
5572
- f.handle = this.vfx.fire({ point: [f.follow.x, f.follow.y, f.follow.z], radius, life: FIRE_CEILING_SECONDS, follow: f.follow, ...smokeColor !== void 0 ? { smokeColor } : {} });
5841
+ f.handle = this.vfx.fire({ point: [f.follow.x, f.follow.y, f.follow.z], radius, life: FIRE_CEILING_SECONDS, follow: f.follow, source: f.object, ...smokeColor !== void 0 ? { smokeColor } : {} });
5573
5842
  }
5574
5843
  updateLeaks(dt) {
5575
5844
  for (let i = this.leaks.length - 1; i >= 0; i--) {
@@ -5610,8 +5879,8 @@ var Renderer = class {
5610
5879
  while (l.acc >= 1) {
5611
5880
  l.acc -= 1;
5612
5881
  const vel = [dir[0] / dl * sp + (this.rng() - 0.5) * 0.25, dir[1] / dl * sp + (this.rng() - 0.5) * 0.25, dir[2] / dl * sp + (this.rng() - 0.5) * 0.25];
5613
- if (l.fluid === "gas") this.vfx.spawn("steam", pt, vel, { color, size: 0.5, alpha: 0.5 });
5614
- else this.vfx.spawn("drips", pt, vel, { color, tag: this.rng() < 0.03 ? this.tagOf(l.object) : 0, owner: this.owner });
5882
+ if (l.fluid === "gas") this.vfx.spawn("steam", pt, vel, { color, size: 0.5, alpha: 0.5, source: l.object });
5883
+ else this.vfx.spawn("drips", pt, vel, { color, tag: this.rng() < 0.03 ? this.tagOf(l.object) : 0, owner: this.owner, source: l.object });
5615
5884
  }
5616
5885
  }
5617
5886
  }
@@ -5644,6 +5913,53 @@ var Renderer = class {
5644
5913
  this.cages.removeObject(home);
5645
5914
  }
5646
5915
  }
5916
+ release(objectId) {
5917
+ const removed = this.releasePieces(objectId);
5918
+ this.unbind(objectId);
5919
+ return removed;
5920
+ }
5921
+ releasePieces(objectId) {
5922
+ const family = this.familyOf(objectId);
5923
+ const pieces = [...family].filter((id) => id !== objectId);
5924
+ const ofFamily = (key) => [...family].some((id) => key.startsWith(`${id}|`));
5925
+ for (let i = this.queue.length - 1; i >= 0; i--) if (family.has(this.queue[i].object)) this.queue.splice(i, 1);
5926
+ for (const [key, a] of [...this.active]) if (family.has(a.object)) this.active.delete(key);
5927
+ for (const [key, f] of [...this.fires]) if (family.has(f.object)) this.stopFire(key);
5928
+ for (const [key, started] of [...this.burnSounds]) if (family.has(started.object)) this.endBurnSound(key);
5929
+ for (const key of [...this.primedBurning]) if (ofFamily(key)) this.primedBurning.delete(key);
5930
+ for (let i = this.leaks.length - 1; i >= 0; i--) if (family.has(this.leaks[i].object)) this.leaks.splice(i, 1);
5931
+ for (let i = this.trickles.length - 1; i >= 0; i--) if (family.has(this.trickles[i].source ?? "")) this.trickles.splice(i, 1);
5932
+ for (const id of family) {
5933
+ this.fragments.removeHome(id);
5934
+ this.ground.removeHome(id);
5935
+ this.cages.removeObject(id);
5936
+ this.vfx.clearSource(id);
5937
+ }
5938
+ this.restore(objectId);
5939
+ for (const id of pieces) {
5940
+ this.pieceSys.remove(id);
5941
+ this.bounds.delete(id);
5942
+ this.hitPoints.forget(id);
5943
+ this.broken.delete(id);
5944
+ this.staticDirty.add(id);
5945
+ if (this.world.has(id)) this.world.remove(id);
5946
+ }
5947
+ if (pieces.length > 0) this.o.onReleased?.(pieces);
5948
+ return pieces;
5949
+ }
5950
+ /** The object and every piece split from it (a piece holds parts whose home is the object, also a piece of a piece). */
5951
+ familyOf(objectId) {
5952
+ const family = /* @__PURE__ */ new Set([objectId]);
5953
+ for (const b of this.bounds.values()) {
5954
+ if (!b.isSplit) continue;
5955
+ for (const pv of b.parts.values()) {
5956
+ if (pv.home !== objectId) continue;
5957
+ family.add(b.id);
5958
+ break;
5959
+ }
5960
+ }
5961
+ return family;
5962
+ }
5647
5963
  restoreHome(home) {
5648
5964
  const homeBound = this.bounds.get(home);
5649
5965
  for (const b of [...this.bounds.values()]) {
@@ -5666,6 +5982,7 @@ var Renderer = class {
5666
5982
  }
5667
5983
  }
5668
5984
  clear() {
5985
+ this.settledBatches.clear();
5669
5986
  this.staticAll = true;
5670
5987
  this.queue.length = 0;
5671
5988
  this.slices.length = 0;
@@ -6311,6 +6628,11 @@ var DESTRUCTION_SOUND_KEYS = {
6311
6628
  explode: { sound: "explosion_boom" }
6312
6629
  }
6313
6630
  };
6631
+ var BLAST_FAR_SOUND = "explosion_far";
6632
+ var BLAST_INDOOR_TAIL_SOUND = "explosion_indoor_tail";
6633
+ var blastSoundIds = (rules = DESTRUCTION_SOUND_KEYS.art_scene) => [
6634
+ .../* @__PURE__ */ new Set([...Object.values(BLAST_SOUND_OF), BLAST_FAR_SOUND, BLAST_INDOOR_TAIL_SOUND, ...Object.values(FIRE_LOOP_OF), "fire_crackle", "fire_pop", ...impactSoundIds(rules)])
6635
+ ];
6314
6636
  var DEFAULT_FIRE = { perFire: 0.08, max: 0.45 };
6315
6637
  var FIRE_FADE_SECONDS = 0.4;
6316
6638
  var DEFAULT_CRACKLES = { base: 2, perSqrtFire: 3, max: 14, volume: 0.5 };
@@ -6392,7 +6714,7 @@ function createDestructionSound(engine, options = {}) {
6392
6714
  const kind = named ?? ((detail?.radius ?? 0) >= BIG_BLAST_RADIUS || volume >= 0.9 ? "big" : "grenade");
6393
6715
  const sound = BLAST_SOUND_OF[kind];
6394
6716
  const distance = engine.plan(sound, { position: point, seed: 1 })?.distance ?? 0;
6395
- return kind !== "molotov" && distance > farDistance ? "explosion_far" : sound;
6717
+ return kind !== "molotov" && distance > farDistance ? BLAST_FAR_SOUND : sound;
6396
6718
  };
6397
6719
  return {
6398
6720
  onSound(key, point, volume, detail) {
@@ -6409,7 +6731,7 @@ function createDestructionSound(engine, options = {}) {
6409
6731
  if (key === "explode" && blastByKind) {
6410
6732
  const sound2 = blastSound(point, volume, detail);
6411
6733
  engine.play(sound2, { position: point, volume });
6412
- if (sound2 !== "explosion_far" && sound2 !== "molotov_break_ignite" && (detail?.confinement ?? 1) >= indoorFrom) engine.play("explosion_indoor_tail", { position: point, volume });
6734
+ if (sound2 !== BLAST_FAR_SOUND && sound2 !== "molotov_break_ignite" && (detail?.confinement ?? 1) >= indoorFrom) engine.play(BLAST_INDOOR_TAIL_SOUND, { position: point, volume });
6413
6735
  return;
6414
6736
  }
6415
6737
  let rule;
@@ -6535,8 +6857,13 @@ export {
6535
6857
  IMPACT_SOUND_KEYS,
6536
6858
  ROCKET_MOTOR_LOOP,
6537
6859
  SCENE_SOUNDS,
6860
+ SETTLED_BATCH_DEFAULTS,
6861
+ SETTLED_BATCH_ORIGIN,
6538
6862
  SMOKE_HISS_LOOP,
6863
+ SUGGESTED_MAX_AWAKE_FRAGMENTS,
6864
+ SUGGESTED_MAX_AWAKE_PIECES,
6539
6865
  blastFireSampleBank,
6866
+ blastSoundIds,
6540
6867
  breakSoundKeys,
6541
6868
  createDestructionRenderer,
6542
6869
  createDestructionSound,