@adatechnology/game-destruction-three 0.29.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8561,7 +8561,7 @@ var GameDestructionThree = (() => {
8561
8561
  return sources;
8562
8562
  }
8563
8563
 
8564
- // ../game-vfx-three/dist/chunk-EE6XER4D.js
8564
+ // ../game-vfx-three/dist/chunk-ACY6ZQC5.js
8565
8565
  var GLOW_VERTEX = `attribute vec4 aP;attribute vec4 aC;varying vec2 vU;varying vec4 vC;
8566
8566
  void main(){vec3 R=vec3(viewMatrix[0][0],viewMatrix[1][0],viewMatrix[2][0]);vec3 Up=vec3(viewMatrix[0][1],viewMatrix[1][1],viewMatrix[2][1]);
8567
8567
  vec3 wp=aP.xyz+(R*position.x+Up*position.y)*aP.w;vU=position.xy;vC=aC;gl_Position=projectionMatrix*viewMatrix*vec4(wp,1.);}`;
@@ -9609,8 +9609,48 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
9609
9609
  }
9610
9610
  };
9611
9611
  }
9612
- var REST_LAYER = 2e-3;
9613
- var REST_LAYERS = 4;
9612
+ var REST_STEP = 15e-4;
9613
+ var REST_TRIES = 8;
9614
+ var SAME_NORMAL = 0.9995;
9615
+ var restBox = () => ({ c: new Float64Array(3), axes: new Float64Array(9), half: new Float64Array(3), ext: new Float64Array(3) });
9616
+ function boxOf(piece, out) {
9617
+ const cx = Math.cos(piece.rx), sx = Math.sin(piece.rx), cy = Math.cos(piece.ry), sy = Math.sin(piece.ry), cz = Math.cos(piece.rz), sz = Math.sin(piece.rz);
9618
+ const a = out.axes;
9619
+ a[0] = cy * cz;
9620
+ a[1] = sx * sy * cz + cx * sz;
9621
+ a[2] = sx * sz - cx * sy * cz;
9622
+ a[3] = -cy * sz;
9623
+ a[4] = cx * cz - sx * sy * sz;
9624
+ a[5] = cx * sy * sz + sx * cz;
9625
+ a[6] = sy;
9626
+ a[7] = -sx * cy;
9627
+ a[8] = cx * cy;
9628
+ out.half[0] = piece.sx / 2;
9629
+ out.half[1] = piece.sy / 2;
9630
+ out.half[2] = piece.sz / 2;
9631
+ out.c[0] = piece.x;
9632
+ out.c[1] = piece.y;
9633
+ out.c[2] = piece.z;
9634
+ for (let w = 0; w < 3; w++) out.ext[w] = Math.abs(a[w]) * out.half[0] + Math.abs(a[3 + w]) * out.half[1] + Math.abs(a[6 + w]) * out.half[2];
9635
+ }
9636
+ function sharedPlane(a, b, push) {
9637
+ for (let w = 0; w < 3; w++) if (Math.abs(a.c[w] - b.c[w]) >= a.ext[w] + b.ext[w] + REST_STEP) return false;
9638
+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) {
9639
+ const ax = a.axes[3 * i], ay = a.axes[3 * i + 1], az = a.axes[3 * i + 2];
9640
+ const dot3 = ax * b.axes[3 * j] + ay * b.axes[3 * j + 1] + az * b.axes[3 * j + 2];
9641
+ if (Math.abs(dot3) < SAME_NORMAL) continue;
9642
+ const ca = ax * a.c[0] + ay * a.c[1] + az * a.c[2];
9643
+ const cb = ax * b.c[0] + ay * b.c[1] + az * b.c[2];
9644
+ for (let side = -1; side <= 1; side += 2) {
9645
+ if (Math.abs(ca + side * a.half[i] - (cb + side * b.half[j])) >= REST_STEP * 0.75) continue;
9646
+ push[0] = ax * side;
9647
+ push[1] = ay * side;
9648
+ push[2] = az * side;
9649
+ return true;
9650
+ }
9651
+ }
9652
+ return false;
9653
+ }
9614
9654
  function debrisLayer(THREE, pool) {
9615
9655
  const geometry = new THREE.BoxGeometry(1, 1, 1);
9616
9656
  const material = new THREE.MeshStandardMaterial({ color: 16777215, roughness: 0.45, metalness: 0.25, flatShading: true });
@@ -9625,6 +9665,36 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
9625
9665
  const matrix = new THREE.Matrix4();
9626
9666
  const colour = new THREE.Color();
9627
9667
  const hidden = new THREE.Matrix4().makeScale(0, 0, 0);
9668
+ const offset = new Float64Array(DEBRIS_CAPACITY * 3);
9669
+ const settled = new Uint8Array(DEBRIS_CAPACITY);
9670
+ const boxes = Array.from({ length: DEBRIS_CAPACITY }, restBox);
9671
+ const push = new Float64Array(3);
9672
+ const settle = (index) => {
9673
+ const box = boxes[index];
9674
+ boxOf(pool.pieces[index], box);
9675
+ let dx = 0, dy = 0, dz = 0;
9676
+ for (let tries = 0; tries < REST_TRIES; tries++) {
9677
+ let clash = false;
9678
+ for (let other = 0; other < DEBRIS_CAPACITY && !clash; other++) {
9679
+ if (other === index || !settled[other]) continue;
9680
+ if (!sharedPlane(box, boxes[other], push)) continue;
9681
+ clash = true;
9682
+ const up = Math.abs(push[1]) > 0.7;
9683
+ const ux = up ? 0 : push[0], uy = up ? 1 : push[1], uz = up ? 0 : push[2];
9684
+ dx += ux * REST_STEP;
9685
+ dy += uy * REST_STEP;
9686
+ dz += uz * REST_STEP;
9687
+ box.c[0] = box.c[0] + ux * REST_STEP;
9688
+ box.c[1] = box.c[1] + uy * REST_STEP;
9689
+ box.c[2] = box.c[2] + uz * REST_STEP;
9690
+ }
9691
+ if (!clash) break;
9692
+ }
9693
+ offset[3 * index] = dx;
9694
+ offset[3 * index + 1] = dy;
9695
+ offset[3 * index + 2] = dz;
9696
+ settled[index] = 1;
9697
+ };
9628
9698
  for (let index = 0; index < DEBRIS_CAPACITY; index++) mesh2.setMatrixAt(index, hidden);
9629
9699
  mesh2.setColorAt(0, colour.setHex(16777215));
9630
9700
  return {
@@ -9633,16 +9703,18 @@ void main(){vec2 d=gl_PointCoord-.5;float r=length(d)*2.;if(r>1.)discard;float a
9633
9703
  let drawn = false;
9634
9704
  for (let index = 0; index < DEBRIS_CAPACITY; index++) {
9635
9705
  const piece = pool.pieces[index];
9706
+ if (!piece.on || !piece.rest) settled[index] = 0;
9636
9707
  if (!piece.on) {
9637
9708
  mesh2.setMatrixAt(index, hidden);
9638
9709
  continue;
9639
9710
  }
9711
+ if (piece.rest && !settled[index]) settle(index);
9640
9712
  drawn = true;
9641
9713
  const shrink = Math.min(1, piece.life / FADE_SECONDS2);
9642
9714
  euler.set(piece.rx, piece.ry, piece.rz);
9643
9715
  quaternion.setFromEuler(euler);
9644
- const lift = piece.rest ? index % REST_LAYERS * REST_LAYER : 0;
9645
- matrix.compose(position.set(piece.x, piece.y + lift, piece.z), quaternion, scale.set(piece.sx * shrink, piece.sy * shrink, piece.sz * shrink));
9716
+ const off2 = piece.rest ? 3 * index : -1;
9717
+ matrix.compose(position.set(piece.x + (off2 >= 0 ? offset[off2] : 0), piece.y + (off2 >= 0 ? offset[off2 + 1] : 0), piece.z + (off2 >= 0 ? offset[off2 + 2] : 0)), quaternion, scale.set(piece.sx * shrink, piece.sy * shrink, piece.sz * shrink));
9646
9718
  mesh2.setMatrixAt(index, matrix);
9647
9719
  mesh2.setColorAt(index, colour.setHex(piece.color));
9648
9720
  }
@@ -11191,18 +11263,18 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
11191
11263
  let by = b[bi + 1];
11192
11264
  let bz = b[bi + 2];
11193
11265
  let bw = b[bi + 3];
11194
- let dot2 = ax * bx + ay * by + az * bz + aw * bw;
11195
- if (dot2 < 0) {
11266
+ let dot3 = ax * bx + ay * by + az * bz + aw * bw;
11267
+ if (dot3 < 0) {
11196
11268
  bx = -bx;
11197
11269
  by = -by;
11198
11270
  bz = -bz;
11199
11271
  bw = -bw;
11200
- dot2 = -dot2;
11272
+ dot3 = -dot3;
11201
11273
  }
11202
11274
  let from = 1 - t;
11203
11275
  let to = t;
11204
- if (dot2 < 0.9995) {
11205
- const angle = Math.acos(dot2);
11276
+ if (dot3 < 0.9995) {
11277
+ const angle = Math.acos(dot3);
11206
11278
  const sine = Math.sin(angle);
11207
11279
  from = Math.sin((1 - t) * angle) / sine;
11208
11280
  to = Math.sin(t * angle) / sine;
@@ -12039,6 +12111,21 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12039
12111
  return { center: box.center, half };
12040
12112
  };
12041
12113
 
12114
+ // src/built-solids.ts
12115
+ var numbers = (value, count) => Array.isArray(value) && value.length === count && value.every((v) => typeof v === "number" && Number.isFinite(v));
12116
+ var isBuiltSolid = (value) => {
12117
+ if (typeof value !== "object" || value === null) return false;
12118
+ const solid = value;
12119
+ return numbers(solid.center, 3) && numbers(solid.half, 3) && numbers(solid.rotation, 4) && (solid.kind === void 0 || typeof solid.kind === "string");
12120
+ };
12121
+ var builtSolidsOf = (mesh2) => {
12122
+ const list = mesh2.userData.solids;
12123
+ if (!Array.isArray(list) || list.length === 0 || !list.every(isBuiltSolid)) return null;
12124
+ return list;
12125
+ };
12126
+ var ROUND_SIDES = 0.05;
12127
+ var isRoundSolid = (solid) => solid.kind === "cylinder" && Math.abs(solid.half[0] - solid.half[2]) <= ROUND_SIDES * Math.max(solid.half[0], solid.half[2]);
12128
+
12042
12129
  // ../game-shapes/dist/index.js
12043
12130
  var MIN_HALF = 0.01;
12044
12131
  var MAX_DEPTH = 3;
@@ -12289,6 +12376,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12289
12376
  // src/static-part-job.ts
12290
12377
  var FIT = 0.01;
12291
12378
  var FILL = 0.5;
12379
+ var SOLID = 0.5;
12292
12380
  var MIN_HALF2 = 5e-3;
12293
12381
  var COLLAPSED = 2e-3;
12294
12382
  var MIN_FACE = 1e-6;
@@ -12325,10 +12413,11 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12325
12413
  const size = [high[0] - low[0], high[1] - low[1], high[2] - low[2]];
12326
12414
  const s = [Math.abs(scale[0]), Math.abs(scale[1]), Math.abs(scale[2])];
12327
12415
  if (Math.max(size[0] * s[0], size[1] * s[1], size[2] * s[2]) < COLLAPSED) return [];
12416
+ if (job.solids && job.solids.length > 0) return job.solids.map((solid) => builtSolidIn(solid, pos, quat2, scale));
12328
12417
  const centre = [(low[0] + high[0]) / 2, (low[1] + high[1]) / 2, (low[2] + high[2]) / 2];
12329
12418
  const half = [size[0] / 2, size[1] / 2, size[2] / 2];
12330
12419
  const straight = { center: centre, half, axes: IDENTITY2, tolerance: [FIT / s[0], FIT / s[1], FIT / s[2]] };
12331
- if (hugs(points, straight) && fillsFaces(points, found, from, straight)) {
12420
+ if (hugs(points, straight) && fillsFaces(points, found, from, straight) && fillsVolume(points, found, from, straight)) {
12332
12421
  const [cx, cy, cz] = turn(centre[0] * scale[0], centre[1] * scale[1], centre[2] * scale[2], quat2);
12333
12422
  return [{ center: [cx + pos[0], cy + pos[1], cz + pos[2]], half: [Math.max(MIN_HALF2, half[0] * s[0]), Math.max(MIN_HALF2, half[1] * s[1]), Math.max(MIN_HALF2, half[2] * s[2])], rotation: [quat2[0], quat2[1], quat2[2], quat2[3]] }];
12334
12423
  }
@@ -12341,9 +12430,24 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12341
12430
  world[i + 2] = e[2] * x + e[6] * y + e[10] * z + e[14];
12342
12431
  }
12343
12432
  const turned = fitOrientedBox(world);
12344
- if (turned && fitsTurned(world, turned) && fillsFaces(world, found, from, turnedBox(turned))) return [turned];
12433
+ if (turned && fitsTurned(world, turned) && fillsFaces(world, found, from, turnedBox(turned)) && fillsVolume(world, found, from, turnedBox(turned))) return [turned];
12345
12434
  return [trimeshOf(world, from, found)];
12346
12435
  }
12436
+ var builtSolidIn = (solid, pos, quat2, scale) => {
12437
+ const [cx, cy, cz] = turn(solid.center[0] * scale[0], solid.center[1] * scale[1], solid.center[2] * scale[2], quat2);
12438
+ const [ax, ay, az, aw] = quat2;
12439
+ const [bx, by, bz, bw] = solid.rotation;
12440
+ const turned = Math.abs(bw) < 1 - 1e-9;
12441
+ const even = (Math.abs(scale[0]) + Math.abs(scale[1]) + Math.abs(scale[2])) / 3;
12442
+ const s = turned ? [even, even, even] : [Math.abs(scale[0]), Math.abs(scale[1]), Math.abs(scale[2])];
12443
+ return {
12444
+ ...isRoundSolid(solid) && Math.abs(s[0] - s[2]) <= 1e-9 ? { round: true } : {},
12445
+ center: [cx + pos[0], cy + pos[1], cz + pos[2]],
12446
+ half: [Math.max(MIN_HALF2, solid.half[0] * s[0]), Math.max(MIN_HALF2, solid.half[1] * s[1]), Math.max(MIN_HALF2, solid.half[2] * s[2])],
12447
+ // the mesh's turn, then the solid's own
12448
+ rotation: [aw * bx + ax * bw + ay * bz - az * by, aw * by - ax * bz + ay * bw + az * bx, aw * bz + ax * by - ay * bx + az * bw, aw * bw - ax * bx - ay * by - az * bz]
12449
+ };
12450
+ };
12347
12451
  var staticSolidsTransfer = (solids) => {
12348
12452
  const out = [];
12349
12453
  for (const solid of solids) if (solid.mesh) out.push(solid.mesh.vertices.buffer, solid.mesh.indices.buffer);
@@ -12382,6 +12486,21 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
12382
12486
  }
12383
12487
  return true;
12384
12488
  };
12489
+ var fillsVolume = (points, found, from, box) => {
12490
+ if (found.length === 0) return true;
12491
+ const whole = 8 * box.half[0] * box.half[1] * box.half[2];
12492
+ if (!(whole > 0)) return true;
12493
+ const [cx, cy, cz] = box.center;
12494
+ let six = 0;
12495
+ for (let i = 0; i + 2 < found.length; i += 3) {
12496
+ const a = (found[i] - from) * 3, b = (found[i + 1] - from) * 3, c = (found[i + 2] - from) * 3;
12497
+ const ax = points[a] - cx, ay = points[a + 1] - cy, az = points[a + 2] - cz;
12498
+ const bx = points[b] - cx, by = points[b + 1] - cy, bz = points[b + 2] - cz;
12499
+ const dx = points[c] - cx, dy = points[c + 1] - cy, dz = points[c + 2] - cz;
12500
+ six += ax * (by * dz - bz * dy) + ay * (bz * dx - bx * dz) + az * (bx * dy - by * dx);
12501
+ }
12502
+ return Math.abs(six) / 6 >= whole * SOLID;
12503
+ };
12385
12504
  var trimeshOf = (world, from, found) => {
12386
12505
  const indices = new Uint32Array(found.length);
12387
12506
  for (let i = 0; i < found.length; i++) indices[i] = found[i] - from;
@@ -13373,6 +13492,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
13373
13492
  const quat2 = new THREE.Quaternion();
13374
13493
  const scale = new THREE.Vector3();
13375
13494
  mv.mesh.matrixWorld.decompose(pos, quat2, scale);
13495
+ const built2 = mv.range ? null : builtSolidsOf(mv.mesh);
13376
13496
  return {
13377
13497
  points,
13378
13498
  matrix: Float64Array.from(matrix),
@@ -13380,7 +13500,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
13380
13500
  quaternion: [quat2.x, quat2.y, quat2.z, quat2.w],
13381
13501
  scale: [scale.x, scale.y, scale.z],
13382
13502
  found: Uint32Array.from(trianglesOfPart(mv, local2)),
13383
- from: local2.from
13503
+ from: local2.from,
13504
+ // a mesh of its own that says what it was built from is held by that (a part of a merged mesh is only some of its mesh)
13505
+ ...built2 ? { solids: built2 } : {}
13384
13506
  };
13385
13507
  };
13386
13508
  var trianglesOfRanges = (mv, ranges) => {
@@ -13424,41 +13546,99 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
13424
13546
  var BOX_VERTICES = 24;
13425
13547
  var MAX_BOXES = 16;
13426
13548
  var CORNER = 1e-4;
13427
- var HOLLOW = 0.5;
13428
- var hollowBoxesOf = (points) => {
13549
+ var RANGED = { share: 0.5, turned: false };
13550
+ var OWN_MESH = { share: 0.8, turned: true };
13551
+ var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
13552
+ var quaternionOf = (x, y, z) => {
13553
+ const [m00, m10, m20] = x;
13554
+ const [m01, m11, m21] = y;
13555
+ const [m02, m12, m22] = z;
13556
+ const trace = m00 + m11 + m22;
13557
+ if (trace > 0) {
13558
+ const s2 = 0.5 / Math.sqrt(trace + 1);
13559
+ return [(m21 - m12) * s2, (m02 - m20) * s2, (m10 - m01) * s2, 0.25 / s2];
13560
+ }
13561
+ if (m00 > m11 && m00 > m22) {
13562
+ const s2 = 2 * Math.sqrt(1 + m00 - m11 - m22);
13563
+ return [0.25 * s2, (m01 + m10) / s2, (m02 + m20) / s2, (m21 - m12) / s2];
13564
+ }
13565
+ if (m11 > m22) {
13566
+ const s2 = 2 * Math.sqrt(1 + m11 - m00 - m22);
13567
+ return [(m01 + m10) / s2, 0.25 * s2, (m12 + m21) / s2, (m02 - m20) / s2];
13568
+ }
13569
+ const s = 2 * Math.sqrt(1 + m22 - m00 - m11);
13570
+ return [(m02 + m20) / s, (m12 + m21) / s, 0.25 * s, (m10 - m01) / s];
13571
+ };
13572
+ var straightBoxOf = (points, first) => {
13573
+ const low = [Infinity, Infinity, Infinity];
13574
+ const high = [-Infinity, -Infinity, -Infinity];
13575
+ for (let v = first; v < first + BOX_VERTICES; v++) {
13576
+ for (let k = 0; k < 3; k++) {
13577
+ low[k] = Math.min(low[k], points[v * 3 + k]);
13578
+ high[k] = Math.max(high[k], points[v * 3 + k]);
13579
+ }
13580
+ }
13581
+ const corners = /* @__PURE__ */ new Set();
13582
+ for (let v = first; v < first + BOX_VERTICES; v++) {
13583
+ let corner = 0;
13584
+ for (let k = 0; k < 3; k++) {
13585
+ const x = points[v * 3 + k];
13586
+ if (Math.abs(x - high[k]) <= CORNER) corner |= 1 << k;
13587
+ else if (Math.abs(x - low[k]) > CORNER) return null;
13588
+ }
13589
+ corners.add(corner);
13590
+ }
13591
+ if (corners.size !== 8) return null;
13592
+ return { center: [(low[0] + high[0]) / 2, (low[1] + high[1]) / 2, (low[2] + high[2]) / 2], half: [(high[0] - low[0]) / 2, (high[1] - low[1]) / 2, (high[2] - low[2]) / 2] };
13593
+ };
13594
+ var turnedBoxOf = (points, first) => {
13595
+ const corners = [];
13596
+ for (let v = first; v < first + BOX_VERTICES; v++) {
13597
+ const p = [points[v * 3], points[v * 3 + 1], points[v * 3 + 2]];
13598
+ if (!corners.some((c) => Math.abs(c[0] - p[0]) <= CORNER && Math.abs(c[1] - p[1]) <= CORNER && Math.abs(c[2] - p[2]) <= CORNER)) corners.push(p);
13599
+ }
13600
+ if (corners.length !== 8) return null;
13601
+ const origin = corners[0];
13602
+ const edges = corners.slice(1).map((c) => [c[0] - origin[0], c[1] - origin[1], c[2] - origin[2]]);
13603
+ const lengths = edges.map((e) => Math.hypot(e[0], e[1], e[2]));
13604
+ const square = (i, j) => Math.abs(dot(edges[i], edges[j])) <= CORNER * (lengths[i] + lengths[j] + 1);
13605
+ for (let i = 0; i < 7; i++) for (let j = i + 1; j < 7; j++) for (let k = j + 1; k < 7; k++) {
13606
+ if (!square(i, j) || !square(i, k) || !square(j, k)) continue;
13607
+ const [a, b, c] = [edges[i], edges[j], edges[k]];
13608
+ const sums = [[0, 0, 0], a, b, c, [a[0] + b[0], a[1] + b[1], a[2] + b[2]], [a[0] + c[0], a[1] + c[1], a[2] + c[2]], [b[0] + c[0], b[1] + c[1], b[2] + c[2]], [a[0] + b[0] + c[0], a[1] + b[1] + c[1], a[2] + b[2] + c[2]]];
13609
+ const found = sums.every((s) => corners.some((p) => Math.abs(p[0] - origin[0] - s[0]) <= 4 * CORNER && Math.abs(p[1] - origin[1] - s[1]) <= 4 * CORNER && Math.abs(p[2] - origin[2] - s[2]) <= 4 * CORNER));
13610
+ if (!found) continue;
13611
+ const [la, lb, lc] = [lengths[i], lengths[j], lengths[k]];
13612
+ if (la <= 0 || lb <= 0 || lc <= 0) return null;
13613
+ const x = [a[0] / la, a[1] / la, a[2] / la];
13614
+ const y = [b[0] / lb, b[1] / lb, b[2] / lb];
13615
+ let z = [c[0] / lc, c[1] / lc, c[2] / lc];
13616
+ const cross5 = [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]];
13617
+ if (dot(cross5, z) < 0) z = [-z[0], -z[1], -z[2]];
13618
+ const far2 = sums[7];
13619
+ return { center: [origin[0] + far2[0] / 2, origin[1] + far2[1] / 2, origin[2] + far2[2] / 2], half: [la / 2, lb / 2, lc / 2], rotation: quaternionOf(x, y, z) };
13620
+ }
13621
+ return null;
13622
+ };
13623
+ var hollowBoxesOf = (points, rule = RANGED) => {
13429
13624
  const count = points.length / 3;
13430
- if (count % BOX_VERTICES !== 0 || count / BOX_VERTICES < 2 || count / BOX_VERTICES > MAX_BOXES) return null;
13625
+ if (count % BOX_VERTICES !== 0 || count / BOX_VERTICES < (rule.turned ? 1 : 2) || count / BOX_VERTICES > MAX_BOXES) return null;
13431
13626
  const boxes = [];
13432
- const all = { low: [Infinity, Infinity, Infinity], high: [-Infinity, -Infinity, -Infinity] };
13627
+ const low = [Infinity, Infinity, Infinity];
13628
+ const high = [-Infinity, -Infinity, -Infinity];
13433
13629
  for (let first = 0; first < count; first += BOX_VERTICES) {
13434
- const low = [Infinity, Infinity, Infinity];
13435
- const high = [-Infinity, -Infinity, -Infinity];
13436
- for (let v = first; v < first + BOX_VERTICES; v++) {
13437
- for (let k = 0; k < 3; k++) {
13438
- low[k] = Math.min(low[k], points[v * 3 + k]);
13439
- high[k] = Math.max(high[k], points[v * 3 + k]);
13440
- }
13441
- }
13442
- const corners = /* @__PURE__ */ new Set();
13443
- for (let v = first; v < first + BOX_VERTICES; v++) {
13444
- let corner = 0;
13445
- for (let k = 0; k < 3; k++) {
13446
- const x = points[v * 3 + k];
13447
- if (Math.abs(x - high[k]) <= CORNER) corner |= 1 << k;
13448
- else if (Math.abs(x - low[k]) > CORNER) return null;
13449
- }
13450
- corners.add(corner);
13451
- }
13452
- if (corners.size !== 8) return null;
13630
+ const box = straightBoxOf(points, first) ?? (rule.turned ? turnedBoxOf(points, first) : null);
13631
+ if (!box) return null;
13632
+ boxes.push(box);
13633
+ }
13634
+ for (let i = 0; i < points.length; i += 3) {
13453
13635
  for (let k = 0; k < 3; k++) {
13454
- all.low[k] = Math.min(all.low[k], low[k]);
13455
- all.high[k] = Math.max(all.high[k], high[k]);
13636
+ low[k] = Math.min(low[k], points[i + k]);
13637
+ high[k] = Math.max(high[k], points[i + k]);
13456
13638
  }
13457
- boxes.push({ low, high });
13458
13639
  }
13459
- const volume = (low, high) => (high[0] - low[0]) * (high[1] - low[1]) * (high[2] - low[2]);
13460
- const filled = boxes.reduce((sum, box) => sum + volume(box.low, box.high), 0);
13461
- return filled < HOLLOW * volume(all.low, all.high) ? boxes : null;
13640
+ const filled = boxes.reduce((sum, box) => sum + 8 * box.half[0] * box.half[1] * box.half[2], 0);
13641
+ return filled < rule.share * (high[0] - low[0]) * (high[1] - low[1]) * (high[2] - low[2]) ? boxes : null;
13462
13642
  };
13463
13643
 
13464
13644
  // src/rigid-pose.ts
@@ -13510,7 +13690,11 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
13510
13690
  row(2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y))
13511
13691
  ];
13512
13692
  };
13513
- var shapeOf = (s) => s.mesh ? { kind: "trimesh", vertices: s.mesh.vertices, indices: s.mesh.indices } : { kind: "box", half: s.half };
13693
+ var shapeOf = (s) => {
13694
+ if (s.mesh) return { kind: "trimesh", vertices: s.mesh.vertices, indices: s.mesh.indices };
13695
+ if (s.round) return { kind: "cylinder", halfHeight: s.half[1], radius: (s.half[0] + s.half[2]) / 2 };
13696
+ return { kind: "box", half: s.half };
13697
+ };
13514
13698
  var EngineStatics = class {
13515
13699
  constructor(world, material) {
13516
13700
  __publicField(this, "world", world);
@@ -13756,30 +13940,30 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
13756
13940
  var SEGMENT_BOX_ROUNDS = 4;
13757
13941
  var PARALLEL2 = 1e-4;
13758
13942
  var sub2 = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
13759
- var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
13943
+ var dot2 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
13760
13944
  var along = (a, d, t) => [a[0] + d[0] * t, a[1] + d[1] * t, a[2] + d[2] * t];
13761
13945
  var clamp01 = (t) => t < 0 ? 0 : t > 1 ? 1 : t;
13762
13946
  var nearestOnSegment = (from, to, p) => {
13763
13947
  const d = sub2(to, from);
13764
- const len2 = dot(d, d);
13765
- return len2 < 1e-12 ? from : along(from, d, clamp01(dot(sub2(p, from), d) / len2));
13948
+ const len2 = dot2(d, d);
13949
+ return len2 < 1e-12 ? from : along(from, d, clamp01(dot2(sub2(p, from), d) / len2));
13766
13950
  };
13767
13951
  var nearestOfSegments = (p1, q1, p2, q2) => {
13768
13952
  const d1 = sub2(q1, p1);
13769
13953
  const d2 = sub2(q2, p2);
13770
13954
  const r = sub2(p1, p2);
13771
- const a = dot(d1, d1);
13772
- const e = dot(d2, d2);
13773
- const f = dot(d2, r);
13955
+ const a = dot2(d1, d1);
13956
+ const e = dot2(d2, d2);
13957
+ const f = dot2(d2, r);
13774
13958
  let s = 0;
13775
13959
  let t = 0;
13776
13960
  if (a < 1e-12 && e < 1e-12) return [p1, p2];
13777
13961
  if (a < 1e-12) t = clamp01(f / e);
13778
13962
  else {
13779
- const c = dot(d1, r);
13963
+ const c = dot2(d1, r);
13780
13964
  if (e < 1e-12) s = clamp01(-c / a);
13781
13965
  else {
13782
- const b = dot(d1, d2);
13966
+ const b = dot2(d1, d2);
13783
13967
  const denom = a * e - b * b;
13784
13968
  if (denom > PARALLEL2 * a * e) s = clamp01((b * f - c * e) / denom);
13785
13969
  else {
@@ -13893,8 +14077,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
13893
14077
  }
13894
14078
  const normal = [nx, ny, nz];
13895
14079
  const mid = [(a.c[0] + b.c[0]) / 2, (a.c[1] + b.c[1]) / 2, (a.c[2] + b.c[2]) / 2];
13896
- const middle = (dot(a.c, normal) - reachAlong2(a, nx, ny, nz) + dot(b.c, normal) + reachAlong2(b, nx, ny, nz)) / 2;
13897
- return { point: along(mid, normal, middle - dot(mid, normal)), normal, depth };
14080
+ const middle = (dot2(a.c, normal) - reachAlong2(a, nx, ny, nz) + dot2(b.c, normal) + reachAlong2(b, nx, ny, nz)) / 2;
14081
+ return { point: along(mid, normal, middle - dot2(mid, normal)), normal, depth };
13898
14082
  };
13899
14083
  var LEVEL_SHARE = 1e-3;
13900
14084
  var boxBoxAlongGround = (a, b) => {
@@ -14375,7 +14559,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
14375
14559
  return a.rotation.every((v, i) => Math.abs(v - b.rotation[i]) < FLUSH);
14376
14560
  };
14377
14561
  var flushAxis = (a, b) => {
14378
- if (!sameTurn(a, b)) return -1;
14562
+ if (a.round || b.round || a.hull || b.hull || !sameTurn(a, b)) return -1;
14379
14563
  let along2 = -1;
14380
14564
  for (let axis2 = 0; axis2 < 3; axis2++) {
14381
14565
  const same2 = Math.abs(a.half[axis2] - b.half[axis2]) < FLUSH && Math.abs(a.center[axis2] - b.center[axis2]) < FLUSH;
@@ -14427,7 +14611,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
14427
14611
  var ROLLING_RESISTANCE = 0.015;
14428
14612
  var MU_DYNAMIC = 0.6;
14429
14613
  var GROUND = { frictionStatic: MU_STATIC, frictionDynamic: MU_DYNAMIC, restitution: 0, rolling: ROLLING_RESISTANCE };
14430
- var groundTileKey = (x, z) => (Math.floor(x / TILE) + TILE_KEY_ORIGIN) * TILE_KEY + (Math.floor(z / TILE) + TILE_KEY_ORIGIN);
14431
14614
  var tileRollingAt = (rollingAt, x, z) => rollingAt((Math.floor(x / TILE) + 0.5) * TILE, (Math.floor(z / TILE) + 0.5) * TILE);
14432
14615
  var STILL_SPEED = 0.12;
14433
14616
  var STILL_SPIN = 0.45;
@@ -14900,7 +15083,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
14900
15083
  return { kind: "compound", children: [{ shape: { kind: "cylinder", halfHeight: b.halfExtents[round2.axis], radius: round2.radius }, position: [0, 0, 0], rotation: rotation2 }] };
14901
15084
  }
14902
15085
  if (b.partBoxes && b.partBoxes.length > 0) {
14903
- return { kind: "compound", children: mergeFlushBoxes(b.partBoxes).map((part, i) => ({ shape: { kind: "box", half: part.half }, position: part.center, ...part.rotation ? { rotation: part.rotation } : {}, tag: i })) };
15086
+ return { kind: "compound", children: mergeFlushBoxes(b.partBoxes).map((part, i) => ({ shape: part.hull ? { kind: "convex", points: [...part.hull] } : part.round ? { kind: "cylinder", halfHeight: part.half[1], radius: (part.half[0] + part.half[2]) / 2 } : { kind: "box", half: part.half }, position: part.center, ...part.rotation ? { rotation: part.rotation } : {}, tag: i })) };
14904
15087
  }
14905
15088
  return { kind: "box", half: b.halfExtents };
14906
15089
  }
@@ -15846,9 +16029,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
15846
16029
  }
15847
16030
  };
15848
16031
  var resolvePhysics = (option) => {
15849
- if (option === "own") return null;
15850
16032
  if (option === void 0 || typeof option !== "object") {
15851
- throw new PhysicsOptionError("the `physics` option is required: pass a PhysicsLoop, a world from the host, or 'own' for the kit's own solver");
16033
+ throw new PhysicsOptionError("the `physics` option is required: pass a PhysicsLoop or a world from the host");
15852
16034
  }
15853
16035
  if (isPhysicsLoop(option)) return { loop: option, stepsItself: false };
15854
16036
  if (typeof option.stepFixed !== "function") {
@@ -15898,44 +16080,20 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
15898
16080
  }
15899
16081
 
15900
16082
  // src/pieces.ts
15901
- var SLAM_MIN_SPEED2 = 2;
15902
- var SLAM_BOUNCE2 = 0.2;
15903
16083
  var BALANCE_TOLERANCE = 0.01;
15904
- var SLAM_FLOOR_NORMAL2 = 0.7;
15905
- var SUB_DT = 1 / 120;
15906
16084
  var MU_STATIC2 = 0.7;
15907
16085
  var MU_DYNAMIC2 = 0.6;
15908
- var SLIP_SPEED = 0.02;
15909
16086
  var ROLLING_RESISTANCE2 = 0.015;
15910
- var ROUND_LYING = Math.SQRT1_2;
15911
16087
  var MIN_PIECE_HALF = 1e-3;
15912
- var OWN_MIN_PIECE_HALF = 0.01;
15913
- var OWN_MIN_MEASURED_HALF = 0.02;
15914
- var minPieceHalf = (physics) => physics === "own" ? OWN_MIN_MEASURED_HALF : MIN_PIECE_HALF;
15915
16088
  var SLEEP_AFTER = 0.5;
15916
16089
  var STILL_SPEED2 = 0.12;
15917
16090
  var STILL_SPIN2 = 0.45;
15918
- var CALM_DRIFT = 0.01;
15919
- var CALM_TURN = 0.05;
15920
- var CALM_SLEEP_AFTER = 1.5;
15921
- var STEADY_TURN2 = 0.1;
15922
16091
  var STEADY_SECONDS2 = 1.5;
15923
- var HARD_LANDING2 = 3;
15924
16092
  var SLOP = 2e-3;
15925
- var NARROW2 = 0.3;
15926
- var SUPPORT_MARGIN = 0.05;
15927
- var TOPPLE2 = 3;
15928
- var TIP_ACCELERATION = 30;
15929
- var TIP_RISING = 0.02;
15930
- var TIP_RISE_AFTER = 0.5;
15931
- var TIP_LYING = 0.25;
15932
16093
  var TIP_SECONDS = 3;
15933
16094
  var STEP = 0.03;
15934
16095
  var WAKE_SAMPLES = 4;
15935
16096
  var WAKE_DROP = 0.05;
15936
- var WARM_SLOTS = 8 + 12 * 7;
15937
- var SOLVER_PASSES = 10;
15938
- var SIDE_BOUNCE = 0.1;
15939
16097
  var EDGE_POINTS = [-0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75];
15940
16098
  var EDGE_SPACING = 0.05;
15941
16099
  var MAX_EDGE_POINTS = 31;
@@ -15952,15 +16110,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
15952
16110
  var SLOPE_MIN_NORMAL = 0.5;
15953
16111
  var LIES_FLAT = 0.985;
15954
16112
  var KEEP_EVERY = 0.5;
15955
- var WAKE_ABOVE_SPEED = 0.05;
15956
- var WAKE_ABOVE_SPIN = 0.1;
15957
16113
  var SURFACE_CELL = 0.5;
15958
16114
  var SURFACE_CELLS_ACROSS = 24;
15959
16115
  var cellKey = (ix, iz) => (ix + 32768) * 65536 + (iz + 32768);
15960
- var MAX_COLLISION_STEPS = 8;
15961
- var MIN_ROUND_RADIUS = 5e-3;
15962
- var BOUNCE_MIN_SPEED = 0.1;
15963
- var BOX_IMPACT_SPEED = 1.5;
15964
16116
  var KNOCK_FLAT = 0.5;
15965
16117
  var SEPARATE_SPEED = 1.5;
15966
16118
  var LIFT_DEPTH = STEP;
@@ -16009,8 +16161,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16009
16161
  // both lose energy in the contact: a log on grass is held by its bark and by the blades
16010
16162
  rollingDamping: (a?.rollingDamping ?? PIECE_ROLLING_DAMPING) + (b?.rollingDamping ?? GROUND_ROLLING_DAMPING)
16011
16163
  });
16012
- var pairRestitution = (a, b) => Math.sqrt((a ?? SLAM_BOUNCE2) * (b ?? SLAM_BOUNCE2));
16013
- 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)));
16014
16164
  var PieceSystem = class {
16015
16165
  constructor(THREE, o) {
16016
16166
  __publicField(this, "THREE", THREE);
@@ -16019,19 +16169,14 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16019
16169
  __publicField(this, "time", 0);
16020
16170
  __publicField(this, "generations", 0);
16021
16171
  __publicField(this, "p");
16022
- __publicField(this, "q");
16023
16172
  __publicField(this, "dq");
16024
- __publicField(this, "nextQ");
16025
16173
  __publicField(this, "m");
16026
- __publicField(this, "hingeM");
16027
16174
  __publicField(this, "ax");
16028
16175
  __publicField(this, "wakeBox");
16029
16176
  __publicField(this, "solids", []);
16030
- /** The engine stepping the pieces (`PieceSystemOptions.physics`), or null for the kit's own solver. */
16177
+ /** The engine stepping the pieces (`PieceSystemOptions.physics`). */
16031
16178
  __publicField(this, "engine");
16032
- /** The host's ground worker, disposed with the system: by the engine, or here when there is none (the kit's own solver lays no tiles). */
16033
- __publicField(this, "groundWorker");
16034
- /** The loop the system steps itself (a world was handed), the loop it only registers on (a loop was handed), or null on `'own'`. */
16179
+ /** The loop the system steps itself (a world was handed) or only registers on (a loop was handed). */
16035
16180
  __publicField(this, "loop");
16036
16181
  __publicField(this, "stepsItself");
16037
16182
  /** The phases' way out of the loop, and whether this frame's `prepare` ran (it runs once, in the first fixed step). */
@@ -16081,12 +16226,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16081
16226
  __publicField(this, "supportNormal", UP16);
16082
16227
  __publicField(this, "supportFriction", null);
16083
16228
  __publicField(this, "supportBody", null);
16084
- /** The terrain's surfaces by rolling resistance and damping (`terrainSurface`), one object each. */
16085
- __publicField(this, "terrainSurfaces", /* @__PURE__ */ new Map());
16086
- /** The terrain's surface by ground tile (`groundTileKey`) this update, null for the default: read once per tile, not per contact per substep. */
16087
- __publicField(this, "surfaceByTile", /* @__PURE__ */ new Map());
16088
- /** A piece is asleep on both sides (the engine's too) or, on the kit's own solver, asleep and not held: nothing of it changes until it wakes. */
16089
- __publicField(this, "isSettled", (body) => this.engine ? this.engine.isSettled(body) : body.sleeping && !body.held);
16229
+ /** A piece is asleep on both sides (the engine's too): nothing of it changes until it wakes. */
16230
+ __publicField(this, "isSettled", (body) => this.engine.isSettled(body));
16090
16231
  __publicField(this, "measureAwake", (body) => {
16091
16232
  const rec = this.measured(body);
16092
16233
  const from = rec.from;
@@ -16110,18 +16251,15 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16110
16251
  if (rec.from !== from || rec.list.length !== count || rec.list[0] !== first) this.reshaped = true;
16111
16252
  });
16112
16253
  this.p = new THREE.Vector3();
16113
- this.q = new THREE.Quaternion();
16114
16254
  this.dq = new THREE.Quaternion();
16115
- this.nextQ = new THREE.Quaternion();
16116
16255
  this.m = new THREE.Matrix4();
16117
- this.hingeM = new THREE.Matrix4();
16118
16256
  this.ax = new THREE.Vector3();
16119
16257
  this.wakeBox = new THREE.Box3();
16120
16258
  const resolved = resolvePhysics(o.physics);
16121
- this.loop = resolved?.loop ?? null;
16122
- this.stepsItself = resolved?.stepsItself ?? false;
16259
+ this.loop = resolved.loop;
16260
+ this.stepsItself = resolved.stepsItself;
16123
16261
  this.trail = o.interpolate ? new PoseTrail() : null;
16124
- this.engine = resolved ? new EnginePieces(THREE, resolved.loop.world, {
16262
+ this.engine = new EnginePieces(THREE, resolved.loop.world, {
16125
16263
  groundAt: o.terrainAt ?? o.groundAt,
16126
16264
  ...o.terrainRollingAt ? { groundRollingAt: o.terrainRollingAt } : {},
16127
16265
  ...o.terrainRollingDampingAt ? { groundRollingDampingAt: o.terrainRollingDampingAt } : {},
@@ -16141,13 +16279,12 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16141
16279
  ...o.heldIgnores ? { heldIgnores: o.heldIgnores } : {},
16142
16280
  ...o.groundWorker ? { groundWorker: o.groundWorker } : {},
16143
16281
  ...o.groundWorkerFrames !== void 0 ? { groundWorkerFrames: o.groundWorkerFrames } : {}
16144
- }) : null;
16145
- this.groundWorker = o.groundWorker ?? null;
16146
- if (resolved && !resolved.stepsItself) this.joinLoop(resolved.loop, this.engine);
16282
+ });
16283
+ if (!resolved.stepsItself) this.joinLoop(resolved.loop, this.engine);
16147
16284
  }
16148
- /** 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. */
16285
+ /** Contact blows on the fixed parts become `blunt` hits of `destruction` (`engine-impacts.ts`). Returns the way to stop it. */
16149
16286
  contactHits(destruction, options) {
16150
- return this.engine && this.loop ? createEngineImpacts(this.loop, this.engine.statics, destruction, options) : null;
16287
+ return createEngineImpacts(this.loop, this.engine.statics, destruction, options);
16151
16288
  }
16152
16289
  /**
16153
16290
  * The pieces a blast at `point` can reach: the bodies the engine's `blastQuery` finds within `radius` (the pieces among them), in the order of `list`, and the pieces that have no
@@ -16155,7 +16292,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16155
16292
  */
16156
16293
  piecesInBlast(blastQuery, point, radius) {
16157
16294
  const engine = this.engine;
16158
- if (!engine) return [...this.list];
16159
16295
  const found = blastQuery.run({ origin: point, radius });
16160
16296
  const reached = /* @__PURE__ */ new Set();
16161
16297
  for (let i = 0; i < found.bodyCount; i++) {
@@ -16164,9 +16300,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16164
16300
  }
16165
16301
  return this.list.filter((piece) => reached.has(piece) || !engine.hasBody(piece));
16166
16302
  }
16167
- /** The engine's fixed bodies as the broad phase of the world's rays, or null when the pieces are not in the engine. */
16303
+ /** The engine's fixed bodies as the broad phase of the world's rays. */
16168
16304
  rayBroadPhase() {
16169
- return this.engine?.rayBroadPhase() ?? null;
16305
+ return this.engine.rayBroadPhase();
16170
16306
  }
16171
16307
  /**
16172
16308
  * 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
@@ -16216,8 +16352,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16216
16352
  dispose() {
16217
16353
  this.trail?.clear();
16218
16354
  for (const leave of this.leaveLoop.splice(0)) leave();
16219
- if (this.engine) this.engine.dispose();
16220
- else this.groundWorker?.dispose();
16355
+ this.engine.dispose();
16221
16356
  }
16222
16357
  /**
16223
16358
  * Pairs born overlapping (both made in the same update, or one made inside the other) deeper than a contact (`LIFT_DEPTH`: chunks of one wall) go apart along the ground by
@@ -16328,7 +16463,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16328
16463
  return existing;
16329
16464
  }
16330
16465
  const awake = this.awake;
16331
- const least = this.engine ? MIN_PIECE_HALF : OWN_MIN_PIECE_HALF;
16466
+ const least = MIN_PIECE_HALF;
16332
16467
  let asleep = false;
16333
16468
  let inHand = false;
16334
16469
  const body = {
@@ -16369,13 +16504,13 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16369
16504
  this.bornAt.set(body, this.time);
16370
16505
  return body;
16371
16506
  }
16372
- /** What the loop's last frame cost (ms) and how many bodies the world had awake: the pair the cost of a body is read from. Null on the kit's own solver. */
16507
+ /** What the loop's last frame cost (ms) and how many bodies the world had awake: the pair the cost of a body is read from. */
16373
16508
  stepCost() {
16374
- return this.loop ? { stepMs: this.loop.frame.stepMs, active: this.loop.world.activeCount } : null;
16509
+ return { stepMs: this.loop.frame.stepMs, active: this.loop.world.activeCount };
16375
16510
  }
16376
- /** Bodies awake in the physics world, or the pieces not asleep on the kit's own solver. */
16511
+ /** Bodies awake in the physics world. */
16377
16512
  activeBodies() {
16378
- return this.loop ? this.loop.world.activeCount : this.list.filter((b) => !b.sleeping).length;
16513
+ return this.loop.world.activeCount;
16379
16514
  }
16380
16515
  /** Move the centre of mass (after a part broke off). */
16381
16516
  setCenter(b, c) {
@@ -16395,12 +16530,12 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16395
16530
  }
16396
16531
  if (gone) {
16397
16532
  this.forgetSolids(gone);
16398
- this.engine?.remove(gone);
16533
+ this.engine.remove(gone);
16399
16534
  }
16400
16535
  }
