@adatechnology/game-shapes-three 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,7 +40,10 @@ const geometry = toGeometry(THREE, buildPrimitive({ kind: 'torus', radius: 0.3,
40
40
  | `mergeByMaterial(THREE, root, space)` | Every visible mesh under `root` baked into `space` and joined per material (non-indexed), on game-shapes' merge; the same bytes `game-props3d`'s version gave |
41
41
  | `releaseObject3D(roots, { keep })` | Frees the GPU side of trees taken out of the scene for good: geometries, materials, textures (maps and shader uniforms) and skeletons, except what a tree in `keep` (the scene) still uses or what is marked `userData.shared`. Returns how many it freed |
42
42
  | `discardObject3D(objects, { keep })` | `removeFromParent()` plus `releaseObject3D` for one object or a list (one walk of the scene), keeping what the rest of its scene draws: the one call for something that leaves the game |
43
+ | `isMesh(object)` | Type guard for a mesh (or a skinned or instanced one) met while walking a tree with `traverse` |
44
+ | `coincidentFacesOf(root, { eps, minArea, includeHidden })` | Faces under `root` that z-fight: triangles on the same plane (within 1 mm), facing the same way, that overlap more than 1 cm². Walks every drawn mesh in world space (instances too; decals with `polygonOffset` are skipped) and names both meshes in each hit. Every package's catalog test runs it on each piece (see `CLAUDE.md` §13) |
43
45
  | `markShared(...resources)` | Marks a palette, kit or catalog resource as shared on purpose, so the release never frees it; same as `userData.shared = true` without touching the resource (digests and goldens stay) |
46
+ | `markPositionsWritten(mesh, v0, v1)` / `rangesWrittenSince(attribute, version)` | Declares, right after the one `needsUpdate = true` of a write, which vertex range of a merged mesh it changed, and reads back the ranges written since a `version`. The destruction renderer measures each part's range of a merged mesh as a collider: a declared write re-measures only the parts in that range; a write that flags `needsUpdate` and declares nothing re-measures every part of the mesh |
44
47
 
45
48
  ## Português
46
49
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { PrimitiveBuffers, ShapeBatch, ShapePoint, MaterialHint, ShapeBuffers } from '@adatechnology/game-shapes';
1
+ import { PrimitiveBuffers, ShapeBatch, ShapePoint, MaterialHint, ShapeBuffers, CoincidentFacesOptions, CoincidentBatch, CoincidentFaceHit } from '@adatechnology/game-shapes';
2
+ export { CoincidentFaceHit, DepthPrecision, GAME_DEPTH_PRECISION, depthResolution, describeCoincidentFaces } from '@adatechnology/game-shapes';
2
3
  import * as THREE_NS from 'three';
3
4
 
4
5
  type Three = typeof THREE_NS;
@@ -109,4 +110,56 @@ declare function releaseObject3D(roots: THREE_NS.Object3D | readonly THREE_NS.Ob
109
110
  */
110
111
  declare function discardObject3D(objects: THREE_NS.Object3D | readonly THREE_NS.Object3D[], options?: ReleaseOptions): ReleaseReport;
111
112
 
112
- export { type ReleaseOptions, type ReleaseReport, SHAPE_GEOMETRY_TYPES, type ShapeGeometriesOptions, type ShapeObject, type Three, type ToGeometryOptions, type ToObjectOptions, catenary, createCord, createMaterials, discardObject3D, markShared, mergeByMaterial, releaseObject3D, shapeGeometries, toGeometry, toObject3D };
113
+ /** A mesh (or a subclass: skinned, instanced) found while walking a tree; three marks them with `isMesh`. */
114
+ declare function isMesh(o: THREE_NS.Object3D | null | undefined): o is THREE_NS.Mesh;
115
+
116
+ /**
117
+ * Flags the mesh's positions for upload (`needsUpdate`) and declares that the write changed the vertices `[v0, v1)`: the write and its declaration share one `version`,
118
+ * so call it once per range written instead of setting `needsUpdate` yourself. A drawing that shares a
119
+ * merged mesh with another that measures its ranges (the house collapsing the range of a wall it draws with holes, under the destruction renderer that measures each
120
+ * part's range as a collider) calls it, so only the parts drawn by that range are measured again, not the whole house (`rangesWrittenSince`). A write that sets `needsUpdate` and declares nothing still counts, for every part of the mesh (`CLAUDE.md` §12).
121
+ */
122
+ declare function markPositionsWritten(mesh: THREE_NS.Mesh, v0: number, v1: number): void;
123
+ /** The ranges written after `version` up to the attribute's version now, or null when one of those writes declared no range (or is forgotten). */
124
+ declare function rangesWrittenSince(position: THREE_NS.BufferAttribute, version: number): Array<readonly [number, number]> | null;
125
+
126
+ interface CoincidentFacesOfOptions extends CoincidentFacesOptions {
127
+ /** Also check meshes that are hidden now (a piece that only shows when the wall breaks). Default false: only what is drawn. */
128
+ readonly includeHidden?: boolean;
129
+ }
130
+ interface MeshBatches {
131
+ readonly batches: CoincidentBatch[];
132
+ /** The mesh each batch came from, at the same index. */
133
+ readonly meshes: THREE_NS.Mesh[];
134
+ }
135
+ /** The triangles of every drawn mesh under `root`, in world space, with the mesh of each batch. */
136
+ declare function meshBatchesOf(root: THREE_NS.Object3D, options?: Pick<CoincidentFacesOfOptions, 'includeHidden'>): MeshBatches;
137
+ /** The triangles of every drawn mesh under `root`, in world space, ready for `coincidentFaces`. */
138
+ declare function coincidentBatchesOf(root: THREE_NS.Object3D, options?: Pick<CoincidentFacesOfOptions, 'includeHidden'>): CoincidentBatch[];
139
+ /**
140
+ * Faces of `root` that z-fight: same plane, same facing, overlapping. Use it in the catalog test of every package that draws pieces, so a
141
+ * piece that comes back with a lining flush to its body fails the test instead of flickering on screen.
142
+ */
143
+ declare function coincidentFacesOf(root: THREE_NS.Object3D, options?: CoincidentFacesOfOptions): CoincidentFaceHit[];
144
+
145
+ interface StandOutOptions {
146
+ /** How far a fighting face of the smaller piece moves out, in metres. Default 0.002 (CLAUDE.md §13). */
147
+ readonly gap?: number;
148
+ /** Rounds of check-and-move; a moved face can meet a third piece. Default 3. */
149
+ readonly rounds?: number;
150
+ }
151
+ interface StandOutReport {
152
+ /** Meshes that were moved out. */
153
+ readonly grown: number;
154
+ /** Face pairs still fighting after the last round (0 when it worked). */
155
+ readonly left: number;
156
+ }
157
+ /**
158
+ * Makes the faces of `root` stop fighting: of each pair of meshes with coincident faces, the face of the smaller one (the label, band, rim
159
+ * or lining) moves `gap` out of the bigger one, the rule of `CLAUDE.md` §13 ("a detail stands out at least 2 mm"). Only the sides that
160
+ * fight move. For pieces ported as they were drawn, where the detail sits flush on its body; a builder of the kit draws the gap itself.
161
+ * Instanced meshes are left alone.
162
+ */
163
+ declare function standOutCoincident(root: THREE_NS.Object3D, options?: StandOutOptions): StandOutReport;
164
+
165
+ export { type CoincidentFacesOfOptions, type MeshBatches, type ReleaseOptions, type ReleaseReport, SHAPE_GEOMETRY_TYPES, type ShapeGeometriesOptions, type ShapeObject, type StandOutOptions, type StandOutReport, type Three, type ToGeometryOptions, type ToObjectOptions, catenary, coincidentBatchesOf, coincidentFacesOf, createCord, createMaterials, discardObject3D, isMesh, markPositionsWritten, markShared, mergeByMaterial, meshBatchesOf, rangesWrittenSince, releaseObject3D, shapeGeometries, standOutCoincident, toGeometry, toObject3D };
@@ -21,15 +21,25 @@ var GameShapesThree = (() => {
21
21
  // src/index.ts
22
22
  var src_exports = {};
23
23
  __export(src_exports, {
24
+ GAME_DEPTH_PRECISION: () => GAME_DEPTH_PRECISION,
24
25
  SHAPE_GEOMETRY_TYPES: () => SHAPE_GEOMETRY_TYPES,
25
26
  catenary: () => catenary,
27
+ coincidentBatchesOf: () => coincidentBatchesOf,
28
+ coincidentFacesOf: () => coincidentFacesOf,
26
29
  createCord: () => createCord,
27
30
  createMaterials: () => createMaterials,
31
+ depthResolution: () => depthResolution,
32
+ describeCoincidentFaces: () => describeCoincidentFaces,
28
33
  discardObject3D: () => discardObject3D,
34
+ isMesh: () => isMesh,
35
+ markPositionsWritten: () => markPositionsWritten,
29
36
  markShared: () => markShared,
30
37
  mergeByMaterial: () => mergeByMaterial,
38
+ meshBatchesOf: () => meshBatchesOf,
39
+ rangesWrittenSince: () => rangesWrittenSince,
31
40
  releaseObject3D: () => releaseObject3D,
32
41
  shapeGeometries: () => shapeGeometries,
42
+ standOutCoincident: () => standOutCoincident,
33
43
  toGeometry: () => toGeometry,
34
44
  toObject3D: () => toObject3D
35
45
  });
@@ -75,7 +85,7 @@ var GameShapesThree = (() => {
75
85
  return geometry;
76
86
  }
77
87
 
78
- // ../game-shapes/dist/chunk-M5N2SHNL.js
88
+ // ../game-shapes/dist/chunk-E3X7UDDV.js
79
89
  function colorHex(color2, fallback = 16777215) {
80
90
  if (color2 === void 0) return fallback;
81
91
  if (typeof color2 === "number") return Math.floor(color2);
@@ -994,17 +1004,19 @@ var GameShapesThree = (() => {
994
1004
  if (p.prevZ) p.prevZ.nextZ = p.nextZ;
995
1005
  if (p.nextZ) p.nextZ.prevZ = p.prevZ;
996
1006
  }
997
- function Node(i, x, y) {
998
- this.i = i;
999
- this.x = x;
1000
- this.y = y;
1001
- this.prev = null;
1002
- this.next = null;
1003
- this.z = 0;
1004
- this.prevZ = null;
1005
- this.nextZ = null;
1006
- this.steiner = false;
1007
- }
1007
+ var Node = class {
1008
+ constructor(i, x, y) {
1009
+ this.i = i;
1010
+ this.x = x;
1011
+ this.y = y;
1012
+ this.prev = null;
1013
+ this.next = null;
1014
+ this.z = 0;
1015
+ this.prevZ = null;
1016
+ this.nextZ = null;
1017
+ this.steiner = false;
1018
+ }
1019
+ };
1008
1020
  function signedArea(data, start, end, dim) {
1009
1021
  let sum = 0;
1010
1022
  for (let i = start, j = end - dim; i < end; i += dim) {
@@ -1550,6 +1562,275 @@ var GameShapesThree = (() => {
1550
1562
  return { positions, normals, uvs };
1551
1563
  }
1552
1564
 
1565
+ // ../game-shapes/dist/index.js
1566
+ var ZERO = [0, 0, 0];
1567
+ function normalOf(t) {
1568
+ const ax = t[1][0] - t[0][0], ay = t[1][1] - t[0][1], az = t[1][2] - t[0][2];
1569
+ const bx = t[2][0] - t[0][0], by = t[2][1] - t[0][1], bz = t[2][2] - t[0][2];
1570
+ const nx = ay * bz - az * by, ny = az * bx - ax * bz, nz = ax * by - ay * bx;
1571
+ const length = Math.hypot(nx, ny, nz);
1572
+ return length < 1e-12 ? ZERO : [nx / length, ny / length, nz / length];
1573
+ }
1574
+ function dominantAxis(n) {
1575
+ const x = Math.abs(n[0]), y = Math.abs(n[1]), z = Math.abs(n[2]);
1576
+ if (x >= y && x >= z) return 0;
1577
+ return y >= z ? 1 : 2;
1578
+ }
1579
+ function keptAxes(drop) {
1580
+ if (drop === 0) return [1, 2];
1581
+ return drop === 1 ? [0, 2] : [0, 1];
1582
+ }
1583
+ function projectTriangle(t, drop) {
1584
+ const [u, w] = keptAxes(drop);
1585
+ return [[t[0][u], t[0][w]], [t[1][u], t[1][w]], [t[2][u], t[2][w]]];
1586
+ }
1587
+ function unprojectPoint(p, drop, plane2) {
1588
+ const [u, w] = keptAxes(drop);
1589
+ const out = [0, 0, 0];
1590
+ out[u] = p[0];
1591
+ out[w] = p[1];
1592
+ out[drop] = (plane2.offset - plane2.n[u] * p[0] - plane2.n[w] * p[1]) / plane2.n[drop];
1593
+ return out;
1594
+ }
1595
+ function cross2(a, b, c) {
1596
+ return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
1597
+ }
1598
+ function edgeCrossing(p0, p1, e0, e1) {
1599
+ const dx = p1[0] - p0[0], dy = p1[1] - p0[1], ex = e1[0] - e0[0], ey = e1[1] - e0[1];
1600
+ const d = dx * ey - dy * ex;
1601
+ if (Math.abs(d) < 1e-15) return p1;
1602
+ const t = ((e0[0] - p0[0]) * ey - (e0[1] - p0[1]) * ex) / d;
1603
+ return [p0[0] + t * dx, p0[1] + t * dy];
1604
+ }
1605
+ function clipByEdge(polygon, e0, e1) {
1606
+ const out = [];
1607
+ for (let j = 0; j < polygon.length; j++) {
1608
+ const current = polygon[j], previous = polygon[(j + polygon.length - 1) % polygon.length];
1609
+ const currentIn = cross2(e0, e1, current) >= -1e-12, previousIn = cross2(e0, e1, previous) >= -1e-12;
1610
+ if (currentIn !== previousIn) out.push(edgeCrossing(previous, current, e0, e1));
1611
+ if (currentIn) out.push(current);
1612
+ }
1613
+ return out;
1614
+ }
1615
+ function polygonAreaAndCenter(polygon) {
1616
+ let twice = 0, cx = 0, cy = 0;
1617
+ for (let i = 0; i < polygon.length; i++) {
1618
+ const p = polygon[i], q = polygon[(i + 1) % polygon.length];
1619
+ twice += p[0] * q[1] - q[0] * p[1];
1620
+ cx += p[0];
1621
+ cy += p[1];
1622
+ }
1623
+ return { area: Math.abs(twice) / 2, center: [cx / polygon.length, cy / polygon.length] };
1624
+ }
1625
+ function overlapOfTriangles(a, b) {
1626
+ const clip = cross2(b[0], b[1], b[2]) >= 0 ? b : [b[0], b[2], b[1]];
1627
+ let polygon = [...a];
1628
+ for (let i = 0; i < 3 && polygon.length > 0; i++) polygon = clipByEdge(polygon, clip[i], clip[(i + 1) % 3]);
1629
+ if (polygon.length < 3) return void 0;
1630
+ const overlap = polygonAreaAndCenter(polygon);
1631
+ return overlap.area < 1e-12 ? void 0 : overlap;
1632
+ }
1633
+ var GAME_DEPTH_PRECISION = { viewDistance: 30, near: 0.05, far: 140, depthBits: 24 };
1634
+ function depthResolution(precision = GAME_DEPTH_PRECISION) {
1635
+ const { viewDistance: z, near, far, depthBits } = precision;
1636
+ return z * z * (far - near) / (far * near * 2 ** depthBits);
1637
+ }
1638
+ function boxOf(t) {
1639
+ const xs = [t[0][0], t[1][0], t[2][0]], ys = [t[0][1], t[1][1], t[2][1]], zs = [t[0][2], t[1][2], t[2][2]];
1640
+ return [Math.min(...xs), Math.min(...ys), Math.min(...zs), Math.max(...xs), Math.max(...ys), Math.max(...zs)];
1641
+ }
1642
+ var SAME_COLOUR = 1 / 512;
1643
+ var SAME_UV = 1e-3;
1644
+ var SAME_FACING = 1 - 1e-6;
1645
+ var PARALLEL = Math.cos(2 * Math.PI / 180);
1646
+ var DEFAULT_MAX_PER_PAIR = 3;
1647
+ var kindOf = (label) => label.replace(/\d+(\.\d+)?/g, "#");
1648
+ function facesOf(batches) {
1649
+ const faces = [];
1650
+ batches.forEach((batch, index) => {
1651
+ const label = batch.label ?? `batch ${index}`;
1652
+ const { positions: p, indices } = batch;
1653
+ const count = indices ? indices.length : p.length / 3;
1654
+ const vertex = (i) => [p[i * 3], p[i * 3 + 1], p[i * 3 + 2]];
1655
+ for (let i = 0; i + 2 < count; i += 3) {
1656
+ const corners = indices ? [indices[i], indices[i + 1], indices[i + 2]] : [i, i + 1, i + 2];
1657
+ const triangle = [vertex(corners[0]), vertex(corners[1]), vertex(corners[2])];
1658
+ const n = normalOf(triangle);
1659
+ if (n[0] === 0 && n[1] === 0 && n[2] === 0) continue;
1660
+ const offset = n[0] * triangle[0][0] + n[1] * triangle[0][1] + n[2] * triangle[0][2];
1661
+ faces.push({ triangle, n, offset, label, doubleSided: batch.doubleSided === true, box: boxOf(triangle), batch, batchIndex: index, corners });
1662
+ }
1663
+ });
1664
+ return faces;
1665
+ }
1666
+ function weightsOf(t, n, point) {
1667
+ const area3 = (a, b, c) => {
1668
+ const ux = b[0] - a[0], uy = b[1] - a[1], uz = b[2] - a[2], vx = c[0] - a[0], vy = c[1] - a[1], vz = c[2] - a[2];
1669
+ return n[0] * (uy * vz - uz * vy) + n[1] * (uz * vx - ux * vz) + n[2] * (ux * vy - uy * vx);
1670
+ };
1671
+ const whole = area3(t[0], t[1], t[2]) || 1;
1672
+ return [area3(point, t[1], t[2]) / whole, area3(t[0], point, t[2]) / whole, area3(t[0], t[1], point) / whole];
1673
+ }
1674
+ function attributeAt(values, size, face, point) {
1675
+ const w = weightsOf(face.triangle, face.n, point);
1676
+ return Array.from({ length: size }, (_, k) => w[0] * values[face.corners[0] * size + k] + w[1] * values[face.corners[1] * size + k] + w[2] * values[face.corners[2] * size + k]);
1677
+ }
1678
+ var close = (a, b, tolerance) => a.every((v, k) => Math.abs(v - b[k]) <= tolerance);
1679
+ function drawAlike(a, b, point) {
1680
+ if (a.batch.look === void 0 || a.batch.look !== b.batch.look) return false;
1681
+ if (a.n[0] * b.n[0] + a.n[1] * b.n[1] + a.n[2] * b.n[2] < SAME_FACING) return false;
1682
+ const ca = a.batch.colors, cb = b.batch.colors;
1683
+ if (ca === void 0 !== (cb === void 0)) return false;
1684
+ if (ca && cb && !close(attributeAt(ca, 3, a, point), attributeAt(cb, 3, b, point), SAME_COLOUR)) return false;
1685
+ const ua = a.batch.uvs, ub = b.batch.uvs;
1686
+ if (ua === void 0 !== (ub === void 0)) return false;
1687
+ return !(ua && ub && !close(attributeAt(ua, 2, a, point), attributeAt(ub, 2, b, point), SAME_UV));
1688
+ }
1689
+ function touch(a, b, slack) {
1690
+ return a[1] <= b[4] + slack && b[1] <= a[4] + slack && a[2] <= b[5] + slack && b[2] <= a[5] + slack && a[0] <= b[3] + slack && b[0] <= a[3] + slack;
1691
+ }
1692
+ function nearHit(a, b, eps, minArea) {
1693
+ const facing = a.n[0] * b.n[0] + a.n[1] * b.n[1] + a.n[2] * b.n[2];
1694
+ if (Math.abs(facing) < PARALLEL) return void 0;
1695
+ if (facing < 0 && !(a.doubleSided || b.doubleSided)) return void 0;
1696
+ const drop = dominantAxis(a.n);
1697
+ const overlap = overlapOfTriangles(projectTriangle(a.triangle, drop), projectTriangle(b.triangle, drop));
1698
+ if (!overlap || overlap.area < minArea) return void 0;
1699
+ const point = unprojectPoint(overlap.center, drop, a);
1700
+ const separation = Math.abs(b.n[0] * point[0] + b.n[1] * point[1] + b.n[2] * point[2] - b.offset);
1701
+ if (separation >= eps) return void 0;
1702
+ if (facing > 0 && drawAlike(a, b, point)) return void 0;
1703
+ return { normal: a.n, offset: a.offset, area: overlap.area, point, labelA: a.label, labelB: b.label, batchA: a.batchIndex, batchB: b.batchIndex, kind: facing > 0 ? "coplanar" : "opposed", separation };
1704
+ }
1705
+ var CELL = 2;
1706
+ var LARGE_CELLS = 64;
1707
+ function nearCoincidentFaces(batches, options) {
1708
+ const eps = depthResolution(options.depth);
1709
+ const minArea = options.minArea ?? 1e-4;
1710
+ const maxHits = options.maxHits ?? 200;
1711
+ const maxPerPair = options.maxPerPair ?? DEFAULT_MAX_PER_PAIR;
1712
+ const faces = facesOf(batches);
1713
+ const perPair = /* @__PURE__ */ new Map();
1714
+ const hits = [];
1715
+ const cells = /* @__PURE__ */ new Map();
1716
+ const large = [];
1717
+ const seen = new Int32Array(faces.length).fill(-1);
1718
+ const cellKey = (x, y, z) => ((x + 4096) * 8192 + (y + 4096)) * 8192 + (z + 4096);
1719
+ const range2 = (lo, hi) => [Math.floor((lo - eps) / CELL), Math.floor((hi + eps) / CELL)];
1720
+ const consider = (index, otherIndex) => {
1721
+ const face = faces[index], other = faces[otherIndex];
1722
+ if (Math.abs(face.n[0] * other.n[0] + face.n[1] * other.n[1] + face.n[2] * other.n[2]) < PARALLEL) return false;
1723
+ if (!touch(other.box, face.box, eps)) return false;
1724
+ const hit = nearHit(other, face, eps, minArea);
1725
+ if (!hit) return false;
1726
+ const [first, second] = [kindOf(other.label), kindOf(face.label)].sort();
1727
+ const key = `${first}|${second}|${hit.kind}`;
1728
+ const count = perPair.get(key) ?? 0;
1729
+ if (count >= maxPerPair) return false;
1730
+ perPair.set(key, count + 1);
1731
+ hits.push(hit);
1732
+ return hits.length >= maxHits;
1733
+ };
1734
+ for (let index = 0; index < faces.length; index++) {
1735
+ const face = faces[index];
1736
+ const [x0, x1] = range2(face.box[0], face.box[3]), [y0, y1] = range2(face.box[1], face.box[4]), [z0, z1] = range2(face.box[2], face.box[5]);
1737
+ const span = (x1 - x0 + 1) * (y1 - y0 + 1) * (z1 - z0 + 1);
1738
+ if (span > LARGE_CELLS) {
1739
+ for (let other = 0; other < index; other++) if (consider(index, other)) return hits;
1740
+ large.push(index);
1741
+ continue;
1742
+ }
1743
+ for (const otherIndex of large) if (consider(index, otherIndex)) return hits;
1744
+ for (let x = x0; x <= x1; x++) for (let y = y0; y <= y1; y++) for (let z = z0; z <= z1; z++) {
1745
+ const key = cellKey(x, y, z);
1746
+ const list2 = cells.get(key);
1747
+ if (!list2) {
1748
+ cells.set(key, [index]);
1749
+ continue;
1750
+ }
1751
+ for (const otherIndex of list2) {
1752
+ if (seen[otherIndex] === index) continue;
1753
+ seen[otherIndex] = index;
1754
+ if (consider(index, otherIndex)) return hits;
1755
+ }
1756
+ list2.push(index);
1757
+ }
1758
+ }
1759
+ return hits;
1760
+ }
1761
+ var NORMAL_STEP = 2e-3;
1762
+ function trianglesOf(batch) {
1763
+ const { positions: p, indices } = batch;
1764
+ const vertex = (i) => [p[i * 3], p[i * 3 + 1], p[i * 3 + 2]];
1765
+ const count = indices ? indices.length : p.length / 3;
1766
+ const out = [];
1767
+ for (let i = 0; i + 2 < count; i += 3) {
1768
+ out.push(indices ? [vertex(indices[i]), vertex(indices[i + 1]), vertex(indices[i + 2])] : [vertex(i), vertex(i + 1), vertex(i + 2)]);
1769
+ }
1770
+ return out;
1771
+ }
1772
+ function directionKey(n) {
1773
+ return n.map((c) => Math.round(c / NORMAL_STEP)).join(",");
1774
+ }
1775
+ function boxesTouch(a, b, slack) {
1776
+ return a[0] <= b[3] + slack && b[0] <= a[3] + slack && a[1] <= b[4] + slack && b[1] <= a[4] + slack && a[2] <= b[5] + slack && b[2] <= a[5] + slack;
1777
+ }
1778
+ function bucketFaces(batches, eps) {
1779
+ const buckets = /* @__PURE__ */ new Map();
1780
+ batches.forEach((batch, index) => {
1781
+ const label = batch.label ?? `batch ${index}`;
1782
+ for (const triangle of trianglesOf(batch)) {
1783
+ const n = normalOf(triangle);
1784
+ if (n[0] === 0 && n[1] === 0 && n[2] === 0) continue;
1785
+ const offset = n[0] * triangle[0][0] + n[1] * triangle[0][1] + n[2] * triangle[0][2];
1786
+ const key = `${directionKey(n)}|${Math.floor(offset / eps)}`;
1787
+ const list2 = buckets.get(key) ?? [];
1788
+ list2.push({ triangle, n, offset, label, batch: index, box: boxOf(triangle) });
1789
+ buckets.set(key, list2);
1790
+ }
1791
+ });
1792
+ return buckets;
1793
+ }
1794
+ function overlapHit(a, b, minArea) {
1795
+ const drop = dominantAxis(a.n);
1796
+ const overlap = overlapOfTriangles(projectTriangle(a.triangle, drop), projectTriangle(b.triangle, drop));
1797
+ if (!overlap || overlap.area < minArea) return void 0;
1798
+ const point = unprojectPoint(overlap.center, drop, a);
1799
+ return { normal: a.n, offset: a.offset, area: overlap.area, point, labelA: a.label, labelB: b.label, batchA: a.batch, batchB: b.batch };
1800
+ }
1801
+ function coincidentFaces(batches, options = {}) {
1802
+ if (options.depth) return nearCoincidentFaces(batches, options);
1803
+ const eps = options.eps ?? 1e-3;
1804
+ const minArea = options.minArea ?? 1e-4;
1805
+ const maxHits = options.maxHits ?? 200;
1806
+ const buckets = bucketFaces(batches, eps);
1807
+ const hits = [];
1808
+ for (const [key, faces] of buckets) {
1809
+ const [direction, slot] = key.split("|");
1810
+ const next = buckets.get(`${direction}|${Number(slot) + 1}`) ?? [];
1811
+ for (let i = 0; i < faces.length; i++) {
1812
+ const a = faces[i];
1813
+ for (let j = i + 1; j < faces.length + next.length; j++) {
1814
+ const b = j < faces.length ? faces[j] : next[j - faces.length];
1815
+ if (Math.abs(a.offset - b.offset) > eps || !boxesTouch(a.box, b.box, eps)) continue;
1816
+ const hit = overlapHit(a, b, minArea);
1817
+ if (hit) hits.push(hit);
1818
+ if (hits.length >= maxHits) return hits;
1819
+ }
1820
+ }
1821
+ }
1822
+ return hits;
1823
+ }
1824
+ function describeCoincidentFaces(hits, limit = 12) {
1825
+ const lines = hits.slice(0, limit).map((h) => {
1826
+ const at = h.point.map((c) => c.toFixed(3)).join(", ");
1827
+ const facing = h.normal.map((c) => c.toFixed(2)).join(", ");
1828
+ return ` ${h.labelA} \xD7 ${h.labelB} at (${at}) facing (${facing}), ${(h.area * 1e4).toFixed(1)} cm\xB2`;
1829
+ });
1830
+ if (hits.length > limit) lines.push(` \u2026 and ${hits.length - limit} more`);
1831
+ return lines.join("\n");
1832
+ }
1833
+
1553
1834
  // src/namespace.ts
1554
1835
  var SHAPE_GEOMETRY_TYPES = ["BoxGeometry", "CylinderGeometry", "ConeGeometry", "SphereGeometry", "PlaneGeometry", "CircleGeometry", "RingGeometry", "LatheGeometry", "TorusGeometry", "ExtrudeGeometry"];
1555
1836
  function linePoints(path) {
@@ -1923,6 +2204,227 @@ var GameShapesThree = (() => {
1923
2204
  }
1924
2205
  return releaseObject3D(list2, { keep });
1925
2206
  }
2207
+
2208
+ // src/guards.ts
2209
+ function isMesh(o) {
2210
+ return !!o && o.isMesh === true;
2211
+ }
2212
+
2213
+ // src/position-writes.ts
2214
+ var KEPT = 256;
2215
+ var declared = /* @__PURE__ */ new WeakMap();
2216
+ function markPositionsWritten(mesh2, v0, v1) {
2217
+ const position = mesh2.geometry?.getAttribute("position");
2218
+ if (!position) return;
2219
+ position.needsUpdate = true;
2220
+ if (v1 <= v0) return;
2221
+ let log = declared.get(position);
2222
+ if (!log) {
2223
+ log = /* @__PURE__ */ new Map();
2224
+ declared.set(position, log);
2225
+ }
2226
+ const ranges = log.get(position.version);
2227
+ if (ranges) ranges.push([v0, v1]);
2228
+ else log.set(position.version, [[v0, v1]]);
2229
+ if (log.size > KEPT) log.delete(log.keys().next().value);
2230
+ }
2231
+ function rangesWrittenSince(position, version) {
2232
+ const log = declared.get(position);
2233
+ const out = [];
2234
+ for (let v = version + 1; v <= position.version; v++) {
2235
+ const ranges = log?.get(v);
2236
+ if (!ranges) return null;
2237
+ out.push(...ranges);
2238
+ }
2239
+ return out;
2240
+ }
2241
+
2242
+ // src/coincident.ts
2243
+ function isFartherLevel(o) {
2244
+ const lod = o.parent;
2245
+ return !!lod?.isLOD && lod.levels.length > 0 && lod.levels[0].object !== o;
2246
+ }
2247
+ function isDrawn(node, root) {
2248
+ for (let o = node; o; o = o.parent) {
2249
+ if (!o.visible || isFartherLevel(o)) return false;
2250
+ if (o === root) return true;
2251
+ }
2252
+ return true;
2253
+ }
2254
+ function isOffsetDecal(mesh2) {
2255
+ const materials = Array.isArray(mesh2.material) ? mesh2.material : [mesh2.material];
2256
+ return materials.length > 0 && materials.every((m) => m?.polygonOffset === true);
2257
+ }
2258
+ function labelOf(mesh2, root) {
2259
+ const names = [];
2260
+ for (let o = mesh2; o && o !== root; o = o.parent) {
2261
+ const part = o.userData?.destructionPart;
2262
+ const name = o.name || (typeof part === "string" ? part : "");
2263
+ if (name) names.unshift(name);
2264
+ }
2265
+ const material = Array.isArray(mesh2.material) ? mesh2.material[0] : mesh2.material;
2266
+ const path = names.join("/") || mesh2.type;
2267
+ return material?.name ? `${path} [${material.name}]` : path;
2268
+ }
2269
+ function worldPositions(position, matrix) {
2270
+ const e = matrix.elements;
2271
+ const out = new Float64Array(position.count * 3);
2272
+ for (let i = 0; i < position.count; i++) {
2273
+ const x = position.getX(i), y = position.getY(i), z = position.getZ(i);
2274
+ const w = e[3] * x + e[7] * y + e[11] * z + e[15] || 1;
2275
+ out[i * 3] = (e[0] * x + e[4] * y + e[8] * z + e[12]) / w;
2276
+ out[i * 3 + 1] = (e[1] * x + e[5] * y + e[9] * z + e[13]) / w;
2277
+ out[i * 3 + 2] = (e[2] * x + e[6] * y + e[10] * z + e[14]) / w;
2278
+ }
2279
+ return out;
2280
+ }
2281
+ var DOUBLE_SIDE = 2;
2282
+ function isDoubleSided(mesh2) {
2283
+ const materials = Array.isArray(mesh2.material) ? mesh2.material : [mesh2.material];
2284
+ return materials.some((m) => m?.side === DOUBLE_SIDE);
2285
+ }
2286
+ var attributeValues = (attribute, size) => {
2287
+ const out = new Array(attribute.count * size);
2288
+ const read = [(i) => attribute.getX(i), (i) => attribute.getY(i), (i) => attribute.getZ(i)];
2289
+ for (let i = 0; i < attribute.count; i++) for (let k = 0; k < size; k++) out[i * size + k] = read[k](i);
2290
+ return out;
2291
+ };
2292
+ function lookOf(mesh2, geometry) {
2293
+ if (Array.isArray(mesh2.material)) return {};
2294
+ const material = mesh2.material;
2295
+ const color2 = material.vertexColors ? geometry.getAttribute("color") : void 0;
2296
+ const textured = Boolean(material.map || material.normalMap || material.bumpMap || material.alphaMap || material.roughnessMap);
2297
+ const uv = textured ? geometry.getAttribute("uv") : void 0;
2298
+ if (textured && !uv) return {};
2299
+ return { look: material.uuid, ...color2 ? { colors: attributeValues(color2, 3) } : {}, ...uv ? { uvs: attributeValues(uv, 2) } : {} };
2300
+ }
2301
+ function drawnIndices(geometry) {
2302
+ const { start, count } = geometry.drawRange;
2303
+ const index = geometry.index?.array;
2304
+ const total = index ? index.length : geometry.getAttribute("position").count;
2305
+ const end = Math.min(total, start + (Number.isFinite(count) ? count : total));
2306
+ if (index) return start === 0 && end === index.length ? index : Array.from(index).slice(start, end);
2307
+ if (start === 0 && end === total) return void 0;
2308
+ return Array.from({ length: end - start }, (_, i) => start + i);
2309
+ }
2310
+ function batchesOfMesh(mesh2, label) {
2311
+ const doubleSided = isDoubleSided(mesh2);
2312
+ const geometry = mesh2.geometry;
2313
+ const position = geometry?.getAttribute("position");
2314
+ if (!geometry || !position) return [];
2315
+ const indices = drawnIndices(geometry);
2316
+ const instanced = mesh2;
2317
+ const look = lookOf(mesh2, geometry);
2318
+ if (!instanced.isInstancedMesh) return [{ positions: worldPositions(position, mesh2.matrixWorld), ...indices ? { indices } : {}, label, doubleSided, ...look }];
2319
+ const batches = [];
2320
+ const instance = mesh2.matrixWorld.clone();
2321
+ const tint = instanced.instanceColor;
2322
+ for (let i = 0; i < instanced.count; i++) {
2323
+ instanced.getMatrixAt(i, instance);
2324
+ instance.premultiply(mesh2.matrixWorld);
2325
+ const instanceLook = tint && look.look !== void 0 ? { ...look, look: `${look.look}:${tint.getX(i)},${tint.getY(i)},${tint.getZ(i)}` } : look;
2326
+ batches.push({ positions: worldPositions(position, instance), ...indices ? { indices } : {}, label: `${label} #${i}`, doubleSided, ...instanceLook });
2327
+ }
2328
+ return batches;
2329
+ }
2330
+ function meshBatchesOf(root, options = {}) {
2331
+ root.updateMatrixWorld(true);
2332
+ const batches = [];
2333
+ const meshes = [];
2334
+ root.traverse((node) => {
2335
+ if (!isMesh(node) || node.isSprite) return;
2336
+ if (!options.includeHidden && !isDrawn(node, root)) return;
2337
+ if (isOffsetDecal(node)) return;
2338
+ for (const batch of batchesOfMesh(node, labelOf(node, root))) {
2339
+ batches.push(batch);
2340
+ meshes.push(node);
2341
+ }
2342
+ });
2343
+ return { batches, meshes };
2344
+ }
2345
+ function coincidentBatchesOf(root, options = {}) {
2346
+ return meshBatchesOf(root, options).batches;
2347
+ }
2348
+ function coincidentFacesOf(root, options = {}) {
2349
+ const { batches, meshes } = meshBatchesOf(root, options);
2350
+ return coincidentFaces(batches, options).filter((hit) => writesDepth(meshes[hit.batchA]) || writesDepth(meshes[hit.batchB]));
2351
+ }
2352
+ function writesDepth(mesh2) {
2353
+ const materials = Array.isArray(mesh2.material) ? mesh2.material : [mesh2.material];
2354
+ return materials.some((m) => m.depthWrite !== false && m.depthTest !== false);
2355
+ }
2356
+
2357
+ // src/stand-out.ts
2358
+ function localSize(mesh2, out) {
2359
+ const geometry = mesh2.geometry;
2360
+ if (!geometry.boundingBox) geometry.computeBoundingBox();
2361
+ return geometry.boundingBox.getSize(out);
2362
+ }
2363
+ function volumeOf(mesh2) {
2364
+ const size = localSize(mesh2, mesh2.position.clone());
2365
+ const scale = mesh2.getWorldScale(mesh2.position.clone());
2366
+ return Math.max(Math.abs(size.x * scale.x), 1e-4) * Math.max(Math.abs(size.y * scale.y), 1e-4) * Math.max(Math.abs(size.z * scale.z), 1e-4);
2367
+ }
2368
+ function markSide(mesh2, hit, sides, way) {
2369
+ const inverse = mesh2.getWorldQuaternion(mesh2.quaternion.clone()).invert();
2370
+ const n = mesh2.position.clone().set(hit.normal[0], hit.normal[1], hit.normal[2]).applyQuaternion(inverse);
2371
+ const scale = mesh2.getWorldScale(mesh2.position.clone());
2372
+ const local = [n.x * Math.sign(scale.x || 1), n.y * Math.sign(scale.y || 1), n.z * Math.sign(scale.z || 1)];
2373
+ const axis = local.reduce((best, v, i) => Math.abs(v) > Math.abs(local[best]) ? i : best, 0);
2374
+ sides[axis * 2 + (local[axis] > 0 ? 1 : 0)] = way;
2375
+ }
2376
+ function pushSides(mesh2, sides, gap) {
2377
+ const size = localSize(mesh2, mesh2.position.clone());
2378
+ const world = mesh2.getWorldScale(mesh2.position.clone());
2379
+ const shift = mesh2.position.clone().set(0, 0, 0);
2380
+ const scale = [mesh2.scale.x, mesh2.scale.y, mesh2.scale.z];
2381
+ const extent = [size.x, size.y, size.z];
2382
+ const worldScale = [Math.abs(world.x), Math.abs(world.y), Math.abs(world.z)];
2383
+ const centre = mesh2.geometry.boundingBox.getCenter(mesh2.position.clone());
2384
+ const centres = [centre.x, centre.y, centre.z];
2385
+ for (let axis = 0; axis < 3; axis++) {
2386
+ const minus = sides[axis * 2] * gap, plus = sides[axis * 2 + 1] * gap;
2387
+ const s = extent[axis] * worldScale[axis];
2388
+ if (!minus && !plus || s < 1e-6 || s + minus + plus < s / 2) continue;
2389
+ const oldScale = scale[axis];
2390
+ scale[axis] = oldScale * (s + minus + plus) / s;
2391
+ const parentPerWorld = oldScale / worldScale[axis];
2392
+ const outward = (plus - minus) / 2 * parentPerWorld;
2393
+ const recentre = centres[axis] * (oldScale - scale[axis]);
2394
+ shift.setComponent(axis, outward + recentre);
2395
+ }
2396
+ mesh2.scale.set(scale[0], scale[1], scale[2]);
2397
+ mesh2.position.add(shift.applyQuaternion(mesh2.quaternion));
2398
+ mesh2.updateMatrixWorld(true);
2399
+ }
2400
+ function standOutCoincident(root, options = {}) {
2401
+ const gap = options.gap ?? 2e-3;
2402
+ const grown = /* @__PURE__ */ new Set();
2403
+ const volumes = /* @__PURE__ */ new Map();
2404
+ const volume = (mesh2) => volumes.get(mesh2) ?? volumes.set(mesh2, volumeOf(mesh2)).get(mesh2);
2405
+ let left = 0;
2406
+ for (let round = 0; round < (options.rounds ?? 3); round++) {
2407
+ const { batches, meshes } = meshBatchesOf(root);
2408
+ const hits = coincidentFaces(batches, { maxHits: Number.POSITIVE_INFINITY });
2409
+ left = hits.length;
2410
+ if (!left) break;
2411
+ const toPush = /* @__PURE__ */ new Map();
2412
+ for (const hit of hits) {
2413
+ const a = meshes[hit.batchA], b = meshes[hit.batchB];
2414
+ const [smaller, bigger] = volume(a) <= volume(b) ? [a, b] : [b, a];
2415
+ const mesh2 = grown.has(smaller) ? bigger : smaller;
2416
+ if (grown.has(mesh2) || mesh2.isInstancedMesh) continue;
2417
+ const sides = toPush.get(mesh2) ?? [0, 0, 0, 0, 0, 0];
2418
+ markSide(mesh2, hit, sides, 1);
2419
+ toPush.set(mesh2, sides);
2420
+ }
2421
+ for (const [mesh2, sides] of toPush) {
2422
+ pushSides(mesh2, sides, gap);
2423
+ grown.add(mesh2);
2424
+ }
2425
+ }
2426
+ return { grown: grown.size, left };
2427
+ }
1926
2428
  return __toCommonJS(src_exports);
1927
2429
  })();
1928
2430
  //# sourceMappingURL=index.global.js.map