16401
16536
  clear() {
16402
16537
  this.trail?.clear();
16403
- this.engine?.clear();
16538
+ this.engine.clear();
16404
16539
  this.list.length = 0;
16405
16540
  this.awake.clear();
16406
16541
  this.layoutDirty = true;
@@ -16514,29 +16649,13 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16514
16649
  }
16515
16650
  return out;
16516
16651
  }
16517
- /**
16518
- * An impulse along the unit normal `n` at `r` (from the centre of mass, world) that stops the point closing in along `n` (with `bounce`); `e` holds the body's rotation.
16519
- */
16520
- contactImpulse(b, e, r, n, bounce2) {
16521
- const v = b.velocity;
16522
- const w = b.angularVelocity;
16523
- const vn = (v[0] + w[1] * r[2] - w[2] * r[1]) * n[0] + (v[1] + w[2] * r[0] - w[0] * r[2]) * n[1] + (v[2] + w[0] * r[1] - w[1] * r[0]) * n[2];
16524
- if (vn >= 0) return;
16525
- const a = this.mulInvInertiaWith(b, e, r[1] * n[2] - r[2] * n[1], r[2] * n[0] - r[0] * n[2], r[0] * n[1] - r[1] * n[0]);
16526
- const k = (a[1] * r[2] - a[2] * r[1]) * n[0] + (a[2] * r[0] - a[0] * r[2]) * n[1] + (a[0] * r[1] - a[1] * r[0]) * n[2];
16527
- const j = -(1 + bounce2) * vn / (1 / b.mass + k);
16528
- for (let i = 0; i < 3; i++) {
16529
- v[i] += j * n[i] / b.mass;
16530
- w[i] += a[i] * j;
16531
- }
16532
- }
16533
16652
  /** A blast at (x, z) of `radius`: the ground within its reach is laid at the next update, before the pieces it makes need it (`EnginePieces.layAhead`). */
16534
16653
  layGroundAt(x, z, radius) {
16535
- this.engine?.layAhead(x, z, radius);
16654
+ this.engine.layAhead(x, z, radius);
16536
16655
  }
16537
16656
  /** What lies inside the disc looks at the ground again: it was dug or heaped under it. */
16538
16657
  wakeRegion(x, z, radius) {
16539
- this.engine?.groundChanged(x, z, radius);
16658
+ this.engine.groundChanged(x, z, radius);
16540
16659
  for (const b of this.list) {
16541
16660
  if (!b.sleeping || b.held) continue;
16542
16661
  if (Math.hypot(b.root.position.x - x, b.root.position.z - z) > radius && !this.lostGroundIn(b, x, z, radius)) continue;
@@ -16579,7 +16698,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16579
16698
  this.trail?.blend(alpha);
16580
16699
  }
16581
16700
  update(dt) {
16582
- if (this.trail && !(this.engine && this.loop && !this.stepsItself)) {
16701
+ if (this.trail && this.stepsItself) {
16583
16702
  this.beginTick();
16584
16703
  this.advance(dt);
16585
16704
  this.trail.commit();
@@ -16588,96 +16707,21 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16588
16707
  this.advance(dt);
16589
16708
  }
16590
16709
  advance(dt) {
16591
- if (this.engine && this.loop) {
16592
- if (!this.stepsItself) {
16593
- this.time = this.loop.frame.time;
16594
- this.keepFar();
16595
- return;
16596
- }
16597
- this.time += dt;
16598
- this.engine.wakePending(this.list, this.awake);
16599
- this.measure();
16600
- this.wakeUnsupported(true);
16601
- if (dt > 0) {
16602
- this.engine.prepare(this.list, dt, dt, this.apartAll(dt), this.awake);
16603
- this.loop.step(dt);
16604
- this.engine.finish(this.list, dt, this.time, this.awake);
16605
- }
16606
- this.measure();
16607
- this.keepBudget();
16710
+ if (!this.stepsItself) {
16711
+ this.time = this.loop.frame.time;
16608
16712
  this.keepFar();
16609
16713
  return;
16610
16714
  }
16611
- const { steps, near: near2 } = this.collisionSteps(dt);
16612
- if (steps === 1) {
16613
- this.time += dt;
16614
- this.step(dt);
16615
- return;
16616
- }
16617
- const start = this.time;
16618
- this.time = start + dt;
16619
- const far2 = (b) => !near2.has(b);
16620
- this.step(dt, { moves: far2, meets: (a, b) => far2(a) && far2(b) });
16621
- for (let i = 0; i < steps; i++) {
16622
- this.time = start + dt * (i + 1) / steps;
16623
- this.step(dt / steps, { moves: (b) => near2.has(b), meets: (a, b) => near2.has(a) || near2.has(b) });
16624
- }
16625
- }
16626
- /**
16627
- * Steps of an update: one, or more while a round piece and a piece it could meet within the update close in fast enough to pass through each other between two (closing at
16628
- * their two speeds they cover at most the round one's radius per step: two cans at 3.6 m/s close 12 cm in a frame, a can is 7 cm across; a plank thrown at a can still counts).
16629
- * A round piece with nothing in reach takes one step, so its sweep against the world (the costly part) runs once; `near` holds the pieces of the pairs that need more.
16630
- */
16631
- collisionSteps(dt) {
16632
- let need = 1;
16633
- const near2 = /* @__PURE__ */ new Set();
16634
- const p = this.p;
16635
- const speedOf = (b) => b.held ? 0 : Math.hypot(b.velocity[0], b.velocity[1], b.velocity[2]);
16636
- for (const b of this.list) {
16637
- if (!b.round || b.held) continue;
16638
- const radius = Math.max(MIN_ROUND_RADIUS, b.round.radius);
16639
- const speed = b.sleeping ? 0 : speedOf(b);
16640
- const c = this.centerOf(b, p);
16641
- const cx = c.x, cy = c.y, cz = c.z;
16642
- const rb = Math.hypot(b.halfExtents[0], b.halfExtents[1], b.halfExtents[2]);
16643
- for (const o of this.list) {
16644
- if (o === b || b.sleeping && o.sleeping) continue;
16645
- const closing = speed + (o.sleeping ? 0 : speedOf(o));
16646
- if (closing * dt < radius * 0.5) continue;
16647
- const reach2 = closing * dt + rb + Math.hypot(o.halfExtents[0], o.halfExtents[1], o.halfExtents[2]);
16648
- const oc = this.centerOf(o, p);
16649
- if (Math.abs(oc.x - cx) > reach2 || Math.abs(oc.y - cy) > reach2 || Math.abs(oc.z - cz) > reach2) continue;
16650
- const pair = Math.ceil(closing * dt / radius);
16651
- if (pair < 2) continue;
16652
- need = Math.max(need, pair);
16653
- near2.add(b);
16654
- near2.add(o);
16655
- }
16656
- }
16657
- return { steps: Math.max(1, Math.min(MAX_COLLISION_STEPS, need)), near: near2 };
16658
- }
16659
- /** A step of `dt`: the pieces `only.moves` takes move (all when absent) and the pairs `only.meets` takes meet, so each pair meets in one of the steps of an update. */
16660
- step(dt, only) {
16661
- this.surfaceByTile.clear();
16715
+ this.time += dt;
16716
+ this.engine.wakePending(this.list, this.awake);
16662
16717
  this.measure();
16663
- this.wakeUnsupported();
16664
- for (const b of this.list) {
16665
- if (b.held) {
16666
- b.velocity = [0, 0, 0];
16667
- b.angularVelocity = [0, 0, 0];
16668
- b.sleeping = false;
16669
- b.still = 0;
16670
- b.calmAt = null;
16671
- continue;
16672
- }
16673
- if (b.sleeping || only && !only.moves(b)) continue;
16674
- this.integrate(b, dt);
16675
- if (b.sleeping) continue;
16676
- const v = b.velocity;
16677
- const w = b.angularVelocity;
16678
- 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);
16718
+ this.wakeUnsupported(true);
16719
+ if (dt > 0) {
16720
+ this.engine.prepare(this.list, dt, dt, this.apartAll(dt), this.awake);
16721
+ this.loop.step(dt);
16722
+ this.engine.finish(this.list, dt, this.time, this.awake);
16679
16723
  }
16680
- this.collide(dt, only?.meets);
16724
+ this.measure();
16681
16725
  this.keepBudget();
16682
16726
  this.keepFar();
16683
16727
  }
@@ -16828,29 +16872,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16828
16872
  }
16829
16873
  return top;
16830
16874
  }
16831
- /** What lay asleep on `b` (a box over its top) wakes at once when `b` moves: a can on a table that goes over goes with it. */
16832
- wakeAbove(b) {
16833
- const below = this.solidOf.get(b);
16834
- if (!below) return;
16835
- const top = below.c[1] + below.half[0] * Math.abs(below.e[1]) + below.half[1] * Math.abs(below.e[5]) + below.half[2] * Math.abs(below.e[9]);
16836
- const x0 = Math.floor((below.c[0] - below.r) / SURFACE_CELL);
16837
- const x1 = Math.floor((below.c[0] + below.r) / SURFACE_CELL);
16838
- const z0 = Math.floor((below.c[2] - below.r) / SURFACE_CELL);
16839
- const z1 = Math.floor((below.c[2] + below.r) / SURFACE_CELL);
16840
- const wide2 = x1 - x0 > SURFACE_CELLS_ACROSS || z1 - z0 > SURFACE_CELLS_ACROSS;
16841
- const look = (part) => {
16842
- const o = part.body;
16843
- const s = this.solidOf.get(o);
16844
- if (!s || !o.sleeping || o.held || o === b) return;
16845
- if (s.c[1] < below.c[1] || s.c[1] - s.r > top + STEP || Math.hypot(s.c[0] - below.c[0], s.c[2] - below.c[2]) > s.r + below.r) return;
16846
- if (boxTopAt(below, s.c[0], s.c[2]) === -Infinity && !this.restsOn(o, b, true)) return;
16847
- o.sleeping = false;
16848
- o.still = 0;
16849
- o.calmAt = null;
16850
- };
16851
- if (wide2) for (const s of this.solids) look(s);
16852
- else for (let ix = x0; ix <= x1; ix++) for (let iz = z0; iz <= z1; iz++) for (const part of this.surfaceGrid.get(cellKey(ix, iz)) ?? []) look(part);
16853
- }
16854
16875
  /**
16855
16876
  * Whether `o` rests on a top of `below` (its parts, or its box): a corner of `o` (its contacts or its box) is over that top and within `STEP` of it. With `lowest`, only its
16856
16877
  * lowest corners count (within `STEP` of its lowest): a can rolling by another is beside it, not on it; without, a board leaning on a seat by its high end rests on the seat.
@@ -16867,36 +16888,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16867
16888
  }
16868
16889
  return false;
16869
16890
  }
16870
- /**
16871
- * The terrain's own surface under a round piece's contact at (x, z) that stands at `y` on the ground `raw` (`groundAt` there), when it is the terrain and not a top above it
16872
- * (`terrainAt`, which `groundAt` equals to the bit where nothing is on it); null otherwise (the default surface). Read as the engine reads it (`tileRollingAt`), once per tile
16873
- * per update, and one object per value, so a substep makes none.
16874
- */
16875
- terrainSurface(x, y, z, raw) {
16876
- const rollingAt = this.o.terrainRollingAt;
16877
- if (!rollingAt || y !== raw || this.o.terrainAt && y !== this.o.terrainAt(x, z)) return null;
16878
- const key = groundTileKey(x, z);
16879
- let surface = this.surfaceByTile.get(key);
16880
- if (surface === void 0) {
16881
- surface = this.tileSurface(rollingAt, x, z);
16882
- this.surfaceByTile.set(key, surface);
16883
- }
16884
- return surface;
16885
- }
16886
- /** The terrain's surface of the tile at (x, z) (`tileRollingAt`), or null when it says nothing (the default surface). */
16887
- tileSurface(rollingAt, x, z) {
16888
- const dampingAt = this.o.terrainRollingDampingAt;
16889
- const rolling = tileRollingAt(rollingAt, x, z);
16890
- const rollingDamping = dampingAt ? tileRollingAt(dampingAt, x, z) : void 0;
16891
- if (rolling === void 0 && rollingDamping === void 0) return null;
16892
- const id = `${rolling ?? ROLLING_RESISTANCE2}|${rollingDamping ?? GROUND_ROLLING_DAMPING}`;
16893
- let surface = this.terrainSurfaces.get(id);
16894
- if (!surface) {
16895
- surface = { static: MU_STATIC2, dynamic: MU_DYNAMIC2, rolling: rolling ?? ROLLING_RESISTANCE2, rollingDamping: rollingDamping ?? GROUND_ROLLING_DAMPING };
16896
- this.terrainSurfaces.set(id, surface);
16897
- }
16898
- return surface;
16899
- }
16900
16891
  /** Where a corner of `self` at `(x, y, z)` lands: the ground, the top of another piece or of something fixed under it. */
16901
16892
  supportAt(self, x, y, z, step) {
16902
16893
  let top = this.o.groundAt(x, z);
@@ -16918,391 +16909,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
16918
16909
  this.supportBody = on?.body ?? null;
16919
16910
  return Math.max(top, fixed);
16920
16911
  }
16921
- /** Stops a piece that ran into something on its way from `start` to `pos` (`sweep`): moves it back to where it met it and takes the speed into it. */
16922
- sweepOn(b, start, pos) {
16923
- const travel = Math.hypot(pos[0] - start[0], pos[1] - start[1], pos[2] - start[2]);
16924
- if (travel < 1e-3) return;
16925
- const hit = this.o.sweep?.(b, start, pos);
16926
- if (!hit || hit.normal[1] > SLAM_FLOOR_NORMAL2) return;
16927
- const v = b.velocity;
16928
- const n = hit.normal;
16929
- const into = -(v[0] * n[0] + v[1] * n[1] + v[2] * n[2]);
16930
- if (into <= 0) return;
16931
- const k = Math.min(1, hit.distance / travel);
16932
- const bounce2 = pairRestitution(b.restitution, hit.restitution);
16933
- for (let i = 0; i < 3; i++) {
16934
- pos[i] = start[i] + (pos[i] - start[i]) * k;
16935
- v[i] += (1 + bounce2) * into * n[i];
16936
- }
16937
- const w = b.angularVelocity;
16938
- w[0] *= 0.5;
16939
- w[1] *= 0.5;
16940
- w[2] *= 0.5;
16941
- if (into >= SLAM_MIN_SPEED2 && this.time - b.lastHit > 0.15) {
16942
- b.lastHit = this.time;
16943
- this.o.onSlam?.(b, hit, into);
16944
- }
16945
- }
16946
- /**
16947
- * The impulse that stops the hinge point of a piece: the point's velocity v + w x r goes to zero through J = -K^-1 (v + w x r), with K = 1/m - [r]x I^-1 [r]x, so what
16948
- * gravity gave the centre turns into a swing about the hinge.
16949
- */
16950
- holdOnHinge(b, hinge, q) {
16951
- const e = this.hingeM.makeRotationFromQuaternion(q).elements;
16952
- const [lx, ly, lz] = hinge.local;
16953
- const r = [e[0] * lx + e[4] * ly + e[8] * lz, e[1] * lx + e[5] * ly + e[9] * lz, e[2] * lx + e[6] * ly + e[10] * lz];
16954
- const v = b.velocity;
16955
- const w = b.angularVelocity;
16956
- const point = [v[0] + w[1] * r[2] - w[2] * r[1], v[1] + w[2] * r[0] - w[0] * r[2], v[2] + w[0] * r[1] - w[1] * r[0]];
16957
- const k = [0, 1, 2].map((i) => {
16958
- const d = [i === 0 ? 1 : 0, i === 1 ? 1 : 0, i === 2 ? 1 : 0];
16959
- const t = this.mulInvInertiaWith(b, e, r[1] * d[2] - r[2] * d[1], r[2] * d[0] - r[0] * d[2], r[0] * d[1] - r[1] * d[0]);
16960
- return [d[0] / b.mass + t[1] * r[2] - t[2] * r[1], d[1] / b.mass + t[2] * r[0] - t[0] * r[2], d[2] / b.mass + t[0] * r[1] - t[1] * r[0]];
16961
- });
16962
- const j = solve3(k, [-point[0], -point[1], -point[2]]);
16963
- if (!j) return;
16964
- for (let i = 0; i < 3; i++) v[i] += j[i] / b.mass;
16965
- const dw = this.mulInvInertiaWith(b, e, r[1] * j[2] - r[2] * j[1], r[2] * j[0] - r[0] * j[2], r[0] * j[1] - r[1] * j[0]);
16966
- for (let i = 0; i < 3; i++) w[i] += dw[i];
16967
- }
16968
- /** Puts the hinge point back where it hangs (what the step's rounding moved it by), moving the centre. */
16969
- keepOnHinge(hinge, pos, q) {
16970
- const e = this.hingeM.makeRotationFromQuaternion(q).elements;
16971
- const [lx, ly, lz] = hinge.local;
16972
- pos[0] = hinge.point[0] - (e[0] * lx + e[4] * ly + e[8] * lz);
16973
- pos[1] = hinge.point[1] - (e[1] * lx + e[5] * ly + e[9] * lz);
16974
- pos[2] = hinge.point[2] - (e[2] * lx + e[6] * ly + e[10] * lz);
16975
- }
16976
- /** The screw tears out: past `HINGE_RELEASE` of turn, or after `HINGE_SECONDS`, the piece falls free. */
16977
- wearHinge(b, hinge, q, dt) {
16978
- hinge.seconds -= dt;
16979
- const [x, y, z, w] = hinge.from;
16980
- const turned = 2 * Math.acos(Math.min(1, Math.abs(q.x * x + q.y * y + q.z * z + q.w * w)));
16981
- if (turned >= HINGE_RELEASE || hinge.seconds <= 0) b.hinge = void 0;
16982
- }
16983
- integrate(b, dt) {
16984
- const c = this.centerOf(b, this.p);
16985
- const pos = [c.x, c.y, c.z];
16986
- const start = [c.x, c.y, c.z];
16987
- const q = this.q.copy(b.root.quaternion);
16988
- const v = b.velocity;
16989
- const w = b.angularVelocity;
16990
- const invM = 1 / b.mass;
16991
- const steps = clamp6(Math.ceil(dt / SUB_DT), 1, 8);
16992
- const h = dt / steps;
16993
- let landing2 = 0;
16994
- let landPoint = [pos[0], pos[1], pos[2]];
16995
- let contactedLast = false;
16996
- const propped = b.propped;
16997
- const proppedAt = b.proppedAt;
16998
- b.propped = void 0;
16999
- b.proppedAt = void 0;
17000
- let touched = false;
17001
- let unstable = false;
17002
- const corners = this.samples(b, false);
17003
- this.m.makeRotationFromQuaternion(q);
17004
- let gLow = Infinity;
17005
- let gHigh = -Infinity;
17006
- for (const [sx, sy, sz] of corners) {
17007
- const e0 = this.m.elements;
17008
- const y = pos[1] + e0[1] * sx + e0[5] * sy + e0[9] * sz;
17009
- const x = pos[0] + e0[0] * sx + e0[4] * sy + e0[8] * sz;
17010
- const z = pos[2] + e0[2] * sx + e0[6] * sy + e0[10] * sz;
17011
- const g = Math.max(this.o.groundAt(x, z), this.o.staticTopAt?.(x, z, y, STEP) ?? -Infinity);
17012
- gLow = Math.min(gLow, g);
17013
- gHigh = Math.max(gHigh, g);
17014
- }
17015
- let local2 = b.round ? this.roundSamples(b, q) : gHigh - gLow > STEP ? this.samples(b, true) : corners;
17016
- let prev = local2.map(() => [0, 0, 0]);
17017
- for (let s = 0; s < steps; s++) {
17018
- if (b.round) {
17019
- const wl0 = Math.hypot(w[0], w[1], w[2]);
17020
- const next = this.nextQ.copy(q);
17021
- if (wl0 > 1e-6) next.premultiply(this.dq.setFromAxisAngle(this.ax.set(w[0] / wl0, w[1] / wl0, w[2] / wl0), wl0 * h)).normalize();
17022
- local2 = this.roundSamples(b, next);
17023
- if (prev.length !== local2.length) prev = local2.map(() => [0, 0, 0]);
17024
- }
17025
- this.m.makeRotationFromQuaternion(q);
17026
- const e0 = this.m.elements;
17027
- for (let i = 0; i < local2.length; i++) {
17028
- const [sx, sy, sz] = local2[i];
17029
- prev[i][0] = pos[0] + e0[0] * sx + e0[4] * sy + e0[8] * sz;
17030
- prev[i][1] = pos[1] + e0[1] * sx + e0[5] * sy + e0[9] * sz;
17031
- prev[i][2] = pos[2] + e0[2] * sx + e0[6] * sy + e0[10] * sz;
17032
- }
17033
- v[1] -= this.o.gravity * h;
17034
- if (b.hinge) this.holdOnHinge(b, b.hinge, q);
17035
- if (propped) {
17036
- const into = v[0] * propped[0] + v[1] * propped[1] + v[2] * propped[2];
17037
- if (into < 0) for (let k = 0; k < 3; k++) v[k] -= into * propped[k];
17038
- }
17039
- pos[0] += v[0] * h;
17040
- pos[1] += v[1] * h;
17041
- pos[2] += v[2] * h;
17042
- const wl = Math.hypot(w[0], w[1], w[2]);
17043
- if (wl > 1e-6) {
17044
- this.dq.setFromAxisAngle(this.ax.set(w[0] / wl, w[1] / wl, w[2] / wl), wl * h);
17045
- q.premultiply(this.dq).normalize();
17046
- }
17047
- if (b.hinge) this.keepOnHinge(b.hinge, pos, q);
17048
- const damp = b.round ? 1 : Math.exp(-0.15 * h);
17049
- w[0] *= damp;
17050
- w[1] *= damp;
17051
- w[2] *= damp;
17052
- this.m.makeRotationFromQuaternion(q);
17053
- const e = this.m.elements;
17054
- const rs = [];
17055
- const ids = [];
17056
- const ns = [];
17057
- const mus = [];
17058
- let maxPen = 0;
17059
- let penNormal = UP16;
17060
- const rise = STEP + Math.max(0, -v[1]) * h * 2;
17061
- let side = null;
17062
- let lowest = Infinity;
17063
- for (let i = 0; i < local2.length; i++) {
17064
- const [sx, sy, sz] = local2[i];
17065
- const r = [e[0] * sx + e[4] * sy + e[8] * sz, e[1] * sx + e[5] * sy + e[9] * sz, e[2] * sx + e[6] * sy + e[10] * sz];
17066
- const px = pos[0] + r[0];
17067
- const pz = pos[2] + r[2];
17068
- const cy = pos[1] + r[1];
17069
- const was = prev[i];
17070
- const raw = this.o.groundAt(px, pz);
17071
- if (raw > cy - SLOP && was[1] < raw - STEP) {
17072
- if (this.o.groundAt(was[0], was[2]) >= raw - STEP) {
17073
- const floor2 = b.floor;
17074
- if (floor2 !== void 0 && floor2 - cy > -SLOP && floor2 < raw - STEP) {
17075
- rs.push(r);
17076
- ids.push(i);
17077
- ns.push(UP16);
17078
- mus.push(pairFriction(b.friction, b.round ? this.terrainSurface(px, floor2, pz, floor2) : null));
17079
- maxPen = Math.max(maxPen, floor2 - cy);
17080
- }
17081
- continue;
17082
- }
17083
- const dx = px - was[0];
17084
- const dz = pz - was[2];
17085
- const len = Math.hypot(dx, dz);
17086
- if (len > 1e-6) {
17087
- let lo = 0;
17088
- let hi = 1;
17089
- for (let it = 0; it < 6; it++) {
17090
- const mid = (lo + hi) / 2;
17091
- if (this.o.groundAt(was[0] + dx * mid, was[2] + dz * mid) >= raw - STEP) hi = mid;
17092
- else lo = mid;
17093
- }
17094
- const back = (1 - lo) * len + 1e-3;
17095
- if (!side || back > side.back) side = { back, dir: [dx / len, dz / len], r };
17096
- }
17097
- continue;
17098
- }
17099
- this.supportNormal = UP16;
17100
- this.supportFriction = null;
17101
- const gy = i < 8 || b.contacts ? this.supportAt(b, px, cy, pz, rise) : Math.max(raw, this.o.staticTopAt?.(px, pz, cy, rise) ?? -Infinity);
17102
- const pen = gy - cy;
17103
- if (pen > -SLOP) {
17104
- rs.push(r);
17105
- ids.push(i);
17106
- ns.push(this.supportNormal);
17107
- mus.push(pairFriction(b.friction, this.supportFriction ?? (b.round ? this.terrainSurface(px, gy, pz, raw) : null)));
17108
- if (pen > maxPen) {
17109
- maxPen = pen;
17110
- penNormal = this.supportNormal;
17111
- }
17112
- lowest = Math.min(lowest, gy);
17113
- }
17114
- }
17115
- if (lowest < Infinity) b.floor = lowest;
17116
- if (b.round && ns.length > 0) {
17117
- const sum = [0, 0, 0];
17118
- for (const one of ns) for (let k = 0; k < 3; k++) sum[k] += one[k];
17119
- const len = Math.hypot(sum[0], sum[1], sum[2]);
17120
- b.surfaceNormal = len > 1e-6 ? [sum[0] / len, sum[1] / len, sum[2] / len] : UP16;
17121
- } else if (b.round && rs.length === 0) b.surfaceNormal = UP16;
17122
- if (side) {
17123
- pos[0] -= side.dir[0] * side.back;
17124
- pos[2] -= side.dir[1] * side.back;
17125
- this.contactImpulse(b, e, side.r, [-side.dir[0], 0, -side.dir[1]], SIDE_BOUNCE);
17126
- }
17127
- contactedLast = rs.length > 0;
17128
- if (contactedLast) touched = true;
17129
- if (!contactedLast) continue;
17130
- const out = Math.max(0, maxPen - SLOP * 0.5) * penNormal[1];
17131
- pos[0] += penNormal[0] * out;
17132
- pos[1] += penNormal[1] * out;
17133
- pos[2] += penNormal[2] * out;
17134
- let impact3 = 0;
17135
- for (const r of rs) impact3 = Math.max(impact3, -(v[1] + w[2] * r[0] - w[0] * r[2]));
17136
- const restitution = impact3 > 2 ? 0.25 : 0;
17137
- if (impact3 > landing2) {
17138
- landing2 = impact3;
17139
- let sx = 0;
17140
- let sz = 0;
17141
- for (const r of rs) {
17142
- sx += r[0];
17143
- sz += r[2];
17144
- }
17145
- const lx = pos[0] + sx / rs.length;
17146
- const lz = pos[2] + sz / rs.length;
17147
- landPoint = [lx, pos[1] - Math.max(...rs.map((r) => -r[1])), lz];
17148
- }
17149
- const pointV = (r) => [v[0] + w[1] * r[2] - w[2] * r[1], v[1] + w[2] * r[0] - w[0] * r[2], v[2] + w[0] * r[1] - w[1] * r[0]];
17150
- const dot2 = (a, c2) => a[0] * c2[0] + a[1] * c2[1] + a[2] * c2[2];
17151
- const goal = rs.map((r, k) => {
17152
- const vn = dot2(pointV(r), ns[k]);
17153
- return vn < 0 ? -restitution * vn : 0;
17154
- });
17155
- const slipping = rs.map((r, k) => {
17156
- const pv = pointV(r);
17157
- pv[1] += this.o.gravity * h;
17158
- const vn = dot2(pv, ns[k]);
17159
- return Math.hypot(pv[0] - vn * ns[k][0], pv[1] - vn * ns[k][1], pv[2] - vn * ns[k][2]) > SLIP_SPEED;
17160
- });
17161
- const vx0 = v[0];
17162
- const vz0 = v[2];
17163
- if (!b.warm || b.warm.length !== WARM_SLOTS * 4) b.warm = new Float64Array(WARM_SLOTS * 4);
17164
- const warm = b.warm;
17165
- const accN = ids.map((id) => id < WARM_SLOTS ? warm[id * 4] : 0);
17166
- const accT = ids.map((id) => id < WARM_SLOTS ? [warm[id * 4 + 1], warm[id * 4 + 2], warm[id * 4 + 3]] : [0, 0, 0]);
17167
- const push = (r, j) => {
17168
- v[0] += j[0] * invM;
17169
- v[1] += j[1] * invM;
17170
- v[2] += j[2] * invM;
17171
- const dw = this.mulInvInertiaWith(b, e, r[1] * j[2] - r[2] * j[1], r[2] * j[0] - r[0] * j[2], r[0] * j[1] - r[1] * j[0]);
17172
- w[0] += dw[0];
17173
- w[1] += dw[1];
17174
- w[2] += dw[2];
17175
- };
17176
- const reach2 = (r, d) => {
17177
- const a = this.mulInvInertiaWith(b, e, r[1] * d[2] - r[2] * d[1], r[2] * d[0] - r[0] * d[2], r[0] * d[1] - r[1] * d[0]);
17178
- return invM + (a[1] * r[2] - a[2] * r[1]) * d[0] + (a[2] * r[0] - a[0] * r[2]) * d[1] + (a[0] * r[1] - a[1] * r[0]) * d[2];
17179
- };
17180
- for (let k = 0; k < rs.length; k++) {
17181
- const n = ns[k];
17182
- const t = accT[k];
17183
- if (accN[k] !== 0 || t[0] !== 0 || t[1] !== 0 || t[2] !== 0) push(rs[k], [n[0] * accN[k] + t[0], n[1] * accN[k] + t[1], n[2] * accN[k] + t[2]]);
17184
- }
17185
- for (let it = 0; it < SOLVER_PASSES; it++) {
17186
- for (let k = 0; k < rs.length; k++) {
17187
- const r = rs[k];
17188
- const n = ns[k];
17189
- const vn = dot2(pointV(r), n);
17190
- const total = Math.max(0, accN[k] + (goal[k] - vn) / reach2(r, n));
17191
- const j = total - accN[k];
17192
- accN[k] = total;
17193
- if (j !== 0) push(r, [n[0] * j, n[1] * j, n[2] * j]);
17194
- const pv = pointV(r);
17195
- const pn = dot2(pv, n);
17196
- const vt = [pv[0] - pn * n[0], pv[1] - pn * n[1], pv[2] - pn * n[2]];
17197
- const speed = Math.hypot(vt[0], vt[1], vt[2]);
17198
- const f = [accT[k][0], accT[k][1], accT[k][2]];
17199
- if (speed > 1e-6) {
17200
- const d = [vt[0] / speed, vt[1] / speed, vt[2] / speed];
17201
- const jt = speed / reach2(r, d);
17202
- f[0] -= d[0] * jt;
17203
- f[1] -= d[1] * jt;
17204
- f[2] -= d[2] * jt;
17205
- } else if (f[0] === 0 && f[1] === 0 && f[2] === 0) continue;
17206
- const most = (slipping[k] ? mus[k].dynamic : mus[k].static) * accN[k];
17207
- const fl = Math.hypot(f[0], f[1], f[2]);
17208
- if (fl > most) {
17209
- f[0] *= most / fl;
17210
- f[1] *= most / fl;
17211
- f[2] *= most / fl;
17212
- }
17213
- const dj = [f[0] - accT[k][0], f[1] - accT[k][1], f[2] - accT[k][2]];
17214
- accT[k] = f;
17215
- if (dj[0] !== 0 || dj[1] !== 0 || dj[2] !== 0) push(r, dj);
17216
- }
17217
- }
17218
- pos[0] += (v[0] - vx0) * h;
17219
- pos[2] += (v[2] - vz0) * h;
17220
- warm.fill(0);
17221
- for (let k = 0; k < rs.length; k++) {
17222
- const id = ids[k];
17223
- if (id >= WARM_SLOTS) continue;
17224
- warm[id * 4] = accN[k];
17225
- warm[id * 4 + 1] = accT[k][0];
17226
- warm[id * 4 + 2] = accT[k][1];
17227
- warm[id * 4 + 3] = accT[k][2];
17228
- }
17229
- let x0 = Infinity, x1 = -Infinity, z0 = Infinity, z1 = -Infinity, low = 0;
17230
- for (const r of rs) {
17231
- x0 = Math.min(x0, r[0]);
17232
- x1 = Math.max(x1, r[0]);
17233
- z0 = Math.min(z0, r[2]);
17234
- z1 = Math.max(z1, r[2]);
17235
- low = Math.min(low, r[1]);
17236
- }
17237
- if (proppedAt) {
17238
- x0 = Math.min(x0, proppedAt[0]);
17239
- x1 = Math.max(x1, proppedAt[0]);
17240
- z0 = Math.min(z0, proppedAt[2]);
17241
- z1 = Math.max(z1, proppedAt[2]);
17242
- }
17243
- const height = -low;
17244
- const wx = x1 - x0;
17245
- const wz = z1 - z0;
17246
- const pastX = x0 > -SUPPORT_MARGIN * wx || x1 < SUPPORT_MARGIN * wx;
17247
- const pastZ = z0 > -SUPPORT_MARGIN * wz || z1 < SUPPORT_MARGIN * wz;
17248
- unstable = !b.round && (Math.min(wx, wz) < NARROW2 * height || pastX || pastZ);
17249
- if (b.tipping) {
17250
- b.tipping.seconds -= h;
17251
- const [hx, hy, hz2] = b.halfExtents;
17252
- const upHalf = Math.abs(e[1]) * hx + Math.abs(e[5]) * hy + Math.abs(e[9]) * hz2;
17253
- const rising = TIP_SECONDS - b.tipping.seconds > TIP_RISE_AFTER && v[1] > TIP_RISING;
17254
- if (upHalf < TIP_LYING || b.tipping.seconds <= 0 || rising) b.tipping = null;
17255
- else {
17256
- w[0] += b.tipping.x * TIP_ACCELERATION * h;
17257
- w[2] += b.tipping.z * TIP_ACCELERATION * h;
17258
- unstable = true;
17259
- }
17260
- }
17261
- if (unstable) {
17262
- const dirX = x0 + x1 > 0 ? -1 : 1;
17263
- const dirZ = z0 + z1 > 0 ? -1 : 1;
17264
- const k = TOPPLE2 * Math.min(height, 1) * h;
17265
- const overZ = pastX === pastZ ? wx <= wz : pastX;
17266
- if (overZ) w[2] -= dirX * k;
17267
- else w[0] += dirZ * k;
17268
- }
17269
- if (b.round) {
17270
- let rolling = 0;
17271
- let damping = 0;
17272
- for (const mu of mus) {
17273
- rolling = Math.max(rolling, mu.rolling ?? ROLLING_RESISTANCE2);
17274
- damping = Math.max(damping, mu.rollingDamping ?? 0);
17275
- }
17276
- this.rollingResistance(b, q, w, h, { rolling, damping });
17277
- } else {
17278
- const rd = Math.exp((rs.length >= 3 ? -3 : -1.5) * h);
17279
- w[0] *= rd;
17280
- w[1] *= rd;
17281
- w[2] *= rd;
17282
- const fd = Math.exp(-0.3 * h);
17283
- v[0] *= fd;
17284
- v[2] *= fd;
17285
- }
17286
- }
17287
- if (b.hinge) this.wearHinge(b, b.hinge, q, dt);
17288
- if (this.o.sweep && !b.held) this.sweepOn(b, start, pos);
17289
- b.root.quaternion.copy(q);
17290
- const off2 = this.ax.copy(b.centerV).applyQuaternion(q);
17291
- b.root.position.set(pos[0] - off2.x, pos[1] - off2.y, pos[2] - off2.z);
17292
- b.root.updateMatrixWorld(true);
17293
- b.onGround = contactedLast;
17294
- if (landing2 > HARD_LANDING2 && this.time - b.lastHit > 0.15) {
17295
- b.lastHit = this.time;
17296
- this.o.onHardLanding(b, landPoint, landing2);
17297
- }
17298
- const still = touched && !unstable && Math.hypot(v[0], v[1], v[2]) < STILL_SPEED2 && Math.hypot(w[0], w[1], w[2]) < STILL_SPIN2;
17299
- if (still) b.still += dt;
17300
- else b.still = 0;
17301
- b.balancing = unstable;
17302
- this.keepsTilt(b, q, dt);
17303
- const held = (touched || propped !== void 0) && !b.tipping;
17304
- if (!b.hinge && (b.still >= SLEEP_AFTER || this.staysInPlace(b, held, pos, q, dt)) && !this.onSteepSupport(b)) this.sleep(b);
17305
- }
17306
16912
  /**
17307
16913
  * Whether `b` lies flat on a settled top (asleep) tilted past what the friction of the two holds (a laptop on a table top gone over at 42 degrees, held by 0.49 up to 26),
17308
16914
  * with every corner that touches on it: it slides, it does not sleep there, and one asleep there wakes. Held by anything else (the floor, a flat top, a side it leans on, a
@@ -17336,15 +16942,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
17336
16942
  b.velocity[0] = b.velocity[1] = b.velocity[2] = 0;
17337
16943
  b.angularVelocity[0] = b.angularVelocity[1] = b.angularVelocity[2] = 0;
17338
16944
  }
17339
- /** 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. */
17340
- keepsTilt(b, q, dt) {
17341
- const at3 = b.steady;
17342
- if (at3 && turnBetween(at3.quaternion, q) <= STEADY_TURN2) {
17343
- at3.seconds += dt;
17344
- return;
17345
- }
17346
- b.steady = { quaternion: [q.x, q.y, q.z, q.w], seconds: 0 };
17347
- }
17348
16945
  /**
17349
16946
  * 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`),
17350
16947
  * 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
@@ -17455,118 +17052,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
17455
17052
  const y = c.y + e[1] * sx + e[5] * sy + e[9] * sz;
17456
17053
  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;
17457
17054
  }
17458
- /** Whether the piece has kept to the same spot on the ground for `CALM_SLEEP_AFTER` (see `CALM_DRIFT`). */
17459
- staysInPlace(b, touched, center, q, dt) {
17460
- const at3 = b.calmAt;
17461
- const turned = at3 ? turnBetween(at3.quaternion, q) : Infinity;
17462
- if (!touched || !at3 || Math.hypot(center[0] - at3.center[0], center[1] - at3.center[1], center[2] - at3.center[2]) > CALM_DRIFT || turned > CALM_TURN) {
17463
- b.calmAt = touched ? { center: [center[0], center[1], center[2]], quaternion: [q.x, q.y, q.z, q.w] } : null;
17464
- b.calm = 0;
17465
- return false;
17466
- }
17467
- b.calm += dt;
17468
- return b.calm >= CALM_SLEEP_AFTER;
17469
- }
17470
- /** Whether the centre `c` of `upper` is over the top of `lower`'s box (as it was at the start of the update). */
17471
- onTopOf(upper, lower, c) {
17472
- const s = this.solidOf.get(lower);
17473
- if (!s) return false;
17474
- const top = boxTopAt(s, c.x, c.z);
17475
- return top > -Infinity && c.y >= top - 0.01;
17476
- }
17477
- /**
17478
- * The points a round piece touches the ground by as it is turned now (`q`): its rims (`contacts`), which hold it standing on an end, and the exact lowest point of each
17479
- * rim (of the ball), so lying on its side it rests on a line and rolls smoothly instead of over the corners of a polygon.
17480
- */
17481
- roundSamples(b, q) {
17482
- const round2 = b.round;
17483
- const rims = b.contacts ?? [];
17484
- if (!round2) return rims;
17485
- const e = this.m.makeRotationFromQuaternion(q).elements;
17486
- const n = b.surfaceNormal ?? UP16;
17487
- const down = [-(e[0] * n[0] + e[1] * n[1] + e[2] * n[2]), -(e[4] * n[0] + e[5] * n[1] + e[6] * n[2]), -(e[8] * n[0] + e[9] * n[1] + e[10] * n[2])];
17488
- if (round2.kind === "sphere") return [...rims, [down[0] * round2.radius, down[1] * round2.radius, down[2] * round2.radius]];
17489
- const k = round2.axis;
17490
- const across = [down[0], down[1], down[2]];
17491
- across[k] = 0;
17492
- const len = Math.hypot(across[0], across[1], across[2]);
17493
- if (len < 1e-3) return rims;
17494
- const lowest = (at3, radius) => {
17495
- const p = [across[0] / len * radius, across[1] / len * radius, across[2] / len * radius];
17496
- p[k] = at3;
17497
- return p;
17498
- };
17499
- const half = b.halfExtents[k];
17500
- const low = (round2.profile ?? [[-half, round2.radius], [half, round2.radius]]).map(([at3, radius]) => lowest(at3, radius));
17501
- return len > ROUND_LYING ? low : [...rims, ...low];
17502
- }
17503
- /**
17504
- * Slows the spin of a round piece on the ground by its rolling resistance: a torque C_rr N r about the axis it rolls on (N = m g n_y on a surface of normal n), so with
17505
- * I = k m r^2 the spin loses C_rr g n_y / (k r) per second, and down a slope of angle t it rolls at g (sin t - C_rr cos t) / (1 + k). Standing on its rim, a can's spin
17506
- * about the rest dies down; lying, it keeps turning about the line it touches by (a tapered bottle rounds its narrow end). Its rolling damping (`PieceFriction.rollingDamping`,
17507
- * the pair's) then takes exp(-d h) of what is left, as the grass or the sand drag more the faster it rolls.
17508
- */
17509
- rollingResistance(b, q, w, h, { rolling, damping }) {
17510
- const round2 = b.round;
17511
- if (!round2) return;
17512
- const e = this.m.makeRotationFromQuaternion(q).elements;
17513
- const cylinder = round2.kind === "cylinder";
17514
- const a = cylinder ? [e[round2.axis * 4], e[round2.axis * 4 + 1], e[round2.axis * 4 + 2]] : [0, 0, 0];
17515
- const along2 = cylinder ? w[0] * a[0] + w[1] * a[1] + w[2] * a[2] : 0;
17516
- const roll = cylinder ? [a[0] * along2, a[1] * along2, a[2] * along2] : [w[0], w[1], w[2]];
17517
- const rest = [w[0] - roll[0], w[1] - roll[1], w[2] - roll[2]];
17518
- const spin = Math.hypot(roll[0], roll[1], roll[2]);
17519
- const upright = b.surfaceNormal?.[1] ?? 1;
17520
- const slow = spin > 0 ? Math.max(0, spin - rolling * this.o.gravity * upright * h / (round2.inertia * round2.radius)) / spin * Math.exp(-damping * h) : 0;
17521
- const lying = cylinder && Math.abs(a[1]) < ROUND_LYING;
17522
- const damp = lying ? 1 : Math.exp(-3 * h);
17523
- for (let i = 0; i < 3; i++) w[i] = roll[i] * slow + rest[i] * damp;
17524
- }
17525
- /** Half the height of the box of a piece as it is turned now. */
17526
- halfHeight(b) {
17527
- const e = this.m.makeRotationFromQuaternion(b.root.quaternion).elements;
17528
- return Math.abs(e[1]) * b.halfExtents[0] + Math.abs(e[5]) * b.halfExtents[1] + Math.abs(e[9]) * b.halfExtents[2];
17529
- }
17530
- /**
17531
- * Pieces against each other. Candidates by sweep and prune along x on their bounding spheres (sorted once per step: fifty cans cost a sort and a handful of pairs, not
17532
- * 1225); a pair with a round piece in it meets by its shapes (`shapeContact`) and exchanges an impulse, two boxes are put apart by their separating axes (`separatePair`).
17533
- */
17534
- collide(dt, meets) {
17535
- const n = this.list.length;
17536
- if (n < 2) return;
17537
- const centers = this.list.map((b) => {
17538
- const c = this.centerOf(b, this.p);
17539
- return [c.x, c.y, c.z];
17540
- });
17541
- const radii = this.list.map((b) => Math.hypot(b.halfExtents[0], b.halfExtents[1], b.halfExtents[2]));
17542
- const order2 = this.list.map((_, i) => i).sort((i, j) => centers[i][0] - radii[i] - (centers[j][0] - radii[j]));
17543
- for (let oi = 0; oi < n; oi++) {
17544
- const i = order2[oi];
17545
- const reach2 = centers[i][0] + radii[i];
17546
- for (let oj = oi + 1; oj < n; oj++) {
17547
- const j = order2[oj];
17548
- if (centers[j][0] - radii[j] > reach2) break;
17549
- const a = this.list[i];
17550
- const b = this.list[j];
17551
- if ((a.held || a.sleeping) && (b.held || b.sleeping)) continue;
17552
- if (meets && !meets(a, b)) continue;
17553
- const r = radii[i] + radii[j];
17554
- const ca = centers[i];
17555
- const cb = centers[j];
17556
- if (Math.abs(ca[1] - cb[1]) > r || Math.abs(ca[2] - cb[2]) > r) continue;
17557
- const stacked = !a.round && !b.round && Math.abs(ca[1] - cb[1]) >= (this.halfHeight(a) + this.halfHeight(b)) * 0.9;
17558
- const onTop = this.onTopOf(b, a, new this.THREE.Vector3(...cb)) || this.onTopOf(a, b, new this.THREE.Vector3(...ca));
17559
- if (a.round || b.round) {
17560
- if (!stacked && !onTop) this.knock(a, b, ca, cb);
17561
- continue;
17562
- }
17563
- if (!this.partsOverlap(a, b)) continue;
17564
- this.boxImpact(a, b, ca, cb, dt);
17565
- this.separatePair(a, b, ca, cb, dt, stacked || onTop || this.restsOn(a, b, false) || this.restsOn(b, a, false));
17566
- }
17567
- }
17568
- this.applyPushes(dt);
17569
- }
17570
17055
  /**
17571
17056
  * Moves each piece by what its pairs put it apart this step (`pushes`), at most `SEPARATE_SPEED` along the ground and as much up: a chunk in five others is not pushed five
17572
17057
  * times as fast, and nothing is ever moved down (into what holds it). A piece still being put apart is moving, though its speed is nil: it does not fall asleep in the other.
@@ -17601,129 +17086,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
17601
17086
  last.push[2] = push[2];
17602
17087
  return last.share;
17603
17088
  }
17604
- /** The shape a piece meets others by (`ContactShape`), as it stands now: a round one a capsule round its axis, any other the boxes of its parts or its box. */
17605
- contactShape(b, c) {
17606
- const e = [...this.m.makeRotationFromQuaternion(b.root.quaternion).elements];
17607
- const round2 = b.round;
17608
- if (round2) {
17609
- if (round2.kind === "sphere") return { kind: "capsule", from: c, to: c, radius: round2.radius };
17610
- const reach2 = Math.max(0, b.halfExtents[round2.axis] - round2.radius);
17611
- const k = round2.axis * 4;
17612
- const d = [e[k] * reach2, e[k + 1] * reach2, e[k + 2] * reach2];
17613
- return { kind: "capsule", from: [c[0] - d[0], c[1] - d[1], c[2] - d[2]], to: [c[0] + d[0], c[1] + d[1], c[2] + d[2]], radius: round2.radius };
17614
- }
17615
- const parts = b.partBoxes ?? [{ center: [0, 0, 0], half: b.halfExtents }];
17616
- return {
17617
- kind: "boxes",
17618
- boxes: parts.map(squareBoxOf).map(({ center, half }) => ({
17619
- c: [c[0] + e[0] * center[0] + e[4] * center[1] + e[8] * center[2], c[1] + e[1] * center[0] + e[5] * center[1] + e[9] * center[2], c[2] + e[2] * center[0] + e[6] * center[1] + e[10] * center[2]],
17620
- e,
17621
- half
17622
- }))
17623
- };
17624
- }
17625
- /**
17626
- * Two pieces that met, one of them round: they are put apart along the normal (by their inverse masses) and, closing in, exchange an impulse
17627
- * j = -(1 + e) v_n / (1/m_a + 1/m_b + the turning of each), with the restitution e of their two materials, and the friction of their surfaces across it. The impulses are
17628
- * equal and opposite, so the momentum of the pair is kept. A held piece is not moved (the hand holds it); a sleeping one wakes when it is knocked.
17629
- */
17630
- knock(a, b, ca, cb) {
17631
- const hit = shapeContact(this.contactShape(a, ca), this.contactShape(b, cb));
17632
- if (!hit) return;
17633
- if (Math.abs(hit.normal[1]) > SLAM_FLOOR_NORMAL2) return;
17634
- this.impact({ a, b, ca, cb, hit, apart: true, above: 0 });
17635
- }
17636
- /**
17637
- * Two boxes that hit each other (a book falling on the top edge of one standing, a board swinging into a row): they exchange the impulse of `knock` at the point they meet,
17638
- * so the one hit turns about that point as well as moving, and a sleeping one wakes. Only a hit faster than `BOX_IMPACT_SPEED`, and no deeper than a contact: pieces resting on each other, or
17639
- * made inside each other, are left to `separatePair`, which holds or slides them without a kick.
17640
- */
17641
- boxImpact(a, b, ca, cb, dt) {
17642
- const hit = shapeContact(this.contactShape(a, ca), this.contactShape(b, cb));
17643
- if (!hit) return;
17644
- const n = hit.normal;
17645
- const va = a.velocity;
17646
- const vb = b.velocity;
17647
- const closing = (va[0] - vb[0]) * n[0] + (va[1] - vb[1]) * n[1] + (va[2] - vb[2]) * n[2];
17648
- if (hit.depth > LIFT_DEPTH + 2 * Math.max(0, -closing) * dt) return;
17649
- this.impact({ a, b, ca, cb, hit, apart: false, above: BOX_IMPACT_SPEED });
17650
- }
17651
- /** The impulse two pieces that met exchange (`knock`), put apart first when `apart`, and only when they close faster than `above` (m/s). */
17652
- impact({ a, b, ca, cb, hit, apart: apart2, above: above2 }) {
17653
- const n = hit.normal;
17654
- const ra = [hit.point[0] - ca[0], hit.point[1] - ca[1], hit.point[2] - ca[2]];
17655
- const rb = [hit.point[0] - cb[0], hit.point[1] - cb[1], hit.point[2] - cb[2]];
17656
- const pointV = (body, r) => {
17657
- const v2 = body.velocity;
17658
- const w = body.angularVelocity;
17659
- return [v2[0] + w[1] * r[2] - w[2] * r[1], v2[1] + w[2] * r[0] - w[0] * r[2], v2[2] + w[0] * r[1] - w[1] * r[0]];
17660
- };
17661
- const relative = () => {
17662
- const va = pointV(a, ra);
17663
- const vb = pointV(b, rb);
17664
- return [va[0] - vb[0], va[1] - vb[1], va[2] - vb[2]];
17665
- };
17666
- const vn0 = relative();
17667
- const closing = vn0[0] * n[0] + vn0[1] * n[1] + vn0[2] * n[2];
17668
- if (closing >= -above2) return;
17669
- const wake = (body) => {
17670
- body.sleeping = false;
17671
- body.still = 0;
17672
- body.calmAt = null;
17673
- };
17674
- if (closing < -WAKE_ABOVE_SPEED) {
17675
- if (a.sleeping) wake(a);
17676
- if (b.sleeping) wake(b);
17677
- }
17678
- const ima = a.held || a.sleeping ? 0 : 1 / a.mass;
17679
- const imb = b.held || b.sleeping ? 0 : 1 / b.mass;
17680
- if (ima + imb === 0) return;
17681
- const ea = [...this.m.makeRotationFromQuaternion(a.root.quaternion).elements];
17682
- const eb = [...this.m.makeRotationFromQuaternion(b.root.quaternion).elements];
17683
- const flat = Math.hypot(n[0], n[2]);
17684
- const out = flat > KNOCK_FLAT ? [n[0] / flat, 0, n[2] / flat] : n;
17685
- const depth = Math.max(0, hit.depth - SLOP) / (flat > KNOCK_FLAT ? flat : 1);
17686
- for (const [body, share, sign] of [[a, ima, 1], [b, imb, -1]]) {
17687
- if (share === 0 || !apart2) continue;
17688
- const move = depth * share * sign / (ima + imb);
17689
- body.root.position.x += out[0] * move;
17690
- body.root.position.y += out[1] * move;
17691
- body.root.position.z += out[2] * move;
17692
- }
17693
- if (closing >= 0) return;
17694
- const turning = (body, e, r, d) => {
17695
- const t2 = this.mulInvInertiaWith(body, e, r[1] * d[2] - r[2] * d[1], r[2] * d[0] - r[0] * d[2], r[0] * d[1] - r[1] * d[0]);
17696
- return (t2[1] * r[2] - t2[2] * r[1]) * d[0] + (t2[2] * r[0] - t2[0] * r[2]) * d[1] + (t2[0] * r[1] - t2[1] * r[0]) * d[2];
17697
- };
17698
- const resist = (d) => ima + imb + (ima > 0 ? turning(a, ea, ra, d) : 0) + (imb > 0 ? turning(b, eb, rb, d) : 0);
17699
- const give = (j2) => {
17700
- if (ima > 0) {
17701
- for (let i = 0; i < 3; i++) a.velocity[i] += j2[i] * ima;
17702
- const dw = this.mulInvInertiaWith(a, ea, ra[1] * j2[2] - ra[2] * j2[1], ra[2] * j2[0] - ra[0] * j2[2], ra[0] * j2[1] - ra[1] * j2[0]);
17703
- for (let i = 0; i < 3; i++) a.angularVelocity[i] += dw[i];
17704
- }
17705
- if (imb > 0) {
17706
- for (let i = 0; i < 3; i++) b.velocity[i] -= j2[i] * imb;
17707
- const dw = this.mulInvInertiaWith(b, eb, rb[1] * j2[2] - rb[2] * j2[1], rb[2] * j2[0] - rb[0] * j2[2], rb[0] * j2[1] - rb[1] * j2[0]);
17708
- for (let i = 0; i < 3; i++) b.angularVelocity[i] -= dw[i];
17709
- }
17710
- };
17711
- const bounce2 = apart2 && -closing > BOUNCE_MIN_SPEED ? pairRestitution(a.restitution, b.restitution) : 0;
17712
- const j = -(1 + bounce2) * closing / resist(n);
17713
- give([n[0] * j, n[1] * j, n[2] * j]);
17714
- const v = relative();
17715
- const vn = v[0] * n[0] + v[1] * n[1] + v[2] * n[2];
17716
- const vt = [v[0] - vn * n[0], v[1] - vn * n[1], v[2] - vn * n[2]];
17717
- const slide = Math.hypot(vt[0], vt[1], vt[2]);
17718
- if (slide < 1e-6) return;
17719
- const t = [vt[0] / slide, vt[1] / slide, vt[2] / slide];
17720
- const jt = Math.min(slide / resist(t), pairFriction(a.friction, b.friction ?? null).dynamic * j);
17721
- give([-t[0] * jt, -t[1] * jt, -t[2] * jt]);
17722
- if (-closing >= SLAM_MIN_SPEED2 && this.time - Math.max(a.lastHit, b.lastHit) > 0.15) {
17723
- a.lastHit = b.lastHit = this.time;
17724
- this.o.onKnock?.(a, b, hit.point, -closing);
17725
- }
17726
- }
17727
17089
  /** Whether a part of `a` and a part of `b` (their boxes of the step, as world-aligned boxes around them) overlap. */
17728
17090
  partsOverlap(a, b) {
17729
17091
  for (const pa of this.surfacesOf.get(a) ?? []) {
@@ -17735,66 +17097,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
17735
17097
  }
17736
17098
  return false;
17737
17099
  }
17738
- /**
17739
- * Two boxes overlapping, put apart by their separating axes (`shapeContact`); a held or sleeping piece is not moved. The move (`SEPARATE_SHARE` of the overlap less `SLOP`) is
17740
- * summed into `pushes` and bounded per piece in `applyPushes`.
17741
- * - Side by side (a normal at least `KNOCK_FLAT` level): apart along the ground only, as in `knock`, split by their inverse masses; the speed they close in with stops.
17742
- * - One over the other as deep as a contact (`LIFT_DEPTH` and what the closing speed sank them this step): left alone when `resting` (stacked, on a top, leaning on a
17743
- * part: its support holds it); else only the upper rises, held up by the lower (`propped`), and its point in the lower stops sinking (`contactImpulse`): never a kick up.
17744
- * - One over the other deeper than that: they were made inside each other (chunks of one wall), or stand on one floor side by side. Lifting the upper out would give it
17745
- * m g d nothing supplied (a 3 m chunk climbing 5 m through a pile), so they slide apart along the ground by their least level overlaps (`boxesApartAlongGround`).
17746
- */
17747
- separatePair(a, b, ca, cb, dt, resting) {
17748
- const sa = this.contactShape(a, ca);
17749
- const sb = this.contactShape(b, cb);
17750
- const hit = shapeContact(sa, sb);
17751
- if (!hit) return;
17752
- const ima = a.held || a.sleeping ? 0 : 1 / a.mass;
17753
- const imb = b.held || b.sleeping ? 0 : 1 / b.mass;
17754
- if (ima + imb === 0) return;
17755
- if (Math.hypot(hit.normal[0], hit.normal[2]) > KNOCK_FLAT) {
17756
- this.slideApart(a, b, ima, imb, levelBoxesApart(sa, sb) ?? hit);
17757
- return;
17758
- }
17759
- const n = hit.normal;
17760
- const va = a.velocity;
17761
- const vb = b.velocity;
17762
- const contact = LIFT_DEPTH + Math.max(0, -((va[0] - vb[0]) * n[0] + (va[1] - vb[1]) * n[1] + (va[2] - vb[2]) * n[2])) * dt;
17763
- if (hit.depth > contact) {
17764
- const level = boxesApartAlongGround(sa, sb);
17765
- if (level) this.slideApart(a, b, ima, imb, level);
17766
- return;
17767
- }
17768
- if (resting) return;
17769
- const [upper, c, up] = n[1] > 0 ? [a, ca, n] : [b, cb, [-n[0], -n[1], -n[2]]];
17770
- if (upper.held || upper.sleeping) return;
17771
- const otherCentre = upper === a ? cb : ca;
17772
- if (c[1] < otherCentre[1] - SLOP) {
17773
- const level = boxesApartAlongGround(sa, sb);
17774
- if (level) this.slideApart(a, b, ima, imb, level);
17775
- return;
17776
- }
17777
- upper.propped = up;
17778
- const e = this.m.makeRotationFromQuaternion(upper.root.quaternion).elements;
17779
- const r = [hit.point[0] - c[0], hit.point[1] - c[1], hit.point[2] - c[2]];
17780
- upper.proppedAt = r;
17781
- const turn2 = this.mulInvInertiaWith(upper, e, r[1] * up[2] - r[2] * up[1], r[2] * up[0] - r[0] * up[2], r[0] * up[1] - r[1] * up[0]);
17782
- const angular = (turn2[1] * r[2] - turn2[2] * r[1]) * up[0] + (turn2[2] * r[0] - turn2[0] * r[2]) * up[1] + (turn2[0] * r[1] - turn2[1] * r[0]) * up[2];
17783
- const lift = SEPARATE_SHARE * Math.max(0, hit.depth - SLOP) / (1 + angular * upper.mass);
17784
- const push = this.pushes.get(upper) ?? [0, 0, 0];
17785
- for (let i = 0; i < 3; i++) push[i] = Math.abs(up[i] * lift) > Math.abs(push[i]) ? up[i] * lift : push[i];
17786
- this.pushes.set(upper, push);
17787
- this.turnAboutCentre(upper, c, [turn2[0] * lift * upper.mass, turn2[1] * lift * upper.mass, turn2[2] * lift * upper.mass]);
17788
- this.contactImpulse(upper, e, r, up, 0);
17789
- }
17790
- /** Turns a piece by the rotation vector `by` (rad) about its centre `c`, which stays where it is. */
17791
- turnAboutCentre(b, c, by) {
17792
- const angle = Math.hypot(by[0], by[1], by[2]);
17793
- if (angle < 1e-9) return;
17794
- b.root.quaternion.premultiply(this.dq.setFromAxisAngle(this.ax.set(by[0] / angle, by[1] / angle, by[2] / angle), angle)).normalize();
17795
- const off2 = this.ax.copy(b.centerV).applyQuaternion(b.root.quaternion);
17796
- b.root.position.set(c[0] - off2.x, c[1] - off2.y, c[2] - off2.z);
17797
- }
17798
17100
  /** Two boxes put apart along the ground by `hit` (its normal from `b` to `a`, laid level), split by their inverse masses; the speed they close in with along it stops. */
17799
17101
  slideApart(a, b, ima, imb, hit) {
17800
17102
  const n = hit.normal;
@@ -17816,12 +17118,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
17816
17118
  }
17817
17119
  }
17818
17120
  };
17819
- function solve3(k, rhs) {
17820
- const det = (a, b, c) => a[0] * (b[1] * c[2] - b[2] * c[1]) - b[0] * (a[1] * c[2] - a[2] * c[1]) + c[0] * (a[1] * b[2] - a[2] * b[1]);
17821
- const d = det(k[0], k[1], k[2]);
17822
- if (Math.abs(d) < 1e-12) return null;
17823
- return [det(rhs, k[1], k[2]) / d, det(k[0], rhs, k[2]) / d, det(k[0], k[1], rhs) / d];
17824
- }
17825
17121
 
17826
17122
  // src/rebar.ts
17827
17123
  var RebarCages = class {
@@ -18496,6 +17792,33 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
18496
17792
  return out;
18497
17793
  };
18498
17794
  var granules = (inp, box, count) => bsp(box, count, [0, 1, 2], inp.rnd).map((b) => ({ center: b.c, size: b.s, q: quat.identity(), shape: "chunk", weight: b.s[0] * b.s[1] * b.s[2] }));
17795
+ var SLAB_MIN = 0.03;
17796
+ var splitAtHit = (root, hit, axes, count, rnd2) => {
17797
+ let pieces = [root];
17798
+ for (const ax of axes) {
17799
+ const half = root.s[ax] / 2;
17800
+ if (hit[ax] - -half < SLAB_MIN || half - hit[ax] < SLAB_MIN) continue;
17801
+ const next = [];
17802
+ for (const b of pieces) {
17803
+ const lo = b.c[ax] - b.s[ax] / 2;
17804
+ const hi = b.c[ax] + b.s[ax] / 2;
17805
+ for (const [from, to] of [[lo, hit[ax]], [hit[ax], hi]]) {
17806
+ const c = [b.c[0], b.c[1], b.c[2]];
17807
+ const s = [b.s[0], b.s[1], b.s[2]];
17808
+ c[ax] = (from + to) / 2;
17809
+ s[ax] = to - from;
17810
+ next.push({ c, s });
17811
+ }
17812
+ }
17813
+ pieces = next;
17814
+ }
17815
+ while (pieces.length < count) {
17816
+ pieces.sort((a, b) => b.s[axes[0]] * b.s[axes[1]] - a.s[axes[0]] * a.s[axes[1]]);
17817
+ const [big, ...rest] = pieces;
17818
+ pieces = [...bsp(big, 2, axes, rnd2), ...rest];
17819
+ }
17820
+ return pieces;
17821
+ };
18499
17822
  var CRUMBS = 6;
18500
17823
  var severAt = (inp, root, at3, gap) => {
18501
17824
  const dims = root.s;
@@ -18558,7 +17881,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
18558
17881
  if (inp.cut) return severAt(inp, root, inp.cut.at, inp.cut.gap);
18559
17882
  if (inp.form === "plies") return plyBreak(inp, root, maxFragments);
18560
17883
  const n2 = Math.min(maxFragments, 2 + Math.floor(rnd2() * 3));
18561
- for (const b of bsp(root, n2, [0, 1, 2], rnd2)) out.push({ center: b.c, size: b.s, q: idq, shape: "slab", weight: b.s[0] * b.s[1] * b.s[2] });
17884
+ const slabs = inp.form === "granules" && dims[t] < Math.min(dims[u], dims[v]) / 4 ? splitAtHit(root, inp.hit, [u, v], n2, rnd2) : bsp(root, n2, [0, 1, 2], rnd2);
17885
+ for (const b of slabs) out.push({ center: b.c, size: b.s, q: idq, shape: "slab", weight: b.s[0] * b.s[1] * b.s[2] });
18562
17886
  if (inp.form !== "granules") return out;
18563
17887
  const crumbs = Math.min(CRUMBS, maxFragments - out.length);
18564
17888
  if (crumbs <= 0) return out;
@@ -26886,6 +26210,11 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
26886
26210
  }).events;
26887
26211
  },
26888
26212
  state: (id) => objects.get(id)?.st ?? impls.get(id)?.impl.state() ?? null,
26213
+ anchoredParts: (id) => objects.get(id)?.parts.filter((p) => p.anchored && !isLost(p)).map((p) => p.spec.id) ?? [],
26214
+ fixedInPlace: (id) => {
26215
+ const o = objects.get(id);
26216
+ return !!o && o.spec.fixed === true && o.parts.some((p) => p.anchored && !isLost(p));
26217
+ },
26889
26218
  snapshot: (id) => {
26890
26219
  const st = objects.get(id)?.st ?? impls.get(id)?.impl.state();
26891
26220
  return st ? clone(st) : null;
@@ -27439,7 +26768,6 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
27439
26768
  var CRATER_RADIUS = 2.5;
27440
26769
  var ORIGIN7 = [4e3, 0, 4e3];
27441
26770
  var warmed = /* @__PURE__ */ new WeakSet();
27442
- var OWN_SOLVER = {};
27443
26771
  var brickWall = (THREE) => {
27444
26772
  const parts = [];
27445
26773
  const geometries = [];
@@ -27469,7 +26797,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
27469
26797
  merged.setIndex(index);
27470
26798
  return { parts, joints: inferJoints(parts), mesh: new THREE.Mesh(merged, new THREE.MeshStandardMaterial()), ranges };
27471
26799
  };
27472
- var runScene = (THREE, makeRenderer, options) => {
26800
+ var runScene = (THREE, makeRenderer, engine, worldDesc) => {
27473
26801
  const scene2 = new THREE.Scene();
27474
26802
  const world = createDestruction();
27475
26803
  const vfx = createVfx({});
@@ -27479,12 +26807,12 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
27479
26807
  let renderer;
27480
26808
  let bound;
27481
26809
  try {
27482
- engineWorld = options.engine?.createWorld(options.world ?? KIT_WORLD);
27483
- const loop = engineWorld ? createPhysicsLoop(engineWorld) : void 0;
26810
+ engineWorld = engine.createWorld(worldDesc ?? KIT_WORLD);
26811
+ const loop = createPhysicsLoop(engineWorld);
27484
26812
  const terrainGridAt = (xs, zs, out) => {
27485
26813
  for (let j = 0; j < zs.length; j++) for (let i = 0; i < xs.length; i++) out[j * xs.length + i] = terrainAt(xs[i], zs[j]);
27486
26814
  };
27487
- renderer = makeRenderer({ physics: loop ?? "own", scene: scene2, world, vfx, eventBudgetMs: Infinity, groundAt: terrainAt, terrainAt, terrainGridAt, jitWarmUp: false });
26815
+ renderer = makeRenderer({ physics: loop, scene: scene2, world, vfx, eventBudgetMs: Infinity, groundAt: terrainAt, terrainAt, terrainGridAt, jitWarmUp: false });
27488
26816
  const wall = brickWall(THREE);
27489
26817
  const root = new THREE.Group();
27490
26818
  root.position.set(...ORIGIN7);
@@ -27511,7 +26839,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
27511
26839
  renderer.wakeRegion(point[0], point[2], CRATER_RADIUS);
27512
26840
  for (let frame2 = 0; frame2 < FRAMES; frame2++) {
27513
26841
  world.update(FRAME_SECONDS);
27514
- loop?.step(FRAME_SECONDS);
26842
+ loop.step(FRAME_SECONDS);
27515
26843
  renderer.update(FRAME_SECONDS);
27516
26844
  const stats = renderer.stats();
27517
26845
  seen.pieces = Math.max(seen.pieces, stats.pieces);
@@ -27520,10 +26848,10 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
27520
26848
  return seen;
27521
26849
  };
27522
26850
  var warmUpDestructionJit = (THREE, makeRenderer, options = {}) => {
27523
- const key = options.engine ?? OWN_SOLVER;
27524
- if (warmed.has(key)) return void 0;
27525
- warmed.add(key);
27526
- return runScene(THREE, makeRenderer, options);
26851
+ const { engine } = options;
26852
+ if (!engine || warmed.has(engine)) return void 0;
26853
+ warmed.add(engine);
26854
+ return runScene(THREE, makeRenderer, engine, options.world);
27527
26855
  };
27528
26856
 
27529
26857
  // src/bend.ts
@@ -27542,10 +26870,10 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
27542
26870
  const turn2 = angle * share * share * (3 - 2 * share);
27543
26871
  const cos2 = Math.cos(turn2);
27544
26872
  const sin2 = Math.sin(turn2);
27545
- const dot2 = kx * rx + ky * ry + kz * rz;
27546
- positions[i] = point[0] + rx * cos2 + (ky * rz - kz * ry) * sin2 + kx * dot2 * (1 - cos2);
27547
- positions[i + 1] = point[1] + ry * cos2 + (kz * rx - kx * rz) * sin2 + ky * dot2 * (1 - cos2);
27548
- positions[i + 2] = point[2] + rz * cos2 + (kx * ry - ky * rx) * sin2 + kz * dot2 * (1 - cos2);
26873
+ const dot3 = kx * rx + ky * ry + kz * rz;
26874
+ positions[i] = point[0] + rx * cos2 + (ky * rz - kz * ry) * sin2 + kx * dot3 * (1 - cos2);
26875
+ positions[i + 1] = point[1] + ry * cos2 + (kz * rx - kx * rz) * sin2 + ky * dot3 * (1 - cos2);
26876
+ positions[i + 2] = point[2] + rz * cos2 + (kx * ry - ky * rx) * sin2 + kz * dot3 * (1 - cos2);
27549
26877
  }
27550
26878
  }
27551
26879
 
@@ -27714,9 +27042,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
27714
27042
  const grown = new Uint32Array(size);
27715
27043
  grown.set(this.candidates);
27716
27044
  this.candidates = grown;
27717
- const numbers = new Uint32Array(Math.max(this.triangles.length, Math.ceil(size / 3)));
27718
- numbers.set(this.triangles);
27719
- this.triangles = numbers;
27045
+ const numbers2 = new Uint32Array(Math.max(this.triangles.length, Math.ceil(size / 3)));
27046
+ numbers2.set(this.triangles);
27047
+ this.triangles = numbers2;
27720
27048
  this.candidateIndex = new this.THREE.BufferAttribute(this.candidates, 1);
27721
27049
  }
27722
27050
  };
@@ -29308,6 +28636,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29308
28636
  var REBAR_COLOR = 7628380;
29309
28637
  var STEEL_DENSITY3 = 7850;
29310
28638
  var CHIP_DECAL_EDGE = 0.05;
28639
+ var CHIP_GAP_REACH = 0.03;
28640
+ var CHIP_GAP_SHADE = 0.4;
28641
+ var CHIP_GAP_WIDTH = 1.15;
29311
28642
  var CRATER_RADIUS2 = 2.5;
29312
28643
  var CRATER_MIN_RADIUS = 0.012;
29313
28644
  var CRATER_LIGHTEN = 0.12;
@@ -29339,10 +28670,71 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29339
28670
  var HINGE_STILL_SPIN = 0.5;
29340
28671
  var PREFIT_SLICE_MS = 1;
29341
28672
  var CONTACT_MESHES = 12;
29342
- var PART_BOX_MESHES = 64;
28673
+ var PART_BOX_MESHES = 96;
29343
28674
  var ROUND_SAMPLES = 400;
29344
- var ROUND_SIDES = 0.12;
28675
+ var ROUND_SIDES2 = 0.12;
29345
28676
  var ROUND_SLACK = 1.12;
28677
+ var ROUND_FILL = 0.9;
28678
+ var FILL_GRID = 8;
28679
+ var hullRadiusAt = (profile, radius, at3) => {
28680
+ if (!profile || profile.length < 2) return radius;
28681
+ const hull = [];
28682
+ for (const point of profile) {
28683
+ while (hull.length >= 2) {
28684
+ const [a, ra] = hull[hull.length - 2];
28685
+ const [b, rb] = hull[hull.length - 1];
28686
+ if ((b - a) * (point[1] - ra) - (rb - ra) * (point[0] - a) >= 0) hull.pop();
28687
+ else break;
28688
+ }
28689
+ hull.push(point);
28690
+ }
28691
+ if (at3 <= hull[0][0]) return hull[0][1];
28692
+ for (let i = 1; i < hull.length; i++) {
28693
+ const [a, ra] = hull[i - 1];
28694
+ const [b, rb] = hull[i];
28695
+ if (at3 <= b) return ra + (rb - ra) * (at3 - a) / (b - a || 1);
28696
+ }
28697
+ return hull[hull.length - 1][1];
28698
+ };
28699
+ var insideDrawn = (mesh2, built2, x, y, z) => {
28700
+ if (built2) {
28701
+ for (const solid of built2) {
28702
+ const [qx, qy, qz, qw] = solid.rotation;
28703
+ const px = x - solid.center[0], py = y - solid.center[1], pz = z - solid.center[2];
28704
+ const tx = 2 * (-qy * pz + qz * py), ty = 2 * (-qz * px + qx * pz), tz = 2 * (-qx * py + qy * px);
28705
+ const lx = px + qw * tx - qy * tz + qz * ty, ly = py + qw * ty - qz * tx + qx * tz, lz = pz + qw * tz - qx * ty + qy * tx;
28706
+ const [hx, hy, hz2] = solid.half;
28707
+ if (solid.kind === "cylinder" || solid.kind === "cone") {
28708
+ if (Math.abs(ly) <= hy && (lx / hx) ** 2 + (lz / hz2) ** 2 <= 1) return true;
28709
+ } else if (solid.kind === "sphere") {
28710
+ if ((lx / hx) ** 2 + (ly / hy) ** 2 + (lz / hz2) ** 2 <= 1) return true;
28711
+ } else if (Math.abs(lx) <= hx && Math.abs(ly) <= hy && Math.abs(lz) <= hz2) return true;
28712
+ }
28713
+ return false;
28714
+ }
28715
+ const geometry = mesh2.geometry;
28716
+ const p = geometry.parameters ?? {};
28717
+ const n = (key, fallback2) => typeof p[key] === "number" ? p[key] : fallback2;
28718
+ switch (geometry.type) {
28719
+ case "BoxGeometry":
28720
+ return Math.abs(x) <= n("width", 1) / 2 && Math.abs(y) <= n("height", 1) / 2 && Math.abs(z) <= n("depth", 1) / 2;
28721
+ case "CylinderGeometry":
28722
+ case "ConeGeometry": {
28723
+ const h = n("height", 1) / 2;
28724
+ if (Math.abs(y) > h || p.openEnded === true) return false;
28725
+ const top = geometry.type === "ConeGeometry" ? 0 : n("radiusTop", 1);
28726
+ const bottom = geometry.type === "ConeGeometry" ? n("radius", 1) : n("radiusBottom", 1);
28727
+ return Math.hypot(x, z) <= bottom + (top - bottom) * (y + h) / (2 * h || 1);
28728
+ }
28729
+ case "SphereGeometry":
28730
+ return Math.hypot(x, y, z) <= n("radius", 1);
28731
+ default: {
28732
+ if (!geometry.boundingBox) geometry.computeBoundingBox();
28733
+ const box = geometry.boundingBox;
28734
+ return !!box && x >= box.min.x && x <= box.max.x && y >= box.min.y && y <= box.max.y && z >= box.min.z && z <= box.max.z;
28735
+ }
28736
+ }
28737
+ };
29346
28738
  var RIM_POINTS = 12;
29347
28739
  var rimPoints = (round2, half) => {
29348
28740
  const out = [];
@@ -29400,6 +28792,16 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29400
28792
  };
29401
28793
  var BROKEN_GAP = 0.03;
29402
28794
  var BROKEN_SAMPLES = [[0.5, 0.5], [0.1, 0.1], [0.9, 0.1], [0.1, 0.9], [0.9, 0.9]];
28795
+ var UNDERMINED_MAX = 64;
28796
+ var UNDERMINED_RIM = 0.04;
28797
+ var UNDERMINED_RIM_DROP = 0.05;
28798
+ var UNDERMINED_RIM_RISE = 0.1;
28799
+ var UNDERMINED_STAND = 0.4;
28800
+ var UNDERMINED_KEEP = 0.6;
28801
+ var SOLIDS_MAX = 64;
28802
+ var UNDERMINED_PUSH = 0.6;
28803
+ var UNDERMINED_STILL = 0.05;
28804
+ var SOLID_WELD = 1e-4;
29403
28805
  var UNCHECKED_KINDS = /* @__PURE__ */ new Set(["structure", "room", "ground"]);
29404
28806
  var FIRE_CEILING_SECONDS = 3600;
29405
28807
  var GENERIC_REFERENCE_RADIUS = 15;
@@ -29510,7 +28912,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29510
28912
  __publicField(this, "blastDebris");
29511
28913
  __publicField(this, "blastWakes");
29512
28914
  __publicField(this, "costMeter");
29513
- /** The step cost the debris policy reads this frame (`debrisCost`), null when there is none (the kit's own solver, or `fixed`). */
28915
+ /** The step cost the debris policy reads this frame (`debrisCost`), null when there is none (`fixed`). */
29514
28916
  __publicField(this, "cost", null);
29515
28917
  __publicField(this, "costFrame", 0);
29516
28918
  /** The pieces faded away (`faded`): their root shrinks, then leaves the scene. */
@@ -29521,6 +28923,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29521
28923
  __publicField(this, "staticBoxes", /* @__PURE__ */ new Map());
29522
28924
  /** `staticSolids` per object, kept until `staticNow` measures the object again for a reason. */
29523
28925
  __publicField(this, "solidCache", /* @__PURE__ */ new Map());
28926
+ /** The fixed bodies a host module gives that are no bound object (`setHostSolids`), and the list last made of each: the same numbers keep the same list. */
28927
+ __publicField(this, "hostSolids", /* @__PURE__ */ new Map());
28928
+ __publicField(this, "hostSolidLists", /* @__PURE__ */ new Map());
29524
28929
  /** 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. */
29525
28930
  __publicField(this, "unsureSolids", /* @__PURE__ */ new Set());
29526
28931
  /** The objects `staticNow` measured again for a reason (an event, a moved root, boxes that changed): their `staticSolids` are measured again too. */
@@ -29544,6 +28949,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29544
28949
  __publicField(this, "pieceBoxes", /* @__PURE__ */ new WeakMap());
29545
28950
  /** Objects broken since the last update: `checkBroken` looks at what is left of them. */
29546
28951
  __publicField(this, "broken", /* @__PURE__ */ new Set());
28952
+ /** Discs of ground that changed since the last update (`wakeRegion`): `checkUndermined` looks at what stood on them. */
28953
+ __publicField(this, "undermined", []);
29547
28954
  __publicField(this, "staticAt", 0);
29548
28955
  __publicField(this, "queue", []);
29549
28956
  /** The cover of each body around a part of the world that went off, read as the event is emitted: before the blast tore or moved anything. */
@@ -29924,8 +29331,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
29924
29331
  }
29925
29332
  if (total.isEmpty()) return { half: [0.25, 0.25, 0.25], center: new this.THREE.Vector3() };
29926
29333
  const size = total.getSize(new this.THREE.Vector3());
29927
- const least = minPieceHalf(this.o.physics);
29928
- return { half: [Math.max(least, size.x / 2), Math.max(least, size.y / 2), Math.max(least, size.z / 2)], center: total.getCenter(new this.THREE.Vector3()) };
29334
+ return { half: [Math.max(MIN_PIECE_HALF, size.x / 2), Math.max(MIN_PIECE_HALF, size.y / 2), Math.max(MIN_PIECE_HALF, size.z / 2)], center: total.getCenter(new this.THREE.Vector3()) };
29929
29335
  }
29930
29336
  /**
29931
29337
  * A hosted body's boxes (`hostedSolids`: its damage zones) cut to the box of what its root draws, in the root's frame: the zones reach past the drawn body (17 cm each
@@ -30116,8 +29522,8 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
30116
29522
  mv.mesh.updateWorldMatrix(true, false);
30117
29523
  m4.multiplyMatrices(inv, mv.mesh.matrixWorld);
30118
29524
  const stride = Math.max(1, Math.floor(pos.count / ROUND_SAMPLES));
30119
- for (let i = 0; i < pos.count; i += stride) {
30120
- p.fromBufferAttribute(pos, i).applyMatrix4(m4);
29525
+ for (let i2 = 0; i2 < pos.count; i2 += stride) {
29526
+ p.fromBufferAttribute(pos, i2).applyMatrix4(m4);
30121
29527
  points.push([p.x - cx, p.y - cy, p.z - cz]);
30122
29528
  }
30123
29529
  }
@@ -30125,22 +29531,64 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
30125
29531
  const drawn = new Float64Array(3);
30126
29532
  for (const q of points) for (let k = 0; k < 3; k++) drawn[k] = Math.max(drawn[k], Math.abs(q[k]));
30127
29533
  const fits = (axis3) => {
30128
- const [i, j] = axis3 === 0 ? [1, 2] : axis3 === 1 ? [0, 2] : [0, 1];
30129
- if (Math.abs(half[i] - half[j]) > ROUND_SIDES * Math.max(half[i], half[j])) return null;
30130
- if (Math.abs(drawn[i] - drawn[j]) > ROUND_SIDES * Math.max(drawn[i], drawn[j])) return null;
30131
- const reach2 = (drawn[i] + drawn[j]) / 2;
30132
- for (const q of points) if (Math.hypot(q[i], q[j]) > reach2 * ROUND_SLACK) return null;
30133
- return (half[i] + half[j]) / 2;
29534
+ const [i2, j2] = axis3 === 0 ? [1, 2] : axis3 === 1 ? [0, 2] : [0, 1];
29535
+ if (Math.abs(half[i2] - half[j2]) > ROUND_SIDES2 * Math.max(half[i2], half[j2])) return null;
29536
+ if (Math.abs(drawn[i2] - drawn[j2]) > ROUND_SIDES2 * Math.max(drawn[i2], drawn[j2])) return null;
29537
+ const reach2 = (drawn[i2] + drawn[j2]) / 2;
29538
+ for (const q of points) if (Math.hypot(q[i2], q[j2]) > reach2 * ROUND_SLACK) return null;
29539
+ return (half[i2] + half[j2]) / 2;
30134
29540
  };
30135
29541
  const radii = [0, 1, 2].map(fits);
30136
29542
  if (radii.every((r) => r !== null)) {
30137
29543
  const radius2 = (half[0] + half[1] + half[2]) / 3;
29544
+ if (this.drawnShareOf(b, body, (q) => Math.hypot(q[0], q[1], q[2]) <= radius2) < ROUND_FILL) return null;
30138
29545
  return { kind: "sphere", axis: 1, radius: radius2, inertia: body.inertiaGiven ?? this.inertiaOf(b, body, "sphere", 1, radius2) };
30139
29546
  }
30140
29547
  const axis2 = [0, 1, 2].find((k) => radii[k] !== null);
30141
29548
  if (axis2 === void 0) return null;
30142
29549
  const radius = radii[axis2] ?? 0;
30143
- return { kind: "cylinder", axis: axis2, radius, inertia: body.inertiaGiven ?? this.inertiaOf(b, body, "cylinder", axis2, radius), profile: profileOf2(points, axis2, half[axis2], radius) };
29550
+ const profile = profileOf2(points, axis2, half[axis2], radius);
29551
+ const [i, j] = axis2 === 0 ? [1, 2] : axis2 === 1 ? [0, 2] : [0, 1];
29552
+ if (this.drawnShareOf(b, body, (q) => Math.abs(q[axis2]) <= half[axis2] && Math.hypot(q[i], q[j]) <= hullRadiusAt(profile, radius, q[axis2])) < ROUND_FILL) return null;
29553
+ return { kind: "cylinder", axis: axis2, radius, inertia: body.inertiaGiven ?? this.inertiaOf(b, body, "cylinder", axis2, radius), profile };
29554
+ }
29555
+ /** The vertices of a mesh about the centre of its box (`lb`, its own space), scaled as it is drawn: the points of the hull the engine holds it by (`PartBox.hull`). */
29556
+ hullOf(mv, lb, scale) {
29557
+ const own = [];
29558
+ this.visuals.rangePoints(mv, new this.THREE.Matrix4(), own);
29559
+ const c = lb.getCenter(new this.THREE.Vector3());
29560
+ const out = [];
29561
+ for (let i = 0; i < own.length; i += 3) out.push((own[i] - c.x) * Math.abs(scale.x), (own[i + 1] - c.y) * Math.abs(scale.y), (own[i + 2] - c.z) * Math.abs(scale.z));
29562
+ return out;
29563
+ }
29564
+ /**
29565
+ * The share of a round body the engine would hold (`inside`: a point from the piece's centre of mass) that is drawn: a grid of points through its box (`FILL_GRID`), those
29566
+ * inside the body, and of them those inside a primitive of the piece (`insideDrawn`). Primitives that overlap count once (a lamp's glow over its shade).
29567
+ */
29568
+ drawnShareOf(b, body, inside) {
29569
+ const inv = specFrameInverse(this.THREE, b.root);
29570
+ const meshes = this.meshesOf(b).filter((mv) => this.visuals.shown(mv) && !mv.host).map((mv) => {
29571
+ mv.mesh.updateWorldMatrix(true, false);
29572
+ return { mesh: mv.mesh, built: builtSolidsOf(mv.mesh), back: new this.THREE.Matrix4().multiplyMatrices(inv, mv.mesh.matrixWorld).invert() };
29573
+ });
29574
+ const [cx, cy, cz] = body.localCenter;
29575
+ const half = body.halfExtents;
29576
+ const p = new this.THREE.Vector3();
29577
+ let shape = 0;
29578
+ let drawn = 0;
29579
+ for (let a = 0; a < FILL_GRID; a++) for (let c = 0; c < FILL_GRID; c++) for (let d = 0; d < FILL_GRID; d++) {
29580
+ const q = [half[0] * ((a + 0.5) / FILL_GRID * 2 - 1), half[1] * ((c + 0.5) / FILL_GRID * 2 - 1), half[2] * ((d + 0.5) / FILL_GRID * 2 - 1)];
29581
+ if (!inside(q)) continue;
29582
+ shape++;
29583
+ for (const m of meshes) {
29584
+ p.set(q[0] + cx, q[1] + cy, q[2] + cz).applyMatrix4(m.back);
29585
+ if (insideDrawn(m.mesh, m.built, p.x, p.y, p.z)) {
29586
+ drawn++;
29587
+ break;
29588
+ }
29589
+ }
29590
+ }
29591
+ return shape === 0 ? 1 : drawn / shape;
30144
29592
  }
30145
29593
  pieces() {
30146
29594
  return [...this.pieceSys.list];
@@ -30230,6 +29678,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
30230
29678
  this.work?.beginFrame();
30231
29679
  if (!this.attached) this.drainQueue();
30232
29680
  this.checkBroken();
29681
+ this.checkUndermined();
30233
29682
  for (const b of this.bounds.values()) b.onFrame?.(dt);
30234
29683
  for (const b of this.bounds.values()) if (b.soilNode && this.world.state(b.id)?.soil?.status === "yielding") this.onSettle(b.id);
30235
29684
  this.settlement.update(dt);
@@ -30619,8 +30068,28 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
30619
30068
  } finally {
30620
30069
  this.measuredMeshes.clear();
30621
30070
  }
30071
+ for (const [id, source] of this.hostSolids) out.set(id, this.hostSolidsOf(id, source()));
30622
30072
  return out;
30623
30073
  }
30074
+ setHostSolids(id, source) {
30075
+ if (source) this.hostSolids.set(id, source);
30076
+ else {
30077
+ this.hostSolids.delete(id);
30078
+ this.hostSolidLists.delete(id);
30079
+ }
30080
+ }
30081
+ /** The module's boxes as static solids: measured again to the same numbers, the list is the one held (an engine finds it unchanged by identity). */
30082
+ hostSolidsOf(id, given) {
30083
+ const kept = this.hostSolidLists.get(id);
30084
+ if (kept && kept.given.length === given.length && given.every((s, i) => s === kept.given[i])) return kept.solids;
30085
+ const next = given.map((s, i) => ({ center: [s.center[0], s.center[1], s.center[2]], half: [s.half[0], s.half[1], s.half[2]], rotation: s.rotation ? [s.rotation[0], s.rotation[1], s.rotation[2], s.rotation[3]] : [0, 0, 0, 1], key: s.key ?? String(i) }));
30086
+ if (kept && sameSolids(kept.solids, next)) {
30087
+ this.hostSolidLists.set(id, { given, solids: kept.solids });
30088
+ return kept.solids;
30089
+ }
30090
+ this.hostSolidLists.set(id, { given, solids: next });
30091
+ return next;
30092
+ }
30624
30093
  /** `staticSolids` for each fixed object of `now`, into `out`. */
30625
30094
  measureEach(now, budget, out) {
30626
30095
  for (const id of now.keys()) {
@@ -31268,9 +30737,33 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31268
30737
  const rotation2 = new T.Quaternion(ev.rotation[0], ev.rotation[1], ev.rotation[2], ev.rotation[3]);
31269
30738
  for (const part of this.bounds.get(ev.object)?.parts.values() ?? []) for (const mv of part.meshes) this.visuals.clearDecals(mv, center, half, rotation2);
31270
30739
  this.vfx.peekWorkshop()?.decals.clearInside(ev.center, [half.x, half.y, half.z], ev.rotation);
30740
+ if (pv) this.drawChipGap(pv, ev, center, rotation2);
31271
30741
  this.vfx.burst("dust", ev.center, [0, 1, 0], ev.units ? Math.min(40, 8 + ev.units.length) : 8, ev.units ? 1.6 : 0.8, { color });
31272
30742
  this.impactSound(pv?.material ?? "", ev.center, 0.7, ev.blow);
31273
30743
  }
30744
+ /**
30745
+ * The gap a unit leaves in an object the renderer draws whole (a concrete pole, a block, a post): on each outer face the unit reached, the broken inside of its material,
30746
+ * as wide as the unit there, so the bars it bared show in a hole and not on a smooth face. A drawing that cuts its own gaps (the house's breach, `drawnSpalls`) takes none.
30747
+ */
30748
+ drawChipGap(pv, ev, center, rotation2) {
30749
+ const mv = this.nearestMesh(pv, center);
30750
+ if (!mv || mv.mesh.userData.drawnSpalls?.includes(ev.part)) return;
30751
+ const def = this.world.materials.get(pv.material);
30752
+ const inner = def?.visual?.innerColor ?? fallbackColor(def);
30753
+ const color = [16, 8, 0].reduce((hex, shift) => hex | Math.round((inner >> shift & 255) * CHIP_GAP_SHADE) << shift, 0);
30754
+ const box = this.visuals.worldBox(mv, new this.THREE.Box3());
30755
+ for (let axis2 = 0; axis2 < 3; axis2++) {
30756
+ for (const side of [-1, 1]) {
30757
+ const normal = new this.THREE.Vector3(axis2 === 0 ? side : 0, axis2 === 1 ? side : 0, axis2 === 2 ? side : 0).applyQuaternion(rotation2);
30758
+ const face = center.clone().addScaledVector(normal, ev.size[axis2] / 2);
30759
+ const k = Math.abs(normal.x) >= Math.abs(normal.y) && Math.abs(normal.x) >= Math.abs(normal.z) ? "x" : Math.abs(normal.y) >= Math.abs(normal.z) ? "y" : "z";
30760
+ const surface = normal[k] > 0 ? box.max[k] : box.min[k];
30761
+ if (Math.abs(face[k] - surface) > CHIP_GAP_REACH) continue;
30762
+ face[k] = surface;
30763
+ this.visuals.addSpall(mv, face, normal, Math.min(ev.size[(axis2 + 1) % 3], ev.size[(axis2 + 2) % 3]) / 2 * CHIP_GAP_WIDTH, color);
30764
+ }
30765
+ }
30766
+ }
31274
30767
  onFracture(ev) {
31275
30768
  const b = this.bounds.get(ev.object);
31276
30769
  const pv = b?.parts.get(ev.part);
@@ -31461,7 +30954,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31461
30954
  if (!old.round) this.setContacts(b, old, this.meshesOf(b).filter((mv) => this.visuals.shown(mv)));
31462
30955
  } else if (old.partBoxes) this.fitPartBoxes(b, old);
31463
30956
  if (!this.splittingAtLoad) old.sleeping = false;
31464
- } else if (kitOriginOf(b.root)?.kind === "furniture" && !this.splittingAtLoad) {
30957
+ } else if (kitOriginOf(b.root)?.kind === "furniture" && !this.splittingAtLoad && !this.heldByWorld(objectId)) {
31465
30958
  const piece = this.makePiece(objectId);
31466
30959
  piece.apart = true;
31467
30960
  this.tipIfTopHeavy(b, true);
@@ -31655,9 +31148,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31655
31148
  });
31656
31149
  if (holds.length !== 1) return null;
31657
31150
  const joint = holds[0];
31658
- const boxOf = (partId) => this.shownBoxes(objectId, partId).reduce((all, one) => all ? all.map((value, k) => k < 3 ? Math.min(value, one[k]) : Math.max(value, one[k])) : [...one], null);
31659
- const a = boxOf(joint.a);
31660
- const c = boxOf(joint.b);
31151
+ const boxOf2 = (partId) => this.shownBoxes(objectId, partId).reduce((all, one) => all ? all.map((value, k) => k < 3 ? Math.min(value, one[k]) : Math.max(value, one[k])) : [...one], null);
31152
+ const a = boxOf2(joint.a);
31153
+ const c = boxOf2(joint.b);
31661
31154
  if (!a || !c) return null;
31662
31155
  const point = [0, 0, 0];
31663
31156
  for (let k = 0; k < 3; k++) point[k] = (Math.max(a[k], c[k]) + Math.min(a[k + 3], c[k + 3])) / 2;
@@ -31747,15 +31240,16 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31747
31240
  if (!body.round) this.setContacts(b, body, left);
31748
31241
  }
31749
31242
  body.sleeping = false;
31243
+ if (!structural && !body.round && !body.held && kitOriginOf(b.root)?.kind === "furniture" && Math.hypot(...body.velocity) <= UNDERMINED_STILL) this.goOverIfBalanced(b, body, left);
31750
31244
  return;
31751
31245
  }
31752
- if (structural) return;
31753
- const boxOf = (mv) => this.visuals.worldBox(mv, new this.THREE.Box3());
31754
- const whole = [...b.parts.values()].flatMap((pv) => pv.meshes).map(boxOf).filter((one) => !one.isEmpty());
31246
+ if (structural || this.heldByWorld(objectId)) return;
31247
+ const boxOf2 = (mv) => this.visuals.worldBox(mv, new this.THREE.Box3());
31248
+ const whole = [...b.parts.values()].flatMap((pv) => pv.meshes).map(boxOf2).filter((one) => !one.isEmpty());
31755
31249
  if (!this.standsOn(objectId, whole.map((one) => [one.min.x, one.min.y, one.min.z, one.max.x, one.max.y, one.max.z]))) return;
31756
31250
  const floor2 = Math.min(...whole.map((one) => one.min.y));
31757
31251
  const feetOf = (boxes) => boxes.filter((one) => one.min.y < floor2 + FEET_BAND).reduce((feet, one) => feet.union(one), new this.THREE.Box3());
31758
- const leftBoxes = left.map(boxOf).filter((one) => !one.isEmpty());
31252
+ const leftBoxes = left.map(boxOf2).filter((one) => !one.isEmpty());
31759
31253
  const now = feetOf(leftBoxes);
31760
31254
  let away = null;
31761
31255
  const was = feetOf(whole);
@@ -31812,7 +31306,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31812
31306
  }
31813
31307
  releaseIfFloating(objectId) {
31814
31308
  const b = this.bounds.get(objectId);
31815
- if (!b || b.piece || this.pieceSys.get(objectId) || !this.autoSplit || UNCHECKED_KINDS.has(this.kindOf(b))) return false;
31309
+ if (!b || b.piece || this.pieceSys.get(objectId) || !this.autoSplit || UNCHECKED_KINDS.has(this.kindOf(b)) || this.heldByWorld(objectId)) return false;
31816
31310
  const boxes = this.shownBoxes(objectId);
31817
31311
  if (boxes.length === 0) return false;
31818
31312
  const whole = new this.THREE.Box3();
@@ -31831,6 +31325,139 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31831
31325
  this.o.onLoosened?.(objectId, piece, "apart");
31832
31326
  return true;
31833
31327
  }
31328
+ /**
31329
+ * The ground changed under what stands on feet (`wakeRegion`: a hole shot, dug or blown in the floor): furniture and what the host lets move (`shoveable`), not a piece yet or
31330
+ * a piece lying still. It looks at its feet again (`lowPoints`): a point of them with nothing left under it (`holdsAt`) no longer holds. While the points that still hold keep its
31331
+ * centre inside their polygon by `UNDERMINED_STAND` it stands (a cabinet on a full base over a small hole); otherwise it becomes a piece if it was not one, its corner over the
31332
+ * gap is started down, and the engine takes it into the hole by its own weight: a bed with a leg over the hole goes down on that corner until its frame meets the floor, and
31333
+ * what lay on it slides or falls off. Structures answer to their own load path.
31334
+ */
31335
+ checkUndermined() {
31336
+ if (this.undermined.length === 0) return;
31337
+ const discs = this.undermined.splice(0);
31338
+ const inDisc = (x, z, d) => Math.hypot(x - d.x, z - d.z) <= d.radius;
31339
+ for (const b of [...this.bounds.values()]) {
31340
+ if (this.kindOf(b) !== "furniture" && !this.o.shoveable?.(b.id)) continue;
31341
+ const was = b.piece ?? this.pieceSys.get(b.id) ?? null;
31342
+ if (was && (was.held || Math.hypot(...was.velocity) > UNDERMINED_STILL)) continue;
31343
+ const meshes = this.meshesOf(b).filter((mv) => this.visuals.shown(mv));
31344
+ const boxes = meshes.map((mv) => this.visuals.worldBox(mv, new this.THREE.Box3())).filter((one) => !one.isEmpty());
31345
+ if (boxes.length === 0) continue;
31346
+ const reach2 = boxes.reduce((all, one) => all.union(one), new this.THREE.Box3());
31347
+ if (!discs.some((d) => Math.hypot(Math.max(reach2.min.x - d.x, 0, d.x - reach2.max.x), Math.max(reach2.min.z - d.z, 0, d.z - reach2.max.z)) <= d.radius)) continue;
31348
+ const feet = this.lowPoints(meshes);
31349
+ if (!feet) continue;
31350
+ const { floor: floor2, points } = feet;
31351
+ const held = [];
31352
+ const lost = [];
31353
+ for (const point of points) (this.holdsAt(b.id, point[0], point[1], floor2) ? held : lost).push(point);
31354
+ if (lost.length === 0) continue;
31355
+ if (!lost.some(([x, z]) => discs.some((d) => inDisc(x, z, d) && this.stoodBeside(x, z, d, floor2)))) continue;
31356
+ const centre = centreOfBoxes(boxes);
31357
+ if (this.standsWith(held, points, centre, floor2)) continue;
31358
+ let body;
31359
+ if (was) body = was;
31360
+ else {
31361
+ const piece = this.makePiece(b.id);
31362
+ body = b.piece ?? piece;
31363
+ body.apart = true;
31364
+ this.setContacts(b, body, meshes, true);
31365
+ }
31366
+ const gx = lost.reduce((sum, p) => sum + p[0], 0) / lost.length - centre[0];
31367
+ const gz = lost.reduce((sum, p) => sum + p[1], 0) / lost.length - centre[2];
31368
+ const length = Math.hypot(gx, gz);
31369
+ body.sleeping = false;
31370
+ body.still = 0;
31371
+ body.calmAt = null;
31372
+ if (held.length > 0 && length > 1e-6) this.pieceSys.impulse(body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + gx, floor2, centre[2] + gz]);
31373
+ if (!was) this.o.onLoosened?.(b.id, body, "ground");
31374
+ }
31375
+ }
31376
+ /**
31377
+ * A piece whose feet that still hold keep its centre inside their polygon by less than `UNDERMINED_STAND` per metre of its height is started down over the nearest edge of
31378
+ * that polygon (its weight does the rest); one that stands on nothing falls by itself.
31379
+ */
31380
+ goOverIfBalanced(b, body, meshes) {
31381
+ const feet = this.lowPoints(meshes);
31382
+ if (!feet) return;
31383
+ const held = feet.points.filter(([x, z]) => this.holdsAt(b.id, x, z, feet.floor));
31384
+ if (held.length < 3) return;
31385
+ const centre = centreOfBoxes(meshes.map((mv) => this.visuals.worldBox(mv, new this.THREE.Box3())).filter((one) => !one.isEmpty()));
31386
+ if (this.standsWith(held, null, centre, feet.floor)) return;
31387
+ const inside = insideBy(convexHull2(held), [centre[0], centre[2]]);
31388
+ const reach2 = Math.max(body.halfExtents[0], body.halfExtents[2]);
31389
+ this.pieceSys.impulse(body, [0, -body.mass * UNDERMINED_PUSH, 0], [centre[0] + inside.out.x * reach2, feet.floor, centre[2] + inside.out.z * reach2]);
31390
+ }
31391
+ /**
31392
+ * Whether what stands on the points `held` of its feet (`all` of them whole) stays up with its centre at `centre`: the centre is inside what holds by `UNDERMINED_STAND` per metre of its height above `floor`, or it keeps
31393
+ * most of the hold it had (`UNDERMINED_KEEP` of how far inside its whole feet `all` the centre was; null when those are gone with a leg).
31394
+ */
31395
+ standsWith(held, all, centre, floor2) {
31396
+ if (held.length < 3) return false;
31397
+ const now = insideBy(convexHull2([...held]), [centre[0], centre[2]]).depth;
31398
+ if (now > UNDERMINED_STAND * (centre[1] - floor2)) return true;
31399
+ return all !== null && now >= UNDERMINED_KEEP * insideBy(convexHull2([...all]), [centre[0], centre[2]]).depth;
31400
+ }
31401
+ /**
31402
+ * Where `meshes` touch the floor, (x, z) in the world, and how high that floor is (their lowest drawn point); null with nothing drawn. The bottom faces (triangles
31403
+ * within `FEET_BAND` of the lowest point) give their corners, the middles of their sides and their own middles: the base of a cabinet is held along its edges and
31404
+ * across, not only at its four corners, and a mesh merged from a frame and its legs is held under each leg, not in the air between them.
31405
+ */
31406
+ lowPoints(meshes) {
31407
+ const faces = [];
31408
+ let floor2 = Infinity;
31409
+ for (const mv of meshes) {
31410
+ mv.mesh.updateWorldMatrix(true, false);
31411
+ const points = [];
31412
+ this.visuals.rangePoints(mv, mv.mesh.matrixWorld, points);
31413
+ const count = points.length / 3;
31414
+ const index = mv.mesh.geometry.getIndex()?.array;
31415
+ const from = mv.range ? mv.range[0] : 0;
31416
+ const total = index ? index.length : count;
31417
+ for (let i = 0; i + 2 < total; i += 3) {
31418
+ const a = (index ? index[i] : i) - from, b = (index ? index[i + 1] : i + 1) - from, c = (index ? index[i + 2] : i + 2) - from;
31419
+ if (a < 0 || b < 0 || c < 0 || a >= count || b >= count || c >= count) continue;
31420
+ for (const k of [a, b, c]) {
31421
+ faces.push(points[k * 3], points[k * 3 + 1], points[k * 3 + 2]);
31422
+ floor2 = Math.min(floor2, points[k * 3 + 1]);
31423
+ }
31424
+ }
31425
+ }
31426
+ if (faces.length === 0) return null;
31427
+ const out = [];
31428
+ const seen = /* @__PURE__ */ new Set();
31429
+ const add2 = (x, z) => {
31430
+ const key = `${Math.round(x * 1e3)},${Math.round(z * 1e3)}`;
31431
+ if (seen.has(key)) return;
31432
+ seen.add(key);
31433
+ out.push([x, z]);
31434
+ };
31435
+ for (let i = 0; i < faces.length; i += 9) {
31436
+ if (faces[i + 1] > floor2 + FEET_BAND || faces[i + 4] > floor2 + FEET_BAND || faces[i + 7] > floor2 + FEET_BAND) continue;
31437
+ const ax = faces[i], az = faces[i + 2], bx = faces[i + 3], bz = faces[i + 5], cx = faces[i + 6], cz = faces[i + 8];
31438
+ add2(ax, az);
31439
+ add2(bx, bz);
31440
+ add2(cx, cz);
31441
+ add2((ax + bx) / 2, (az + bz) / 2);
31442
+ add2((bx + cx) / 2, (bz + cz) / 2);
31443
+ add2((ax + cx) / 2, (az + cz) / 2);
31444
+ add2((ax + bx + cx) / 3, (az + bz + cz) / 3);
31445
+ }
31446
+ return out.length > 0 ? { floor: floor2, points: out } : null;
31447
+ }
31448
+ /** Whether the ground, a fixed top or a piece (not `objectId` itself) is within `BROKEN_GAP` under the point (x, z) of a foot at height `y`. */
31449
+ holdsAt(objectId, x, z, y) {
31450
+ return Math.max(this.groundAt(x, z), this.staticTopAtBut(objectId, x, z, y, BROKEN_GAP), this.pieceSys.topAt(x, z, y, BROKEN_GAP, objectId)) >= y - BROKEN_GAP;
31451
+ }
31452
+ /** Whether the ground just past the disc `d`, on the way from its middle to the foot at (x, z), is where the object's feet (`floor`) were: it stood on the ground that went. */
31453
+ stoodBeside(x, z, d, floor2) {
31454
+ const fx = x - d.x, fz = z - d.z;
31455
+ const length = Math.hypot(fx, fz);
31456
+ const ux = length > 1e-6 ? fx / length : 1, uz = length > 1e-6 ? fz / length : 0;
31457
+ const reach2 = d.radius + UNDERMINED_RIM;
31458
+ const ground = this.groundAt(d.x + ux * reach2, d.z + uz * reach2);
31459
+ return ground >= floor2 - BROKEN_GAP - UNDERMINED_RIM_DROP && ground <= floor2 + UNDERMINED_RIM_RISE;
31460
+ }
31834
31461
  /** Whether the lowest of `boxes` (world boxes of the object `objectId`) has the ground, a fixed top or a piece within `BROKEN_GAP` under it. */
31835
31462
  standsOn(objectId, boxes) {
31836
31463
  if (boxes.length === 0) return false;
@@ -31847,6 +31474,10 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31847
31474
  return false;
31848
31475
  }
31849
31476
  /** 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. */
31477
+ /** Whether what is left of the object is fixed where it was laid and still anchored (`DestructionWorld.fixedInPlace`): it stands by its load path, it is never let go as a piece. */
31478
+ heldByWorld(objectId) {
31479
+ return this.world.fixedInPlace(objectId);
31480
+ }
31850
31481
  kindOf(b) {
31851
31482
  for (let o = b.root; o; o = o.parent) {
31852
31483
  const kind = kitOriginOf(o)?.kind;
@@ -31885,7 +31516,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31885
31516
  * what holds it and it goes over until the top meets the floor. Past `CONTACT_MESHES` meshes it keeps the corners of its box; up to `PART_BOX_MESHES`, what lands on it lands
31886
31517
  * on its parts.
31887
31518
  */
31888
- setContacts(b, body, meshes) {
31519
+ setContacts(b, body, meshes, fitWhole = false) {
31889
31520
  if (meshes.length > PART_BOX_MESHES) {
31890
31521
  body.contacts = void 0;
31891
31522
  body.partBoxes = void 0;
@@ -31902,7 +31533,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
31902
31533
  this.visuals.localBox(mv, lb);
31903
31534
  if (lb.isEmpty()) continue;
31904
31535
  m4.multiplyMatrices(inv, mv.mesh.matrixWorld);
31905
- this.partBoxesOf(mv, { lb, m4, from: [cx, cy, cz] }, boxes);
31536
+ this.partBoxesOf(mv, { lb, m4, from: [cx, cy, cz], fitWhole }, boxes);
31906
31537
  lb.applyMatrix4(m4);
31907
31538
  for (let i = 0; i < 8; i++) points.push([(i & 1 ? lb.max.x : lb.min.x) - cx, (i & 2 ? lb.max.y : lb.min.y) - cy, (i & 4 ? lb.max.z : lb.min.z) - cz]);
31908
31539
  }
@@ -32023,28 +31654,67 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
32023
31654
  return own;
32024
31655
  }
32025
31656
  /**
32026
- * The boxes of one mesh in the piece's frame, from its centre of mass, turned as the mesh is drawn: a plain mesh is its geometry's box in its own space, turned by its
32027
- * place in the piece; a part drawn by a range of a merged mesh (a roof sheet in the house's roof mesh) is fitted to its own vertices (`fitOrientedBoxes`), since the box
31657
+ * The boxes of one mesh in the piece's frame, from its centre of mass, turned as the mesh is drawn: a mesh drawn as boxes round the air is those boxes (`hollowBoxesOf`);
31658
+ * else a plain mesh is its geometry's box in its own space, turned by its place in the piece; a part drawn by a range of a merged mesh (a roof sheet in the house's roof mesh) is fitted to its own vertices (`fitOrientedBoxes`), since the box
32028
31659
  * of those vertices in the merged mesh's space is the box around a tilted sheet, mostly air.
32029
31660
  */
32030
31661
  partBoxesOf(mv, at3, out) {
32031
31662
  const [cx, cy, cz] = at3.from;
32032
- if (mv.range) {
32033
- const own = [];
32034
- this.visuals.rangePoints(mv, new this.THREE.Matrix4(), own);
32035
- const drawn = hollowBoxesOf(own);
32036
- if (drawn) {
32037
- const pos2 = new this.THREE.Vector3();
32038
- const quat3 = new this.THREE.Quaternion();
32039
- const scale2 = new this.THREE.Vector3();
32040
- at3.m4.decompose(pos2, quat3, scale2);
32041
- for (const box of drawn) {
32042
- const c2 = new this.THREE.Vector3((box.low[0] + box.high[0]) / 2, (box.low[1] + box.high[1]) / 2, (box.low[2] + box.high[2]) / 2).applyMatrix4(at3.m4);
32043
- const half = [Math.abs((box.high[0] - box.low[0]) * scale2.x) / 2, Math.abs((box.high[1] - box.low[1]) * scale2.y) / 2, Math.abs((box.high[2] - box.low[2]) * scale2.z) / 2];
32044
- out.push({ center: [c2.x - cx, c2.y - cy, c2.z - cz], half, rotation: [quat3.x, quat3.y, quat3.z, quat3.w] });
32045
- }
32046
- return;
31663
+ const built2 = mv.range ? null : builtSolidsOf(mv.mesh);
31664
+ const solids = at3.fitWhole && !mv.range && !built2 ? solidBoxesOf(mv.mesh.geometry) : null;
31665
+ if (solids) {
31666
+ const pos2 = new this.THREE.Vector3();
31667
+ const quat3 = new this.THREE.Quaternion();
31668
+ const scale2 = new this.THREE.Vector3();
31669
+ at3.m4.decompose(pos2, quat3, scale2);
31670
+ for (const box of solids) {
31671
+ const c2 = new this.THREE.Vector3((box[0] + box[3]) / 2, (box[1] + box[4]) / 2, (box[2] + box[5]) / 2).applyMatrix4(at3.m4);
31672
+ const half2 = [Math.max(5e-3, Math.abs((box[3] - box[0]) * scale2.x) / 2), Math.max(5e-3, Math.abs((box[4] - box[1]) * scale2.y) / 2), Math.max(5e-3, Math.abs((box[5] - box[2]) * scale2.z) / 2)];
31673
+ out.push({ center: [c2.x - cx, c2.y - cy, c2.z - cz], half: half2, rotation: [quat3.x, quat3.y, quat3.z, quat3.w] });
31674
+ }
31675
+ return;
31676
+ }
31677
+ if (built2) {
31678
+ const pos2 = new this.THREE.Vector3();
31679
+ const quat3 = new this.THREE.Quaternion();
31680
+ const scale2 = new this.THREE.Vector3();
31681
+ at3.m4.decompose(pos2, quat3, scale2);
31682
+ const c2 = new this.THREE.Vector3();
31683
+ const q = new this.THREE.Quaternion();
31684
+ const even = (Math.abs(scale2.x) + Math.abs(scale2.y) + Math.abs(scale2.z)) / 3;
31685
+ for (const solid of built2) {
31686
+ c2.set(solid.center[0], solid.center[1], solid.center[2]).applyMatrix4(at3.m4);
31687
+ q.set(solid.rotation[0], solid.rotation[1], solid.rotation[2], solid.rotation[3]);
31688
+ const turned = Math.abs(q.w) < 1 - 1e-9;
31689
+ const s = turned ? [even, even, even] : [Math.abs(scale2.x), Math.abs(scale2.y), Math.abs(scale2.z)];
31690
+ q.premultiply(quat3).normalize();
31691
+ const round2 = isRoundSolid(solid) && Math.abs(s[0] - s[2]) <= 1e-9;
31692
+ out.push({ center: [c2.x - cx, c2.y - cy, c2.z - cz], half: [Math.max(5e-3, solid.half[0] * s[0]), Math.max(5e-3, solid.half[1] * s[1]), Math.max(5e-3, solid.half[2] * s[2])], rotation: [q.x, q.y, q.z, q.w], ...round2 ? { round: true } : {} });
31693
+ }
31694
+ return;
31695
+ }
31696
+ const own = [];
31697
+ this.visuals.rangePoints(mv, new this.THREE.Matrix4(), own);
31698
+ const drawn = hollowBoxesOf(own, mv.range ? RANGED : OWN_MESH);
31699
+ if (drawn) {
31700
+ const pos2 = new this.THREE.Vector3();
31701
+ const quat3 = new this.THREE.Quaternion();
31702
+ const scale2 = new this.THREE.Vector3();
31703
+ at3.m4.decompose(pos2, quat3, scale2);
31704
+ const c2 = new this.THREE.Vector3();
31705
+ const q = new this.THREE.Quaternion();
31706
+ const even = (Math.abs(scale2.x) + Math.abs(scale2.y) + Math.abs(scale2.z)) / 3;
31707
+ for (const box of drawn) {
31708
+ c2.set(box.center[0], box.center[1], box.center[2]).applyMatrix4(at3.m4);
31709
+ const half2 = box.rotation ? [box.half[0] * even, box.half[1] * even, box.half[2] * even] : [Math.abs(box.half[0] * scale2.x), Math.abs(box.half[1] * scale2.y), Math.abs(box.half[2] * scale2.z)];
31710
+ if (box.rotation) q.set(box.rotation[0], box.rotation[1], box.rotation[2], box.rotation[3]).premultiply(quat3).normalize();
31711
+ else q.copy(quat3);
31712
+ const thin = mv.range ? 0 : 5e-3;
31713
+ out.push({ center: [c2.x - cx, c2.y - cy, c2.z - cz], half: [Math.max(thin, half2[0]), Math.max(thin, half2[1]), Math.max(thin, half2[2])], rotation: [q.x, q.y, q.z, q.w] });
32047
31714
  }
31715
+ return;
31716
+ }
31717
+ if (mv.range) {
32048
31718
  if (isRigidPose(at3.m4.elements)) {
32049
31719
  const turn2 = new this.THREE.Quaternion().setFromRotationMatrix(at3.m4);
32050
31720
  const c2 = new this.THREE.Vector3();
@@ -32067,11 +31737,14 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
32067
31737
  at3.m4.decompose(pos, quat2, scale);
32068
31738
  const c = at3.lb.getCenter(new this.THREE.Vector3()).applyMatrix4(at3.m4);
32069
31739
  const size = at3.lb.getSize(new this.THREE.Vector3());
32070
- out.push({
32071
- center: [c.x - cx, c.y - cy, c.z - cz],
32072
- half: [Math.max(5e-3, Math.abs(size.x * scale.x) / 2), Math.max(5e-3, Math.abs(size.y * scale.y) / 2), Math.max(5e-3, Math.abs(size.z * scale.z) / 2)],
32073
- rotation: [quat2.x, quat2.y, quat2.z, quat2.w]
32074
- });
31740
+ const half = [Math.max(5e-3, Math.abs(size.x * scale.x) / 2), Math.max(5e-3, Math.abs(size.y * scale.y) / 2), Math.max(5e-3, Math.abs(size.z * scale.z) / 2)];
31741
+ const geometry = mv.mesh.geometry;
31742
+ const params = geometry.parameters ?? {};
31743
+ const whole = typeof params.thetaLength !== "number" || Math.abs(params.thetaLength - 2 * Math.PI) < 1e-6;
31744
+ const cylinder = geometry.type === "CylinderGeometry" && !mv.range;
31745
+ const straight = cylinder && whole && params.openEnded !== true && isRoundSolid({ kind: params.radiusTop === params.radiusBottom ? "cylinder" : "cone", half });
31746
+ const curved = !mv.range && !straight && (cylinder || geometry.type === "ConeGeometry" || geometry.type === "SphereGeometry");
31747
+ out.push({ center: [c.x - cx, c.y - cy, c.z - cz], half, rotation: [quat2.x, quat2.y, quat2.z, quat2.w], ...straight ? { round: true } : {}, ...curved ? { hull: this.hullOf(mv, at3.lb, scale) } : {} });
32075
31748
  }
32076
31749
  /**
32077
31750
  * A piece of furniture standing on feet too close for its height (a board on two legs in a line, a lone leg) does not stay up: the box of a piece hides that its weight is up
@@ -32648,6 +32321,7 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
32648
32321
  wakeRegion(x, z, radius) {
32649
32322
  this.fragments.wakeRegion(x, z, radius);
32650
32323
  this.pieceSys.wakeRegion(x, z, radius);
32324
+ if (this.autoSplit && this.undermined.length < UNDERMINED_MAX) this.undermined.push({ x, z, radius });
32651
32325
  }
32652
32326
  stats() {
32653
32327
  return { fragments: this.fragments.count, particles: this.vfx.sprites().live + this.ownedVfxParticles(), pieces: this.pieceSys.list.length, decals: this.visuals.decalCount + this.ground.count };
@@ -32706,6 +32380,55 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
32706
32380
  };
32707
32381
  return ch(16) | ch(8) | ch(0);
32708
32382
  }
32383
+ function solidBoxesOf(geometry) {
32384
+ const position = geometry.getAttribute("position");
32385
+ if (!position || position.count <= 24) return null;
32386
+ const parent = new Int32Array(position.count);
32387
+ for (let i = 0; i < parent.length; i++) parent[i] = i;
32388
+ const find = (i) => {
32389
+ while (parent[i] !== i) {
32390
+ parent[i] = parent[parent[i]];
32391
+ i = parent[i];
32392
+ }
32393
+ return i;
32394
+ };
32395
+ const join = (a, b) => {
32396
+ const ra = find(a), rb = find(b);
32397
+ if (ra !== rb) parent[ra] = rb;
32398
+ };
32399
+ const corners = /* @__PURE__ */ new Map();
32400
+ for (let i = 0; i < position.count; i++) {
32401
+ const key = `${Math.round(position.getX(i) / SOLID_WELD)},${Math.round(position.getY(i) / SOLID_WELD)},${Math.round(position.getZ(i) / SOLID_WELD)}`;
32402
+ const first = corners.get(key);
32403
+ if (first === void 0) corners.set(key, i);
32404
+ else join(i, first);
32405
+ }
32406
+ const index = geometry.getIndex();
32407
+ const triangles2 = index ? index.count / 3 : position.count / 3;
32408
+ for (let t = 0; t < triangles2; t++) {
32409
+ const a = index ? index.getX(t * 3) : t * 3;
32410
+ join(a, index ? index.getX(t * 3 + 1) : t * 3 + 1);
32411
+ join(a, index ? index.getX(t * 3 + 2) : t * 3 + 2);
32412
+ }
32413
+ const boxes = /* @__PURE__ */ new Map();
32414
+ for (let i = 0; i < position.count; i++) {
32415
+ const root = find(i);
32416
+ const x = position.getX(i), y = position.getY(i), z = position.getZ(i);
32417
+ const box = boxes.get(root);
32418
+ if (!box) {
32419
+ if (boxes.size >= SOLIDS_MAX) return null;
32420
+ boxes.set(root, [x, y, z, x, y, z]);
32421
+ continue;
32422
+ }
32423
+ box[0] = Math.min(box[0], x);
32424
+ box[1] = Math.min(box[1], y);
32425
+ box[2] = Math.min(box[2], z);
32426
+ box[3] = Math.max(box[3], x);
32427
+ box[4] = Math.max(box[4], y);
32428
+ box[5] = Math.max(box[5], z);
32429
+ }
32430
+ return boxes.size > 1 ? [...boxes.values()] : null;
32431
+ }
32709
32432
  function convexHull2(points) {
32710
32433
  const sorted = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
32711
32434
  if (sorted.length < 3) return sorted;
@@ -32937,9 +32660,9 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
32937
32660
  if (!bases.has(base)) bases.set(base, { id: base, category: tiers[0]?.category ?? "", layers: { close: tiers[0]?.layers.close ?? [] } });
32938
32661
  }
32939
32662
  for (const sound of bases.values()) {
32940
- const numbers = options.sounds?.[sound.id] ?? options.defaults?.(sound);
32663
+ const numbers2 = options.sounds?.[sound.id] ?? options.defaults?.(sound);
32941
32664
  const close = refsOf(sound.layers.close, baseUrl);
32942
- if (!numbers || close.length === 0) continue;
32665
+ if (!numbers2 || close.length === 0) continue;
32943
32666
  const tiers = (tiersOf.get(sound.id) ?? []).map((tier) => {
32944
32667
  const name = splitTier(tier.id).tier;
32945
32668
  const tierFar = refsOf(tier.layers.far, baseUrl);
@@ -32951,20 +32674,20 @@ vec3 c=mix(uDeep,uFoam,dome>.5?.8:.65+.35*vY);float alpha=body*vA;if(alpha<.004)
32951
32674
  const files = [sound, ...tiersOf.get(sound.id) ?? []].flatMap((entry) => Object.values(entry.layers).flatMap((entries2) => entries2 ?? []));
32952
32675
  samples.push({
32953
32676
  id: sound.id,
32954
- bus: numbers.bus,
32677
+ bus: numbers2.bus,
32955
32678
  close,
32956
32679
  ...far2.length > 0 ? { far: far2 } : {},
32957
32680
  ...tiers.length > 0 ? { tiers } : {},
32958
- ...numbers.crossover ? { crossover: numbers.crossover } : {},
32959
- ...indoor.length > 0 || outdoor.length > 0 ? { tail: { ...indoor.length > 0 ? { indoor } : {}, ...outdoor.length > 0 ? { outdoor } : {}, ...numbers.tailGain === void 0 ? {} : { gain: numbers.tailGain } } } : {},
32960
- ...numbers.pitch === void 0 ? {} : { pitch: numbers.pitch },
32961
- ...numbers.gain === void 0 ? {} : { gain: numbers.gain },
32962
- ...numbers.falloff ? { falloff: numbers.falloff } : {},
32963
- ...numbers.cutoffK === void 0 ? {} : { cutoffK: numbers.cutoffK },
32964
- ...numbers.group ? { group: numbers.group } : {},
32965
- ...numbers.priority === void 0 ? {} : { priority: numbers.priority },
32966
- ...numbers.choke ? { choke: numbers.choke } : {},
32967
- ...numbers.fallback ? { fallback: numbers.fallback } : {},
32681
+ ...numbers2.crossover ? { crossover: numbers2.crossover } : {},
32682
+ ...indoor.length > 0 || outdoor.length > 0 ? { tail: { ...indoor.length > 0 ? { indoor } : {}, ...outdoor.length > 0 ? { outdoor } : {}, ...numbers2.tailGain === void 0 ? {} : { gain: numbers2.tailGain } } } : {},
32683
+ ...numbers2.pitch === void 0 ? {} : { pitch: numbers2.pitch },
32684
+ ...numbers2.gain === void 0 ? {} : { gain: numbers2.gain },
32685
+ ...numbers2.falloff ? { falloff: numbers2.falloff } : {},
32686
+ ...numbers2.cutoffK === void 0 ? {} : { cutoffK: numbers2.cutoffK },
32687
+ ...numbers2.group ? { group: numbers2.group } : {},
32688
+ ...numbers2.priority === void 0 ? {} : { priority: numbers2.priority },
32689
+ ...numbers2.choke ? { choke: numbers2.choke } : {},
32690
+ ...numbers2.fallback ? { fallback: numbers2.fallback } : {},
32968
32691
  sources: files.map((file) => `${file.file}: ${file.source} ${file.author} ${file.license}`)
32969
32692
  });
32970
32693
  }