@needle-tools/three-mesh-effects 0.0.0-stage → 0.1.0-alpha

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.
Files changed (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +88 -3
  3. package/build/deformation-runtime.js +2143 -0
  4. package/build/deformation-runtime.js.map +7 -0
  5. package/build/impostor-runtime-needle-engine.js +42 -0
  6. package/build/impostor-runtime-needle-engine.js.map +7 -0
  7. package/build/impostor-runtime.js +1333 -0
  8. package/build/impostor-runtime.js.map +7 -0
  9. package/build/internal/deformation/cloth-surface.js +288 -0
  10. package/build/internal/deformation/cloth-surface.js.map +7 -0
  11. package/build/internal/deformation/fur-surface.js +130 -0
  12. package/build/internal/deformation/fur-surface.js.map +7 -0
  13. package/build/internal/deformation/ik-constraints.js +44 -0
  14. package/build/internal/deformation/ik-constraints.js.map +7 -0
  15. package/build/internal/deformation/joints-json.js +197 -0
  16. package/build/internal/deformation/joints-json.js.map +7 -0
  17. package/build/internal/deformation/limits.js +16 -0
  18. package/build/internal/deformation/limits.js.map +7 -0
  19. package/build/internal/deformation/motion-settings.js +12 -0
  20. package/build/internal/deformation/motion-settings.js.map +7 -0
  21. package/build/internal/deformation/pin-cloth.js +196 -0
  22. package/build/internal/deformation/pin-cloth.js.map +7 -0
  23. package/build/internal/deformation/pin-ik.js +650 -0
  24. package/build/internal/deformation/pin-ik.js.map +7 -0
  25. package/build/internal/deformation/pin-types.js +12 -0
  26. package/build/internal/deformation/pin-types.js.map +7 -0
  27. package/build/internal/deformation/pin-wiggle.js +249 -0
  28. package/build/internal/deformation/pin-wiggle.js.map +7 -0
  29. package/build/internal/deformation/pose-slots.js +84 -0
  30. package/build/internal/deformation/pose-slots.js.map +7 -0
  31. package/build/internal/deformation/pose-timeline.js +210 -0
  32. package/build/internal/deformation/pose-timeline.js.map +7 -0
  33. package/build/internal/deformation/rig-drivers.js +48 -0
  34. package/build/internal/deformation/rig-drivers.js.map +7 -0
  35. package/build/internal/deformation/rig-extension.js +334 -0
  36. package/build/internal/deformation/rig-extension.js.map +7 -0
  37. package/build/internal/deformation/rig-runtime.js +2141 -0
  38. package/build/internal/deformation/rig-runtime.js.map +7 -0
  39. package/build/internal/deformation/wind.js +34 -0
  40. package/build/internal/deformation/wind.js.map +7 -0
  41. package/build/internal/impostor/impostor-metadata.js +77 -0
  42. package/build/internal/impostor/impostor-metadata.js.map +7 -0
  43. package/build/internal/impostor/impostor-node-material.js +1331 -0
  44. package/build/internal/impostor/impostor-node-material.js.map +7 -0
  45. package/build/internal/impostor/impostor-runtime-support.js +162 -0
  46. package/build/internal/impostor/impostor-runtime-support.js.map +7 -0
  47. package/build/internal/impostor/octahedral.js +232 -0
  48. package/build/internal/impostor/octahedral.js.map +7 -0
  49. package/build/internal/pixel-impostor/pixel-impostor-display.js +728 -0
  50. package/build/internal/pixel-impostor/pixel-impostor-display.js.map +7 -0
  51. package/build/internal/pixel-impostor/pixel-impostor-metadata.js +71 -0
  52. package/build/internal/pixel-impostor/pixel-impostor-metadata.js.map +7 -0
  53. package/build/internal/pixel-impostor/pixel-impostor-runtime.js +150 -0
  54. package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +7 -0
  55. package/build/internal/public/deformation-runtime.js +2143 -0
  56. package/build/internal/public/deformation-runtime.js.map +7 -0
  57. package/build/internal/public/impostor-runtime-needle-engine.js +42 -0
  58. package/build/internal/public/impostor-runtime-needle-engine.js.map +7 -0
  59. package/build/internal/public/impostor-runtime.js +1333 -0
  60. package/build/internal/public/impostor-runtime.js.map +7 -0
  61. package/build/internal/public/pixel-impostor-runtime.js +876 -0
  62. package/build/internal/public/pixel-impostor-runtime.js.map +7 -0
  63. package/build/internal/public/wrap-effects.js +5640 -0
  64. package/build/internal/public/wrap-effects.js.map +7 -0
  65. package/build/internal/rendering/skin-projection.js +4630 -0
  66. package/build/internal/rendering/skin-projection.js.map +7 -0
  67. package/build/internal/rendering/surface-query.js +4519 -0
  68. package/build/internal/rendering/surface-query.js.map +7 -0
  69. package/build/internal/rendering/wireframe.js +112 -0
  70. package/build/internal/rendering/wireframe.js.map +7 -0
  71. package/build/internal/rendering/wrap-preview-settings.js +126 -0
  72. package/build/internal/rendering/wrap-preview-settings.js.map +7 -0
  73. package/build/internal/rendering/wrap-preview.js +5610 -0
  74. package/build/internal/rendering/wrap-preview.js.map +7 -0
  75. package/build/internal/rendering/wrap-skin.js +4746 -0
  76. package/build/internal/rendering/wrap-skin.js.map +7 -0
  77. package/build/pixel-impostor-runtime.js +876 -0
  78. package/build/pixel-impostor-runtime.js.map +7 -0
  79. package/build/types/deformation/cloth-surface.d.ts +39 -0
  80. package/build/types/deformation/cloth-surface.js +1 -0
  81. package/build/types/deformation/fur-surface.d.ts +27 -0
  82. package/build/types/deformation/fur-surface.js +1 -0
  83. package/build/types/deformation/ik-constraints.d.ts +18 -0
  84. package/build/types/deformation/ik-constraints.js +1 -0
  85. package/build/types/deformation/joints-json.d.ts +17 -0
  86. package/build/types/deformation/joints-json.js +1 -0
  87. package/build/types/deformation/limits.d.ts +23 -0
  88. package/build/types/deformation/limits.js +1 -0
  89. package/build/types/deformation/motion-settings.d.ts +9 -0
  90. package/build/types/deformation/motion-settings.js +1 -0
  91. package/build/types/deformation/pin-cloth.d.ts +28 -0
  92. package/build/types/deformation/pin-cloth.js +1 -0
  93. package/build/types/deformation/pin-ik.d.ts +37 -0
  94. package/build/types/deformation/pin-ik.js +1 -0
  95. package/build/types/deformation/pin-types.d.ts +53 -0
  96. package/build/types/deformation/pin-types.js +1 -0
  97. package/build/types/deformation/pin-wiggle.d.ts +16 -0
  98. package/build/types/deformation/pin-wiggle.js +1 -0
  99. package/build/types/deformation/pose-slots.d.ts +41 -0
  100. package/build/types/deformation/pose-slots.js +1 -0
  101. package/build/types/deformation/pose-timeline.d.ts +65 -0
  102. package/build/types/deformation/pose-timeline.js +1 -0
  103. package/build/types/deformation/rig-drivers.d.ts +19 -0
  104. package/build/types/deformation/rig-drivers.js +1 -0
  105. package/build/types/deformation/rig-extension.d.ts +33 -0
  106. package/build/types/deformation/rig-extension.js +1 -0
  107. package/build/types/deformation/rig-runtime.d.ts +95 -0
  108. package/build/types/deformation/rig-runtime.js +1 -0
  109. package/build/types/deformation/wind.d.ts +16 -0
  110. package/build/types/deformation/wind.js +1 -0
  111. package/build/types/impostor/impostor-metadata.d.ts +61 -0
  112. package/build/types/impostor/impostor-metadata.js +1 -0
  113. package/build/types/impostor/impostor-node-material.d.ts +140 -0
  114. package/build/types/impostor/impostor-node-material.js +1 -0
  115. package/build/types/impostor/impostor-runtime-support.d.ts +52 -0
  116. package/build/types/impostor/impostor-runtime-support.js +1 -0
  117. package/build/types/impostor/octahedral.d.ts +84 -0
  118. package/build/types/impostor/octahedral.js +1 -0
  119. package/build/types/pixel-impostor/pixel-impostor-display.d.ts +48 -0
  120. package/build/types/pixel-impostor/pixel-impostor-display.js +1 -0
  121. package/build/types/pixel-impostor/pixel-impostor-metadata.d.ts +34 -0
  122. package/build/types/pixel-impostor/pixel-impostor-metadata.js +1 -0
  123. package/build/types/pixel-impostor/pixel-impostor-runtime.d.ts +18 -0
  124. package/build/types/pixel-impostor/pixel-impostor-runtime.js +1 -0
  125. package/build/types/public/deformation-runtime.d.ts +3 -0
  126. package/build/types/public/deformation-runtime.js +1 -0
  127. package/build/types/public/impostor-runtime-needle-engine.d.ts +31 -0
  128. package/build/types/public/impostor-runtime-needle-engine.js +1 -0
  129. package/build/types/public/impostor-runtime.d.ts +6 -0
  130. package/build/types/public/impostor-runtime.js +1 -0
  131. package/build/types/public/pixel-impostor-runtime.d.ts +3 -0
  132. package/build/types/public/pixel-impostor-runtime.js +1 -0
  133. package/build/types/public/wrap-effects.d.ts +4 -0
  134. package/build/types/public/wrap-effects.js +1 -0
  135. package/build/types/rendering/skin-projection.d.ts +44 -0
  136. package/build/types/rendering/skin-projection.js +1 -0
  137. package/build/types/rendering/surface-query.d.ts +66 -0
  138. package/build/types/rendering/surface-query.js +1 -0
  139. package/build/types/rendering/wireframe.d.ts +25 -0
  140. package/build/types/rendering/wireframe.js +1 -0
  141. package/build/types/rendering/wrap-preview-settings.d.ts +22 -0
  142. package/build/types/rendering/wrap-preview-settings.js +1 -0
  143. package/build/types/rendering/wrap-preview.d.ts +39 -0
  144. package/build/types/rendering/wrap-preview.js +1 -0
  145. package/build/types/rendering/wrap-skin.d.ts +14 -0
  146. package/build/types/rendering/wrap-skin.js +1 -0
  147. package/build/wrap-effects.js +5640 -0
  148. package/build/wrap-effects.js.map +7 -0
  149. package/package.json +94 -6
  150. package/src/deformation/cloth-surface.ts +223 -0
  151. package/src/deformation/fur-surface.ts +129 -0
  152. package/src/deformation/ik-constraints.ts +37 -0
  153. package/src/deformation/joints-json.ts +94 -0
  154. package/src/deformation/limits.ts +25 -0
  155. package/src/deformation/motion-settings.ts +9 -0
  156. package/src/deformation/pin-cloth.ts +149 -0
  157. package/src/deformation/pin-ik.ts +582 -0
  158. package/src/deformation/pin-types.ts +22 -0
  159. package/src/deformation/pin-wiggle.ts +119 -0
  160. package/src/deformation/pose-slots.ts +106 -0
  161. package/src/deformation/pose-timeline.ts +242 -0
  162. package/src/deformation/rig-drivers.ts +32 -0
  163. package/src/deformation/rig-extension.ts +87 -0
  164. package/src/deformation/rig-runtime.ts +416 -0
  165. package/src/deformation/wind.ts +36 -0
  166. package/src/impostor/impostor-metadata.js +137 -0
  167. package/src/impostor/impostor-node-material.js +1581 -0
  168. package/src/impostor/impostor-runtime-support.js +139 -0
  169. package/src/impostor/octahedral.js +280 -0
  170. package/src/pixel-impostor/pixel-impostor-display.js +794 -0
  171. package/src/pixel-impostor/pixel-impostor-metadata.js +74 -0
  172. package/src/pixel-impostor/pixel-impostor-runtime.js +78 -0
  173. package/src/public/deformation-runtime.ts +3 -0
  174. package/src/public/impostor-runtime-needle-engine.js +56 -0
  175. package/src/public/impostor-runtime.js +21 -0
  176. package/src/public/pixel-impostor-runtime.js +5 -0
  177. package/src/public/wrap-effects.js +21 -0
  178. package/src/rendering/skin-projection.js +113 -0
  179. package/src/rendering/surface-query.js +88 -0
  180. package/src/rendering/wireframe.js +115 -0
  181. package/src/rendering/wrap-preview-settings.js +123 -0
  182. package/src/rendering/wrap-preview.js +645 -0
  183. package/src/rendering/wrap-skin.js +109 -0
@@ -0,0 +1,4746 @@
1
+ // @ts-nocheck
2
+
3
+ // src/rendering/wrap-skin.js
4
+ import * as THREE from "three";
5
+
6
+ // src/rendering/skin-projection.js
7
+ import { Triangle as Triangle4, Vector3 as Vector312 } from "three";
8
+
9
+ // src/rendering/surface-query.js
10
+ import { BackSide as BackSide2, BufferAttribute as BufferAttribute3, BufferGeometry, FrontSide as FrontSide2, Ray as Ray2, Vector3 as Vector311 } from "three";
11
+
12
+ // ../../node_modules/three-mesh-bvh/src/core/BVH.js
13
+ import { Box3 as Box33 } from "three";
14
+
15
+ // ../../node_modules/three-mesh-bvh/src/core/Constants.js
16
+ var CENTER = 0;
17
+ var AVERAGE = 1;
18
+ var SAH = 2;
19
+ var CONTAINED = 2;
20
+ var PRIMITIVE_INTERSECT_COST = 1.25;
21
+ var TRAVERSAL_COST = 1;
22
+ var BYTES_PER_NODE = 6 * 4 + 4 + 4;
23
+ var UINT32_PER_NODE = BYTES_PER_NODE / 4;
24
+ var IS_LEAFNODE_FLAG = 65535;
25
+ var LEAFNODE_MASK_32 = IS_LEAFNODE_FLAG << 16;
26
+ var FLOAT32_EPSILON = Math.pow(2, -24);
27
+ var SKIP_GENERATION = Symbol("SKIP_GENERATION");
28
+ var DEFAULT_OPTIONS = {
29
+ strategy: CENTER,
30
+ maxDepth: 40,
31
+ targetLeafSize: 10,
32
+ useSharedArrayBuffer: false,
33
+ setBoundingBox: true,
34
+ onProgress: null,
35
+ indirect: false,
36
+ verbose: true,
37
+ range: null,
38
+ [SKIP_GENERATION]: false
39
+ };
40
+
41
+ // ../../node_modules/three-mesh-bvh/src/utils/ArrayBoxUtilities.js
42
+ function arrayToBox(nodeIndex32, array, target) {
43
+ target.min.x = array[nodeIndex32];
44
+ target.min.y = array[nodeIndex32 + 1];
45
+ target.min.z = array[nodeIndex32 + 2];
46
+ target.max.x = array[nodeIndex32 + 3];
47
+ target.max.y = array[nodeIndex32 + 4];
48
+ target.max.z = array[nodeIndex32 + 5];
49
+ return target;
50
+ }
51
+ function getLongestEdgeIndex(bounds) {
52
+ let splitDimIdx = -1;
53
+ let splitDist = -Infinity;
54
+ for (let i = 0; i < 3; i++) {
55
+ const dist = bounds[i + 3] - bounds[i];
56
+ if (dist > splitDist) {
57
+ splitDist = dist;
58
+ splitDimIdx = i;
59
+ }
60
+ }
61
+ return splitDimIdx;
62
+ }
63
+ function copyBounds(source, target) {
64
+ target.set(source);
65
+ }
66
+ function unionBounds(a, b, target) {
67
+ let aVal, bVal;
68
+ for (let d = 0; d < 3; d++) {
69
+ const d3 = d + 3;
70
+ aVal = a[d];
71
+ bVal = b[d];
72
+ target[d] = aVal < bVal ? aVal : bVal;
73
+ aVal = a[d3];
74
+ bVal = b[d3];
75
+ target[d3] = aVal > bVal ? aVal : bVal;
76
+ }
77
+ }
78
+ function expandByPrimitiveBounds(startIndex, primitiveBounds, bounds) {
79
+ for (let d = 0; d < 3; d++) {
80
+ const tCenter = primitiveBounds[startIndex + 2 * d];
81
+ const tHalf = primitiveBounds[startIndex + 2 * d + 1];
82
+ const tMin = tCenter - tHalf;
83
+ const tMax = tCenter + tHalf;
84
+ if (tMin < bounds[d]) {
85
+ bounds[d] = tMin;
86
+ }
87
+ if (tMax > bounds[d + 3]) {
88
+ bounds[d + 3] = tMax;
89
+ }
90
+ }
91
+ }
92
+ function computeSurfaceArea(bounds) {
93
+ const d0 = bounds[3] - bounds[0];
94
+ const d1 = bounds[4] - bounds[1];
95
+ const d2 = bounds[5] - bounds[2];
96
+ return 2 * (d0 * d1 + d1 * d2 + d2 * d0);
97
+ }
98
+
99
+ // ../../node_modules/three-mesh-bvh/src/core/utils/nodeBufferUtils.js
100
+ function IS_LEAF(n16, uint16Array2) {
101
+ return uint16Array2[n16 + 15] === IS_LEAFNODE_FLAG;
102
+ }
103
+ function OFFSET(n32, uint32Array2) {
104
+ return uint32Array2[n32 + 6];
105
+ }
106
+ function COUNT(n16, uint16Array2) {
107
+ return uint16Array2[n16 + 14];
108
+ }
109
+ function LEFT_NODE(n32) {
110
+ return n32 + UINT32_PER_NODE;
111
+ }
112
+ function RIGHT_NODE(n32, uint32Array2) {
113
+ const relativeOffset = uint32Array2[n32 + 6];
114
+ return n32 + relativeOffset * UINT32_PER_NODE;
115
+ }
116
+ function SPLIT_AXIS(n32, uint32Array2) {
117
+ return uint32Array2[n32 + 7];
118
+ }
119
+ function BOUNDING_DATA_INDEX(n32) {
120
+ return n32;
121
+ }
122
+
123
+ // ../../node_modules/three-mesh-bvh/src/core/build/computeBoundsUtils.js
124
+ function getBounds(primitiveBounds, offset, count, target, centroidTarget) {
125
+ let minx = Infinity;
126
+ let miny = Infinity;
127
+ let minz = Infinity;
128
+ let maxx = -Infinity;
129
+ let maxy = -Infinity;
130
+ let maxz = -Infinity;
131
+ let cminx = Infinity;
132
+ let cminy = Infinity;
133
+ let cminz = Infinity;
134
+ let cmaxx = -Infinity;
135
+ let cmaxy = -Infinity;
136
+ let cmaxz = -Infinity;
137
+ const boundsOffset = primitiveBounds.offset || 0;
138
+ for (let i = (offset - boundsOffset) * 6, end = (offset + count - boundsOffset) * 6; i < end; i += 6) {
139
+ const cx = primitiveBounds[i + 0];
140
+ const hx = primitiveBounds[i + 1];
141
+ const lx = cx - hx;
142
+ const rx = cx + hx;
143
+ if (lx < minx) minx = lx;
144
+ if (rx > maxx) maxx = rx;
145
+ if (cx < cminx) cminx = cx;
146
+ if (cx > cmaxx) cmaxx = cx;
147
+ const cy = primitiveBounds[i + 2];
148
+ const hy = primitiveBounds[i + 3];
149
+ const ly = cy - hy;
150
+ const ry = cy + hy;
151
+ if (ly < miny) miny = ly;
152
+ if (ry > maxy) maxy = ry;
153
+ if (cy < cminy) cminy = cy;
154
+ if (cy > cmaxy) cmaxy = cy;
155
+ const cz = primitiveBounds[i + 4];
156
+ const hz = primitiveBounds[i + 5];
157
+ const lz = cz - hz;
158
+ const rz = cz + hz;
159
+ if (lz < minz) minz = lz;
160
+ if (rz > maxz) maxz = rz;
161
+ if (cz < cminz) cminz = cz;
162
+ if (cz > cmaxz) cmaxz = cz;
163
+ }
164
+ target[0] = minx;
165
+ target[1] = miny;
166
+ target[2] = minz;
167
+ target[3] = maxx;
168
+ target[4] = maxy;
169
+ target[5] = maxz;
170
+ centroidTarget[0] = cminx;
171
+ centroidTarget[1] = cminy;
172
+ centroidTarget[2] = cminz;
173
+ centroidTarget[3] = cmaxx;
174
+ centroidTarget[4] = cmaxy;
175
+ centroidTarget[5] = cmaxz;
176
+ }
177
+
178
+ // ../../node_modules/three-mesh-bvh/src/core/build/splitUtils.js
179
+ var BIN_COUNT = 32;
180
+ var binsSort = (a, b) => a.candidate - b.candidate;
181
+ var sahBins = /* @__PURE__ */ new Array(BIN_COUNT).fill().map(() => {
182
+ return {
183
+ count: 0,
184
+ bounds: new Float32Array(6),
185
+ rightCacheBounds: new Float32Array(6),
186
+ leftCacheBounds: new Float32Array(6),
187
+ candidate: 0
188
+ };
189
+ });
190
+ var leftBounds = /* @__PURE__ */ new Float32Array(6);
191
+ function getOptimalSplit(nodeBoundingData, centroidBoundingData, primitiveBounds, offset, count, strategy) {
192
+ let axis = -1;
193
+ let pos = 0;
194
+ if (strategy === CENTER) {
195
+ axis = getLongestEdgeIndex(centroidBoundingData);
196
+ if (axis !== -1) {
197
+ pos = (centroidBoundingData[axis] + centroidBoundingData[axis + 3]) / 2;
198
+ }
199
+ } else if (strategy === AVERAGE) {
200
+ axis = getLongestEdgeIndex(nodeBoundingData);
201
+ if (axis !== -1) {
202
+ pos = getAverage(primitiveBounds, offset, count, axis);
203
+ }
204
+ } else if (strategy === SAH) {
205
+ const rootSurfaceArea = computeSurfaceArea(nodeBoundingData);
206
+ let bestCost = PRIMITIVE_INTERSECT_COST * count;
207
+ const boundsOffset = primitiveBounds.offset || 0;
208
+ const cStart = (offset - boundsOffset) * 6;
209
+ const cEnd = (offset + count - boundsOffset) * 6;
210
+ for (let a = 0; a < 3; a++) {
211
+ const axisLeft = centroidBoundingData[a];
212
+ const axisRight = centroidBoundingData[a + 3];
213
+ const axisLength = axisRight - axisLeft;
214
+ const binWidth = axisLength / BIN_COUNT;
215
+ if (count < BIN_COUNT / 4) {
216
+ const truncatedBins = [...sahBins];
217
+ truncatedBins.length = count;
218
+ let b = 0;
219
+ for (let c = cStart; c < cEnd; c += 6, b++) {
220
+ const bin = truncatedBins[b];
221
+ bin.candidate = primitiveBounds[c + 2 * a];
222
+ bin.count = 0;
223
+ const {
224
+ bounds,
225
+ leftCacheBounds,
226
+ rightCacheBounds
227
+ } = bin;
228
+ for (let d = 0; d < 3; d++) {
229
+ rightCacheBounds[d] = Infinity;
230
+ rightCacheBounds[d + 3] = -Infinity;
231
+ leftCacheBounds[d] = Infinity;
232
+ leftCacheBounds[d + 3] = -Infinity;
233
+ bounds[d] = Infinity;
234
+ bounds[d + 3] = -Infinity;
235
+ }
236
+ expandByPrimitiveBounds(c, primitiveBounds, bounds);
237
+ }
238
+ truncatedBins.sort(binsSort);
239
+ let splitCount = count;
240
+ for (let bi = 0; bi < splitCount; bi++) {
241
+ const bin = truncatedBins[bi];
242
+ while (bi + 1 < splitCount && truncatedBins[bi + 1].candidate === bin.candidate) {
243
+ truncatedBins.splice(bi + 1, 1);
244
+ splitCount--;
245
+ }
246
+ }
247
+ for (let c = cStart; c < cEnd; c += 6) {
248
+ const center = primitiveBounds[c + 2 * a];
249
+ for (let bi = 0; bi < splitCount; bi++) {
250
+ const bin = truncatedBins[bi];
251
+ if (center >= bin.candidate) {
252
+ expandByPrimitiveBounds(c, primitiveBounds, bin.rightCacheBounds);
253
+ } else {
254
+ expandByPrimitiveBounds(c, primitiveBounds, bin.leftCacheBounds);
255
+ bin.count++;
256
+ }
257
+ }
258
+ }
259
+ for (let bi = 0; bi < splitCount; bi++) {
260
+ const bin = truncatedBins[bi];
261
+ const leftCount = bin.count;
262
+ const rightCount = count - bin.count;
263
+ const leftBounds2 = bin.leftCacheBounds;
264
+ const rightBounds = bin.rightCacheBounds;
265
+ let leftProb = 0;
266
+ if (leftCount !== 0) {
267
+ leftProb = computeSurfaceArea(leftBounds2) / rootSurfaceArea;
268
+ }
269
+ let rightProb = 0;
270
+ if (rightCount !== 0) {
271
+ rightProb = computeSurfaceArea(rightBounds) / rootSurfaceArea;
272
+ }
273
+ const cost = TRAVERSAL_COST + PRIMITIVE_INTERSECT_COST * (leftProb * leftCount + rightProb * rightCount);
274
+ if (cost < bestCost) {
275
+ axis = a;
276
+ bestCost = cost;
277
+ pos = bin.candidate;
278
+ }
279
+ }
280
+ } else {
281
+ for (let i = 0; i < BIN_COUNT; i++) {
282
+ const bin = sahBins[i];
283
+ bin.count = 0;
284
+ bin.candidate = axisLeft + binWidth + i * binWidth;
285
+ const bounds = bin.bounds;
286
+ for (let d = 0; d < 3; d++) {
287
+ bounds[d] = Infinity;
288
+ bounds[d + 3] = -Infinity;
289
+ }
290
+ }
291
+ for (let c = cStart; c < cEnd; c += 6) {
292
+ const triCenter = primitiveBounds[c + 2 * a];
293
+ const relativeCenter = triCenter - axisLeft;
294
+ let binIndex = ~~(relativeCenter / binWidth);
295
+ if (binIndex >= BIN_COUNT) binIndex = BIN_COUNT - 1;
296
+ const bin = sahBins[binIndex];
297
+ bin.count++;
298
+ expandByPrimitiveBounds(c, primitiveBounds, bin.bounds);
299
+ }
300
+ const lastBin = sahBins[BIN_COUNT - 1];
301
+ copyBounds(lastBin.bounds, lastBin.rightCacheBounds);
302
+ for (let i = BIN_COUNT - 2; i >= 0; i--) {
303
+ const bin = sahBins[i];
304
+ const nextBin = sahBins[i + 1];
305
+ unionBounds(bin.bounds, nextBin.rightCacheBounds, bin.rightCacheBounds);
306
+ }
307
+ let leftCount = 0;
308
+ for (let i = 0; i < BIN_COUNT - 1; i++) {
309
+ const bin = sahBins[i];
310
+ const binCount = bin.count;
311
+ const bounds = bin.bounds;
312
+ const nextBin = sahBins[i + 1];
313
+ const rightBounds = nextBin.rightCacheBounds;
314
+ if (binCount !== 0) {
315
+ if (leftCount === 0) {
316
+ copyBounds(bounds, leftBounds);
317
+ } else {
318
+ unionBounds(bounds, leftBounds, leftBounds);
319
+ }
320
+ }
321
+ leftCount += binCount;
322
+ let leftProb = 0;
323
+ let rightProb = 0;
324
+ if (leftCount !== 0) {
325
+ leftProb = computeSurfaceArea(leftBounds) / rootSurfaceArea;
326
+ }
327
+ const rightCount = count - leftCount;
328
+ if (rightCount !== 0) {
329
+ rightProb = computeSurfaceArea(rightBounds) / rootSurfaceArea;
330
+ }
331
+ const cost = TRAVERSAL_COST + PRIMITIVE_INTERSECT_COST * (leftProb * leftCount + rightProb * rightCount);
332
+ if (cost < bestCost) {
333
+ axis = a;
334
+ bestCost = cost;
335
+ pos = bin.candidate;
336
+ }
337
+ }
338
+ }
339
+ }
340
+ } else {
341
+ console.warn(`BVH: Invalid build strategy value ${strategy} used.`);
342
+ }
343
+ return { axis, pos };
344
+ }
345
+ function getAverage(primitiveBounds, offset, count, axis) {
346
+ let avg = 0;
347
+ const boundsOffset = primitiveBounds.offset;
348
+ for (let i = offset, end = offset + count; i < end; i++) {
349
+ avg += primitiveBounds[(i - boundsOffset) * 6 + axis * 2];
350
+ }
351
+ return avg / count;
352
+ }
353
+
354
+ // ../../node_modules/three-mesh-bvh/src/core/BVHNode.js
355
+ var BVHNode = class {
356
+ constructor() {
357
+ this.boundingData = new Float32Array(6);
358
+ }
359
+ };
360
+
361
+ // ../../node_modules/three-mesh-bvh/src/core/build/sortUtils.js
362
+ function partition(buffer, stride, primitiveBounds, offset, count, split) {
363
+ let left = offset;
364
+ let right = offset + count - 1;
365
+ const pos = split.pos;
366
+ const axisOffset = split.axis * 2;
367
+ const boundsOffset = primitiveBounds.offset || 0;
368
+ while (true) {
369
+ while (left <= right && primitiveBounds[(left - boundsOffset) * 6 + axisOffset] < pos) {
370
+ left++;
371
+ }
372
+ while (left <= right && primitiveBounds[(right - boundsOffset) * 6 + axisOffset] >= pos) {
373
+ right--;
374
+ }
375
+ if (left < right) {
376
+ for (let i = 0; i < stride; i++) {
377
+ let t0 = buffer[left * stride + i];
378
+ buffer[left * stride + i] = buffer[right * stride + i];
379
+ buffer[right * stride + i] = t0;
380
+ }
381
+ for (let i = 0; i < 6; i++) {
382
+ const l = left - boundsOffset;
383
+ const r = right - boundsOffset;
384
+ const tb = primitiveBounds[l * 6 + i];
385
+ primitiveBounds[l * 6 + i] = primitiveBounds[r * 6 + i];
386
+ primitiveBounds[r * 6 + i] = tb;
387
+ }
388
+ left++;
389
+ right--;
390
+ } else {
391
+ return left;
392
+ }
393
+ }
394
+ }
395
+
396
+ // ../../node_modules/three-mesh-bvh/src/core/build/buildUtils.js
397
+ var float32Array;
398
+ var uint32Array;
399
+ var uint16Array;
400
+ var uint8Array;
401
+ var MAX_POINTER = Math.pow(2, 32);
402
+ function countNodes(node) {
403
+ if ("count" in node) {
404
+ return 1;
405
+ } else {
406
+ return 1 + countNodes(node.left) + countNodes(node.right);
407
+ }
408
+ }
409
+ function populateBuffer(byteOffset, node, buffer) {
410
+ float32Array = new Float32Array(buffer);
411
+ uint32Array = new Uint32Array(buffer);
412
+ uint16Array = new Uint16Array(buffer);
413
+ uint8Array = new Uint8Array(buffer);
414
+ return _populateBuffer(byteOffset, node);
415
+ }
416
+ function _populateBuffer(byteOffset, node) {
417
+ const node32Index = byteOffset / 4;
418
+ const node16Index = byteOffset / 2;
419
+ const isLeaf = "count" in node;
420
+ const boundingData = node.boundingData;
421
+ for (let i = 0; i < 6; i++) {
422
+ float32Array[node32Index + i] = boundingData[i];
423
+ }
424
+ if (isLeaf) {
425
+ if (node.buffer) {
426
+ uint8Array.set(new Uint8Array(node.buffer), byteOffset);
427
+ return byteOffset + node.buffer.byteLength;
428
+ } else {
429
+ uint32Array[node32Index + 6] = node.offset;
430
+ uint16Array[node16Index + 14] = node.count;
431
+ uint16Array[node16Index + 15] = IS_LEAFNODE_FLAG;
432
+ return byteOffset + BYTES_PER_NODE;
433
+ }
434
+ } else {
435
+ const { left, right, splitAxis } = node;
436
+ const leftByteOffset = byteOffset + BYTES_PER_NODE;
437
+ let rightByteOffset = _populateBuffer(leftByteOffset, left);
438
+ const currentNodeIndex = byteOffset / BYTES_PER_NODE;
439
+ const rightNodeIndex = rightByteOffset / BYTES_PER_NODE;
440
+ const relativeRightIndex = rightNodeIndex - currentNodeIndex;
441
+ if (relativeRightIndex > MAX_POINTER) {
442
+ throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");
443
+ }
444
+ uint32Array[node32Index + 6] = relativeRightIndex;
445
+ uint32Array[node32Index + 7] = splitAxis;
446
+ return _populateBuffer(rightByteOffset, right);
447
+ }
448
+ }
449
+
450
+ // ../../node_modules/three-mesh-bvh/src/core/build/buildTree.js
451
+ function buildTree(bvh, primitiveBounds, offset, count, options, loadRange) {
452
+ const {
453
+ maxDepth,
454
+ verbose,
455
+ targetLeafSize,
456
+ _strictLeafSize = Infinity,
457
+ strategy,
458
+ onProgress
459
+ } = options;
460
+ const partitionBuffer = bvh.primitiveBuffer;
461
+ const partitionStride = bvh.primitiveBufferStride;
462
+ const cacheCentroidBoundingData = new Float32Array(6);
463
+ let reachedMaxDepth = false;
464
+ const root = new BVHNode();
465
+ getBounds(primitiveBounds, offset, count, root.boundingData, cacheCentroidBoundingData);
466
+ splitNode(root, offset, count, cacheCentroidBoundingData);
467
+ return root;
468
+ function triggerProgress(primitivesProcessed) {
469
+ if (onProgress) {
470
+ onProgress((primitivesProcessed - loadRange.offset) / loadRange.count);
471
+ }
472
+ }
473
+ function splitNode(node, offset2, count2, centroidBoundingData = null, depth = 0) {
474
+ if (!reachedMaxDepth && depth >= maxDepth) {
475
+ reachedMaxDepth = true;
476
+ if (verbose) {
477
+ console.warn(`BVH: Max depth of ${maxDepth} reached when generating BVH. Consider increasing maxDepth.`);
478
+ }
479
+ }
480
+ const mustSplit = count2 > _strictLeafSize;
481
+ if (count2 <= targetLeafSize && !mustSplit || depth >= maxDepth) {
482
+ triggerProgress(offset2 + count2);
483
+ node.offset = offset2;
484
+ node.count = count2;
485
+ return node;
486
+ }
487
+ const split = getOptimalSplit(node.boundingData, centroidBoundingData, primitiveBounds, offset2, count2, strategy);
488
+ let splitOffset = split.axis === -1 ? -1 : partition(partitionBuffer, partitionStride, primitiveBounds, offset2, count2, split);
489
+ if (split.axis === -1 || splitOffset === offset2 || splitOffset === offset2 + count2) {
490
+ if (!mustSplit) {
491
+ triggerProgress(offset2 + count2);
492
+ node.offset = offset2;
493
+ node.count = count2;
494
+ return node;
495
+ }
496
+ split.axis = Math.max(0, getLongestEdgeIndex(node.boundingData));
497
+ splitOffset = offset2 + Math.max(1, Math.floor(count2 / 2));
498
+ }
499
+ node.splitAxis = split.axis;
500
+ const left = new BVHNode();
501
+ const lstart = offset2;
502
+ const lcount = splitOffset - offset2;
503
+ node.left = left;
504
+ getBounds(primitiveBounds, lstart, lcount, left.boundingData, cacheCentroidBoundingData);
505
+ splitNode(left, lstart, lcount, cacheCentroidBoundingData, depth + 1);
506
+ const right = new BVHNode();
507
+ const rstart = splitOffset;
508
+ const rcount = count2 - lcount;
509
+ node.right = right;
510
+ getBounds(primitiveBounds, rstart, rcount, right.boundingData, cacheCentroidBoundingData);
511
+ splitNode(right, rstart, rcount, cacheCentroidBoundingData, depth + 1);
512
+ return node;
513
+ }
514
+ }
515
+ function buildPackedTree(bvh, options) {
516
+ const BufferConstructor = options.useSharedArrayBuffer ? SharedArrayBuffer : ArrayBuffer;
517
+ const rootRanges = bvh.getRootRanges(options.range);
518
+ const firstRange = rootRanges[0];
519
+ const lastRange = rootRanges[rootRanges.length - 1];
520
+ const fullRange = {
521
+ offset: firstRange.offset,
522
+ count: lastRange.offset + lastRange.count - firstRange.offset
523
+ };
524
+ const primitiveBounds = new Float32Array(6 * fullRange.count);
525
+ primitiveBounds.offset = fullRange.offset;
526
+ bvh.computePrimitiveBounds(fullRange.offset, fullRange.count, primitiveBounds);
527
+ bvh._roots = rootRanges.map((range) => {
528
+ const root = buildTree(bvh, primitiveBounds, range.offset, range.count, options, fullRange);
529
+ const nodeCount = countNodes(root);
530
+ const buffer = new BufferConstructor(BYTES_PER_NODE * nodeCount);
531
+ populateBuffer(0, root, buffer);
532
+ return buffer;
533
+ });
534
+ }
535
+
536
+ // ../../node_modules/three-mesh-bvh/src/core/cast/shapecast.js
537
+ import { Box3 } from "three";
538
+
539
+ // ../../node_modules/three-mesh-bvh/src/utils/PrimitivePool.js
540
+ var PrimitivePool = class {
541
+ constructor(getNewPrimitive) {
542
+ this._getNewPrimitive = getNewPrimitive;
543
+ this._primitives = [];
544
+ }
545
+ getPrimitive() {
546
+ const primitives = this._primitives;
547
+ if (primitives.length === 0) {
548
+ return this._getNewPrimitive();
549
+ } else {
550
+ return primitives.pop();
551
+ }
552
+ }
553
+ releasePrimitive(primitive) {
554
+ this._primitives.push(primitive);
555
+ }
556
+ };
557
+
558
+ // ../../node_modules/three-mesh-bvh/src/core/utils/BufferStack.js
559
+ var _BufferStack = class {
560
+ constructor() {
561
+ this.float32Array = null;
562
+ this.uint16Array = null;
563
+ this.uint32Array = null;
564
+ const stack = [];
565
+ let prevBuffer = null;
566
+ this.setBuffer = (buffer) => {
567
+ if (prevBuffer) {
568
+ stack.push(prevBuffer);
569
+ }
570
+ prevBuffer = buffer;
571
+ this.float32Array = new Float32Array(buffer);
572
+ this.uint16Array = new Uint16Array(buffer);
573
+ this.uint32Array = new Uint32Array(buffer);
574
+ };
575
+ this.clearBuffer = () => {
576
+ prevBuffer = null;
577
+ this.float32Array = null;
578
+ this.uint16Array = null;
579
+ this.uint32Array = null;
580
+ if (stack.length !== 0) {
581
+ this.setBuffer(stack.pop());
582
+ }
583
+ };
584
+ }
585
+ };
586
+ var BufferStack = /* @__PURE__ */ new _BufferStack();
587
+
588
+ // ../../node_modules/three-mesh-bvh/src/core/cast/shapecast.js
589
+ var _box1;
590
+ var _box2;
591
+ var boxStack = [];
592
+ var boxPool = /* @__PURE__ */ new PrimitivePool(() => new Box3());
593
+ function shapecast(bvh, root, intersectsBounds, intersectsRange, boundsTraverseOrder, nodeOffset) {
594
+ _box1 = boxPool.getPrimitive();
595
+ _box2 = boxPool.getPrimitive();
596
+ boxStack.push(_box1, _box2);
597
+ BufferStack.setBuffer(bvh._roots[root]);
598
+ const result = shapecastTraverse(0, bvh.geometry, intersectsBounds, intersectsRange, boundsTraverseOrder, nodeOffset);
599
+ BufferStack.clearBuffer();
600
+ boxPool.releasePrimitive(_box1);
601
+ boxPool.releasePrimitive(_box2);
602
+ boxStack.pop();
603
+ boxStack.pop();
604
+ const length = boxStack.length;
605
+ if (length > 0) {
606
+ _box2 = boxStack[length - 1];
607
+ _box1 = boxStack[length - 2];
608
+ }
609
+ return result;
610
+ }
611
+ function shapecastTraverse(nodeIndex32, geometry, intersectsBoundsFunc, intersectsRangeFunc, nodeScoreFunc = null, nodeIndexOffset = 0, depth = 0) {
612
+ const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack;
613
+ let nodeIndex16 = nodeIndex32 * 2;
614
+ const isLeaf = IS_LEAF(nodeIndex16, uint16Array2);
615
+ if (isLeaf) {
616
+ const offset = OFFSET(nodeIndex32, uint32Array2);
617
+ const count = COUNT(nodeIndex16, uint16Array2);
618
+ arrayToBox(BOUNDING_DATA_INDEX(nodeIndex32), float32Array2, _box1);
619
+ return intersectsRangeFunc(offset, count, false, depth, nodeIndexOffset + nodeIndex32 / UINT32_PER_NODE, _box1);
620
+ } else {
621
+ let getLeftOffset = function(nodeIndex322) {
622
+ const { uint16Array: uint16Array3, uint32Array: uint32Array3 } = BufferStack;
623
+ let nodeIndex162 = nodeIndex322 * 2;
624
+ while (!IS_LEAF(nodeIndex162, uint16Array3)) {
625
+ nodeIndex322 = LEFT_NODE(nodeIndex322);
626
+ nodeIndex162 = nodeIndex322 * 2;
627
+ }
628
+ return OFFSET(nodeIndex322, uint32Array3);
629
+ }, getRightEndOffset = function(nodeIndex322) {
630
+ const { uint16Array: uint16Array3, uint32Array: uint32Array3 } = BufferStack;
631
+ let nodeIndex162 = nodeIndex322 * 2;
632
+ while (!IS_LEAF(nodeIndex162, uint16Array3)) {
633
+ nodeIndex322 = RIGHT_NODE(nodeIndex322, uint32Array3);
634
+ nodeIndex162 = nodeIndex322 * 2;
635
+ }
636
+ return OFFSET(nodeIndex322, uint32Array3) + COUNT(nodeIndex162, uint16Array3);
637
+ };
638
+ const left = LEFT_NODE(nodeIndex32);
639
+ const right = RIGHT_NODE(nodeIndex32, uint32Array2);
640
+ let c1 = left;
641
+ let c2 = right;
642
+ let score1, score2;
643
+ let box1, box2;
644
+ if (nodeScoreFunc) {
645
+ box1 = _box1;
646
+ box2 = _box2;
647
+ arrayToBox(BOUNDING_DATA_INDEX(c1), float32Array2, box1);
648
+ arrayToBox(BOUNDING_DATA_INDEX(c2), float32Array2, box2);
649
+ score1 = nodeScoreFunc(box1);
650
+ score2 = nodeScoreFunc(box2);
651
+ if (score2 < score1) {
652
+ c1 = right;
653
+ c2 = left;
654
+ const temp5 = score1;
655
+ score1 = score2;
656
+ score2 = temp5;
657
+ box1 = box2;
658
+ }
659
+ }
660
+ if (!box1) {
661
+ box1 = _box1;
662
+ arrayToBox(BOUNDING_DATA_INDEX(c1), float32Array2, box1);
663
+ }
664
+ const isC1Leaf = IS_LEAF(c1 * 2, uint16Array2);
665
+ const c1Intersection = intersectsBoundsFunc(box1, isC1Leaf, score1, depth + 1, nodeIndexOffset + c1 / UINT32_PER_NODE);
666
+ let c1StopTraversal;
667
+ if (c1Intersection === CONTAINED) {
668
+ const offset = getLeftOffset(c1);
669
+ const end = getRightEndOffset(c1);
670
+ const count = end - offset;
671
+ c1StopTraversal = intersectsRangeFunc(offset, count, true, depth + 1, nodeIndexOffset + c1 / UINT32_PER_NODE, box1);
672
+ } else {
673
+ c1StopTraversal = c1Intersection && shapecastTraverse(
674
+ c1,
675
+ geometry,
676
+ intersectsBoundsFunc,
677
+ intersectsRangeFunc,
678
+ nodeScoreFunc,
679
+ nodeIndexOffset,
680
+ depth + 1
681
+ );
682
+ }
683
+ if (c1StopTraversal) return true;
684
+ box2 = _box2;
685
+ arrayToBox(BOUNDING_DATA_INDEX(c2), float32Array2, box2);
686
+ const isC2Leaf = IS_LEAF(c2 * 2, uint16Array2);
687
+ const c2Intersection = intersectsBoundsFunc(box2, isC2Leaf, score2, depth + 1, nodeIndexOffset + c2 / UINT32_PER_NODE);
688
+ let c2StopTraversal;
689
+ if (c2Intersection === CONTAINED) {
690
+ const offset = getLeftOffset(c2);
691
+ const end = getRightEndOffset(c2);
692
+ const count = end - offset;
693
+ c2StopTraversal = intersectsRangeFunc(offset, count, true, depth + 1, nodeIndexOffset + c2 / UINT32_PER_NODE, box2);
694
+ } else {
695
+ c2StopTraversal = c2Intersection && shapecastTraverse(
696
+ c2,
697
+ geometry,
698
+ intersectsBoundsFunc,
699
+ intersectsRangeFunc,
700
+ nodeScoreFunc,
701
+ nodeIndexOffset,
702
+ depth + 1
703
+ );
704
+ }
705
+ if (c2StopTraversal) return true;
706
+ return false;
707
+ }
708
+ }
709
+
710
+ // ../../node_modules/three-mesh-bvh/src/core/cast/bvhcast.js
711
+ import { Box3 as Box32, Matrix4 } from "three";
712
+ var _bufferStack1 = /* @__PURE__ */ new BufferStack.constructor();
713
+ var _bufferStack2 = /* @__PURE__ */ new BufferStack.constructor();
714
+ var _boxPool = /* @__PURE__ */ new PrimitivePool(() => new Box32());
715
+ var _leftBox1 = /* @__PURE__ */ new Box32();
716
+ var _rightBox1 = /* @__PURE__ */ new Box32();
717
+ var _leftBox2 = /* @__PURE__ */ new Box32();
718
+ var _rightBox2 = /* @__PURE__ */ new Box32();
719
+ var _active = false;
720
+ function bvhcast(bvh, otherBvh, matrixToLocal, intersectsRanges) {
721
+ if (_active) {
722
+ throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");
723
+ }
724
+ _active = true;
725
+ const roots = bvh._roots;
726
+ const otherRoots = otherBvh._roots;
727
+ let result;
728
+ let nodeOffset1 = 0;
729
+ let nodeOffset2 = 0;
730
+ const invMat = new Matrix4().copy(matrixToLocal).invert();
731
+ for (let i = 0, il = roots.length; i < il; i++) {
732
+ _bufferStack1.setBuffer(roots[i]);
733
+ nodeOffset2 = 0;
734
+ const localBox = _boxPool.getPrimitive();
735
+ arrayToBox(BOUNDING_DATA_INDEX(0), _bufferStack1.float32Array, localBox);
736
+ localBox.applyMatrix4(invMat);
737
+ for (let j = 0, jl = otherRoots.length; j < jl; j++) {
738
+ _bufferStack2.setBuffer(otherRoots[j]);
739
+ result = _traverse(
740
+ 0,
741
+ 0,
742
+ matrixToLocal,
743
+ invMat,
744
+ intersectsRanges,
745
+ nodeOffset1,
746
+ nodeOffset2,
747
+ 0,
748
+ 0,
749
+ localBox
750
+ );
751
+ _bufferStack2.clearBuffer();
752
+ nodeOffset2 += otherRoots[j].byteLength / BYTES_PER_NODE;
753
+ if (result) {
754
+ break;
755
+ }
756
+ }
757
+ _boxPool.releasePrimitive(localBox);
758
+ _bufferStack1.clearBuffer();
759
+ nodeOffset1 += roots[i].byteLength / BYTES_PER_NODE;
760
+ if (result) {
761
+ break;
762
+ }
763
+ }
764
+ _active = false;
765
+ return result;
766
+ }
767
+ function _traverse(node1Index32, node2Index32, matrix2to1, matrix1to2, intersectsRangesFunc, node1IndexOffset = 0, node2IndexOffset = 0, depth1 = 0, depth2 = 0, currBox = null, reversed = false) {
768
+ let bufferStack1, bufferStack2;
769
+ if (reversed) {
770
+ bufferStack1 = _bufferStack2;
771
+ bufferStack2 = _bufferStack1;
772
+ } else {
773
+ bufferStack1 = _bufferStack1;
774
+ bufferStack2 = _bufferStack2;
775
+ }
776
+ const float32Array1 = bufferStack1.float32Array, uint32Array1 = bufferStack1.uint32Array, uint16Array1 = bufferStack1.uint16Array, float32Array2 = bufferStack2.float32Array, uint32Array2 = bufferStack2.uint32Array, uint16Array2 = bufferStack2.uint16Array;
777
+ const node1Index16 = node1Index32 * 2;
778
+ const node2Index16 = node2Index32 * 2;
779
+ const isLeaf1 = IS_LEAF(node1Index16, uint16Array1);
780
+ const isLeaf2 = IS_LEAF(node2Index16, uint16Array2);
781
+ let result = false;
782
+ if (isLeaf2 && isLeaf1) {
783
+ if (reversed) {
784
+ result = intersectsRangesFunc(
785
+ OFFSET(node2Index32, uint32Array2),
786
+ COUNT(node2Index32 * 2, uint16Array2),
787
+ OFFSET(node1Index32, uint32Array1),
788
+ COUNT(node1Index32 * 2, uint16Array1),
789
+ depth2,
790
+ node2IndexOffset + node2Index32 / UINT32_PER_NODE,
791
+ depth1,
792
+ node1IndexOffset + node1Index32 / UINT32_PER_NODE
793
+ );
794
+ } else {
795
+ result = intersectsRangesFunc(
796
+ OFFSET(node1Index32, uint32Array1),
797
+ COUNT(node1Index32 * 2, uint16Array1),
798
+ OFFSET(node2Index32, uint32Array2),
799
+ COUNT(node2Index32 * 2, uint16Array2),
800
+ depth1,
801
+ node1IndexOffset + node1Index32 / UINT32_PER_NODE,
802
+ depth2,
803
+ node2IndexOffset + node2Index32 / UINT32_PER_NODE
804
+ );
805
+ }
806
+ } else if (isLeaf2) {
807
+ const newBox = _boxPool.getPrimitive();
808
+ arrayToBox(BOUNDING_DATA_INDEX(node2Index32), float32Array2, newBox);
809
+ newBox.applyMatrix4(matrix2to1);
810
+ const cl1 = LEFT_NODE(node1Index32);
811
+ const cr1 = RIGHT_NODE(node1Index32, uint32Array1);
812
+ arrayToBox(BOUNDING_DATA_INDEX(cl1), float32Array1, _leftBox1);
813
+ arrayToBox(BOUNDING_DATA_INDEX(cr1), float32Array1, _rightBox1);
814
+ const intersectCl1 = newBox.intersectsBox(_leftBox1);
815
+ const intersectCr1 = newBox.intersectsBox(_rightBox1);
816
+ result = intersectCl1 && _traverse(
817
+ node2Index32,
818
+ cl1,
819
+ matrix1to2,
820
+ matrix2to1,
821
+ intersectsRangesFunc,
822
+ node2IndexOffset,
823
+ node1IndexOffset,
824
+ depth2,
825
+ depth1 + 1,
826
+ newBox,
827
+ !reversed
828
+ ) || intersectCr1 && _traverse(
829
+ node2Index32,
830
+ cr1,
831
+ matrix1to2,
832
+ matrix2to1,
833
+ intersectsRangesFunc,
834
+ node2IndexOffset,
835
+ node1IndexOffset,
836
+ depth2,
837
+ depth1 + 1,
838
+ newBox,
839
+ !reversed
840
+ );
841
+ _boxPool.releasePrimitive(newBox);
842
+ } else {
843
+ const cl2 = LEFT_NODE(node2Index32);
844
+ const cr2 = RIGHT_NODE(node2Index32, uint32Array2);
845
+ arrayToBox(BOUNDING_DATA_INDEX(cl2), float32Array2, _leftBox2);
846
+ arrayToBox(BOUNDING_DATA_INDEX(cr2), float32Array2, _rightBox2);
847
+ const leftIntersects = currBox.intersectsBox(_leftBox2);
848
+ const rightIntersects = currBox.intersectsBox(_rightBox2);
849
+ if (leftIntersects && rightIntersects) {
850
+ result = _traverse(
851
+ node1Index32,
852
+ cl2,
853
+ matrix2to1,
854
+ matrix1to2,
855
+ intersectsRangesFunc,
856
+ node1IndexOffset,
857
+ node2IndexOffset,
858
+ depth1,
859
+ depth2 + 1,
860
+ currBox,
861
+ reversed
862
+ ) || _traverse(
863
+ node1Index32,
864
+ cr2,
865
+ matrix2to1,
866
+ matrix1to2,
867
+ intersectsRangesFunc,
868
+ node1IndexOffset,
869
+ node2IndexOffset,
870
+ depth1,
871
+ depth2 + 1,
872
+ currBox,
873
+ reversed
874
+ );
875
+ } else if (leftIntersects) {
876
+ if (isLeaf1) {
877
+ result = _traverse(
878
+ node1Index32,
879
+ cl2,
880
+ matrix2to1,
881
+ matrix1to2,
882
+ intersectsRangesFunc,
883
+ node1IndexOffset,
884
+ node2IndexOffset,
885
+ depth1,
886
+ depth2 + 1,
887
+ currBox,
888
+ reversed
889
+ );
890
+ } else {
891
+ const newBox = _boxPool.getPrimitive();
892
+ newBox.copy(_leftBox2).applyMatrix4(matrix2to1);
893
+ const cl1 = LEFT_NODE(node1Index32);
894
+ const cr1 = RIGHT_NODE(node1Index32, uint32Array1);
895
+ arrayToBox(BOUNDING_DATA_INDEX(cl1), float32Array1, _leftBox1);
896
+ arrayToBox(BOUNDING_DATA_INDEX(cr1), float32Array1, _rightBox1);
897
+ const intersectCl1 = newBox.intersectsBox(_leftBox1);
898
+ const intersectCr1 = newBox.intersectsBox(_rightBox1);
899
+ result = intersectCl1 && _traverse(
900
+ cl2,
901
+ cl1,
902
+ matrix1to2,
903
+ matrix2to1,
904
+ intersectsRangesFunc,
905
+ node2IndexOffset,
906
+ node1IndexOffset,
907
+ depth2,
908
+ depth1 + 1,
909
+ newBox,
910
+ !reversed
911
+ ) || intersectCr1 && _traverse(
912
+ cl2,
913
+ cr1,
914
+ matrix1to2,
915
+ matrix2to1,
916
+ intersectsRangesFunc,
917
+ node2IndexOffset,
918
+ node1IndexOffset,
919
+ depth2,
920
+ depth1 + 1,
921
+ newBox,
922
+ !reversed
923
+ );
924
+ _boxPool.releasePrimitive(newBox);
925
+ }
926
+ } else if (rightIntersects) {
927
+ if (isLeaf1) {
928
+ result = _traverse(
929
+ node1Index32,
930
+ cr2,
931
+ matrix2to1,
932
+ matrix1to2,
933
+ intersectsRangesFunc,
934
+ node1IndexOffset,
935
+ node2IndexOffset,
936
+ depth1,
937
+ depth2 + 1,
938
+ currBox,
939
+ reversed
940
+ );
941
+ } else {
942
+ const newBox = _boxPool.getPrimitive();
943
+ newBox.copy(_rightBox2).applyMatrix4(matrix2to1);
944
+ const cl1 = LEFT_NODE(node1Index32);
945
+ const cr1 = RIGHT_NODE(node1Index32, uint32Array1);
946
+ arrayToBox(BOUNDING_DATA_INDEX(cl1), float32Array1, _leftBox1);
947
+ arrayToBox(BOUNDING_DATA_INDEX(cr1), float32Array1, _rightBox1);
948
+ const intersectCl1 = newBox.intersectsBox(_leftBox1);
949
+ const intersectCr1 = newBox.intersectsBox(_rightBox1);
950
+ result = intersectCl1 && _traverse(
951
+ cr2,
952
+ cl1,
953
+ matrix1to2,
954
+ matrix2to1,
955
+ intersectsRangesFunc,
956
+ node2IndexOffset,
957
+ node1IndexOffset,
958
+ depth2,
959
+ depth1 + 1,
960
+ newBox,
961
+ !reversed
962
+ ) || intersectCr1 && _traverse(
963
+ cr2,
964
+ cr1,
965
+ matrix1to2,
966
+ matrix2to1,
967
+ intersectsRangesFunc,
968
+ node2IndexOffset,
969
+ node1IndexOffset,
970
+ depth2,
971
+ depth1 + 1,
972
+ newBox,
973
+ !reversed
974
+ );
975
+ _boxPool.releasePrimitive(newBox);
976
+ }
977
+ }
978
+ }
979
+ return result;
980
+ }
981
+
982
+ // ../../node_modules/three-mesh-bvh/src/core/BVHTraversalHelper.js
983
+ var BVHTraversalHelper = new class {
984
+ constructor() {
985
+ let buffer = null;
986
+ let uint32Array2 = null;
987
+ let uint16Array2 = null;
988
+ let traversing = false;
989
+ this.root = null;
990
+ this.buffer = null;
991
+ this.uint32Array = null;
992
+ this.uint16Array = null;
993
+ this.setBVH = (bvh, root) => {
994
+ if (traversing) {
995
+ throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");
996
+ }
997
+ this.root = root;
998
+ this.buffer = buffer = bvh._roots[root];
999
+ this.uint16Array = uint16Array2 = new Uint16Array(buffer);
1000
+ this.uint32Array = uint32Array2 = new Uint32Array(buffer);
1001
+ };
1002
+ this.reset = () => {
1003
+ this.root = null;
1004
+ this.buffer = buffer = null;
1005
+ this.uint16Array = uint16Array2 = null;
1006
+ this.uint32Array = uint32Array2 = null;
1007
+ };
1008
+ this.getRangeStart = (node32Index) => {
1009
+ let node16Index = node32Index * 2;
1010
+ while (!IS_LEAF(node16Index, uint16Array2)) {
1011
+ node32Index = LEFT_NODE(node32Index);
1012
+ node16Index = node32Index * 2;
1013
+ }
1014
+ return OFFSET(node32Index, uint32Array2);
1015
+ };
1016
+ this.getRangeEnd = (node32Index) => {
1017
+ let node16Index = node32Index * 2;
1018
+ while (!IS_LEAF(node16Index, uint16Array2)) {
1019
+ node32Index = RIGHT_NODE(node32Index, uint32Array2);
1020
+ node16Index = node32Index * 2;
1021
+ }
1022
+ return OFFSET(node32Index, uint32Array2) + COUNT(node16Index, uint16Array2);
1023
+ };
1024
+ const walk = (callback, node32Index, depth) => {
1025
+ const node16Index = node32Index * 2;
1026
+ const isLeaf = IS_LEAF(node16Index, uint16Array2);
1027
+ const stopTraversal = callback(depth, isLeaf, node32Index);
1028
+ if (!stopTraversal && !isLeaf) {
1029
+ const left = LEFT_NODE(node32Index);
1030
+ const right = RIGHT_NODE(node32Index, uint32Array2);
1031
+ walk(callback, left, depth + 1);
1032
+ walk(callback, right, depth + 1);
1033
+ }
1034
+ };
1035
+ this.traverseBuffer = (callback) => {
1036
+ if (traversing) {
1037
+ throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");
1038
+ }
1039
+ traversing = true;
1040
+ try {
1041
+ walk(callback, 0, 0);
1042
+ } finally {
1043
+ traversing = false;
1044
+ }
1045
+ };
1046
+ this.traverse = (callback) => {
1047
+ this.traverseBuffer((depth, isLeaf, node32Index) => {
1048
+ if (isLeaf) {
1049
+ const node16Index = node32Index * 2;
1050
+ const offset = uint32Array2[node32Index + 6];
1051
+ const count = uint16Array2[node16Index + 14];
1052
+ return callback(depth, isLeaf, new Float32Array(buffer, node32Index * 4, 6), offset, count);
1053
+ } else {
1054
+ const splitAxis = SPLIT_AXIS(node32Index, uint32Array2);
1055
+ return callback(depth, isLeaf, new Float32Array(buffer, node32Index * 4, 6), splitAxis);
1056
+ }
1057
+ });
1058
+ };
1059
+ }
1060
+ }();
1061
+
1062
+ // ../../node_modules/three-mesh-bvh/src/core/BVH.js
1063
+ var _tempBox = /* @__PURE__ */ new Box33();
1064
+ var _tempBuffer = /* @__PURE__ */ new Float32Array(6);
1065
+ var BVH = class {
1066
+ constructor() {
1067
+ this._roots = null;
1068
+ this.primitiveBuffer = null;
1069
+ this.primitiveBufferStride = null;
1070
+ }
1071
+ init(options) {
1072
+ options = {
1073
+ ...DEFAULT_OPTIONS,
1074
+ ...options
1075
+ };
1076
+ if ("maxLeafSize" in options) {
1077
+ console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.');
1078
+ options = {
1079
+ ...options,
1080
+ targetLeafSize: options.maxLeafSize
1081
+ };
1082
+ }
1083
+ buildPackedTree(this, options);
1084
+ }
1085
+ getRootRanges() {
1086
+ throw new Error("BVH: getRootRanges() not implemented");
1087
+ }
1088
+ // write the i-th primitive bounds in a 6-value min / max format to the buffer
1089
+ // starting at the given "writeOffset"
1090
+ writePrimitiveBounds() {
1091
+ throw new Error("BVH: writePrimitiveBounds() not implemented");
1092
+ }
1093
+ // writes the union bounds of all primitives in the given range in a min / max format
1094
+ // to the buffer
1095
+ writePrimitiveRangeBounds(offset, count, targetBuffer, baseIndex) {
1096
+ let minX = Infinity;
1097
+ let minY = Infinity;
1098
+ let minZ = Infinity;
1099
+ let maxX = -Infinity;
1100
+ let maxY = -Infinity;
1101
+ let maxZ = -Infinity;
1102
+ for (let i = offset, end = offset + count; i < end; i++) {
1103
+ this.writePrimitiveBounds(i, _tempBuffer, 0);
1104
+ const [lx, ly, lz, rx, ry, rz] = _tempBuffer;
1105
+ if (lx < minX) minX = lx;
1106
+ if (rx > maxX) maxX = rx;
1107
+ if (ly < minY) minY = ly;
1108
+ if (ry > maxY) maxY = ry;
1109
+ if (lz < minZ) minZ = lz;
1110
+ if (rz > maxZ) maxZ = rz;
1111
+ }
1112
+ targetBuffer[baseIndex + 0] = minX;
1113
+ targetBuffer[baseIndex + 1] = minY;
1114
+ targetBuffer[baseIndex + 2] = minZ;
1115
+ targetBuffer[baseIndex + 3] = maxX;
1116
+ targetBuffer[baseIndex + 4] = maxY;
1117
+ targetBuffer[baseIndex + 5] = maxZ;
1118
+ return targetBuffer;
1119
+ }
1120
+ computePrimitiveBounds(offset, count, targetBuffer) {
1121
+ const boundsOffset = targetBuffer.offset || 0;
1122
+ for (let i = offset, end = offset + count; i < end; i++) {
1123
+ this.writePrimitiveBounds(i, _tempBuffer, 0);
1124
+ const [lx, ly, lz, rx, ry, rz] = _tempBuffer;
1125
+ const cx = (lx + rx) / 2;
1126
+ const cy = (ly + ry) / 2;
1127
+ const cz = (lz + rz) / 2;
1128
+ const hx = (rx - lx) / 2;
1129
+ const hy = (ry - ly) / 2;
1130
+ const hz = (rz - lz) / 2;
1131
+ const baseIndex = (i - boundsOffset) * 6;
1132
+ targetBuffer[baseIndex + 0] = cx;
1133
+ targetBuffer[baseIndex + 1] = hx + (Math.abs(cx) + hx) * FLOAT32_EPSILON;
1134
+ targetBuffer[baseIndex + 2] = cy;
1135
+ targetBuffer[baseIndex + 3] = hy + (Math.abs(cy) + hy) * FLOAT32_EPSILON;
1136
+ targetBuffer[baseIndex + 4] = cz;
1137
+ targetBuffer[baseIndex + 5] = hz + (Math.abs(cz) + hz) * FLOAT32_EPSILON;
1138
+ }
1139
+ return targetBuffer;
1140
+ }
1141
+ /**
1142
+ * Adjusts all primitive offsets stored in the BVH leaf nodes by the given value. Useful when
1143
+ * geometry buffers have been shifted or compacted (e.g. when merging geometries).
1144
+ * @param {number} offset
1145
+ */
1146
+ shiftPrimitiveOffsets(offset) {
1147
+ const indirectBuffer = this._indirectBuffer;
1148
+ if (indirectBuffer) {
1149
+ for (let i = 0, l = indirectBuffer.length; i < l; i++) {
1150
+ indirectBuffer[i] += offset;
1151
+ }
1152
+ } else {
1153
+ const roots = this._roots;
1154
+ for (let rootIndex = 0; rootIndex < roots.length; rootIndex++) {
1155
+ const root = roots[rootIndex];
1156
+ const uint32Array2 = new Uint32Array(root);
1157
+ const uint16Array2 = new Uint16Array(root);
1158
+ const totalNodes = root.byteLength / BYTES_PER_NODE;
1159
+ for (let node = 0; node < totalNodes; node++) {
1160
+ const node32Index = UINT32_PER_NODE * node;
1161
+ const node16Index = 2 * node32Index;
1162
+ if (IS_LEAF(node16Index, uint16Array2)) {
1163
+ uint32Array2[node32Index + 6] += offset;
1164
+ }
1165
+ }
1166
+ }
1167
+ }
1168
+ }
1169
+ /**
1170
+ * Traverses all nodes of the BVH, invoking a callback for each node.
1171
+ *
1172
+ * For leaf nodes the callback receives `( depth, isLeaf, boundingData, offset, count )`.
1173
+ * For internal nodes it receives `( depth, isLeaf, boundingData, splitAxis )` and may
1174
+ * return `true` to stop descending into that node's children.
1175
+ *
1176
+ * @param {Function} callback
1177
+ * @param {number} [rootIndex=0]
1178
+ */
1179
+ traverse(callback, rootIndex = 0) {
1180
+ BVHTraversalHelper.setBVH(this, rootIndex);
1181
+ BVHTraversalHelper.traverse(callback);
1182
+ BVHTraversalHelper.reset();
1183
+ }
1184
+ /**
1185
+ * Refits all BVH node bounds to reflect the current primitive positions. Faster than
1186
+ * rebuilding the BVH but produces a less optimal tree after large vertex deformations.
1187
+ */
1188
+ refit() {
1189
+ const roots = this._roots;
1190
+ for (let rootIndex = 0, rootCount = roots.length; rootIndex < rootCount; rootIndex++) {
1191
+ const buffer = roots[rootIndex];
1192
+ const uint32Array2 = new Uint32Array(buffer);
1193
+ const uint16Array2 = new Uint16Array(buffer);
1194
+ const float32Array2 = new Float32Array(buffer);
1195
+ const totalNodes = buffer.byteLength / BYTES_PER_NODE;
1196
+ for (let nodeIndex = totalNodes - 1; nodeIndex >= 0; nodeIndex--) {
1197
+ const nodeIndex32 = nodeIndex * UINT32_PER_NODE;
1198
+ const nodeIndex16 = nodeIndex32 * 2;
1199
+ const isLeaf = IS_LEAF(nodeIndex16, uint16Array2);
1200
+ if (isLeaf) {
1201
+ const offset = OFFSET(nodeIndex32, uint32Array2);
1202
+ const count = COUNT(nodeIndex16, uint16Array2);
1203
+ this.writePrimitiveRangeBounds(offset, count, _tempBuffer, 0);
1204
+ float32Array2.set(_tempBuffer, nodeIndex32);
1205
+ } else {
1206
+ const left = LEFT_NODE(nodeIndex32);
1207
+ const right = RIGHT_NODE(nodeIndex32, uint32Array2);
1208
+ for (let i = 0; i < 3; i++) {
1209
+ const leftMin = float32Array2[left + i];
1210
+ const leftMax = float32Array2[left + i + 3];
1211
+ const rightMin = float32Array2[right + i];
1212
+ const rightMax = float32Array2[right + i + 3];
1213
+ float32Array2[nodeIndex32 + i] = leftMin < rightMin ? leftMin : rightMin;
1214
+ float32Array2[nodeIndex32 + i + 3] = leftMax > rightMax ? leftMax : rightMax;
1215
+ }
1216
+ }
1217
+ }
1218
+ }
1219
+ }
1220
+ /**
1221
+ * Computes the axis-aligned bounding box of all primitives in the BVH.
1222
+ * @param {Box3} target - Target box to write the result into.
1223
+ * @returns {Box3}
1224
+ */
1225
+ getBoundingBox(target) {
1226
+ target.makeEmpty();
1227
+ const roots = this._roots;
1228
+ roots.forEach((buffer) => {
1229
+ arrayToBox(0, new Float32Array(buffer), _tempBox);
1230
+ target.union(_tempBox);
1231
+ });
1232
+ return target;
1233
+ }
1234
+ /**
1235
+ * A generalized traversal function for performing spatial queries against the BVH. Returns
1236
+ * `true` as soon as a primitive has been reported as intersected. The tree is traversed
1237
+ * depth-first; `boundsTraverseOrder` controls which child is visited first. Returning
1238
+ * `CONTAINED` from `intersectsBounds` skips further child traversal and intersects all
1239
+ * primitives in that subtree immediately.
1240
+ *
1241
+ * @param {Object} callbacks
1242
+ * @param {IntersectsBoundsCallback} callbacks.intersectsBounds
1243
+ * @param {IntersectsRangeCallback} [callbacks.intersectsRange]
1244
+ * @param {BoundsTraverseOrderCallback} [callbacks.boundsTraverseOrder]
1245
+ * @returns {boolean}
1246
+ */
1247
+ // TODO: see if we can get rid of "iterateFunc" here as well as the primitive so the function
1248
+ // API aligns with the "shapecast" implementation
1249
+ shapecast(callbacks) {
1250
+ let {
1251
+ boundsTraverseOrder,
1252
+ intersectsBounds,
1253
+ intersectsRange,
1254
+ intersectsPrimitive,
1255
+ scratchPrimitive,
1256
+ iterate
1257
+ } = callbacks;
1258
+ if (intersectsRange && intersectsPrimitive) {
1259
+ const originalIntersectsRange = intersectsRange;
1260
+ intersectsRange = (offset, count, contained, depth, nodeIndex) => {
1261
+ if (!originalIntersectsRange(offset, count, contained, depth, nodeIndex)) {
1262
+ return iterate(offset, count, this, intersectsPrimitive, contained, depth, scratchPrimitive);
1263
+ }
1264
+ return true;
1265
+ };
1266
+ } else if (!intersectsRange) {
1267
+ if (intersectsPrimitive) {
1268
+ intersectsRange = (offset, count, contained, depth) => {
1269
+ return iterate(offset, count, this, intersectsPrimitive, contained, depth, scratchPrimitive);
1270
+ };
1271
+ } else {
1272
+ intersectsRange = (offset, count, contained) => {
1273
+ return contained;
1274
+ };
1275
+ }
1276
+ }
1277
+ let result = false;
1278
+ let nodeOffset = 0;
1279
+ const roots = this._roots;
1280
+ for (let i = 0, l = roots.length; i < l; i++) {
1281
+ const root = roots[i];
1282
+ result = shapecast(this, i, intersectsBounds, intersectsRange, boundsTraverseOrder, nodeOffset);
1283
+ if (result) {
1284
+ break;
1285
+ }
1286
+ nodeOffset += root.byteLength / BYTES_PER_NODE;
1287
+ }
1288
+ return result;
1289
+ }
1290
+ /**
1291
+ * Simultaneously traverses two BVH structures to find intersecting primitive pairs. Returns
1292
+ * `true` as soon as any intersection is reported. Both trees are traversed depth-first with
1293
+ * alternating descent. `matrixToLocal` transforms `otherBvh` into the local space of this BVH.
1294
+ *
1295
+ * @param {BVH} otherBvh
1296
+ * @param {Matrix4} matrixToLocal
1297
+ * @param {Object} callbacks
1298
+ * @param {IntersectsRangesCallback} callbacks.intersectsRanges
1299
+ * @returns {boolean}
1300
+ */
1301
+ bvhcast(otherBvh, matrixToLocal, callbacks) {
1302
+ let { intersectsRanges } = callbacks;
1303
+ return bvhcast(this, otherBvh, matrixToLocal, intersectsRanges);
1304
+ }
1305
+ };
1306
+
1307
+ // ../../node_modules/three-mesh-bvh/src/core/GeometryBVH.js
1308
+ import { Box3 as Box34 } from "three";
1309
+
1310
+ // ../../node_modules/three-mesh-bvh/src/utils/BufferUtils.js
1311
+ function isSharedArrayBufferSupported() {
1312
+ return typeof SharedArrayBuffer !== "undefined";
1313
+ }
1314
+
1315
+ // ../../node_modules/three-mesh-bvh/src/core/build/geometryUtils.js
1316
+ import { BufferAttribute } from "three";
1317
+ function getVertexCount(geo) {
1318
+ return geo.index ? geo.index.count : geo.attributes.position.count;
1319
+ }
1320
+ function getTriCount(geo) {
1321
+ return getVertexCount(geo) / 3;
1322
+ }
1323
+ function getIndexArray(vertexCount, BufferConstructor = ArrayBuffer) {
1324
+ if (vertexCount > 65535) {
1325
+ return new Uint32Array(new BufferConstructor(4 * vertexCount));
1326
+ } else {
1327
+ return new Uint16Array(new BufferConstructor(2 * vertexCount));
1328
+ }
1329
+ }
1330
+ function ensureIndex(geo, options) {
1331
+ if (!geo.index) {
1332
+ const vertexCount = geo.attributes.position.count;
1333
+ const BufferConstructor = options.useSharedArrayBuffer ? SharedArrayBuffer : ArrayBuffer;
1334
+ const index = getIndexArray(vertexCount, BufferConstructor);
1335
+ geo.setIndex(new BufferAttribute(index, 1));
1336
+ for (let i = 0; i < vertexCount; i++) {
1337
+ index[i] = i;
1338
+ }
1339
+ }
1340
+ }
1341
+ function getFullPrimitiveRange(geo, range, stride) {
1342
+ const primitiveCount = getVertexCount(geo) / stride;
1343
+ const drawRange = range ? range : geo.drawRange;
1344
+ const start = drawRange.start / stride;
1345
+ const end = (drawRange.start + drawRange.count) / stride;
1346
+ const offset = Math.max(0, start);
1347
+ const count = Math.min(primitiveCount, end) - offset;
1348
+ return {
1349
+ offset: Math.floor(offset),
1350
+ count: Math.floor(count)
1351
+ };
1352
+ }
1353
+ function getPrimitiveGroupRanges(geo, stride) {
1354
+ return geo.groups.map((group) => ({
1355
+ offset: group.start / stride,
1356
+ count: group.count / stride
1357
+ }));
1358
+ }
1359
+ function getRootPrimitiveRanges(geo, range, stride) {
1360
+ const drawRange = getFullPrimitiveRange(geo, range, stride);
1361
+ const primitiveRanges = getPrimitiveGroupRanges(geo, stride);
1362
+ if (!primitiveRanges.length) {
1363
+ return [drawRange];
1364
+ }
1365
+ const ranges = [];
1366
+ const drawRangeStart = drawRange.offset;
1367
+ const drawRangeEnd = drawRange.offset + drawRange.count;
1368
+ const primitiveCount = getVertexCount(geo) / stride;
1369
+ const events = [];
1370
+ for (const group of primitiveRanges) {
1371
+ const { offset, count } = group;
1372
+ const groupStart = offset;
1373
+ const groupCount = isFinite(count) ? count : primitiveCount - offset;
1374
+ const groupEnd = offset + groupCount;
1375
+ if (groupStart < drawRangeEnd && groupEnd > drawRangeStart) {
1376
+ events.push({ pos: Math.max(drawRangeStart, groupStart), isStart: true });
1377
+ events.push({ pos: Math.min(drawRangeEnd, groupEnd), isStart: false });
1378
+ }
1379
+ }
1380
+ events.sort((a, b) => {
1381
+ if (a.pos !== b.pos) {
1382
+ return a.pos - b.pos;
1383
+ } else {
1384
+ return a.type === "end" ? -1 : 1;
1385
+ }
1386
+ });
1387
+ let activeGroups = 0;
1388
+ let lastPos = null;
1389
+ for (const event of events) {
1390
+ const newPos = event.pos;
1391
+ if (activeGroups !== 0 && newPos !== lastPos) {
1392
+ ranges.push({
1393
+ offset: lastPos,
1394
+ count: newPos - lastPos
1395
+ });
1396
+ }
1397
+ activeGroups += event.isStart ? 1 : -1;
1398
+ lastPos = newPos;
1399
+ }
1400
+ return ranges;
1401
+ }
1402
+
1403
+ // ../../node_modules/three-mesh-bvh/src/core/GeometryBVH.js
1404
+ function generateIndirectBuffer(ranges, useSharedArrayBuffer) {
1405
+ const lastRange = ranges[ranges.length - 1];
1406
+ const useUint32 = lastRange.offset + lastRange.count > 2 ** 16;
1407
+ const length = ranges.reduce((acc, val) => acc + val.count, 0);
1408
+ const byteCount = useUint32 ? 4 : 2;
1409
+ const buffer = useSharedArrayBuffer ? new SharedArrayBuffer(length * byteCount) : new ArrayBuffer(length * byteCount);
1410
+ const indirectBuffer = useUint32 ? new Uint32Array(buffer) : new Uint16Array(buffer);
1411
+ let index = 0;
1412
+ for (let r = 0; r < ranges.length; r++) {
1413
+ const { offset, count } = ranges[r];
1414
+ for (let i = 0; i < count; i++) {
1415
+ indirectBuffer[index + i] = offset + i;
1416
+ }
1417
+ index += count;
1418
+ }
1419
+ return indirectBuffer;
1420
+ }
1421
+ var GeometryBVH = class extends BVH {
1422
+ /**
1423
+ * Whether the BVH was built in indirect mode.
1424
+ * @type {boolean}
1425
+ * @readonly
1426
+ */
1427
+ get indirect() {
1428
+ return !!this._indirectBuffer;
1429
+ }
1430
+ get primitiveStride() {
1431
+ return null;
1432
+ }
1433
+ get primitiveBufferStride() {
1434
+ return this.indirect ? 1 : this.primitiveStride;
1435
+ }
1436
+ set primitiveBufferStride(v) {
1437
+ }
1438
+ get primitiveBuffer() {
1439
+ return this.indirect ? this._indirectBuffer : this.geometry.index.array;
1440
+ }
1441
+ set primitiveBuffer(v) {
1442
+ }
1443
+ constructor(geometry, options = {}) {
1444
+ if (!geometry.isBufferGeometry) {
1445
+ throw new Error("BVH: Only BufferGeometries are supported.");
1446
+ } else if (geometry.index && geometry.index.isInterleavedBufferAttribute) {
1447
+ throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.");
1448
+ }
1449
+ if (options.useSharedArrayBuffer && !isSharedArrayBufferSupported()) {
1450
+ throw new Error("BVH: SharedArrayBuffer is not available.");
1451
+ }
1452
+ super();
1453
+ this.geometry = geometry;
1454
+ this.resolvePrimitiveIndex = options.indirect ? (i) => this._indirectBuffer[i] : (i) => i;
1455
+ this.primitiveBuffer = null;
1456
+ this.primitiveBufferStride = null;
1457
+ this._indirectBuffer = null;
1458
+ options = {
1459
+ ...DEFAULT_OPTIONS,
1460
+ ...options
1461
+ };
1462
+ if (!options[SKIP_GENERATION]) {
1463
+ this.init(options);
1464
+ }
1465
+ }
1466
+ init(options) {
1467
+ const { geometry, primitiveStride } = this;
1468
+ if (options.indirect) {
1469
+ const ranges = getRootPrimitiveRanges(geometry, options.range, primitiveStride);
1470
+ const indirectBuffer = generateIndirectBuffer(ranges, options.useSharedArrayBuffer);
1471
+ this._indirectBuffer = indirectBuffer;
1472
+ } else {
1473
+ ensureIndex(geometry, options);
1474
+ }
1475
+ super.init(options);
1476
+ if (!geometry.boundingBox && options.setBoundingBox) {
1477
+ geometry.boundingBox = this.getBoundingBox(new Box34());
1478
+ }
1479
+ }
1480
+ // Abstract methods to be implemented by subclasses
1481
+ getRootRanges(range) {
1482
+ if (this.indirect) {
1483
+ return [{ offset: 0, count: this._indirectBuffer.length }];
1484
+ } else {
1485
+ return getRootPrimitiveRanges(this.geometry, range, this.primitiveStride);
1486
+ }
1487
+ }
1488
+ raycastObject3D() {
1489
+ throw new Error("BVH: raycastObject3D() not implemented");
1490
+ }
1491
+ };
1492
+
1493
+ // ../../node_modules/three-mesh-bvh/src/core/MeshBVH.js
1494
+ import { BufferAttribute as BufferAttribute2, FrontSide, Ray, Vector3 as Vector310, Matrix4 as Matrix47 } from "three";
1495
+
1496
+ // ../../node_modules/three-mesh-bvh/src/math/OrientedBox.js
1497
+ import { Vector3 as Vector34, Matrix4 as Matrix42, Line3 as Line33 } from "three";
1498
+
1499
+ // ../../node_modules/three-mesh-bvh/src/math/SeparatingAxisBounds.js
1500
+ import { Vector3 } from "three";
1501
+ var SeparatingAxisBounds = class {
1502
+ constructor() {
1503
+ this.min = Infinity;
1504
+ this.max = -Infinity;
1505
+ }
1506
+ setFromPointsField(points, field) {
1507
+ let min = Infinity;
1508
+ let max = -Infinity;
1509
+ for (let i = 0, l = points.length; i < l; i++) {
1510
+ const p = points[i];
1511
+ const val = p[field];
1512
+ min = val < min ? val : min;
1513
+ max = val > max ? val : max;
1514
+ }
1515
+ this.min = min;
1516
+ this.max = max;
1517
+ }
1518
+ setFromPoints(axis, points) {
1519
+ let min = Infinity;
1520
+ let max = -Infinity;
1521
+ for (let i = 0, l = points.length; i < l; i++) {
1522
+ const p = points[i];
1523
+ const val = axis.dot(p);
1524
+ min = val < min ? val : min;
1525
+ max = val > max ? val : max;
1526
+ }
1527
+ this.min = min;
1528
+ this.max = max;
1529
+ }
1530
+ isSeparated(other) {
1531
+ return this.min > other.max || other.min > this.max;
1532
+ }
1533
+ };
1534
+ SeparatingAxisBounds.prototype.setFromBox = /* @__PURE__ */ (function() {
1535
+ const p = /* @__PURE__ */ new Vector3();
1536
+ return function setFromBox(axis, box) {
1537
+ const boxMin = box.min;
1538
+ const boxMax = box.max;
1539
+ let min = Infinity;
1540
+ let max = -Infinity;
1541
+ for (let x = 0; x <= 1; x++) {
1542
+ for (let y = 0; y <= 1; y++) {
1543
+ for (let z = 0; z <= 1; z++) {
1544
+ p.x = boxMin.x * x + boxMax.x * (1 - x);
1545
+ p.y = boxMin.y * y + boxMax.y * (1 - y);
1546
+ p.z = boxMin.z * z + boxMax.z * (1 - z);
1547
+ const val = axis.dot(p);
1548
+ min = Math.min(val, min);
1549
+ max = Math.max(val, max);
1550
+ }
1551
+ }
1552
+ }
1553
+ this.min = min;
1554
+ this.max = max;
1555
+ };
1556
+ })();
1557
+
1558
+ // ../../node_modules/three-mesh-bvh/src/math/ExtendedTriangle.js
1559
+ import { Triangle, Vector3 as Vector33, Vector2 as Vector22, Line3 as Line32, Plane as Plane2 } from "three";
1560
+
1561
+ // ../../node_modules/three-mesh-bvh/src/math/MathUtilities.js
1562
+ import { Vector3 as Vector32, Vector2, Plane, Line3 } from "three";
1563
+ var closestPointLineToLine = /* @__PURE__ */ (function() {
1564
+ const dir1 = /* @__PURE__ */ new Vector32();
1565
+ const dir2 = /* @__PURE__ */ new Vector32();
1566
+ const v02 = /* @__PURE__ */ new Vector32();
1567
+ return function closestPointLineToLine2(l1, l2, result) {
1568
+ const v0 = l1.start;
1569
+ const v10 = dir1;
1570
+ const v2 = l2.start;
1571
+ const v32 = dir2;
1572
+ v02.subVectors(v0, v2);
1573
+ dir1.subVectors(l1.end, l1.start);
1574
+ dir2.subVectors(l2.end, l2.start);
1575
+ const d0232 = v02.dot(v32);
1576
+ const d3210 = v32.dot(v10);
1577
+ const d3232 = v32.dot(v32);
1578
+ const d0210 = v02.dot(v10);
1579
+ const d1010 = v10.dot(v10);
1580
+ const denom = d1010 * d3232 - d3210 * d3210;
1581
+ let d, d2;
1582
+ if (denom !== 0) {
1583
+ d = (d0232 * d3210 - d0210 * d3232) / denom;
1584
+ } else {
1585
+ d = 0;
1586
+ }
1587
+ d2 = (d0232 + d * d3210) / d3232;
1588
+ result.x = d;
1589
+ result.y = d2;
1590
+ };
1591
+ })();
1592
+ var closestPointsSegmentToSegment = /* @__PURE__ */ (function() {
1593
+ const paramResult = /* @__PURE__ */ new Vector2();
1594
+ const temp14 = /* @__PURE__ */ new Vector32();
1595
+ const temp23 = /* @__PURE__ */ new Vector32();
1596
+ return function closestPointsSegmentToSegment2(l1, l2, target1, target2) {
1597
+ closestPointLineToLine(l1, l2, paramResult);
1598
+ let d = paramResult.x;
1599
+ let d2 = paramResult.y;
1600
+ if (d >= 0 && d <= 1 && d2 >= 0 && d2 <= 1) {
1601
+ l1.at(d, target1);
1602
+ l2.at(d2, target2);
1603
+ return;
1604
+ } else if (d >= 0 && d <= 1) {
1605
+ if (d2 < 0) {
1606
+ l2.at(0, target2);
1607
+ } else {
1608
+ l2.at(1, target2);
1609
+ }
1610
+ l1.closestPointToPoint(target2, true, target1);
1611
+ return;
1612
+ } else if (d2 >= 0 && d2 <= 1) {
1613
+ if (d < 0) {
1614
+ l1.at(0, target1);
1615
+ } else {
1616
+ l1.at(1, target1);
1617
+ }
1618
+ l2.closestPointToPoint(target1, true, target2);
1619
+ return;
1620
+ } else {
1621
+ let p;
1622
+ if (d < 0) {
1623
+ p = l1.start;
1624
+ } else {
1625
+ p = l1.end;
1626
+ }
1627
+ let p2;
1628
+ if (d2 < 0) {
1629
+ p2 = l2.start;
1630
+ } else {
1631
+ p2 = l2.end;
1632
+ }
1633
+ const closestPoint = temp14;
1634
+ const closestPoint2 = temp23;
1635
+ l1.closestPointToPoint(p2, true, temp14);
1636
+ l2.closestPointToPoint(p, true, temp23);
1637
+ if (closestPoint.distanceToSquared(p2) <= closestPoint2.distanceToSquared(p)) {
1638
+ target1.copy(closestPoint);
1639
+ target2.copy(p2);
1640
+ return;
1641
+ } else {
1642
+ target1.copy(p);
1643
+ target2.copy(closestPoint2);
1644
+ return;
1645
+ }
1646
+ }
1647
+ };
1648
+ })();
1649
+ var sphereIntersectTriangle = /* @__PURE__ */ (function() {
1650
+ const closestPointTemp = /* @__PURE__ */ new Vector32();
1651
+ const projectedPointTemp = /* @__PURE__ */ new Vector32();
1652
+ const planeTemp = /* @__PURE__ */ new Plane();
1653
+ const lineTemp = /* @__PURE__ */ new Line3();
1654
+ return function sphereIntersectTriangle2(sphere, triangle4) {
1655
+ const { radius, center } = sphere;
1656
+ const { a, b, c } = triangle4;
1657
+ lineTemp.start = a;
1658
+ lineTemp.end = b;
1659
+ const closestPoint1 = lineTemp.closestPointToPoint(center, true, closestPointTemp);
1660
+ if (closestPoint1.distanceTo(center) <= radius) return true;
1661
+ lineTemp.start = a;
1662
+ lineTemp.end = c;
1663
+ const closestPoint2 = lineTemp.closestPointToPoint(center, true, closestPointTemp);
1664
+ if (closestPoint2.distanceTo(center) <= radius) return true;
1665
+ lineTemp.start = b;
1666
+ lineTemp.end = c;
1667
+ const closestPoint3 = lineTemp.closestPointToPoint(center, true, closestPointTemp);
1668
+ if (closestPoint3.distanceTo(center) <= radius) return true;
1669
+ const plane = triangle4.getPlane(planeTemp);
1670
+ const dp = Math.abs(plane.distanceToPoint(center));
1671
+ if (dp <= radius) {
1672
+ const pp = plane.projectPoint(center, projectedPointTemp);
1673
+ const cp = triangle4.containsPoint(pp);
1674
+ if (cp) return true;
1675
+ }
1676
+ return false;
1677
+ };
1678
+ })();
1679
+
1680
+ // ../../node_modules/three-mesh-bvh/src/math/ExtendedTriangle.js
1681
+ var componentKeys = ["x", "y", "z"];
1682
+ var ZERO_EPSILON = 1e-15;
1683
+ var ZERO_EPSILON_SQR = ZERO_EPSILON * ZERO_EPSILON;
1684
+ function isNearZero(value) {
1685
+ return Math.abs(value) < ZERO_EPSILON;
1686
+ }
1687
+ var ExtendedTriangle = class extends Triangle {
1688
+ constructor(...args) {
1689
+ super(...args);
1690
+ this.isExtendedTriangle = true;
1691
+ this.satAxes = new Array(4).fill().map(() => new Vector33());
1692
+ this.satBounds = new Array(4).fill().map(() => new SeparatingAxisBounds());
1693
+ this.points = [this.a, this.b, this.c];
1694
+ this.plane = new Plane2();
1695
+ this.isDegenerateIntoSegment = false;
1696
+ this.isDegenerateIntoPoint = false;
1697
+ this.degenerateSegment = new Line32();
1698
+ this.needsUpdate = true;
1699
+ }
1700
+ /**
1701
+ * Returns whether the triangle intersects the given sphere.
1702
+ * @param {Sphere} sphere
1703
+ * @returns {boolean}
1704
+ */
1705
+ intersectsSphere(sphere) {
1706
+ return sphereIntersectTriangle(sphere, this);
1707
+ }
1708
+ update() {
1709
+ const a = this.a;
1710
+ const b = this.b;
1711
+ const c = this.c;
1712
+ const points = this.points;
1713
+ const satAxes = this.satAxes;
1714
+ const satBounds = this.satBounds;
1715
+ const axis0 = satAxes[0];
1716
+ const sab0 = satBounds[0];
1717
+ this.getNormal(axis0);
1718
+ sab0.setFromPoints(axis0, points);
1719
+ const axis1 = satAxes[1];
1720
+ const sab1 = satBounds[1];
1721
+ axis1.subVectors(a, b);
1722
+ sab1.setFromPoints(axis1, points);
1723
+ const axis2 = satAxes[2];
1724
+ const sab2 = satBounds[2];
1725
+ axis2.subVectors(b, c);
1726
+ sab2.setFromPoints(axis2, points);
1727
+ const axis3 = satAxes[3];
1728
+ const sab3 = satBounds[3];
1729
+ axis3.subVectors(c, a);
1730
+ sab3.setFromPoints(axis3, points);
1731
+ const lengthAB = axis1.length();
1732
+ const lengthBC = axis2.length();
1733
+ const lengthCA = axis3.length();
1734
+ this.isDegenerateIntoPoint = false;
1735
+ this.isDegenerateIntoSegment = false;
1736
+ if (lengthAB < ZERO_EPSILON) {
1737
+ if (lengthBC < ZERO_EPSILON || lengthCA < ZERO_EPSILON) {
1738
+ this.isDegenerateIntoPoint = true;
1739
+ } else {
1740
+ this.isDegenerateIntoSegment = true;
1741
+ this.degenerateSegment.start.copy(a);
1742
+ this.degenerateSegment.end.copy(c);
1743
+ }
1744
+ } else if (lengthBC < ZERO_EPSILON) {
1745
+ if (lengthCA < ZERO_EPSILON) {
1746
+ this.isDegenerateIntoPoint = true;
1747
+ } else {
1748
+ this.isDegenerateIntoSegment = true;
1749
+ this.degenerateSegment.start.copy(b);
1750
+ this.degenerateSegment.end.copy(a);
1751
+ }
1752
+ } else if (lengthCA < ZERO_EPSILON) {
1753
+ this.isDegenerateIntoSegment = true;
1754
+ this.degenerateSegment.start.copy(c);
1755
+ this.degenerateSegment.end.copy(b);
1756
+ }
1757
+ this.plane.setFromNormalAndCoplanarPoint(axis0, a);
1758
+ this.needsUpdate = false;
1759
+ }
1760
+ };
1761
+ ExtendedTriangle.prototype.closestPointToSegment = /* @__PURE__ */ (function() {
1762
+ const point1 = /* @__PURE__ */ new Vector33();
1763
+ const point2 = /* @__PURE__ */ new Vector33();
1764
+ const edge = /* @__PURE__ */ new Line32();
1765
+ return function distanceToSegment(segment, target1 = null, target2 = null) {
1766
+ const { start, end } = segment;
1767
+ const points = this.points;
1768
+ let distSq;
1769
+ let closestDistanceSq = Infinity;
1770
+ for (let i = 0; i < 3; i++) {
1771
+ const nexti = (i + 1) % 3;
1772
+ edge.start.copy(points[i]);
1773
+ edge.end.copy(points[nexti]);
1774
+ closestPointsSegmentToSegment(edge, segment, point1, point2);
1775
+ distSq = point1.distanceToSquared(point2);
1776
+ if (distSq < closestDistanceSq) {
1777
+ closestDistanceSq = distSq;
1778
+ if (target1) target1.copy(point1);
1779
+ if (target2) target2.copy(point2);
1780
+ }
1781
+ }
1782
+ this.closestPointToPoint(start, point1);
1783
+ distSq = start.distanceToSquared(point1);
1784
+ if (distSq < closestDistanceSq) {
1785
+ closestDistanceSq = distSq;
1786
+ if (target1) target1.copy(point1);
1787
+ if (target2) target2.copy(start);
1788
+ }
1789
+ this.closestPointToPoint(end, point1);
1790
+ distSq = end.distanceToSquared(point1);
1791
+ if (distSq < closestDistanceSq) {
1792
+ closestDistanceSq = distSq;
1793
+ if (target1) target1.copy(point1);
1794
+ if (target2) target2.copy(end);
1795
+ }
1796
+ return Math.sqrt(closestDistanceSq);
1797
+ };
1798
+ })();
1799
+ ExtendedTriangle.prototype.intersectsTriangle = /* @__PURE__ */ (function() {
1800
+ const saTri2 = /* @__PURE__ */ new ExtendedTriangle();
1801
+ const cachedSatBounds = /* @__PURE__ */ new SeparatingAxisBounds();
1802
+ const cachedSatBounds2 = /* @__PURE__ */ new SeparatingAxisBounds();
1803
+ const tmpVec = /* @__PURE__ */ new Vector33();
1804
+ const dir1 = /* @__PURE__ */ new Vector33();
1805
+ const dir2 = /* @__PURE__ */ new Vector33();
1806
+ const tempDir = /* @__PURE__ */ new Vector33();
1807
+ const edge1 = /* @__PURE__ */ new Line32();
1808
+ const edge2 = /* @__PURE__ */ new Line32();
1809
+ const tempPoint = /* @__PURE__ */ new Vector33();
1810
+ const bounds1 = /* @__PURE__ */ new Vector22();
1811
+ const bounds2 = /* @__PURE__ */ new Vector22();
1812
+ function coplanarIntersectsTriangle(self, other, target, suppressLog) {
1813
+ const planeNormal = tmpVec;
1814
+ if (!self.isDegenerateIntoPoint && !self.isDegenerateIntoSegment) {
1815
+ planeNormal.copy(self.plane.normal);
1816
+ } else {
1817
+ planeNormal.copy(other.plane.normal);
1818
+ }
1819
+ const satBounds1 = self.satBounds;
1820
+ const satAxes1 = self.satAxes;
1821
+ for (let i = 1; i < 4; i++) {
1822
+ const sb = satBounds1[i];
1823
+ const sa = satAxes1[i];
1824
+ cachedSatBounds.setFromPoints(sa, other.points);
1825
+ if (sb.isSeparated(cachedSatBounds)) return false;
1826
+ tempDir.copy(planeNormal).cross(sa);
1827
+ cachedSatBounds.setFromPoints(tempDir, self.points);
1828
+ cachedSatBounds2.setFromPoints(tempDir, other.points);
1829
+ if (cachedSatBounds.isSeparated(cachedSatBounds2)) return false;
1830
+ }
1831
+ const satBounds2 = other.satBounds;
1832
+ const satAxes2 = other.satAxes;
1833
+ for (let i = 1; i < 4; i++) {
1834
+ const sb = satBounds2[i];
1835
+ const sa = satAxes2[i];
1836
+ cachedSatBounds.setFromPoints(sa, self.points);
1837
+ if (sb.isSeparated(cachedSatBounds)) return false;
1838
+ tempDir.crossVectors(planeNormal, sa);
1839
+ cachedSatBounds.setFromPoints(tempDir, self.points);
1840
+ cachedSatBounds2.setFromPoints(tempDir, other.points);
1841
+ if (cachedSatBounds.isSeparated(cachedSatBounds2)) return false;
1842
+ }
1843
+ if (target) {
1844
+ if (!suppressLog) {
1845
+ console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0.");
1846
+ }
1847
+ target.start.set(0, 0, 0);
1848
+ target.end.set(0, 0, 0);
1849
+ }
1850
+ return true;
1851
+ }
1852
+ function findSingleBounds(a, b, c, aProj, bProj, cProj, aDist, bDist, cDist, bounds, edge) {
1853
+ let t = aDist / (aDist - bDist);
1854
+ bounds.x = aProj + (bProj - aProj) * t;
1855
+ edge.start.subVectors(b, a).multiplyScalar(t).add(a);
1856
+ t = aDist / (aDist - cDist);
1857
+ bounds.y = aProj + (cProj - aProj) * t;
1858
+ edge.end.subVectors(c, a).multiplyScalar(t).add(a);
1859
+ }
1860
+ function findIntersectionLineBounds(self, aProj, bProj, cProj, abDist, acDist, aDist, bDist, cDist, bounds, edge) {
1861
+ if (abDist > 0) {
1862
+ findSingleBounds(self.c, self.a, self.b, cProj, aProj, bProj, cDist, aDist, bDist, bounds, edge);
1863
+ } else if (acDist > 0) {
1864
+ findSingleBounds(self.b, self.a, self.c, bProj, aProj, cProj, bDist, aDist, cDist, bounds, edge);
1865
+ } else if (bDist * cDist > 0 || aDist != 0) {
1866
+ findSingleBounds(self.a, self.b, self.c, aProj, bProj, cProj, aDist, bDist, cDist, bounds, edge);
1867
+ } else if (bDist != 0) {
1868
+ findSingleBounds(self.b, self.a, self.c, bProj, aProj, cProj, bDist, aDist, cDist, bounds, edge);
1869
+ } else if (cDist != 0) {
1870
+ findSingleBounds(self.c, self.a, self.b, cProj, aProj, bProj, cDist, aDist, bDist, bounds, edge);
1871
+ } else {
1872
+ return true;
1873
+ }
1874
+ return false;
1875
+ }
1876
+ function intersectTriangleSegment(triangle4, degenerateTriangle, target, suppressLog) {
1877
+ const segment = degenerateTriangle.degenerateSegment;
1878
+ const startDist = triangle4.plane.distanceToPoint(segment.start);
1879
+ const endDist = triangle4.plane.distanceToPoint(segment.end);
1880
+ if (isNearZero(startDist)) {
1881
+ if (isNearZero(endDist)) {
1882
+ return coplanarIntersectsTriangle(triangle4, degenerateTriangle, target, suppressLog);
1883
+ } else {
1884
+ if (target) {
1885
+ target.start.copy(segment.start);
1886
+ target.end.copy(segment.start);
1887
+ }
1888
+ return triangle4.containsPoint(segment.start);
1889
+ }
1890
+ } else if (isNearZero(endDist)) {
1891
+ if (target) {
1892
+ target.start.copy(segment.end);
1893
+ target.end.copy(segment.end);
1894
+ }
1895
+ return triangle4.containsPoint(segment.end);
1896
+ } else {
1897
+ if (triangle4.plane.intersectLine(segment, tmpVec) != null) {
1898
+ if (target) {
1899
+ target.start.copy(tmpVec);
1900
+ target.end.copy(tmpVec);
1901
+ }
1902
+ return triangle4.containsPoint(tmpVec);
1903
+ } else {
1904
+ return false;
1905
+ }
1906
+ }
1907
+ }
1908
+ function intersectTrianglePoint(triangle4, degenerateTriangle, target) {
1909
+ const point = degenerateTriangle.a;
1910
+ if (isNearZero(triangle4.plane.distanceToPoint(point)) && triangle4.containsPoint(point)) {
1911
+ if (target) {
1912
+ target.start.copy(point);
1913
+ target.end.copy(point);
1914
+ }
1915
+ return true;
1916
+ } else {
1917
+ return false;
1918
+ }
1919
+ }
1920
+ function intersectSegmentPoint(segmentTri, pointTri, target) {
1921
+ const segment = segmentTri.degenerateSegment;
1922
+ const point = pointTri.a;
1923
+ segment.closestPointToPoint(point, true, tmpVec);
1924
+ if (point.distanceToSquared(tmpVec) < ZERO_EPSILON_SQR) {
1925
+ if (target) {
1926
+ target.start.copy(point);
1927
+ target.end.copy(point);
1928
+ }
1929
+ return true;
1930
+ } else {
1931
+ return false;
1932
+ }
1933
+ }
1934
+ function handleDegenerateCases(self, other, target, suppressLog) {
1935
+ if (self.isDegenerateIntoSegment) {
1936
+ if (other.isDegenerateIntoSegment) {
1937
+ const segment1 = self.degenerateSegment;
1938
+ const segment2 = other.degenerateSegment;
1939
+ const delta1 = dir1;
1940
+ const delta2 = dir2;
1941
+ segment1.delta(delta1);
1942
+ segment2.delta(delta2);
1943
+ const startDelta = tmpVec.subVectors(segment2.start, segment1.start);
1944
+ const denom = delta1.x * delta2.y - delta1.y * delta2.x;
1945
+ if (isNearZero(denom)) {
1946
+ return false;
1947
+ }
1948
+ const t = (startDelta.x * delta2.y - startDelta.y * delta2.x) / denom;
1949
+ const u = -(delta1.x * startDelta.y - delta1.y * startDelta.x) / denom;
1950
+ if (t < 0 || t > 1 || u < 0 || u > 1) {
1951
+ return false;
1952
+ }
1953
+ const z1 = segment1.start.z + delta1.z * t;
1954
+ const z2 = segment2.start.z + delta2.z * u;
1955
+ if (isNearZero(z1 - z2)) {
1956
+ if (target) {
1957
+ target.start.copy(segment1.start).addScaledVector(delta1, t);
1958
+ target.end.copy(segment1.start).addScaledVector(delta1, t);
1959
+ }
1960
+ return true;
1961
+ } else {
1962
+ return false;
1963
+ }
1964
+ } else if (other.isDegenerateIntoPoint) {
1965
+ return intersectSegmentPoint(self, other, target);
1966
+ } else {
1967
+ return intersectTriangleSegment(other, self, target, suppressLog);
1968
+ }
1969
+ } else if (self.isDegenerateIntoPoint) {
1970
+ if (other.isDegenerateIntoPoint) {
1971
+ if (other.a.distanceToSquared(self.a) < ZERO_EPSILON_SQR) {
1972
+ if (target) {
1973
+ target.start.copy(self.a);
1974
+ target.end.copy(self.a);
1975
+ }
1976
+ return true;
1977
+ } else {
1978
+ return false;
1979
+ }
1980
+ } else if (other.isDegenerateIntoSegment) {
1981
+ return intersectSegmentPoint(other, self, target);
1982
+ } else {
1983
+ return intersectTrianglePoint(other, self, target);
1984
+ }
1985
+ } else {
1986
+ if (other.isDegenerateIntoPoint) {
1987
+ return intersectTrianglePoint(self, other, target);
1988
+ } else if (other.isDegenerateIntoSegment) {
1989
+ return intersectTriangleSegment(self, other, target, suppressLog);
1990
+ }
1991
+ }
1992
+ }
1993
+ return function intersectsTriangle(other, target = null, suppressLog = false) {
1994
+ if (this.needsUpdate) {
1995
+ this.update();
1996
+ }
1997
+ if (!other.isExtendedTriangle) {
1998
+ saTri2.copy(other);
1999
+ saTri2.update();
2000
+ other = saTri2;
2001
+ } else if (other.needsUpdate) {
2002
+ other.update();
2003
+ }
2004
+ const res = handleDegenerateCases(this, other, target, suppressLog);
2005
+ if (res !== void 0) {
2006
+ return res;
2007
+ }
2008
+ const plane1 = this.plane;
2009
+ const plane2 = other.plane;
2010
+ let a1Dist = plane2.distanceToPoint(this.a);
2011
+ let b1Dist = plane2.distanceToPoint(this.b);
2012
+ let c1Dist = plane2.distanceToPoint(this.c);
2013
+ if (isNearZero(a1Dist))
2014
+ a1Dist = 0;
2015
+ if (isNearZero(b1Dist))
2016
+ b1Dist = 0;
2017
+ if (isNearZero(c1Dist))
2018
+ c1Dist = 0;
2019
+ const a1b1Dist = a1Dist * b1Dist;
2020
+ const a1c1Dist = a1Dist * c1Dist;
2021
+ if (a1b1Dist > 0 && a1c1Dist > 0) {
2022
+ return false;
2023
+ }
2024
+ let a2Dist = plane1.distanceToPoint(other.a);
2025
+ let b2Dist = plane1.distanceToPoint(other.b);
2026
+ let c2Dist = plane1.distanceToPoint(other.c);
2027
+ if (isNearZero(a2Dist))
2028
+ a2Dist = 0;
2029
+ if (isNearZero(b2Dist))
2030
+ b2Dist = 0;
2031
+ if (isNearZero(c2Dist))
2032
+ c2Dist = 0;
2033
+ const a2b2Dist = a2Dist * b2Dist;
2034
+ const a2c2Dist = a2Dist * c2Dist;
2035
+ if (a2b2Dist > 0 && a2c2Dist > 0) {
2036
+ return false;
2037
+ }
2038
+ dir1.copy(plane1.normal);
2039
+ dir2.copy(plane2.normal);
2040
+ const intersectionLine = dir1.cross(dir2);
2041
+ let componentIndex = 0;
2042
+ let maxComponent = Math.abs(intersectionLine.x);
2043
+ const comp1 = Math.abs(intersectionLine.y);
2044
+ if (comp1 > maxComponent) {
2045
+ maxComponent = comp1;
2046
+ componentIndex = 1;
2047
+ }
2048
+ const comp2 = Math.abs(intersectionLine.z);
2049
+ if (comp2 > maxComponent) {
2050
+ componentIndex = 2;
2051
+ }
2052
+ const key = componentKeys[componentIndex];
2053
+ const a1Proj = this.a[key];
2054
+ const b1Proj = this.b[key];
2055
+ const c1Proj = this.c[key];
2056
+ const a2Proj = other.a[key];
2057
+ const b2Proj = other.b[key];
2058
+ const c2Proj = other.c[key];
2059
+ if (findIntersectionLineBounds(this, a1Proj, b1Proj, c1Proj, a1b1Dist, a1c1Dist, a1Dist, b1Dist, c1Dist, bounds1, edge1)) {
2060
+ return coplanarIntersectsTriangle(this, other, target, suppressLog);
2061
+ }
2062
+ if (findIntersectionLineBounds(other, a2Proj, b2Proj, c2Proj, a2b2Dist, a2c2Dist, a2Dist, b2Dist, c2Dist, bounds2, edge2)) {
2063
+ return coplanarIntersectsTriangle(this, other, target, suppressLog);
2064
+ }
2065
+ if (bounds1.y < bounds1.x) {
2066
+ const tmp = bounds1.y;
2067
+ bounds1.y = bounds1.x;
2068
+ bounds1.x = tmp;
2069
+ tempPoint.copy(edge1.start);
2070
+ edge1.start.copy(edge1.end);
2071
+ edge1.end.copy(tempPoint);
2072
+ }
2073
+ if (bounds2.y < bounds2.x) {
2074
+ const tmp = bounds2.y;
2075
+ bounds2.y = bounds2.x;
2076
+ bounds2.x = tmp;
2077
+ tempPoint.copy(edge2.start);
2078
+ edge2.start.copy(edge2.end);
2079
+ edge2.end.copy(tempPoint);
2080
+ }
2081
+ if (bounds1.y < bounds2.x || bounds2.y < bounds1.x) {
2082
+ return false;
2083
+ }
2084
+ if (target) {
2085
+ if (bounds2.x > bounds1.x) {
2086
+ target.start.copy(edge2.start);
2087
+ } else {
2088
+ target.start.copy(edge1.start);
2089
+ }
2090
+ if (bounds2.y < bounds1.y) {
2091
+ target.end.copy(edge2.end);
2092
+ } else {
2093
+ target.end.copy(edge1.end);
2094
+ }
2095
+ }
2096
+ return true;
2097
+ };
2098
+ })();
2099
+ ExtendedTriangle.prototype.distanceToPoint = /* @__PURE__ */ (function() {
2100
+ const target = /* @__PURE__ */ new Vector33();
2101
+ return function distanceToPoint(point) {
2102
+ this.closestPointToPoint(point, target);
2103
+ return point.distanceTo(target);
2104
+ };
2105
+ })();
2106
+ ExtendedTriangle.prototype.distanceToTriangle = /* @__PURE__ */ (function() {
2107
+ const point = /* @__PURE__ */ new Vector33();
2108
+ const point2 = /* @__PURE__ */ new Vector33();
2109
+ const cornerFields = ["a", "b", "c"];
2110
+ const line1 = /* @__PURE__ */ new Line32();
2111
+ const line2 = /* @__PURE__ */ new Line32();
2112
+ return function distanceToTriangle(other, target1 = null, target2 = null) {
2113
+ const lineTarget = target1 || target2 ? line1 : null;
2114
+ if (this.intersectsTriangle(other, lineTarget, true)) {
2115
+ if (target1 || target2) {
2116
+ if (target1) lineTarget.getCenter(target1);
2117
+ if (target2) lineTarget.getCenter(target2);
2118
+ }
2119
+ return 0;
2120
+ }
2121
+ let closestDistanceSq = Infinity;
2122
+ for (let i = 0; i < 3; i++) {
2123
+ let dist;
2124
+ const field = cornerFields[i];
2125
+ const otherVec = other[field];
2126
+ this.closestPointToPoint(otherVec, point);
2127
+ dist = otherVec.distanceToSquared(point);
2128
+ if (dist < closestDistanceSq) {
2129
+ closestDistanceSq = dist;
2130
+ if (target1) target1.copy(point);
2131
+ if (target2) target2.copy(otherVec);
2132
+ }
2133
+ const thisVec = this[field];
2134
+ other.closestPointToPoint(thisVec, point);
2135
+ dist = thisVec.distanceToSquared(point);
2136
+ if (dist < closestDistanceSq) {
2137
+ closestDistanceSq = dist;
2138
+ if (target1) target1.copy(thisVec);
2139
+ if (target2) target2.copy(point);
2140
+ }
2141
+ }
2142
+ for (let i = 0; i < 3; i++) {
2143
+ const f11 = cornerFields[i];
2144
+ const f12 = cornerFields[(i + 1) % 3];
2145
+ line1.set(this[f11], this[f12]);
2146
+ for (let i2 = 0; i2 < 3; i2++) {
2147
+ const f21 = cornerFields[i2];
2148
+ const f22 = cornerFields[(i2 + 1) % 3];
2149
+ line2.set(other[f21], other[f22]);
2150
+ closestPointsSegmentToSegment(line1, line2, point, point2);
2151
+ const dist = point.distanceToSquared(point2);
2152
+ if (dist < closestDistanceSq) {
2153
+ closestDistanceSq = dist;
2154
+ if (target1) target1.copy(point);
2155
+ if (target2) target2.copy(point2);
2156
+ }
2157
+ }
2158
+ }
2159
+ return Math.sqrt(closestDistanceSq);
2160
+ };
2161
+ })();
2162
+
2163
+ // ../../node_modules/three-mesh-bvh/src/math/OrientedBox.js
2164
+ var OrientedBox = class {
2165
+ constructor(min, max, matrix) {
2166
+ this.isOrientedBox = true;
2167
+ this.min = new Vector34();
2168
+ this.max = new Vector34();
2169
+ this.matrix = new Matrix42();
2170
+ this.invMatrix = new Matrix42();
2171
+ this.points = new Array(8).fill().map(() => new Vector34());
2172
+ this.satAxes = new Array(3).fill().map(() => new Vector34());
2173
+ this.satBounds = new Array(3).fill().map(() => new SeparatingAxisBounds());
2174
+ this.alignedSatBounds = new Array(3).fill().map(() => new SeparatingAxisBounds());
2175
+ this.needsUpdate = false;
2176
+ if (min) this.min.copy(min);
2177
+ if (max) this.max.copy(max);
2178
+ if (matrix) this.matrix.copy(matrix);
2179
+ }
2180
+ /**
2181
+ * Sets the oriented box parameters.
2182
+ * @param {Vector3} min
2183
+ * @param {Vector3} max
2184
+ * @param {Matrix4} matrix
2185
+ */
2186
+ set(min, max, matrix) {
2187
+ this.min.copy(min);
2188
+ this.max.copy(max);
2189
+ this.matrix.copy(matrix);
2190
+ this.needsUpdate = true;
2191
+ }
2192
+ copy(other) {
2193
+ this.min.copy(other.min);
2194
+ this.max.copy(other.max);
2195
+ this.matrix.copy(other.matrix);
2196
+ this.needsUpdate = true;
2197
+ }
2198
+ };
2199
+ OrientedBox.prototype.update = /* @__PURE__ */ (function() {
2200
+ return function update() {
2201
+ const matrix = this.matrix;
2202
+ const min = this.min;
2203
+ const max = this.max;
2204
+ const points = this.points;
2205
+ for (let x = 0; x <= 1; x++) {
2206
+ for (let y = 0; y <= 1; y++) {
2207
+ for (let z = 0; z <= 1; z++) {
2208
+ const i = (1 << 0) * x | (1 << 1) * y | (1 << 2) * z;
2209
+ const v = points[i];
2210
+ v.x = x ? max.x : min.x;
2211
+ v.y = y ? max.y : min.y;
2212
+ v.z = z ? max.z : min.z;
2213
+ v.applyMatrix4(matrix);
2214
+ }
2215
+ }
2216
+ }
2217
+ const satBounds = this.satBounds;
2218
+ const satAxes = this.satAxes;
2219
+ const minVec = points[0];
2220
+ for (let i = 0; i < 3; i++) {
2221
+ const axis = satAxes[i];
2222
+ const sb = satBounds[i];
2223
+ const index = 1 << i;
2224
+ const pi = points[index];
2225
+ axis.subVectors(minVec, pi);
2226
+ sb.setFromPoints(axis, points);
2227
+ }
2228
+ const alignedSatBounds = this.alignedSatBounds;
2229
+ alignedSatBounds[0].setFromPointsField(points, "x");
2230
+ alignedSatBounds[1].setFromPointsField(points, "y");
2231
+ alignedSatBounds[2].setFromPointsField(points, "z");
2232
+ this.invMatrix.copy(this.matrix).invert();
2233
+ this.needsUpdate = false;
2234
+ };
2235
+ })();
2236
+ OrientedBox.prototype.intersectsBox = /* @__PURE__ */ (function() {
2237
+ const aabbBounds = /* @__PURE__ */ new SeparatingAxisBounds();
2238
+ return function intersectsBox(box) {
2239
+ if (this.needsUpdate) {
2240
+ this.update();
2241
+ }
2242
+ const min = box.min;
2243
+ const max = box.max;
2244
+ const satBounds = this.satBounds;
2245
+ const satAxes = this.satAxes;
2246
+ const alignedSatBounds = this.alignedSatBounds;
2247
+ aabbBounds.min = min.x;
2248
+ aabbBounds.max = max.x;
2249
+ if (alignedSatBounds[0].isSeparated(aabbBounds)) return false;
2250
+ aabbBounds.min = min.y;
2251
+ aabbBounds.max = max.y;
2252
+ if (alignedSatBounds[1].isSeparated(aabbBounds)) return false;
2253
+ aabbBounds.min = min.z;
2254
+ aabbBounds.max = max.z;
2255
+ if (alignedSatBounds[2].isSeparated(aabbBounds)) return false;
2256
+ for (let i = 0; i < 3; i++) {
2257
+ const axis = satAxes[i];
2258
+ const sb = satBounds[i];
2259
+ aabbBounds.setFromBox(axis, box);
2260
+ if (sb.isSeparated(aabbBounds)) return false;
2261
+ }
2262
+ return true;
2263
+ };
2264
+ })();
2265
+ OrientedBox.prototype.intersectsTriangle = /* @__PURE__ */ (function() {
2266
+ const saTri = /* @__PURE__ */ new ExtendedTriangle();
2267
+ const pointsArr = /* @__PURE__ */ new Array(3);
2268
+ const cachedSatBounds = /* @__PURE__ */ new SeparatingAxisBounds();
2269
+ const cachedSatBounds2 = /* @__PURE__ */ new SeparatingAxisBounds();
2270
+ const cachedAxis = /* @__PURE__ */ new Vector34();
2271
+ return function intersectsTriangle(triangle4) {
2272
+ if (this.needsUpdate) {
2273
+ this.update();
2274
+ }
2275
+ if (!triangle4.isExtendedTriangle) {
2276
+ saTri.copy(triangle4);
2277
+ saTri.update();
2278
+ triangle4 = saTri;
2279
+ } else if (triangle4.needsUpdate) {
2280
+ triangle4.update();
2281
+ }
2282
+ const satBounds = this.satBounds;
2283
+ const satAxes = this.satAxes;
2284
+ pointsArr[0] = triangle4.a;
2285
+ pointsArr[1] = triangle4.b;
2286
+ pointsArr[2] = triangle4.c;
2287
+ for (let i = 0; i < 3; i++) {
2288
+ const sb = satBounds[i];
2289
+ const sa = satAxes[i];
2290
+ cachedSatBounds.setFromPoints(sa, pointsArr);
2291
+ if (sb.isSeparated(cachedSatBounds)) return false;
2292
+ }
2293
+ const triSatBounds = triangle4.satBounds;
2294
+ const triSatAxes = triangle4.satAxes;
2295
+ const points = this.points;
2296
+ for (let i = 0; i < 3; i++) {
2297
+ const sb = triSatBounds[i];
2298
+ const sa = triSatAxes[i];
2299
+ cachedSatBounds.setFromPoints(sa, points);
2300
+ if (sb.isSeparated(cachedSatBounds)) return false;
2301
+ }
2302
+ for (let i = 0; i < 3; i++) {
2303
+ const sa1 = satAxes[i];
2304
+ for (let i2 = 0; i2 < 4; i2++) {
2305
+ const sa2 = triSatAxes[i2];
2306
+ cachedAxis.crossVectors(sa1, sa2);
2307
+ cachedSatBounds.setFromPoints(cachedAxis, pointsArr);
2308
+ cachedSatBounds2.setFromPoints(cachedAxis, points);
2309
+ if (cachedSatBounds.isSeparated(cachedSatBounds2)) return false;
2310
+ }
2311
+ }
2312
+ return true;
2313
+ };
2314
+ })();
2315
+ OrientedBox.prototype.closestPointToPoint = /* @__PURE__ */ (function() {
2316
+ return function closestPointToPoint2(point, target1) {
2317
+ if (this.needsUpdate) {
2318
+ this.update();
2319
+ }
2320
+ target1.copy(point).applyMatrix4(this.invMatrix).clamp(this.min, this.max).applyMatrix4(this.matrix);
2321
+ return target1;
2322
+ };
2323
+ })();
2324
+ OrientedBox.prototype.distanceToPoint = (function() {
2325
+ const target = new Vector34();
2326
+ return function distanceToPoint(point) {
2327
+ this.closestPointToPoint(point, target);
2328
+ return point.distanceTo(target);
2329
+ };
2330
+ })();
2331
+ OrientedBox.prototype.distanceToBox = /* @__PURE__ */ (function() {
2332
+ const xyzFields = ["x", "y", "z"];
2333
+ const segments1 = /* @__PURE__ */ new Array(12).fill().map(() => new Line33());
2334
+ const segments2 = /* @__PURE__ */ new Array(12).fill().map(() => new Line33());
2335
+ const point1 = /* @__PURE__ */ new Vector34();
2336
+ const point2 = /* @__PURE__ */ new Vector34();
2337
+ return function distanceToBox(box, threshold = 0, target1 = null, target2 = null) {
2338
+ if (this.needsUpdate) {
2339
+ this.update();
2340
+ }
2341
+ if (this.intersectsBox(box)) {
2342
+ if (target1 || target2) {
2343
+ box.getCenter(point2);
2344
+ this.closestPointToPoint(point2, point1);
2345
+ box.closestPointToPoint(point1, point2);
2346
+ if (target1) target1.copy(point1);
2347
+ if (target2) target2.copy(point2);
2348
+ }
2349
+ return 0;
2350
+ }
2351
+ const threshold2 = threshold * threshold;
2352
+ const min = box.min;
2353
+ const max = box.max;
2354
+ const points = this.points;
2355
+ let closestDistanceSq = Infinity;
2356
+ for (let i = 0; i < 8; i++) {
2357
+ const p = points[i];
2358
+ point2.copy(p).clamp(min, max);
2359
+ const dist = p.distanceToSquared(point2);
2360
+ if (dist < closestDistanceSq) {
2361
+ closestDistanceSq = dist;
2362
+ if (target1) target1.copy(p);
2363
+ if (target2) target2.copy(point2);
2364
+ if (dist < threshold2) return Math.sqrt(dist);
2365
+ }
2366
+ }
2367
+ let count = 0;
2368
+ for (let i = 0; i < 3; i++) {
2369
+ for (let i1 = 0; i1 <= 1; i1++) {
2370
+ for (let i2 = 0; i2 <= 1; i2++) {
2371
+ const nextIndex = (i + 1) % 3;
2372
+ const nextIndex2 = (i + 2) % 3;
2373
+ const index = i1 << nextIndex | i2 << nextIndex2;
2374
+ const index2 = 1 << i | i1 << nextIndex | i2 << nextIndex2;
2375
+ const p1 = points[index];
2376
+ const p2 = points[index2];
2377
+ const line1 = segments1[count];
2378
+ line1.set(p1, p2);
2379
+ const f1 = xyzFields[i];
2380
+ const f2 = xyzFields[nextIndex];
2381
+ const f3 = xyzFields[nextIndex2];
2382
+ const line2 = segments2[count];
2383
+ const start = line2.start;
2384
+ const end = line2.end;
2385
+ start[f1] = min[f1];
2386
+ start[f2] = i1 ? min[f2] : max[f2];
2387
+ start[f3] = i2 ? min[f3] : max[f2];
2388
+ end[f1] = max[f1];
2389
+ end[f2] = i1 ? min[f2] : max[f2];
2390
+ end[f3] = i2 ? min[f3] : max[f2];
2391
+ count++;
2392
+ }
2393
+ }
2394
+ }
2395
+ for (let x = 0; x <= 1; x++) {
2396
+ for (let y = 0; y <= 1; y++) {
2397
+ for (let z = 0; z <= 1; z++) {
2398
+ point2.x = x ? max.x : min.x;
2399
+ point2.y = y ? max.y : min.y;
2400
+ point2.z = z ? max.z : min.z;
2401
+ this.closestPointToPoint(point2, point1);
2402
+ const dist = point2.distanceToSquared(point1);
2403
+ if (dist < closestDistanceSq) {
2404
+ closestDistanceSq = dist;
2405
+ if (target1) target1.copy(point1);
2406
+ if (target2) target2.copy(point2);
2407
+ if (dist < threshold2) return Math.sqrt(dist);
2408
+ }
2409
+ }
2410
+ }
2411
+ }
2412
+ for (let i = 0; i < 12; i++) {
2413
+ const l1 = segments1[i];
2414
+ for (let i2 = 0; i2 < 12; i2++) {
2415
+ const l2 = segments2[i2];
2416
+ closestPointsSegmentToSegment(l1, l2, point1, point2);
2417
+ const dist = point1.distanceToSquared(point2);
2418
+ if (dist < closestDistanceSq) {
2419
+ closestDistanceSq = dist;
2420
+ if (target1) target1.copy(point1);
2421
+ if (target2) target2.copy(point2);
2422
+ if (dist < threshold2) return Math.sqrt(dist);
2423
+ }
2424
+ }
2425
+ }
2426
+ return Math.sqrt(closestDistanceSq);
2427
+ };
2428
+ })();
2429
+
2430
+ // ../../node_modules/three-mesh-bvh/src/utils/ExtendedTrianglePool.js
2431
+ var ExtendedTrianglePoolBase = class extends PrimitivePool {
2432
+ constructor() {
2433
+ super(() => new ExtendedTriangle());
2434
+ }
2435
+ };
2436
+ var ExtendedTrianglePool = /* @__PURE__ */ new ExtendedTrianglePoolBase();
2437
+
2438
+ // ../../node_modules/three-mesh-bvh/src/core/cast/closestPointToPoint.js
2439
+ import { Vector3 as Vector35 } from "three";
2440
+ var temp = /* @__PURE__ */ new Vector35();
2441
+ var temp1 = /* @__PURE__ */ new Vector35();
2442
+ function closestPointToPoint(bvh, point, target = {}, minThreshold = 0, maxThreshold = Infinity) {
2443
+ const minThresholdSq = minThreshold * minThreshold;
2444
+ const maxThresholdSq = maxThreshold * maxThreshold;
2445
+ let closestDistanceSq = Infinity;
2446
+ let closestDistanceTriIndex = null;
2447
+ bvh.shapecast(
2448
+ {
2449
+ boundsTraverseOrder: (box) => {
2450
+ temp.copy(point).clamp(box.min, box.max);
2451
+ return temp.distanceToSquared(point);
2452
+ },
2453
+ intersectsBounds: (box, isLeaf, score) => {
2454
+ return score < closestDistanceSq && score < maxThresholdSq;
2455
+ },
2456
+ intersectsTriangle: (tri, triIndex) => {
2457
+ tri.closestPointToPoint(point, temp);
2458
+ const distSq = point.distanceToSquared(temp);
2459
+ if (distSq < closestDistanceSq) {
2460
+ temp1.copy(temp);
2461
+ closestDistanceSq = distSq;
2462
+ closestDistanceTriIndex = triIndex;
2463
+ }
2464
+ if (distSq < minThresholdSq) {
2465
+ return true;
2466
+ } else {
2467
+ return false;
2468
+ }
2469
+ }
2470
+ }
2471
+ );
2472
+ if (closestDistanceSq === Infinity) return null;
2473
+ const closestDistance = Math.sqrt(closestDistanceSq);
2474
+ if (!target.point) target.point = temp1.clone();
2475
+ else target.point.copy(temp1);
2476
+ target.distance = closestDistance, target.faceIndex = closestDistanceTriIndex;
2477
+ return target;
2478
+ }
2479
+
2480
+ // ../../node_modules/three-mesh-bvh/src/utils/ThreeRayIntersectUtilities.js
2481
+ import { Vector3 as Vector36, Vector2 as Vector23, Triangle as Triangle2, DoubleSide, BackSide, REVISION } from "three";
2482
+ var IS_GT_REVISION_169 = parseInt(REVISION) >= 169;
2483
+ var IS_LT_REVISION_161 = parseInt(REVISION) <= 161;
2484
+ var _vA = /* @__PURE__ */ new Vector36();
2485
+ var _vB = /* @__PURE__ */ new Vector36();
2486
+ var _vC = /* @__PURE__ */ new Vector36();
2487
+ var _uvA = /* @__PURE__ */ new Vector23();
2488
+ var _uvB = /* @__PURE__ */ new Vector23();
2489
+ var _uvC = /* @__PURE__ */ new Vector23();
2490
+ var _normalA = /* @__PURE__ */ new Vector36();
2491
+ var _normalB = /* @__PURE__ */ new Vector36();
2492
+ var _normalC = /* @__PURE__ */ new Vector36();
2493
+ var _intersectionPoint = /* @__PURE__ */ new Vector36();
2494
+ function checkIntersection(ray, pA, pB, pC, point, side, near, far) {
2495
+ let intersect;
2496
+ if (side === BackSide) {
2497
+ intersect = ray.intersectTriangle(pC, pB, pA, true, point);
2498
+ } else {
2499
+ intersect = ray.intersectTriangle(pA, pB, pC, side !== DoubleSide, point);
2500
+ }
2501
+ if (intersect === null) return null;
2502
+ const distance = ray.origin.distanceTo(point);
2503
+ if (distance < near || distance > far) return null;
2504
+ return {
2505
+ distance,
2506
+ point: point.clone()
2507
+ };
2508
+ }
2509
+ function checkBufferGeometryIntersection(ray, position, normal, uv, uv1, a, b, c, side, near, far) {
2510
+ _vA.fromBufferAttribute(position, a);
2511
+ _vB.fromBufferAttribute(position, b);
2512
+ _vC.fromBufferAttribute(position, c);
2513
+ const intersection = checkIntersection(ray, _vA, _vB, _vC, _intersectionPoint, side, near, far);
2514
+ if (intersection) {
2515
+ if (uv) {
2516
+ _uvA.fromBufferAttribute(uv, a);
2517
+ _uvB.fromBufferAttribute(uv, b);
2518
+ _uvC.fromBufferAttribute(uv, c);
2519
+ intersection.uv = new Vector23();
2520
+ const res = Triangle2.getInterpolation(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, intersection.uv);
2521
+ if (!IS_GT_REVISION_169) {
2522
+ intersection.uv = res;
2523
+ }
2524
+ }
2525
+ if (uv1) {
2526
+ _uvA.fromBufferAttribute(uv1, a);
2527
+ _uvB.fromBufferAttribute(uv1, b);
2528
+ _uvC.fromBufferAttribute(uv1, c);
2529
+ intersection.uv1 = new Vector23();
2530
+ const res = Triangle2.getInterpolation(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, intersection.uv1);
2531
+ if (!IS_GT_REVISION_169) {
2532
+ intersection.uv1 = res;
2533
+ }
2534
+ if (IS_LT_REVISION_161) {
2535
+ intersection.uv2 = intersection.uv1;
2536
+ }
2537
+ }
2538
+ if (normal) {
2539
+ _normalA.fromBufferAttribute(normal, a);
2540
+ _normalB.fromBufferAttribute(normal, b);
2541
+ _normalC.fromBufferAttribute(normal, c);
2542
+ intersection.normal = new Vector36();
2543
+ const res = Triangle2.getInterpolation(_intersectionPoint, _vA, _vB, _vC, _normalA, _normalB, _normalC, intersection.normal);
2544
+ if (intersection.normal.dot(ray.direction) > 0) {
2545
+ intersection.normal.multiplyScalar(-1);
2546
+ }
2547
+ if (!IS_GT_REVISION_169) {
2548
+ intersection.normal = res;
2549
+ }
2550
+ }
2551
+ const face = {
2552
+ a,
2553
+ b,
2554
+ c,
2555
+ normal: new Vector36(),
2556
+ materialIndex: 0
2557
+ };
2558
+ Triangle2.getNormal(_vA, _vB, _vC, face.normal);
2559
+ intersection.face = face;
2560
+ intersection.faceIndex = a;
2561
+ if (IS_GT_REVISION_169) {
2562
+ const barycoord = new Vector36();
2563
+ Triangle2.getBarycoord(_intersectionPoint, _vA, _vB, _vC, barycoord);
2564
+ intersection.barycoord = barycoord;
2565
+ }
2566
+ }
2567
+ return intersection;
2568
+ }
2569
+ function getSide(materialOrSide) {
2570
+ return materialOrSide && materialOrSide.isMaterial ? materialOrSide.side : materialOrSide;
2571
+ }
2572
+ function intersectTri(geometry, materialOrSide, ray, tri, intersections, near, far) {
2573
+ const triOffset = tri * 3;
2574
+ let a = triOffset + 0;
2575
+ let b = triOffset + 1;
2576
+ let c = triOffset + 2;
2577
+ const { index, groups } = geometry;
2578
+ if (geometry.index) {
2579
+ a = index.getX(a);
2580
+ b = index.getX(b);
2581
+ c = index.getX(c);
2582
+ }
2583
+ const { position, normal, uv, uv1 } = geometry.attributes;
2584
+ if (Array.isArray(materialOrSide)) {
2585
+ const firstIndex = tri * 3;
2586
+ for (let i = 0, l = groups.length; i < l; i++) {
2587
+ const { start, count, materialIndex } = groups[i];
2588
+ if (firstIndex >= start && firstIndex < start + count) {
2589
+ const side = getSide(materialOrSide[materialIndex]);
2590
+ const intersection = checkBufferGeometryIntersection(ray, position, normal, uv, uv1, a, b, c, side, near, far);
2591
+ if (intersection) {
2592
+ intersection.faceIndex = tri;
2593
+ intersection.face.materialIndex = materialIndex;
2594
+ if (intersections) {
2595
+ intersections.push(intersection);
2596
+ } else {
2597
+ return intersection;
2598
+ }
2599
+ }
2600
+ }
2601
+ }
2602
+ } else {
2603
+ const side = getSide(materialOrSide);
2604
+ const intersection = checkBufferGeometryIntersection(ray, position, normal, uv, uv1, a, b, c, side, near, far);
2605
+ if (intersection) {
2606
+ intersection.faceIndex = tri;
2607
+ intersection.face.materialIndex = 0;
2608
+ if (intersections) {
2609
+ intersections.push(intersection);
2610
+ } else {
2611
+ return intersection;
2612
+ }
2613
+ }
2614
+ }
2615
+ return null;
2616
+ }
2617
+
2618
+ // ../../node_modules/three-mesh-bvh/src/utils/TriangleUtilities.js
2619
+ import { Vector2 as Vector24, Vector3 as Vector37, Triangle as Triangle3 } from "three";
2620
+ function setTriangle(tri, i, index, pos) {
2621
+ const ta = tri.a;
2622
+ const tb = tri.b;
2623
+ const tc = tri.c;
2624
+ let i0 = i;
2625
+ let i1 = i + 1;
2626
+ let i2 = i + 2;
2627
+ if (index) {
2628
+ i0 = index.getX(i0);
2629
+ i1 = index.getX(i1);
2630
+ i2 = index.getX(i2);
2631
+ }
2632
+ ta.x = pos.getX(i0);
2633
+ ta.y = pos.getY(i0);
2634
+ ta.z = pos.getZ(i0);
2635
+ tb.x = pos.getX(i1);
2636
+ tb.y = pos.getY(i1);
2637
+ tb.z = pos.getZ(i1);
2638
+ tc.x = pos.getX(i2);
2639
+ tc.y = pos.getY(i2);
2640
+ tc.z = pos.getZ(i2);
2641
+ }
2642
+
2643
+ // ../../node_modules/three-mesh-bvh/src/core/utils/iterationUtils.generated.js
2644
+ function intersectTris(bvh, materialOrSide, ray, offset, count, intersections, near, far) {
2645
+ const { geometry, _indirectBuffer } = bvh;
2646
+ for (let i = offset, end = offset + count; i < end; i++) {
2647
+ intersectTri(geometry, materialOrSide, ray, i, intersections, near, far);
2648
+ }
2649
+ }
2650
+ function intersectClosestTri(bvh, materialOrSide, ray, offset, count, near, far) {
2651
+ const { geometry, _indirectBuffer } = bvh;
2652
+ let dist = Infinity;
2653
+ let res = null;
2654
+ for (let i = offset, end = offset + count; i < end; i++) {
2655
+ let intersection;
2656
+ intersection = intersectTri(geometry, materialOrSide, ray, i, null, near, far);
2657
+ if (intersection && intersection.distance < dist) {
2658
+ res = intersection;
2659
+ dist = intersection.distance;
2660
+ }
2661
+ }
2662
+ return res;
2663
+ }
2664
+ function iterateOverTriangles(offset, count, bvh, intersectsTriangleFunc, contained, depth, triangle4) {
2665
+ const { geometry } = bvh;
2666
+ const { index } = geometry;
2667
+ const pos = geometry.attributes.position;
2668
+ for (let i = offset, l = count + offset; i < l; i++) {
2669
+ let tri;
2670
+ tri = i;
2671
+ setTriangle(triangle4, tri * 3, index, pos);
2672
+ triangle4.needsUpdate = true;
2673
+ if (intersectsTriangleFunc(triangle4, tri, contained, depth)) {
2674
+ return true;
2675
+ }
2676
+ }
2677
+ return false;
2678
+ }
2679
+
2680
+ // ../../node_modules/three-mesh-bvh/src/core/cast/refit.generated.js
2681
+ function refit(bvh, nodeIndices = null) {
2682
+ if (nodeIndices && Array.isArray(nodeIndices)) {
2683
+ nodeIndices = new Set(nodeIndices);
2684
+ }
2685
+ const geometry = bvh.geometry;
2686
+ const indexArr = geometry.index ? geometry.index.array : null;
2687
+ const posAttr = geometry.attributes.position;
2688
+ let buffer, uint32Array2, uint16Array2, float32Array2;
2689
+ let byteOffset = 0;
2690
+ const roots = bvh._roots;
2691
+ for (let i = 0, l = roots.length; i < l; i++) {
2692
+ buffer = roots[i];
2693
+ uint32Array2 = new Uint32Array(buffer);
2694
+ uint16Array2 = new Uint16Array(buffer);
2695
+ float32Array2 = new Float32Array(buffer);
2696
+ _traverse2(0, byteOffset);
2697
+ byteOffset += buffer.byteLength;
2698
+ }
2699
+ function _traverse2(nodeIndex32, byteOffset2, force = false) {
2700
+ const nodeIndex16 = nodeIndex32 * 2;
2701
+ if (IS_LEAF(nodeIndex16, uint16Array2)) {
2702
+ const offset = OFFSET(nodeIndex32, uint32Array2);
2703
+ const count = COUNT(nodeIndex16, uint16Array2);
2704
+ let minx = Infinity;
2705
+ let miny = Infinity;
2706
+ let minz = Infinity;
2707
+ let maxx = -Infinity;
2708
+ let maxy = -Infinity;
2709
+ let maxz = -Infinity;
2710
+ for (let i = 3 * offset, l = 3 * (offset + count); i < l; i++) {
2711
+ let index = indexArr[i];
2712
+ const x = posAttr.getX(index);
2713
+ const y = posAttr.getY(index);
2714
+ const z = posAttr.getZ(index);
2715
+ if (x < minx) minx = x;
2716
+ if (x > maxx) maxx = x;
2717
+ if (y < miny) miny = y;
2718
+ if (y > maxy) maxy = y;
2719
+ if (z < minz) minz = z;
2720
+ if (z > maxz) maxz = z;
2721
+ }
2722
+ if (float32Array2[nodeIndex32 + 0] !== minx || float32Array2[nodeIndex32 + 1] !== miny || float32Array2[nodeIndex32 + 2] !== minz || float32Array2[nodeIndex32 + 3] !== maxx || float32Array2[nodeIndex32 + 4] !== maxy || float32Array2[nodeIndex32 + 5] !== maxz) {
2723
+ float32Array2[nodeIndex32 + 0] = minx;
2724
+ float32Array2[nodeIndex32 + 1] = miny;
2725
+ float32Array2[nodeIndex32 + 2] = minz;
2726
+ float32Array2[nodeIndex32 + 3] = maxx;
2727
+ float32Array2[nodeIndex32 + 4] = maxy;
2728
+ float32Array2[nodeIndex32 + 5] = maxz;
2729
+ return true;
2730
+ } else {
2731
+ return false;
2732
+ }
2733
+ } else {
2734
+ const left = LEFT_NODE(nodeIndex32);
2735
+ const right = RIGHT_NODE(nodeIndex32, uint32Array2);
2736
+ let forceChildren = force;
2737
+ let includesLeft = false;
2738
+ let includesRight = false;
2739
+ if (nodeIndices) {
2740
+ if (!forceChildren) {
2741
+ const leftNodeId = left / UINT32_PER_NODE + byteOffset2 / BYTES_PER_NODE;
2742
+ const rightNodeId = right / UINT32_PER_NODE + byteOffset2 / BYTES_PER_NODE;
2743
+ includesLeft = nodeIndices.has(leftNodeId);
2744
+ includesRight = nodeIndices.has(rightNodeId);
2745
+ forceChildren = !includesLeft && !includesRight;
2746
+ }
2747
+ } else {
2748
+ includesLeft = true;
2749
+ includesRight = true;
2750
+ }
2751
+ const traverseLeft = forceChildren || includesLeft;
2752
+ const traverseRight = forceChildren || includesRight;
2753
+ let leftChange = false;
2754
+ if (traverseLeft) {
2755
+ leftChange = _traverse2(left, byteOffset2, forceChildren);
2756
+ }
2757
+ let rightChange = false;
2758
+ if (traverseRight) {
2759
+ rightChange = _traverse2(right, byteOffset2, forceChildren);
2760
+ }
2761
+ const didChange = leftChange || rightChange;
2762
+ if (didChange) {
2763
+ for (let i = 0; i < 3; i++) {
2764
+ const left_i = left + i;
2765
+ const right_i = right + i;
2766
+ const minLeftValue = float32Array2[left_i];
2767
+ const maxLeftValue = float32Array2[left_i + 3];
2768
+ const minRightValue = float32Array2[right_i];
2769
+ const maxRightValue = float32Array2[right_i + 3];
2770
+ float32Array2[nodeIndex32 + i] = minLeftValue < minRightValue ? minLeftValue : minRightValue;
2771
+ float32Array2[nodeIndex32 + i + 3] = maxLeftValue > maxRightValue ? maxLeftValue : maxRightValue;
2772
+ }
2773
+ }
2774
+ return didChange;
2775
+ }
2776
+ }
2777
+ }
2778
+
2779
+ // ../../node_modules/three-mesh-bvh/src/core/utils/intersectUtils.js
2780
+ function intersectsNodeBounds(nodeIndex32, array, ray, near, far) {
2781
+ let tmin, tmax, tymin, tymax, tzmin, tzmax;
2782
+ const invdirx = 1 / ray.direction.x, invdiry = 1 / ray.direction.y, invdirz = 1 / ray.direction.z;
2783
+ const ox = ray.origin.x;
2784
+ const oy = ray.origin.y;
2785
+ const oz = ray.origin.z;
2786
+ let minx = array[nodeIndex32];
2787
+ let maxx = array[nodeIndex32 + 3];
2788
+ let miny = array[nodeIndex32 + 1];
2789
+ let maxy = array[nodeIndex32 + 3 + 1];
2790
+ let minz = array[nodeIndex32 + 2];
2791
+ let maxz = array[nodeIndex32 + 3 + 2];
2792
+ if (invdirx >= 0) {
2793
+ tmin = (minx - ox) * invdirx;
2794
+ tmax = (maxx - ox) * invdirx;
2795
+ } else {
2796
+ tmin = (maxx - ox) * invdirx;
2797
+ tmax = (minx - ox) * invdirx;
2798
+ }
2799
+ if (invdiry >= 0) {
2800
+ tymin = (miny - oy) * invdiry;
2801
+ tymax = (maxy - oy) * invdiry;
2802
+ } else {
2803
+ tymin = (maxy - oy) * invdiry;
2804
+ tymax = (miny - oy) * invdiry;
2805
+ }
2806
+ if (tmin > tymax || tymin > tmax) return false;
2807
+ if (tymin > tmin || isNaN(tmin)) tmin = tymin;
2808
+ if (tymax < tmax || isNaN(tmax)) tmax = tymax;
2809
+ if (invdirz >= 0) {
2810
+ tzmin = (minz - oz) * invdirz;
2811
+ tzmax = (maxz - oz) * invdirz;
2812
+ } else {
2813
+ tzmin = (maxz - oz) * invdirz;
2814
+ tzmax = (minz - oz) * invdirz;
2815
+ }
2816
+ if (tmin > tzmax || tzmin > tmax) return false;
2817
+ if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
2818
+ if (tzmax < tmax || tmax !== tmax) tmax = tzmax;
2819
+ return tmin <= far && tmax >= near;
2820
+ }
2821
+
2822
+ // ../../node_modules/three-mesh-bvh/src/core/utils/iterationUtils_indirect.generated.js
2823
+ function intersectTris_indirect(bvh, materialOrSide, ray, offset, count, intersections, near, far) {
2824
+ const { geometry, _indirectBuffer } = bvh;
2825
+ for (let i = offset, end = offset + count; i < end; i++) {
2826
+ let vi = _indirectBuffer ? _indirectBuffer[i] : i;
2827
+ intersectTri(geometry, materialOrSide, ray, vi, intersections, near, far);
2828
+ }
2829
+ }
2830
+ function intersectClosestTri_indirect(bvh, materialOrSide, ray, offset, count, near, far) {
2831
+ const { geometry, _indirectBuffer } = bvh;
2832
+ let dist = Infinity;
2833
+ let res = null;
2834
+ for (let i = offset, end = offset + count; i < end; i++) {
2835
+ let intersection;
2836
+ intersection = intersectTri(geometry, materialOrSide, ray, _indirectBuffer ? _indirectBuffer[i] : i, null, near, far);
2837
+ if (intersection && intersection.distance < dist) {
2838
+ res = intersection;
2839
+ dist = intersection.distance;
2840
+ }
2841
+ }
2842
+ return res;
2843
+ }
2844
+ function iterateOverTriangles_indirect(offset, count, bvh, intersectsTriangleFunc, contained, depth, triangle4) {
2845
+ const { geometry } = bvh;
2846
+ const { index } = geometry;
2847
+ const pos = geometry.attributes.position;
2848
+ for (let i = offset, l = count + offset; i < l; i++) {
2849
+ let tri;
2850
+ tri = bvh.resolveTriangleIndex(i);
2851
+ setTriangle(triangle4, tri * 3, index, pos);
2852
+ triangle4.needsUpdate = true;
2853
+ if (intersectsTriangleFunc(triangle4, tri, contained, depth)) {
2854
+ return true;
2855
+ }
2856
+ }
2857
+ return false;
2858
+ }
2859
+
2860
+ // ../../node_modules/three-mesh-bvh/src/core/cast/raycast.generated.js
2861
+ function raycast(bvh, root, materialOrSide, ray, intersects, near, far) {
2862
+ BufferStack.setBuffer(bvh._roots[root]);
2863
+ _raycast(0, bvh, materialOrSide, ray, intersects, near, far);
2864
+ BufferStack.clearBuffer();
2865
+ }
2866
+ function _raycast(nodeIndex32, bvh, materialOrSide, ray, intersects, near, far) {
2867
+ const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack;
2868
+ const nodeIndex16 = nodeIndex32 * 2;
2869
+ const isLeaf = IS_LEAF(nodeIndex16, uint16Array2);
2870
+ if (isLeaf) {
2871
+ const offset = OFFSET(nodeIndex32, uint32Array2);
2872
+ const count = COUNT(nodeIndex16, uint16Array2);
2873
+ intersectTris(bvh, materialOrSide, ray, offset, count, intersects, near, far);
2874
+ } else {
2875
+ const leftIndex = LEFT_NODE(nodeIndex32);
2876
+ if (intersectsNodeBounds(leftIndex, float32Array2, ray, near, far)) {
2877
+ _raycast(leftIndex, bvh, materialOrSide, ray, intersects, near, far);
2878
+ }
2879
+ const rightIndex = RIGHT_NODE(nodeIndex32, uint32Array2);
2880
+ if (intersectsNodeBounds(rightIndex, float32Array2, ray, near, far)) {
2881
+ _raycast(rightIndex, bvh, materialOrSide, ray, intersects, near, far);
2882
+ }
2883
+ }
2884
+ }
2885
+
2886
+ // ../../node_modules/three-mesh-bvh/src/core/cast/raycastFirst.generated.js
2887
+ var _xyzFields = ["x", "y", "z"];
2888
+ function raycastFirst(bvh, root, materialOrSide, ray, near, far) {
2889
+ BufferStack.setBuffer(bvh._roots[root]);
2890
+ const result = _raycastFirst(0, bvh, materialOrSide, ray, near, far);
2891
+ BufferStack.clearBuffer();
2892
+ return result;
2893
+ }
2894
+ function _raycastFirst(nodeIndex32, bvh, materialOrSide, ray, near, far) {
2895
+ const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack;
2896
+ let nodeIndex16 = nodeIndex32 * 2;
2897
+ const isLeaf = IS_LEAF(nodeIndex16, uint16Array2);
2898
+ if (isLeaf) {
2899
+ const offset = OFFSET(nodeIndex32, uint32Array2);
2900
+ const count = COUNT(nodeIndex16, uint16Array2);
2901
+ return intersectClosestTri(bvh, materialOrSide, ray, offset, count, near, far);
2902
+ } else {
2903
+ const splitAxis = SPLIT_AXIS(nodeIndex32, uint32Array2);
2904
+ const xyzAxis = _xyzFields[splitAxis];
2905
+ const rayDir = ray.direction[xyzAxis];
2906
+ const leftToRight = rayDir >= 0;
2907
+ let c1, c2;
2908
+ if (leftToRight) {
2909
+ c1 = LEFT_NODE(nodeIndex32);
2910
+ c2 = RIGHT_NODE(nodeIndex32, uint32Array2);
2911
+ } else {
2912
+ c1 = RIGHT_NODE(nodeIndex32, uint32Array2);
2913
+ c2 = LEFT_NODE(nodeIndex32);
2914
+ }
2915
+ const c1Intersection = intersectsNodeBounds(c1, float32Array2, ray, near, far);
2916
+ const c1Result = c1Intersection ? _raycastFirst(c1, bvh, materialOrSide, ray, near, far) : null;
2917
+ if (c1Result) {
2918
+ const point = c1Result.point[xyzAxis];
2919
+ const isOutside = leftToRight ? point <= float32Array2[c2 + splitAxis] : (
2920
+ // min bounding data
2921
+ point >= float32Array2[c2 + splitAxis + 3]
2922
+ );
2923
+ if (isOutside) {
2924
+ return c1Result;
2925
+ }
2926
+ }
2927
+ const c2Intersection = intersectsNodeBounds(c2, float32Array2, ray, near, far);
2928
+ const c2Result = c2Intersection ? _raycastFirst(c2, bvh, materialOrSide, ray, near, far) : null;
2929
+ if (c1Result && c2Result) {
2930
+ return c1Result.distance <= c2Result.distance ? c1Result : c2Result;
2931
+ } else {
2932
+ return c1Result || c2Result || null;
2933
+ }
2934
+ }
2935
+ }
2936
+
2937
+ // ../../node_modules/three-mesh-bvh/src/core/cast/intersectsGeometry.generated.js
2938
+ import { Box3 as Box35, Matrix4 as Matrix43 } from "three";
2939
+ var boundingBox = /* @__PURE__ */ new Box35();
2940
+ var triangle = /* @__PURE__ */ new ExtendedTriangle();
2941
+ var triangle2 = /* @__PURE__ */ new ExtendedTriangle();
2942
+ var invertedMat = /* @__PURE__ */ new Matrix43();
2943
+ var obb = /* @__PURE__ */ new OrientedBox();
2944
+ var obb2 = /* @__PURE__ */ new OrientedBox();
2945
+ function intersectsGeometry(bvh, root, otherGeometry, geometryToBvh) {
2946
+ BufferStack.setBuffer(bvh._roots[root]);
2947
+ const result = _intersectsGeometry(0, bvh, otherGeometry, geometryToBvh);
2948
+ BufferStack.clearBuffer();
2949
+ return result;
2950
+ }
2951
+ function _intersectsGeometry(nodeIndex32, bvh, otherGeometry, geometryToBvh, cachedObb = null) {
2952
+ const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack;
2953
+ let nodeIndex16 = nodeIndex32 * 2;
2954
+ if (cachedObb === null) {
2955
+ if (!otherGeometry.boundingBox) {
2956
+ otherGeometry.computeBoundingBox();
2957
+ }
2958
+ obb.set(otherGeometry.boundingBox.min, otherGeometry.boundingBox.max, geometryToBvh);
2959
+ cachedObb = obb;
2960
+ }
2961
+ const isLeaf = IS_LEAF(nodeIndex16, uint16Array2);
2962
+ if (isLeaf) {
2963
+ const thisGeometry = bvh.geometry;
2964
+ const thisIndex = thisGeometry.index;
2965
+ const thisPos = thisGeometry.attributes.position;
2966
+ const otherIndex = otherGeometry.index;
2967
+ const otherPos = otherGeometry.attributes.position;
2968
+ const offset = OFFSET(nodeIndex32, uint32Array2);
2969
+ const count = COUNT(nodeIndex16, uint16Array2);
2970
+ invertedMat.copy(geometryToBvh).invert();
2971
+ if (otherGeometry.boundsTree) {
2972
+ arrayToBox(BOUNDING_DATA_INDEX(nodeIndex32), float32Array2, obb2);
2973
+ obb2.matrix.copy(invertedMat);
2974
+ obb2.needsUpdate = true;
2975
+ const res = otherGeometry.boundsTree.shapecast({
2976
+ intersectsBounds: (box) => obb2.intersectsBox(box),
2977
+ intersectsTriangle: (tri) => {
2978
+ tri.a.applyMatrix4(geometryToBvh);
2979
+ tri.b.applyMatrix4(geometryToBvh);
2980
+ tri.c.applyMatrix4(geometryToBvh);
2981
+ tri.needsUpdate = true;
2982
+ for (let i = offset * 3, l = (count + offset) * 3; i < l; i += 3) {
2983
+ setTriangle(triangle2, i, thisIndex, thisPos);
2984
+ triangle2.needsUpdate = true;
2985
+ if (tri.intersectsTriangle(triangle2)) {
2986
+ return true;
2987
+ }
2988
+ }
2989
+ return false;
2990
+ }
2991
+ });
2992
+ return res;
2993
+ } else {
2994
+ const otherTriangleCount = getTriCount(otherGeometry);
2995
+ for (let i = offset * 3, l = (count + offset) * 3; i < l; i += 3) {
2996
+ setTriangle(triangle, i, thisIndex, thisPos);
2997
+ triangle.a.applyMatrix4(invertedMat);
2998
+ triangle.b.applyMatrix4(invertedMat);
2999
+ triangle.c.applyMatrix4(invertedMat);
3000
+ triangle.needsUpdate = true;
3001
+ for (let i2 = 0, l2 = otherTriangleCount * 3; i2 < l2; i2 += 3) {
3002
+ setTriangle(triangle2, i2, otherIndex, otherPos);
3003
+ triangle2.needsUpdate = true;
3004
+ if (triangle.intersectsTriangle(triangle2)) {
3005
+ return true;
3006
+ }
3007
+ }
3008
+ }
3009
+ }
3010
+ } else {
3011
+ const left = LEFT_NODE(nodeIndex32);
3012
+ const right = RIGHT_NODE(nodeIndex32, uint32Array2);
3013
+ arrayToBox(BOUNDING_DATA_INDEX(left), float32Array2, boundingBox);
3014
+ const leftIntersection = cachedObb.intersectsBox(boundingBox) && _intersectsGeometry(left, bvh, otherGeometry, geometryToBvh, cachedObb);
3015
+ if (leftIntersection) return true;
3016
+ arrayToBox(BOUNDING_DATA_INDEX(right), float32Array2, boundingBox);
3017
+ const rightIntersection = cachedObb.intersectsBox(boundingBox) && _intersectsGeometry(right, bvh, otherGeometry, geometryToBvh, cachedObb);
3018
+ if (rightIntersection) return true;
3019
+ return false;
3020
+ }
3021
+ }
3022
+
3023
+ // ../../node_modules/three-mesh-bvh/src/core/cast/closestPointToGeometry.generated.js
3024
+ import { Matrix4 as Matrix44, Vector3 as Vector38 } from "three";
3025
+ var tempMatrix = /* @__PURE__ */ new Matrix44();
3026
+ var obb3 = /* @__PURE__ */ new OrientedBox();
3027
+ var obb22 = /* @__PURE__ */ new OrientedBox();
3028
+ var temp12 = /* @__PURE__ */ new Vector38();
3029
+ var temp2 = /* @__PURE__ */ new Vector38();
3030
+ var temp3 = /* @__PURE__ */ new Vector38();
3031
+ var temp4 = /* @__PURE__ */ new Vector38();
3032
+ function closestPointToGeometry(bvh, otherGeometry, geometryToBvh, target1 = {}, target2 = {}, minThreshold = 0, maxThreshold = Infinity) {
3033
+ if (!otherGeometry.boundingBox) {
3034
+ otherGeometry.computeBoundingBox();
3035
+ }
3036
+ obb3.set(otherGeometry.boundingBox.min, otherGeometry.boundingBox.max, geometryToBvh);
3037
+ obb3.needsUpdate = true;
3038
+ const geometry = bvh.geometry;
3039
+ const pos = geometry.attributes.position;
3040
+ const index = geometry.index;
3041
+ const otherPos = otherGeometry.attributes.position;
3042
+ const otherIndex = otherGeometry.index;
3043
+ const triangle4 = ExtendedTrianglePool.getPrimitive();
3044
+ const triangle23 = ExtendedTrianglePool.getPrimitive();
3045
+ let tempTarget1 = temp12;
3046
+ let tempTargetDest1 = temp2;
3047
+ let tempTarget2 = null;
3048
+ let tempTargetDest2 = null;
3049
+ if (target2) {
3050
+ tempTarget2 = temp3;
3051
+ tempTargetDest2 = temp4;
3052
+ }
3053
+ let closestDistance = Infinity;
3054
+ let closestDistanceTriIndex = null;
3055
+ let closestDistanceOtherTriIndex = null;
3056
+ tempMatrix.copy(geometryToBvh).invert();
3057
+ obb22.matrix.copy(tempMatrix);
3058
+ bvh.shapecast(
3059
+ {
3060
+ boundsTraverseOrder: (box) => {
3061
+ return obb3.distanceToBox(box);
3062
+ },
3063
+ intersectsBounds: (box, isLeaf, score) => {
3064
+ if (score < closestDistance && score < maxThreshold) {
3065
+ if (isLeaf) {
3066
+ obb22.min.copy(box.min);
3067
+ obb22.max.copy(box.max);
3068
+ obb22.needsUpdate = true;
3069
+ }
3070
+ return true;
3071
+ }
3072
+ return false;
3073
+ },
3074
+ intersectsRange: (offset, count) => {
3075
+ if (otherGeometry.boundsTree) {
3076
+ const otherBvh = otherGeometry.boundsTree;
3077
+ return otherBvh.shapecast({
3078
+ boundsTraverseOrder: (box) => {
3079
+ return obb22.distanceToBox(box);
3080
+ },
3081
+ intersectsBounds: (box, isLeaf, score) => {
3082
+ return score < closestDistance && score < maxThreshold;
3083
+ },
3084
+ intersectsRange: (otherOffset, otherCount) => {
3085
+ for (let i2 = otherOffset, l2 = otherOffset + otherCount; i2 < l2; i2++) {
3086
+ setTriangle(triangle23, 3 * i2, otherIndex, otherPos);
3087
+ triangle23.a.applyMatrix4(geometryToBvh);
3088
+ triangle23.b.applyMatrix4(geometryToBvh);
3089
+ triangle23.c.applyMatrix4(geometryToBvh);
3090
+ triangle23.needsUpdate = true;
3091
+ for (let i = offset, l = offset + count; i < l; i++) {
3092
+ setTriangle(triangle4, 3 * i, index, pos);
3093
+ triangle4.needsUpdate = true;
3094
+ const dist = triangle4.distanceToTriangle(triangle23, tempTarget1, tempTarget2);
3095
+ if (dist < closestDistance) {
3096
+ tempTargetDest1.copy(tempTarget1);
3097
+ if (tempTargetDest2) {
3098
+ tempTargetDest2.copy(tempTarget2);
3099
+ }
3100
+ closestDistance = dist;
3101
+ closestDistanceTriIndex = i;
3102
+ closestDistanceOtherTriIndex = i2;
3103
+ }
3104
+ if (dist < minThreshold) {
3105
+ return true;
3106
+ }
3107
+ }
3108
+ }
3109
+ }
3110
+ });
3111
+ } else {
3112
+ const triCount = getTriCount(otherGeometry);
3113
+ for (let i2 = 0, l2 = triCount; i2 < l2; i2++) {
3114
+ setTriangle(triangle23, 3 * i2, otherIndex, otherPos);
3115
+ triangle23.a.applyMatrix4(geometryToBvh);
3116
+ triangle23.b.applyMatrix4(geometryToBvh);
3117
+ triangle23.c.applyMatrix4(geometryToBvh);
3118
+ triangle23.needsUpdate = true;
3119
+ for (let i = offset, l = offset + count; i < l; i++) {
3120
+ setTriangle(triangle4, 3 * i, index, pos);
3121
+ triangle4.needsUpdate = true;
3122
+ const dist = triangle4.distanceToTriangle(triangle23, tempTarget1, tempTarget2);
3123
+ if (dist < closestDistance) {
3124
+ tempTargetDest1.copy(tempTarget1);
3125
+ if (tempTargetDest2) {
3126
+ tempTargetDest2.copy(tempTarget2);
3127
+ }
3128
+ closestDistance = dist;
3129
+ closestDistanceTriIndex = i;
3130
+ closestDistanceOtherTriIndex = i2;
3131
+ }
3132
+ if (dist < minThreshold) {
3133
+ return true;
3134
+ }
3135
+ }
3136
+ }
3137
+ }
3138
+ }
3139
+ }
3140
+ );
3141
+ ExtendedTrianglePool.releasePrimitive(triangle4);
3142
+ ExtendedTrianglePool.releasePrimitive(triangle23);
3143
+ if (closestDistance === Infinity) {
3144
+ return null;
3145
+ }
3146
+ if (!target1.point) {
3147
+ target1.point = tempTargetDest1.clone();
3148
+ } else {
3149
+ target1.point.copy(tempTargetDest1);
3150
+ }
3151
+ target1.distance = closestDistance, target1.faceIndex = closestDistanceTriIndex;
3152
+ if (target2) {
3153
+ if (!target2.point) target2.point = tempTargetDest2.clone();
3154
+ else target2.point.copy(tempTargetDest2);
3155
+ target2.point.applyMatrix4(tempMatrix);
3156
+ tempTargetDest1.applyMatrix4(tempMatrix);
3157
+ target2.distance = tempTargetDest1.sub(target2.point).length();
3158
+ target2.faceIndex = closestDistanceOtherTriIndex;
3159
+ }
3160
+ return target1;
3161
+ }
3162
+
3163
+ // ../../node_modules/three-mesh-bvh/src/core/cast/refit_indirect.generated.js
3164
+ function refit_indirect(bvh, nodeIndices = null) {
3165
+ if (nodeIndices && Array.isArray(nodeIndices)) {
3166
+ nodeIndices = new Set(nodeIndices);
3167
+ }
3168
+ const geometry = bvh.geometry;
3169
+ const indexArr = geometry.index ? geometry.index.array : null;
3170
+ const posAttr = geometry.attributes.position;
3171
+ let buffer, uint32Array2, uint16Array2, float32Array2;
3172
+ let byteOffset = 0;
3173
+ const roots = bvh._roots;
3174
+ for (let i = 0, l = roots.length; i < l; i++) {
3175
+ buffer = roots[i];
3176
+ uint32Array2 = new Uint32Array(buffer);
3177
+ uint16Array2 = new Uint16Array(buffer);
3178
+ float32Array2 = new Float32Array(buffer);
3179
+ _traverse2(0, byteOffset);
3180
+ byteOffset += buffer.byteLength;
3181
+ }
3182
+ function _traverse2(nodeIndex32, byteOffset2, force = false) {
3183
+ const nodeIndex16 = nodeIndex32 * 2;
3184
+ if (IS_LEAF(nodeIndex16, uint16Array2)) {
3185
+ const offset = OFFSET(nodeIndex32, uint32Array2);
3186
+ const count = COUNT(nodeIndex16, uint16Array2);
3187
+ let minx = Infinity;
3188
+ let miny = Infinity;
3189
+ let minz = Infinity;
3190
+ let maxx = -Infinity;
3191
+ let maxy = -Infinity;
3192
+ let maxz = -Infinity;
3193
+ for (let i = offset, l = offset + count; i < l; i++) {
3194
+ const t = 3 * bvh.resolveTriangleIndex(i);
3195
+ for (let j = 0; j < 3; j++) {
3196
+ let index = t + j;
3197
+ index = indexArr ? indexArr[index] : index;
3198
+ const x = posAttr.getX(index);
3199
+ const y = posAttr.getY(index);
3200
+ const z = posAttr.getZ(index);
3201
+ if (x < minx) minx = x;
3202
+ if (x > maxx) maxx = x;
3203
+ if (y < miny) miny = y;
3204
+ if (y > maxy) maxy = y;
3205
+ if (z < minz) minz = z;
3206
+ if (z > maxz) maxz = z;
3207
+ }
3208
+ }
3209
+ if (float32Array2[nodeIndex32 + 0] !== minx || float32Array2[nodeIndex32 + 1] !== miny || float32Array2[nodeIndex32 + 2] !== minz || float32Array2[nodeIndex32 + 3] !== maxx || float32Array2[nodeIndex32 + 4] !== maxy || float32Array2[nodeIndex32 + 5] !== maxz) {
3210
+ float32Array2[nodeIndex32 + 0] = minx;
3211
+ float32Array2[nodeIndex32 + 1] = miny;
3212
+ float32Array2[nodeIndex32 + 2] = minz;
3213
+ float32Array2[nodeIndex32 + 3] = maxx;
3214
+ float32Array2[nodeIndex32 + 4] = maxy;
3215
+ float32Array2[nodeIndex32 + 5] = maxz;
3216
+ return true;
3217
+ } else {
3218
+ return false;
3219
+ }
3220
+ } else {
3221
+ const left = LEFT_NODE(nodeIndex32);
3222
+ const right = RIGHT_NODE(nodeIndex32, uint32Array2);
3223
+ let forceChildren = force;
3224
+ let includesLeft = false;
3225
+ let includesRight = false;
3226
+ if (nodeIndices) {
3227
+ if (!forceChildren) {
3228
+ const leftNodeId = left / UINT32_PER_NODE + byteOffset2 / BYTES_PER_NODE;
3229
+ const rightNodeId = right / UINT32_PER_NODE + byteOffset2 / BYTES_PER_NODE;
3230
+ includesLeft = nodeIndices.has(leftNodeId);
3231
+ includesRight = nodeIndices.has(rightNodeId);
3232
+ forceChildren = !includesLeft && !includesRight;
3233
+ }
3234
+ } else {
3235
+ includesLeft = true;
3236
+ includesRight = true;
3237
+ }
3238
+ const traverseLeft = forceChildren || includesLeft;
3239
+ const traverseRight = forceChildren || includesRight;
3240
+ let leftChange = false;
3241
+ if (traverseLeft) {
3242
+ leftChange = _traverse2(left, byteOffset2, forceChildren);
3243
+ }
3244
+ let rightChange = false;
3245
+ if (traverseRight) {
3246
+ rightChange = _traverse2(right, byteOffset2, forceChildren);
3247
+ }
3248
+ const didChange = leftChange || rightChange;
3249
+ if (didChange) {
3250
+ for (let i = 0; i < 3; i++) {
3251
+ const left_i = left + i;
3252
+ const right_i = right + i;
3253
+ const minLeftValue = float32Array2[left_i];
3254
+ const maxLeftValue = float32Array2[left_i + 3];
3255
+ const minRightValue = float32Array2[right_i];
3256
+ const maxRightValue = float32Array2[right_i + 3];
3257
+ float32Array2[nodeIndex32 + i] = minLeftValue < minRightValue ? minLeftValue : minRightValue;
3258
+ float32Array2[nodeIndex32 + i + 3] = maxLeftValue > maxRightValue ? maxLeftValue : maxRightValue;
3259
+ }
3260
+ }
3261
+ return didChange;
3262
+ }
3263
+ }
3264
+ }
3265
+
3266
+ // ../../node_modules/three-mesh-bvh/src/core/cast/raycast_indirect.generated.js
3267
+ function raycast_indirect(bvh, root, materialOrSide, ray, intersects, near, far) {
3268
+ BufferStack.setBuffer(bvh._roots[root]);
3269
+ _raycast2(0, bvh, materialOrSide, ray, intersects, near, far);
3270
+ BufferStack.clearBuffer();
3271
+ }
3272
+ function _raycast2(nodeIndex32, bvh, materialOrSide, ray, intersects, near, far) {
3273
+ const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack;
3274
+ const nodeIndex16 = nodeIndex32 * 2;
3275
+ const isLeaf = IS_LEAF(nodeIndex16, uint16Array2);
3276
+ if (isLeaf) {
3277
+ const offset = OFFSET(nodeIndex32, uint32Array2);
3278
+ const count = COUNT(nodeIndex16, uint16Array2);
3279
+ intersectTris_indirect(bvh, materialOrSide, ray, offset, count, intersects, near, far);
3280
+ } else {
3281
+ const leftIndex = LEFT_NODE(nodeIndex32);
3282
+ if (intersectsNodeBounds(leftIndex, float32Array2, ray, near, far)) {
3283
+ _raycast2(leftIndex, bvh, materialOrSide, ray, intersects, near, far);
3284
+ }
3285
+ const rightIndex = RIGHT_NODE(nodeIndex32, uint32Array2);
3286
+ if (intersectsNodeBounds(rightIndex, float32Array2, ray, near, far)) {
3287
+ _raycast2(rightIndex, bvh, materialOrSide, ray, intersects, near, far);
3288
+ }
3289
+ }
3290
+ }
3291
+
3292
+ // ../../node_modules/three-mesh-bvh/src/core/cast/raycastFirst_indirect.generated.js
3293
+ var _xyzFields2 = ["x", "y", "z"];
3294
+ function raycastFirst_indirect(bvh, root, materialOrSide, ray, near, far) {
3295
+ BufferStack.setBuffer(bvh._roots[root]);
3296
+ const result = _raycastFirst2(0, bvh, materialOrSide, ray, near, far);
3297
+ BufferStack.clearBuffer();
3298
+ return result;
3299
+ }
3300
+ function _raycastFirst2(nodeIndex32, bvh, materialOrSide, ray, near, far) {
3301
+ const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack;
3302
+ let nodeIndex16 = nodeIndex32 * 2;
3303
+ const isLeaf = IS_LEAF(nodeIndex16, uint16Array2);
3304
+ if (isLeaf) {
3305
+ const offset = OFFSET(nodeIndex32, uint32Array2);
3306
+ const count = COUNT(nodeIndex16, uint16Array2);
3307
+ return intersectClosestTri_indirect(bvh, materialOrSide, ray, offset, count, near, far);
3308
+ } else {
3309
+ const splitAxis = SPLIT_AXIS(nodeIndex32, uint32Array2);
3310
+ const xyzAxis = _xyzFields2[splitAxis];
3311
+ const rayDir = ray.direction[xyzAxis];
3312
+ const leftToRight = rayDir >= 0;
3313
+ let c1, c2;
3314
+ if (leftToRight) {
3315
+ c1 = LEFT_NODE(nodeIndex32);
3316
+ c2 = RIGHT_NODE(nodeIndex32, uint32Array2);
3317
+ } else {
3318
+ c1 = RIGHT_NODE(nodeIndex32, uint32Array2);
3319
+ c2 = LEFT_NODE(nodeIndex32);
3320
+ }
3321
+ const c1Intersection = intersectsNodeBounds(c1, float32Array2, ray, near, far);
3322
+ const c1Result = c1Intersection ? _raycastFirst2(c1, bvh, materialOrSide, ray, near, far) : null;
3323
+ if (c1Result) {
3324
+ const point = c1Result.point[xyzAxis];
3325
+ const isOutside = leftToRight ? point <= float32Array2[c2 + splitAxis] : (
3326
+ // min bounding data
3327
+ point >= float32Array2[c2 + splitAxis + 3]
3328
+ );
3329
+ if (isOutside) {
3330
+ return c1Result;
3331
+ }
3332
+ }
3333
+ const c2Intersection = intersectsNodeBounds(c2, float32Array2, ray, near, far);
3334
+ const c2Result = c2Intersection ? _raycastFirst2(c2, bvh, materialOrSide, ray, near, far) : null;
3335
+ if (c1Result && c2Result) {
3336
+ return c1Result.distance <= c2Result.distance ? c1Result : c2Result;
3337
+ } else {
3338
+ return c1Result || c2Result || null;
3339
+ }
3340
+ }
3341
+ }
3342
+
3343
+ // ../../node_modules/three-mesh-bvh/src/core/cast/intersectsGeometry_indirect.generated.js
3344
+ import { Box3 as Box36, Matrix4 as Matrix45 } from "three";
3345
+ var boundingBox2 = /* @__PURE__ */ new Box36();
3346
+ var triangle3 = /* @__PURE__ */ new ExtendedTriangle();
3347
+ var triangle22 = /* @__PURE__ */ new ExtendedTriangle();
3348
+ var invertedMat2 = /* @__PURE__ */ new Matrix45();
3349
+ var obb4 = /* @__PURE__ */ new OrientedBox();
3350
+ var obb23 = /* @__PURE__ */ new OrientedBox();
3351
+ function intersectsGeometry_indirect(bvh, root, otherGeometry, geometryToBvh) {
3352
+ BufferStack.setBuffer(bvh._roots[root]);
3353
+ const result = _intersectsGeometry2(0, bvh, otherGeometry, geometryToBvh);
3354
+ BufferStack.clearBuffer();
3355
+ return result;
3356
+ }
3357
+ function _intersectsGeometry2(nodeIndex32, bvh, otherGeometry, geometryToBvh, cachedObb = null) {
3358
+ const { float32Array: float32Array2, uint16Array: uint16Array2, uint32Array: uint32Array2 } = BufferStack;
3359
+ let nodeIndex16 = nodeIndex32 * 2;
3360
+ if (cachedObb === null) {
3361
+ if (!otherGeometry.boundingBox) {
3362
+ otherGeometry.computeBoundingBox();
3363
+ }
3364
+ obb4.set(otherGeometry.boundingBox.min, otherGeometry.boundingBox.max, geometryToBvh);
3365
+ cachedObb = obb4;
3366
+ }
3367
+ const isLeaf = IS_LEAF(nodeIndex16, uint16Array2);
3368
+ if (isLeaf) {
3369
+ const thisGeometry = bvh.geometry;
3370
+ const thisIndex = thisGeometry.index;
3371
+ const thisPos = thisGeometry.attributes.position;
3372
+ const otherIndex = otherGeometry.index;
3373
+ const otherPos = otherGeometry.attributes.position;
3374
+ const offset = OFFSET(nodeIndex32, uint32Array2);
3375
+ const count = COUNT(nodeIndex16, uint16Array2);
3376
+ invertedMat2.copy(geometryToBvh).invert();
3377
+ if (otherGeometry.boundsTree) {
3378
+ arrayToBox(BOUNDING_DATA_INDEX(nodeIndex32), float32Array2, obb23);
3379
+ obb23.matrix.copy(invertedMat2);
3380
+ obb23.needsUpdate = true;
3381
+ const res = otherGeometry.boundsTree.shapecast({
3382
+ intersectsBounds: (box) => obb23.intersectsBox(box),
3383
+ intersectsTriangle: (tri) => {
3384
+ tri.a.applyMatrix4(geometryToBvh);
3385
+ tri.b.applyMatrix4(geometryToBvh);
3386
+ tri.c.applyMatrix4(geometryToBvh);
3387
+ tri.needsUpdate = true;
3388
+ for (let i = offset, l = count + offset; i < l; i++) {
3389
+ setTriangle(triangle22, 3 * bvh.resolveTriangleIndex(i), thisIndex, thisPos);
3390
+ triangle22.needsUpdate = true;
3391
+ if (tri.intersectsTriangle(triangle22)) {
3392
+ return true;
3393
+ }
3394
+ }
3395
+ return false;
3396
+ }
3397
+ });
3398
+ return res;
3399
+ } else {
3400
+ const otherTriangleCount = getTriCount(otherGeometry);
3401
+ for (let i = offset, l = count + offset; i < l; i++) {
3402
+ const ti = bvh.resolveTriangleIndex(i);
3403
+ setTriangle(triangle3, 3 * ti, thisIndex, thisPos);
3404
+ triangle3.a.applyMatrix4(invertedMat2);
3405
+ triangle3.b.applyMatrix4(invertedMat2);
3406
+ triangle3.c.applyMatrix4(invertedMat2);
3407
+ triangle3.needsUpdate = true;
3408
+ for (let i2 = 0, l2 = otherTriangleCount * 3; i2 < l2; i2 += 3) {
3409
+ setTriangle(triangle22, i2, otherIndex, otherPos);
3410
+ triangle22.needsUpdate = true;
3411
+ if (triangle3.intersectsTriangle(triangle22)) {
3412
+ return true;
3413
+ }
3414
+ }
3415
+ }
3416
+ }
3417
+ } else {
3418
+ const left = LEFT_NODE(nodeIndex32);
3419
+ const right = RIGHT_NODE(nodeIndex32, uint32Array2);
3420
+ arrayToBox(BOUNDING_DATA_INDEX(left), float32Array2, boundingBox2);
3421
+ const leftIntersection = cachedObb.intersectsBox(boundingBox2) && _intersectsGeometry2(left, bvh, otherGeometry, geometryToBvh, cachedObb);
3422
+ if (leftIntersection) return true;
3423
+ arrayToBox(BOUNDING_DATA_INDEX(right), float32Array2, boundingBox2);
3424
+ const rightIntersection = cachedObb.intersectsBox(boundingBox2) && _intersectsGeometry2(right, bvh, otherGeometry, geometryToBvh, cachedObb);
3425
+ if (rightIntersection) return true;
3426
+ return false;
3427
+ }
3428
+ }
3429
+
3430
+ // ../../node_modules/three-mesh-bvh/src/core/cast/closestPointToGeometry_indirect.generated.js
3431
+ import { Matrix4 as Matrix46, Vector3 as Vector39 } from "three";
3432
+ var tempMatrix2 = /* @__PURE__ */ new Matrix46();
3433
+ var obb5 = /* @__PURE__ */ new OrientedBox();
3434
+ var obb24 = /* @__PURE__ */ new OrientedBox();
3435
+ var temp13 = /* @__PURE__ */ new Vector39();
3436
+ var temp22 = /* @__PURE__ */ new Vector39();
3437
+ var temp32 = /* @__PURE__ */ new Vector39();
3438
+ var temp42 = /* @__PURE__ */ new Vector39();
3439
+ function closestPointToGeometry_indirect(bvh, otherGeometry, geometryToBvh, target1 = {}, target2 = {}, minThreshold = 0, maxThreshold = Infinity) {
3440
+ if (!otherGeometry.boundingBox) {
3441
+ otherGeometry.computeBoundingBox();
3442
+ }
3443
+ obb5.set(otherGeometry.boundingBox.min, otherGeometry.boundingBox.max, geometryToBvh);
3444
+ obb5.needsUpdate = true;
3445
+ const geometry = bvh.geometry;
3446
+ const pos = geometry.attributes.position;
3447
+ const index = geometry.index;
3448
+ const otherPos = otherGeometry.attributes.position;
3449
+ const otherIndex = otherGeometry.index;
3450
+ const triangle4 = ExtendedTrianglePool.getPrimitive();
3451
+ const triangle23 = ExtendedTrianglePool.getPrimitive();
3452
+ let tempTarget1 = temp13;
3453
+ let tempTargetDest1 = temp22;
3454
+ let tempTarget2 = null;
3455
+ let tempTargetDest2 = null;
3456
+ if (target2) {
3457
+ tempTarget2 = temp32;
3458
+ tempTargetDest2 = temp42;
3459
+ }
3460
+ let closestDistance = Infinity;
3461
+ let closestDistanceTriIndex = null;
3462
+ let closestDistanceOtherTriIndex = null;
3463
+ tempMatrix2.copy(geometryToBvh).invert();
3464
+ obb24.matrix.copy(tempMatrix2);
3465
+ bvh.shapecast(
3466
+ {
3467
+ boundsTraverseOrder: (box) => {
3468
+ return obb5.distanceToBox(box);
3469
+ },
3470
+ intersectsBounds: (box, isLeaf, score) => {
3471
+ if (score < closestDistance && score < maxThreshold) {
3472
+ if (isLeaf) {
3473
+ obb24.min.copy(box.min);
3474
+ obb24.max.copy(box.max);
3475
+ obb24.needsUpdate = true;
3476
+ }
3477
+ return true;
3478
+ }
3479
+ return false;
3480
+ },
3481
+ intersectsRange: (offset, count) => {
3482
+ if (otherGeometry.boundsTree) {
3483
+ const otherBvh = otherGeometry.boundsTree;
3484
+ return otherBvh.shapecast({
3485
+ boundsTraverseOrder: (box) => {
3486
+ return obb24.distanceToBox(box);
3487
+ },
3488
+ intersectsBounds: (box, isLeaf, score) => {
3489
+ return score < closestDistance && score < maxThreshold;
3490
+ },
3491
+ intersectsRange: (otherOffset, otherCount) => {
3492
+ for (let i2 = otherOffset, l2 = otherOffset + otherCount; i2 < l2; i2++) {
3493
+ const ti2 = otherBvh.resolveTriangleIndex(i2);
3494
+ setTriangle(triangle23, 3 * ti2, otherIndex, otherPos);
3495
+ triangle23.a.applyMatrix4(geometryToBvh);
3496
+ triangle23.b.applyMatrix4(geometryToBvh);
3497
+ triangle23.c.applyMatrix4(geometryToBvh);
3498
+ triangle23.needsUpdate = true;
3499
+ for (let i = offset, l = offset + count; i < l; i++) {
3500
+ const ti = bvh.resolveTriangleIndex(i);
3501
+ setTriangle(triangle4, 3 * ti, index, pos);
3502
+ triangle4.needsUpdate = true;
3503
+ const dist = triangle4.distanceToTriangle(triangle23, tempTarget1, tempTarget2);
3504
+ if (dist < closestDistance) {
3505
+ tempTargetDest1.copy(tempTarget1);
3506
+ if (tempTargetDest2) {
3507
+ tempTargetDest2.copy(tempTarget2);
3508
+ }
3509
+ closestDistance = dist;
3510
+ closestDistanceTriIndex = i;
3511
+ closestDistanceOtherTriIndex = i2;
3512
+ }
3513
+ if (dist < minThreshold) {
3514
+ return true;
3515
+ }
3516
+ }
3517
+ }
3518
+ }
3519
+ });
3520
+ } else {
3521
+ const triCount = getTriCount(otherGeometry);
3522
+ for (let i2 = 0, l2 = triCount; i2 < l2; i2++) {
3523
+ setTriangle(triangle23, 3 * i2, otherIndex, otherPos);
3524
+ triangle23.a.applyMatrix4(geometryToBvh);
3525
+ triangle23.b.applyMatrix4(geometryToBvh);
3526
+ triangle23.c.applyMatrix4(geometryToBvh);
3527
+ triangle23.needsUpdate = true;
3528
+ for (let i = offset, l = offset + count; i < l; i++) {
3529
+ const ti = bvh.resolveTriangleIndex(i);
3530
+ setTriangle(triangle4, 3 * ti, index, pos);
3531
+ triangle4.needsUpdate = true;
3532
+ const dist = triangle4.distanceToTriangle(triangle23, tempTarget1, tempTarget2);
3533
+ if (dist < closestDistance) {
3534
+ tempTargetDest1.copy(tempTarget1);
3535
+ if (tempTargetDest2) {
3536
+ tempTargetDest2.copy(tempTarget2);
3537
+ }
3538
+ closestDistance = dist;
3539
+ closestDistanceTriIndex = i;
3540
+ closestDistanceOtherTriIndex = i2;
3541
+ }
3542
+ if (dist < minThreshold) {
3543
+ return true;
3544
+ }
3545
+ }
3546
+ }
3547
+ }
3548
+ }
3549
+ }
3550
+ );
3551
+ ExtendedTrianglePool.releasePrimitive(triangle4);
3552
+ ExtendedTrianglePool.releasePrimitive(triangle23);
3553
+ if (closestDistance === Infinity) {
3554
+ return null;
3555
+ }
3556
+ if (!target1.point) {
3557
+ target1.point = tempTargetDest1.clone();
3558
+ } else {
3559
+ target1.point.copy(tempTargetDest1);
3560
+ }
3561
+ target1.distance = closestDistance, target1.faceIndex = closestDistanceTriIndex;
3562
+ if (target2) {
3563
+ if (!target2.point) target2.point = tempTargetDest2.clone();
3564
+ else target2.point.copy(tempTargetDest2);
3565
+ target2.point.applyMatrix4(tempMatrix2);
3566
+ tempTargetDest1.applyMatrix4(tempMatrix2);
3567
+ target2.distance = tempTargetDest1.sub(target2.point).length();
3568
+ target2.faceIndex = closestDistanceOtherTriIndex;
3569
+ }
3570
+ return target1;
3571
+ }
3572
+
3573
+ // ../../node_modules/three-mesh-bvh/src/utils/GeometryRayIntersectUtilities.js
3574
+ function convertRaycastIntersect(hit, object, raycaster) {
3575
+ if (hit === null) {
3576
+ return null;
3577
+ }
3578
+ hit.point.applyMatrix4(object.matrixWorld);
3579
+ hit.distance = hit.point.distanceTo(raycaster.ray.origin);
3580
+ hit.object = object;
3581
+ return hit;
3582
+ }
3583
+
3584
+ // ../../node_modules/three-mesh-bvh/src/core/MeshBVH.js
3585
+ var _obb = /* @__PURE__ */ new OrientedBox();
3586
+ var _ray = /* @__PURE__ */ new Ray();
3587
+ var _direction = /* @__PURE__ */ new Vector310();
3588
+ var _inverseMatrix = /* @__PURE__ */ new Matrix47();
3589
+ var _worldScale = /* @__PURE__ */ new Vector310();
3590
+ var _getters = ["getX", "getY", "getZ"];
3591
+ var MeshBVH = class _MeshBVH extends GeometryBVH {
3592
+ /**
3593
+ * Generates a representation of the complete bounds tree and the geometry index buffer which
3594
+ * can be used to recreate a bounds tree using the `deserialize` function. The `serialize` and
3595
+ * `deserialize` functions can be used to generate a MeshBVH asynchronously in a background web
3596
+ * worker to prevent the main thread from stuttering. The BVH roots buffer stored in the
3597
+ * serialized representation are the same as the ones used by the original BVH so they should
3598
+ * not be modified. If `SharedArrayBuffers` are used then the same BVH memory can be used for
3599
+ * multiple BVH in multiple WebWorkers.
3600
+ *
3601
+ * @static
3602
+ * @param {MeshBVH} bvh - The BVH to serialize.
3603
+ * @param {Object} [options]
3604
+ * @param {boolean} [options.cloneBuffers=true] - If `true`, the index and BVH root buffers
3605
+ * are cloned so the serialized data is independent of the live BVH.
3606
+ * @returns {SerializedBVH}
3607
+ */
3608
+ static serialize(bvh, options = {}) {
3609
+ options = {
3610
+ cloneBuffers: true,
3611
+ ...options
3612
+ };
3613
+ const geometry = bvh.geometry;
3614
+ const rootData = bvh._roots;
3615
+ const indirectBuffer = bvh._indirectBuffer;
3616
+ const indexAttribute = geometry.getIndex();
3617
+ const result = {
3618
+ version: 1,
3619
+ roots: null,
3620
+ index: null,
3621
+ indirectBuffer: null
3622
+ };
3623
+ if (options.cloneBuffers) {
3624
+ result.roots = rootData.map((root) => root.slice());
3625
+ result.index = indexAttribute ? indexAttribute.array.slice() : null;
3626
+ result.indirectBuffer = indirectBuffer ? indirectBuffer.slice() : null;
3627
+ } else {
3628
+ result.roots = rootData;
3629
+ result.index = indexAttribute ? indexAttribute.array : null;
3630
+ result.indirectBuffer = indirectBuffer;
3631
+ }
3632
+ return result;
3633
+ }
3634
+ /**
3635
+ * Returns a new MeshBVH instance from the serialized data. `geometry` is the geometry used
3636
+ * to generate the original BVH `data` was derived from. The root buffers stored in `data`
3637
+ * are set directly on the new BVH so the memory is shared.
3638
+ *
3639
+ * @static
3640
+ * @param {SerializedBVH} data - Serialized BVH data.
3641
+ * @param {BufferGeometry} geometry - The geometry the BVH was originally built from.
3642
+ * @param {Object} [options]
3643
+ * @param {boolean} [options.setIndex=true] - If `true`, sets `geometry.index` from the
3644
+ * serialized index buffer (creating one if none exists).
3645
+ * @returns {MeshBVH}
3646
+ */
3647
+ static deserialize(data, geometry, options = {}) {
3648
+ options = {
3649
+ setIndex: true,
3650
+ indirect: Boolean(data.indirectBuffer),
3651
+ ...options
3652
+ };
3653
+ const { index, roots, indirectBuffer } = data;
3654
+ if (!data.version) {
3655
+ console.warn(
3656
+ "MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."
3657
+ );
3658
+ fixupVersion0(roots);
3659
+ }
3660
+ const bvh = new _MeshBVH(geometry, { ...options, [SKIP_GENERATION]: true });
3661
+ bvh._roots = roots;
3662
+ bvh._indirectBuffer = indirectBuffer || null;
3663
+ if (options.setIndex) {
3664
+ const indexAttribute = geometry.getIndex();
3665
+ if (indexAttribute === null) {
3666
+ const newIndex = new BufferAttribute2(data.index, 1, false);
3667
+ geometry.setIndex(newIndex);
3668
+ } else if (indexAttribute.array !== index) {
3669
+ indexAttribute.array.set(index);
3670
+ indexAttribute.needsUpdate = true;
3671
+ }
3672
+ }
3673
+ return bvh;
3674
+ function fixupVersion0(roots2) {
3675
+ for (let rootIndex = 0; rootIndex < roots2.length; rootIndex++) {
3676
+ const root = roots2[rootIndex];
3677
+ const uint32Array2 = new Uint32Array(root);
3678
+ const uint16Array2 = new Uint16Array(root);
3679
+ for (let node = 0, l = root.byteLength / BYTES_PER_NODE; node < l; node++) {
3680
+ const node32Index = UINT32_PER_NODE * node;
3681
+ const node16Index = 2 * node32Index;
3682
+ if (!IS_LEAF(node16Index, uint16Array2)) {
3683
+ uint32Array2[node32Index + 6] = uint32Array2[node32Index + 6] / UINT32_PER_NODE - node;
3684
+ }
3685
+ }
3686
+ }
3687
+ }
3688
+ }
3689
+ get primitiveStride() {
3690
+ return 3;
3691
+ }
3692
+ /**
3693
+ * Helper function for use when `indirect` is set to true. This function takes a triangle
3694
+ * index in the BVH layout and returns the associated triangle index in the geometry index
3695
+ * buffer or position attribute.
3696
+ * @type {function(number): number}
3697
+ * @readonly
3698
+ */
3699
+ get resolveTriangleIndex() {
3700
+ return this.resolvePrimitiveIndex;
3701
+ }
3702
+ constructor(geometry, options = {}) {
3703
+ if (options.maxLeafTris) {
3704
+ console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.');
3705
+ options = {
3706
+ ...options,
3707
+ targetLeafSize: options.maxLeafTris
3708
+ };
3709
+ }
3710
+ super(geometry, options);
3711
+ }
3712
+ /**
3713
+ * Adjusts all triangle offsets stored in the BVH by the given offset. This is useful when the
3714
+ * triangle data has been compacted or shifted in the geometry buffers (e.g. in `BatchedMesh`
3715
+ * when geometries are compacted using the 'optimize' function or constructing a 'merged' BVH).
3716
+ * This function only adjusts the BVH to point to different triangles in the geometry. The
3717
+ * geometry's index buffer and/or position attributes must be updated separately to match.
3718
+ *
3719
+ * @param {number} offset
3720
+ * @returns {void}
3721
+ */
3722
+ // implement abstract methods from BVH base class
3723
+ shiftTriangleOffsets(offset) {
3724
+ return super.shiftPrimitiveOffsets(offset);
3725
+ }
3726
+ // write primitive bounds to the buffer - used only for validateBounds at the moment
3727
+ writePrimitiveBounds(i, targetBuffer, baseIndex) {
3728
+ const geometry = this.geometry;
3729
+ const indirectBuffer = this._indirectBuffer;
3730
+ const posAttr = geometry.attributes.position;
3731
+ const index = geometry.index ? geometry.index.array : null;
3732
+ const tri = indirectBuffer ? indirectBuffer[i] : i;
3733
+ const tri3 = tri * 3;
3734
+ let ai = tri3 + 0;
3735
+ let bi = tri3 + 1;
3736
+ let ci = tri3 + 2;
3737
+ if (index) {
3738
+ ai = index[ai];
3739
+ bi = index[bi];
3740
+ ci = index[ci];
3741
+ }
3742
+ for (let el = 0; el < 3; el++) {
3743
+ const a = posAttr[_getters[el]](ai);
3744
+ const b = posAttr[_getters[el]](bi);
3745
+ const c = posAttr[_getters[el]](ci);
3746
+ let min = a;
3747
+ if (b < min) min = b;
3748
+ if (c < min) min = c;
3749
+ let max = a;
3750
+ if (b > max) max = b;
3751
+ if (c > max) max = c;
3752
+ targetBuffer[baseIndex + el] = min;
3753
+ targetBuffer[baseIndex + el + 3] = max;
3754
+ }
3755
+ return targetBuffer;
3756
+ }
3757
+ // precomputes the bounding box for each triangle; required for quickly calculating tree splits.
3758
+ // result is an array of size count * 6 where triangle i maps to a
3759
+ // [x_center, x_delta, y_center, y_delta, z_center, z_delta] tuple starting at index (i - offset) * 6,
3760
+ // representing the center and half-extent in each dimension of triangle i
3761
+ computePrimitiveBounds(offset, count, targetBuffer) {
3762
+ const geometry = this.geometry;
3763
+ const indirectBuffer = this._indirectBuffer;
3764
+ const posAttr = geometry.attributes.position;
3765
+ const index = geometry.index ? geometry.index.array : null;
3766
+ const normalized = posAttr.normalized;
3767
+ if (offset < 0 || count + offset - targetBuffer.offset > targetBuffer.length / 6) {
3768
+ throw new Error("MeshBVH: compute triangle bounds range is invalid.");
3769
+ }
3770
+ const posArr = posAttr.array;
3771
+ const bufferOffset = posAttr.offset || 0;
3772
+ let stride = 3;
3773
+ if (posAttr.isInterleavedBufferAttribute) {
3774
+ stride = posAttr.data.stride;
3775
+ }
3776
+ const getters = ["getX", "getY", "getZ"];
3777
+ const writeOffset = targetBuffer.offset;
3778
+ for (let i = offset, l = offset + count; i < l; i++) {
3779
+ const tri = indirectBuffer ? indirectBuffer[i] : i;
3780
+ const tri3 = tri * 3;
3781
+ const boundsIndexOffset = (i - writeOffset) * 6;
3782
+ let ai = tri3 + 0;
3783
+ let bi = tri3 + 1;
3784
+ let ci = tri3 + 2;
3785
+ if (index) {
3786
+ ai = index[ai];
3787
+ bi = index[bi];
3788
+ ci = index[ci];
3789
+ }
3790
+ if (!normalized) {
3791
+ ai = ai * stride + bufferOffset;
3792
+ bi = bi * stride + bufferOffset;
3793
+ ci = ci * stride + bufferOffset;
3794
+ }
3795
+ for (let el = 0; el < 3; el++) {
3796
+ let a, b, c;
3797
+ if (normalized) {
3798
+ a = posAttr[getters[el]](ai);
3799
+ b = posAttr[getters[el]](bi);
3800
+ c = posAttr[getters[el]](ci);
3801
+ } else {
3802
+ a = posArr[ai + el];
3803
+ b = posArr[bi + el];
3804
+ c = posArr[ci + el];
3805
+ }
3806
+ let min = a;
3807
+ if (b < min) min = b;
3808
+ if (c < min) min = c;
3809
+ let max = a;
3810
+ if (b > max) max = b;
3811
+ if (c > max) max = c;
3812
+ const halfExtents = (max - min) / 2;
3813
+ const el2 = el * 2;
3814
+ targetBuffer[boundsIndexOffset + el2 + 0] = min + halfExtents;
3815
+ targetBuffer[boundsIndexOffset + el2 + 1] = halfExtents + (Math.abs(min) + halfExtents) * FLOAT32_EPSILON;
3816
+ }
3817
+ }
3818
+ return targetBuffer;
3819
+ }
3820
+ /**
3821
+ * A convenience function for performing a raycast based on a mesh. Results are formed like
3822
+ * three.js raycast results in world frame.
3823
+ *
3824
+ * @param {Object3D} object
3825
+ * @param {Raycaster} raycaster
3826
+ * @param {Array<Intersection>} [intersects=[]]
3827
+ * @returns {Array<Intersection>}
3828
+ */
3829
+ raycastObject3D(object, raycaster, intersects = []) {
3830
+ const { material } = object;
3831
+ if (material === void 0) {
3832
+ return;
3833
+ }
3834
+ _inverseMatrix.copy(object.matrixWorld).invert();
3835
+ _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
3836
+ _worldScale.setFromMatrixScale(object.matrixWorld);
3837
+ _direction.copy(_ray.direction).multiply(_worldScale);
3838
+ const scaleFactor = _direction.length();
3839
+ const near = raycaster.near / scaleFactor;
3840
+ const far = raycaster.far / scaleFactor;
3841
+ if (raycaster.firstHitOnly === true) {
3842
+ let hit = this.raycastFirst(_ray, material, near, far);
3843
+ hit = convertRaycastIntersect(hit, object, raycaster);
3844
+ if (hit) {
3845
+ intersects.push(hit);
3846
+ }
3847
+ } else {
3848
+ const hits = this.raycast(_ray, material, near, far);
3849
+ for (let i = 0, l = hits.length; i < l; i++) {
3850
+ const hit = convertRaycastIntersect(hits[i], object, raycaster);
3851
+ if (hit) {
3852
+ intersects.push(hit);
3853
+ }
3854
+ }
3855
+ }
3856
+ return intersects;
3857
+ }
3858
+ /**
3859
+ * Refit the node bounds to the current triangle positions. This is quicker than regenerating
3860
+ * a new BVH but will not be optimal after significant changes to the vertices. `nodeIndices`
3861
+ * is a set of node indices (provided by the `shapecast` function) that need to be refit
3862
+ * including all internal nodes.
3863
+ *
3864
+ * @param {Set<number>|Array<number>|null} [nodeIndices=null]
3865
+ */
3866
+ refit(nodeIndices = null) {
3867
+ const refitFunc = this.indirect ? refit_indirect : refit;
3868
+ return refitFunc(this, nodeIndices);
3869
+ }
3870
+ /* Core Cast Functions */
3871
+ /**
3872
+ * Returns all raycast triangle hits in unsorted order. It is expected that `ray` is in the
3873
+ * frame of the BVH already. Likewise the returned results are also provided in the local
3874
+ * frame of the BVH. The `side` identifier is used to determine the side to check when
3875
+ * raycasting or a material with the given side field can be passed. If an array of materials
3876
+ * is provided then it is expected that the geometry has groups and the appropriate material
3877
+ * side is used per group.
3878
+ *
3879
+ * Note that unlike three.js' Raycaster results the points and distances in the intersections
3880
+ * returned from this function are relative to the local frame of the MeshBVH. When using the
3881
+ * `acceleratedRaycast` function as an override for `Mesh.raycast` they are transformed into
3882
+ * world space to be consistent with three's results.
3883
+ *
3884
+ * @param {Ray} ray
3885
+ * @param {number|Material|Array<Material>} [materialOrSide=FrontSide]
3886
+ * @param {number} [near=0]
3887
+ * @param {number} [far=Infinity]
3888
+ * @returns {Array<Intersection>}
3889
+ */
3890
+ raycast(ray, materialOrSide = FrontSide, near = 0, far = Infinity) {
3891
+ const roots = this._roots;
3892
+ const intersects = [];
3893
+ const raycastFunc = this.indirect ? raycast_indirect : raycast;
3894
+ for (let i = 0, l = roots.length; i < l; i++) {
3895
+ raycastFunc(this, i, materialOrSide, ray, intersects, near, far);
3896
+ }
3897
+ return intersects;
3898
+ }
3899
+ /**
3900
+ * Returns the first raycast hit in the model. This is typically much faster than returning
3901
+ * all hits. See `raycast` for information on the side and material options as well as the
3902
+ * frame of the returned intersections.
3903
+ *
3904
+ * @param {Ray} ray
3905
+ * @param {number|Material|Array<Material>} [materialOrSide=FrontSide]
3906
+ * @param {number} [near=0]
3907
+ * @param {number} [far=Infinity]
3908
+ * @returns {Intersection|null}
3909
+ */
3910
+ raycastFirst(ray, materialOrSide = FrontSide, near = 0, far = Infinity) {
3911
+ const roots = this._roots;
3912
+ let closestResult = null;
3913
+ const raycastFirstFunc = this.indirect ? raycastFirst_indirect : raycastFirst;
3914
+ for (let i = 0, l = roots.length; i < l; i++) {
3915
+ const result = raycastFirstFunc(this, i, materialOrSide, ray, near, far);
3916
+ if (result != null && (closestResult == null || result.distance < closestResult.distance)) {
3917
+ closestResult = result;
3918
+ }
3919
+ }
3920
+ return closestResult;
3921
+ }
3922
+ /**
3923
+ * Returns whether or not the mesh intersects the given geometry.
3924
+ *
3925
+ * The `geometryToBvh` parameter is the transform of the geometry in the BVH's local frame.
3926
+ *
3927
+ * Performance improves considerably if the provided geometry also has a `boundsTree`.
3928
+ *
3929
+ * @param {BufferGeometry} otherGeometry
3930
+ * @param {Matrix4} geometryToBvh - Transform of `otherGeometry` into the local space of
3931
+ * this BVH.
3932
+ * @returns {boolean}
3933
+ */
3934
+ intersectsGeometry(otherGeometry, geomToMesh) {
3935
+ let result = false;
3936
+ const roots = this._roots;
3937
+ const intersectsGeometryFunc = this.indirect ? intersectsGeometry_indirect : intersectsGeometry;
3938
+ for (let i = 0, l = roots.length; i < l; i++) {
3939
+ result = intersectsGeometryFunc(this, i, otherGeometry, geomToMesh);
3940
+ if (result) {
3941
+ break;
3942
+ }
3943
+ }
3944
+ return result;
3945
+ }
3946
+ /**
3947
+ * A generalized cast function that can be used to implement intersection logic for custom
3948
+ * shapes. This is used internally for `intersectsBox`, `intersectsSphere`, and more. The
3949
+ * function returns as soon as a triangle has been reported as intersected and returns `true`
3950
+ * if a triangle has been intersected.
3951
+ *
3952
+ * @param {Object} callbacks
3953
+ * @param {IntersectsBoundsCallback} callbacks.intersectsBounds
3954
+ * @param {IntersectsTriangleCallback} [callbacks.intersectsTriangle]
3955
+ * @param {IntersectsRangeCallback} [callbacks.intersectsRange]
3956
+ * @param {BoundsTraverseOrderCallback} [callbacks.boundsTraverseOrder]
3957
+ * @returns {boolean}
3958
+ */
3959
+ shapecast(callbacks) {
3960
+ const triangle4 = ExtendedTrianglePool.getPrimitive();
3961
+ const result = super.shapecast(
3962
+ {
3963
+ ...callbacks,
3964
+ intersectsPrimitive: callbacks.intersectsTriangle,
3965
+ scratchPrimitive: triangle4,
3966
+ // TODO: is the performance significant enough for the added complexity here?
3967
+ // can we just use one function?
3968
+ iterate: this.indirect ? iterateOverTriangles_indirect : iterateOverTriangles
3969
+ }
3970
+ );
3971
+ ExtendedTrianglePool.releasePrimitive(triangle4);
3972
+ return result;
3973
+ }
3974
+ /**
3975
+ * A generalized cast function that traverses two BVH structures simultaneously to perform
3976
+ * intersection tests between them. This is used internally by `intersectsGeometry`. The
3977
+ * function returns `true` as soon as a triangle pair has been reported as intersected by
3978
+ * the callbacks.
3979
+ *
3980
+ * `matrixToLocal` is a Matrix4 that transforms `otherBvh` into the local space of this BVH.
3981
+ * The other BVH's triangles are transformed by this matrix before intersection tests.
3982
+ *
3983
+ * @param {MeshBVH} otherBvh
3984
+ * @param {Matrix4} matrixToLocal - Transforms `otherBvh` into the local space of this BVH.
3985
+ * @param {Object} callbacks
3986
+ * @param {IntersectsRangesCallback} [callbacks.intersectsRanges]
3987
+ * @param {IntersectsTrianglesCallback} [callbacks.intersectsTriangles]
3988
+ * @returns {boolean}
3989
+ */
3990
+ bvhcast(otherBvh, matrixToLocal, callbacks) {
3991
+ let {
3992
+ intersectsRanges,
3993
+ intersectsTriangles
3994
+ } = callbacks;
3995
+ const triangle1 = ExtendedTrianglePool.getPrimitive();
3996
+ const indexAttr1 = this.geometry.index;
3997
+ const positionAttr1 = this.geometry.attributes.position;
3998
+ const assignTriangle1 = this.indirect ? (i1) => {
3999
+ const ti = this.resolveTriangleIndex(i1);
4000
+ setTriangle(triangle1, ti * 3, indexAttr1, positionAttr1);
4001
+ } : (i1) => {
4002
+ setTriangle(triangle1, i1 * 3, indexAttr1, positionAttr1);
4003
+ };
4004
+ const triangle23 = ExtendedTrianglePool.getPrimitive();
4005
+ const indexAttr2 = otherBvh.geometry.index;
4006
+ const positionAttr2 = otherBvh.geometry.attributes.position;
4007
+ const assignTriangle2 = otherBvh.indirect ? (i2) => {
4008
+ const ti2 = otherBvh.resolveTriangleIndex(i2);
4009
+ setTriangle(triangle23, ti2 * 3, indexAttr2, positionAttr2);
4010
+ } : (i2) => {
4011
+ setTriangle(triangle23, i2 * 3, indexAttr2, positionAttr2);
4012
+ };
4013
+ if (intersectsTriangles) {
4014
+ if (!(otherBvh instanceof _MeshBVH)) {
4015
+ throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');
4016
+ }
4017
+ const iterateOverDoubleTriangles = (offset1, count1, offset2, count2, depth1, nodeIndex1, depth2, nodeIndex2) => {
4018
+ for (let i2 = offset2, l2 = offset2 + count2; i2 < l2; i2++) {
4019
+ assignTriangle2(i2);
4020
+ triangle23.a.applyMatrix4(matrixToLocal);
4021
+ triangle23.b.applyMatrix4(matrixToLocal);
4022
+ triangle23.c.applyMatrix4(matrixToLocal);
4023
+ triangle23.needsUpdate = true;
4024
+ for (let i1 = offset1, l1 = offset1 + count1; i1 < l1; i1++) {
4025
+ assignTriangle1(i1);
4026
+ triangle1.needsUpdate = true;
4027
+ if (intersectsTriangles(triangle1, triangle23, i1, i2, depth1, nodeIndex1, depth2, nodeIndex2)) {
4028
+ return true;
4029
+ }
4030
+ }
4031
+ }
4032
+ return false;
4033
+ };
4034
+ if (intersectsRanges) {
4035
+ const originalIntersectsRanges = intersectsRanges;
4036
+ intersectsRanges = function(offset1, count1, offset2, count2, depth1, nodeIndex1, depth2, nodeIndex2) {
4037
+ if (!originalIntersectsRanges(offset1, count1, offset2, count2, depth1, nodeIndex1, depth2, nodeIndex2)) {
4038
+ return iterateOverDoubleTriangles(offset1, count1, offset2, count2, depth1, nodeIndex1, depth2, nodeIndex2);
4039
+ }
4040
+ return true;
4041
+ };
4042
+ } else {
4043
+ intersectsRanges = iterateOverDoubleTriangles;
4044
+ }
4045
+ }
4046
+ return super.bvhcast(otherBvh, matrixToLocal, { intersectsRanges });
4047
+ }
4048
+ /* Derived Cast Functions */
4049
+ /**
4050
+ * Returns whether or not the mesh intersects the given box.
4051
+ *
4052
+ * The `boxToBvh` parameter is the transform of the box in the meshes frame.
4053
+ *
4054
+ * @param {Box3} box
4055
+ * @param {Matrix4} boxToBvh - Transform of the box in the local space of this BVH.
4056
+ * @returns {boolean}
4057
+ */
4058
+ intersectsBox(box, boxToMesh) {
4059
+ _obb.set(box.min, box.max, boxToMesh);
4060
+ _obb.needsUpdate = true;
4061
+ return this.shapecast(
4062
+ {
4063
+ intersectsBounds: (box2) => _obb.intersectsBox(box2),
4064
+ intersectsTriangle: (tri) => _obb.intersectsTriangle(tri)
4065
+ }
4066
+ );
4067
+ }
4068
+ /**
4069
+ * Returns whether or not the mesh intersects the given sphere.
4070
+ *
4071
+ * @param {Sphere} sphere
4072
+ * @returns {boolean}
4073
+ */
4074
+ intersectsSphere(sphere) {
4075
+ return this.shapecast(
4076
+ {
4077
+ intersectsBounds: (box) => sphere.intersectsBox(box),
4078
+ intersectsTriangle: (tri) => tri.intersectsSphere(sphere)
4079
+ }
4080
+ );
4081
+ }
4082
+ /**
4083
+ * Computes the closest distance from the geometry to the mesh and puts the closest point on
4084
+ * the mesh in `target1` (in the frame of the BVH) and the closest point on the other
4085
+ * geometry in `target2` (in the geometry frame). If `target1` is not provided a new Object
4086
+ * is created and returned from the function.
4087
+ *
4088
+ * The `geometryToBvh` parameter is the transform of the geometry in the BVH's local frame.
4089
+ *
4090
+ * If a point is found that is closer than `minThreshold` then the function will return that
4091
+ * result early. Any triangles or points outside of `maxThreshold` are ignored. If no point
4092
+ * is found within the min / max thresholds then `null` is returned and the target objects
4093
+ * are not modified.
4094
+ *
4095
+ * The returned faceIndex in `target1` and `target2` can be used with the standalone function
4096
+ * `getTriangleHitPointInfo` to obtain more information like UV coordinates, triangle normal
4097
+ * and materialIndex.
4098
+ *
4099
+ * _Note that this function can be very slow if `geometry` does not have a
4100
+ * `geometry.boundsTree` computed._
4101
+ *
4102
+ * @param {BufferGeometry} otherGeometry
4103
+ * @param {Matrix4} geometryToBvh - Transform of `otherGeometry` into the local space of
4104
+ * this BVH.
4105
+ * @param {HitPointInfo} [target1={}]
4106
+ * @param {HitPointInfo} [target2={}]
4107
+ * @param {number} [minThreshold=0]
4108
+ * @param {number} [maxThreshold=Infinity]
4109
+ * @returns {HitPointInfo|null}
4110
+ */
4111
+ closestPointToGeometry(otherGeometry, geometryToBvh, target1 = {}, target2 = {}, minThreshold = 0, maxThreshold = Infinity) {
4112
+ const closestPointToGeometryFunc = this.indirect ? closestPointToGeometry_indirect : closestPointToGeometry;
4113
+ return closestPointToGeometryFunc(
4114
+ this,
4115
+ otherGeometry,
4116
+ geometryToBvh,
4117
+ target1,
4118
+ target2,
4119
+ minThreshold,
4120
+ maxThreshold
4121
+ );
4122
+ }
4123
+ /**
4124
+ * Computes the closest distance from the point to the mesh and gives additional information
4125
+ * in `target`. The target can be left undefined to default to a new object which is
4126
+ * ultimately returned by the function.
4127
+ *
4128
+ * If a point is found that is closer than `minThreshold` then the function will return that
4129
+ * result early. Any triangles or points outside of `maxThreshold` are ignored. If no point
4130
+ * is found within the min / max thresholds then `null` is returned and the `target` object
4131
+ * is not modified.
4132
+ *
4133
+ * The returned faceIndex can be used with the standalone function `getTriangleHitPointInfo`
4134
+ * to obtain more information like UV coordinates, triangle normal and materialIndex.
4135
+ *
4136
+ * @param {Vector3} point
4137
+ * @param {HitPointInfo} [target={}]
4138
+ * @param {number} [minThreshold=0]
4139
+ * @param {number} [maxThreshold=Infinity]
4140
+ * @returns {HitPointInfo|null}
4141
+ */
4142
+ closestPointToPoint(point, target = {}, minThreshold = 0, maxThreshold = Infinity) {
4143
+ return closestPointToPoint(
4144
+ this,
4145
+ point,
4146
+ target,
4147
+ minThreshold,
4148
+ maxThreshold
4149
+ );
4150
+ }
4151
+ };
4152
+
4153
+ // ../../node_modules/three-mesh-bvh/src/webgl/glsl/common_functions.glsl.js
4154
+ var common_functions = (
4155
+ /* glsl */
4156
+ `
4157
+
4158
+ // A stack of uint32 indices can can store the indices for
4159
+ // a perfectly balanced tree with a depth up to 31. Lower stack
4160
+ // depth gets higher performance.
4161
+ //
4162
+ // However not all trees are balanced. Best value to set this to
4163
+ // is the trees max depth.
4164
+ #ifndef BVH_STACK_DEPTH
4165
+ #define BVH_STACK_DEPTH 60
4166
+ #endif
4167
+
4168
+ #ifndef INFINITY
4169
+ #define INFINITY 1e20
4170
+ #endif
4171
+
4172
+ // Utilities
4173
+ uvec4 uTexelFetch1D( usampler2D tex, uint index ) {
4174
+
4175
+ uint width = uint( textureSize( tex, 0 ).x );
4176
+ uvec2 uv;
4177
+ uv.x = index % width;
4178
+ uv.y = index / width;
4179
+
4180
+ return texelFetch( tex, ivec2( uv ), 0 );
4181
+
4182
+ }
4183
+
4184
+ ivec4 iTexelFetch1D( isampler2D tex, uint index ) {
4185
+
4186
+ uint width = uint( textureSize( tex, 0 ).x );
4187
+ uvec2 uv;
4188
+ uv.x = index % width;
4189
+ uv.y = index / width;
4190
+
4191
+ return texelFetch( tex, ivec2( uv ), 0 );
4192
+
4193
+ }
4194
+
4195
+ vec4 texelFetch1D( sampler2D tex, uint index ) {
4196
+
4197
+ uint width = uint( textureSize( tex, 0 ).x );
4198
+ uvec2 uv;
4199
+ uv.x = index % width;
4200
+ uv.y = index / width;
4201
+
4202
+ return texelFetch( tex, ivec2( uv ), 0 );
4203
+
4204
+ }
4205
+
4206
+ vec4 textureSampleBarycoord( sampler2D tex, vec3 barycoord, uvec3 faceIndices ) {
4207
+
4208
+ return
4209
+ barycoord.x * texelFetch1D( tex, faceIndices.x ) +
4210
+ barycoord.y * texelFetch1D( tex, faceIndices.y ) +
4211
+ barycoord.z * texelFetch1D( tex, faceIndices.z );
4212
+
4213
+ }
4214
+
4215
+ void ndcToCameraRay(
4216
+ vec2 coord, mat4 cameraWorld, mat4 invProjectionMatrix,
4217
+ out vec3 rayOrigin, out vec3 rayDirection
4218
+ ) {
4219
+
4220
+ // get camera look direction and near plane for camera clipping
4221
+ vec4 lookDirection = cameraWorld * vec4( 0.0, 0.0, - 1.0, 0.0 );
4222
+ vec4 nearVector = invProjectionMatrix * vec4( 0.0, 0.0, - 1.0, 1.0 );
4223
+ float near = abs( nearVector.z / nearVector.w );
4224
+
4225
+ // get the camera direction and position from camera matrices
4226
+ vec4 origin = cameraWorld * vec4( 0.0, 0.0, 0.0, 1.0 );
4227
+ vec4 direction = invProjectionMatrix * vec4( coord, 0.5, 1.0 );
4228
+ direction /= direction.w;
4229
+ direction = cameraWorld * direction - origin;
4230
+
4231
+ // slide the origin along the ray until it sits at the near clip plane position
4232
+ origin.xyz += direction.xyz * near / dot( direction, lookDirection );
4233
+
4234
+ rayOrigin = origin.xyz;
4235
+ rayDirection = direction.xyz;
4236
+
4237
+ }
4238
+ `
4239
+ );
4240
+
4241
+ // ../../node_modules/three-mesh-bvh/src/webgl/glsl/bvh_ray_functions.glsl.js
4242
+ var bvh_ray_functions = (
4243
+ /* glsl */
4244
+ `
4245
+
4246
+ #ifndef TRI_INTERSECT_EPSILON
4247
+ #define TRI_INTERSECT_EPSILON 1e-5
4248
+ #endif
4249
+
4250
+ // Raycasting
4251
+ bool intersectsBounds( vec3 rayOrigin, vec3 rayDirection, vec3 boundsMin, vec3 boundsMax, out float dist ) {
4252
+
4253
+ // https://www.reddit.com/r/opengl/comments/8ntzz5/fast_glsl_ray_box_intersection/
4254
+ // https://tavianator.com/2011/ray_box.html
4255
+ vec3 invDir = 1.0 / rayDirection;
4256
+
4257
+ // find intersection distances for each plane
4258
+ vec3 tMinPlane = invDir * ( boundsMin - rayOrigin );
4259
+ vec3 tMaxPlane = invDir * ( boundsMax - rayOrigin );
4260
+
4261
+ // get the min and max distances from each intersection
4262
+ vec3 tMinHit = min( tMaxPlane, tMinPlane );
4263
+ vec3 tMaxHit = max( tMaxPlane, tMinPlane );
4264
+
4265
+ // get the furthest hit distance
4266
+ vec2 t = max( tMinHit.xx, tMinHit.yz );
4267
+ float t0 = max( t.x, t.y );
4268
+
4269
+ // get the minimum hit distance
4270
+ t = min( tMaxHit.xx, tMaxHit.yz );
4271
+ float t1 = min( t.x, t.y );
4272
+
4273
+ // set distance to 0.0 if the ray starts inside the box
4274
+ dist = max( t0, 0.0 );
4275
+
4276
+ return t1 >= dist;
4277
+
4278
+ }
4279
+
4280
+ bool intersectsTriangle(
4281
+ vec3 rayOrigin, vec3 rayDirection, vec3 a, vec3 b, vec3 c,
4282
+ out vec3 barycoord, out vec3 norm, out float dist, out float side
4283
+ ) {
4284
+
4285
+ // https://stackoverflow.com/questions/42740765/intersection-between-line-and-triangle-in-3d
4286
+ vec3 edge1 = b - a;
4287
+ vec3 edge2 = c - a;
4288
+ norm = cross( edge1, edge2 );
4289
+
4290
+ float det = - dot( rayDirection, norm );
4291
+ float invdet = 1.0 / det;
4292
+
4293
+ vec3 AO = rayOrigin - a;
4294
+ vec3 DAO = cross( AO, rayDirection );
4295
+
4296
+ vec4 uvt;
4297
+ uvt.x = dot( edge2, DAO ) * invdet;
4298
+ uvt.y = - dot( edge1, DAO ) * invdet;
4299
+ uvt.z = dot( AO, norm ) * invdet;
4300
+ uvt.w = 1.0 - uvt.x - uvt.y;
4301
+
4302
+ // set the hit information
4303
+ barycoord = uvt.wxy; // arranged in A, B, C order
4304
+ dist = uvt.z;
4305
+ side = sign( det );
4306
+ norm = side * normalize( norm );
4307
+
4308
+ // add an epsilon to avoid misses between triangles
4309
+ uvt += vec4( TRI_INTERSECT_EPSILON );
4310
+
4311
+ return all( greaterThanEqual( uvt, vec4( 0.0 ) ) );
4312
+
4313
+ }
4314
+
4315
+ bool intersectTriangles(
4316
+ // geometry info and triangle range
4317
+ sampler2D positionAttr, usampler2D indexAttr, uint offset, uint count,
4318
+
4319
+ // ray
4320
+ vec3 rayOrigin, vec3 rayDirection,
4321
+
4322
+ // outputs
4323
+ inout float minDistance, inout uvec4 faceIndices, inout vec3 faceNormal, inout vec3 barycoord,
4324
+ inout float side, inout float dist
4325
+ ) {
4326
+
4327
+ bool found = false;
4328
+ vec3 localBarycoord, localNormal;
4329
+ float localDist, localSide;
4330
+ for ( uint i = offset, l = offset + count; i < l; i ++ ) {
4331
+
4332
+ uvec3 indices = uTexelFetch1D( indexAttr, i ).xyz;
4333
+ vec3 a = texelFetch1D( positionAttr, indices.x ).rgb;
4334
+ vec3 b = texelFetch1D( positionAttr, indices.y ).rgb;
4335
+ vec3 c = texelFetch1D( positionAttr, indices.z ).rgb;
4336
+
4337
+ if (
4338
+ intersectsTriangle( rayOrigin, rayDirection, a, b, c, localBarycoord, localNormal, localDist, localSide )
4339
+ && localDist < minDistance
4340
+ ) {
4341
+
4342
+ found = true;
4343
+ minDistance = localDist;
4344
+
4345
+ faceIndices = uvec4( indices.xyz, i );
4346
+ faceNormal = localNormal;
4347
+
4348
+ side = localSide;
4349
+ barycoord = localBarycoord;
4350
+ dist = localDist;
4351
+
4352
+ }
4353
+
4354
+ }
4355
+
4356
+ return found;
4357
+
4358
+ }
4359
+
4360
+ bool intersectsBVHNodeBounds( vec3 rayOrigin, vec3 rayDirection, sampler2D bvhBounds, uint currNodeIndex, out float dist ) {
4361
+
4362
+ uint cni2 = currNodeIndex * 2u;
4363
+ vec3 boundsMin = texelFetch1D( bvhBounds, cni2 ).xyz;
4364
+ vec3 boundsMax = texelFetch1D( bvhBounds, cni2 + 1u ).xyz;
4365
+ return intersectsBounds( rayOrigin, rayDirection, boundsMin, boundsMax, dist );
4366
+
4367
+ }
4368
+
4369
+ // use a macro to hide the fact that we need to expand the struct into separate fields
4370
+ #define bvhIntersectFirstHit( bvh, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist ) _bvhIntersectFirstHit( bvh.position, bvh.index, bvh.bvhBounds, bvh.bvhContents, rayOrigin, rayDirection, faceIndices, faceNormal, barycoord, side, dist )
4371
+
4372
+ bool _bvhIntersectFirstHit(
4373
+ // bvh info
4374
+ sampler2D bvh_position, usampler2D bvh_index, sampler2D bvh_bvhBounds, usampler2D bvh_bvhContents,
4375
+
4376
+ // ray
4377
+ vec3 rayOrigin, vec3 rayDirection,
4378
+
4379
+ // output variables split into separate variables due to output precision
4380
+ inout uvec4 faceIndices, inout vec3 faceNormal, inout vec3 barycoord,
4381
+ inout float side, inout float dist
4382
+ ) {
4383
+
4384
+ // stack needs to be twice as long as the deepest tree we expect because
4385
+ // we push both the left and right child onto the stack every traversal
4386
+ int pointer = 0;
4387
+ uint stack[ BVH_STACK_DEPTH ];
4388
+ stack[ 0 ] = 0u;
4389
+
4390
+ float triangleDistance = INFINITY;
4391
+ bool found = false;
4392
+ while ( pointer > - 1 && pointer < BVH_STACK_DEPTH ) {
4393
+
4394
+ uint currNodeIndex = stack[ pointer ];
4395
+ pointer --;
4396
+
4397
+ // check if we intersect the current bounds
4398
+ float boundsHitDistance;
4399
+ if (
4400
+ ! intersectsBVHNodeBounds( rayOrigin, rayDirection, bvh_bvhBounds, currNodeIndex, boundsHitDistance )
4401
+ || boundsHitDistance > triangleDistance
4402
+ ) {
4403
+
4404
+ continue;
4405
+
4406
+ }
4407
+
4408
+ uvec2 boundsInfo = uTexelFetch1D( bvh_bvhContents, currNodeIndex ).xy;
4409
+ bool isLeaf = bool( boundsInfo.x & 0xffff0000u );
4410
+
4411
+ if ( isLeaf ) {
4412
+
4413
+ uint count = boundsInfo.x & 0x0000ffffu;
4414
+ uint offset = boundsInfo.y;
4415
+
4416
+ found = intersectTriangles(
4417
+ bvh_position, bvh_index, offset, count,
4418
+ rayOrigin, rayDirection, triangleDistance,
4419
+ faceIndices, faceNormal, barycoord, side, dist
4420
+ ) || found;
4421
+
4422
+ } else {
4423
+
4424
+ uint leftIndex = currNodeIndex + 1u;
4425
+ uint splitAxis = boundsInfo.x & 0x0000ffffu;
4426
+ uint rightIndex = currNodeIndex + boundsInfo.y;
4427
+
4428
+ bool leftToRight = rayDirection[ splitAxis ] >= 0.0;
4429
+ uint c1 = leftToRight ? leftIndex : rightIndex;
4430
+ uint c2 = leftToRight ? rightIndex : leftIndex;
4431
+
4432
+ // set c2 in the stack so we traverse it later. We need to keep track of a pointer in
4433
+ // the stack while we traverse. The second pointer added is the one that will be
4434
+ // traversed first
4435
+ pointer ++;
4436
+ stack[ pointer ] = c2;
4437
+
4438
+ pointer ++;
4439
+ stack[ pointer ] = c1;
4440
+
4441
+ }
4442
+
4443
+ }
4444
+
4445
+ return found;
4446
+
4447
+ }
4448
+ `
4449
+ );
4450
+
4451
+ // ../../node_modules/three-mesh-bvh/src/index.js
4452
+ var shaderIntersectFunction = `
4453
+ ${common_functions}
4454
+ ${bvh_ray_functions}
4455
+ `;
4456
+
4457
+ // src/rendering/surface-query.js
4458
+ function assertQueryMesh(mesh) {
4459
+ if (!(mesh.positions instanceof Float32Array) || mesh.positions.length % 3) throw new TypeError("Invalid mesh positions.");
4460
+ if (!(mesh.indices instanceof Uint32Array) || mesh.indices.length % 3) throw new TypeError("Invalid mesh indices.");
4461
+ const count = mesh.positions.length / 3;
4462
+ for (const index of mesh.indices) if (index >= count) throw new RangeError("Mesh index exceeds vertex count.");
4463
+ }
4464
+ function createSurfaceQuery(mesh, options = {}) {
4465
+ assertQueryMesh(mesh);
4466
+ const geometry = new BufferGeometry();
4467
+ geometry.setAttribute("position", new BufferAttribute3(mesh.positions, 3));
4468
+ if (mesh.normals && !options.geometryOnly) geometry.setAttribute("normal", new BufferAttribute3(mesh.normals, 3));
4469
+ if (mesh.uvs && !options.geometryOnly) geometry.setAttribute("uv", new BufferAttribute3(mesh.uvs, 2));
4470
+ geometry.setIndex(new BufferAttribute3(mesh.indices, 1));
4471
+ const bvh = new MeshBVH(geometry, {
4472
+ strategy: options.fastBuild ? AVERAGE : SAH,
4473
+ indirect: true,
4474
+ verbose: false
4475
+ });
4476
+ return createSurfaceQueryFromBvh(geometry, bvh);
4477
+ }
4478
+ function createSurfaceQueryFromBvh(geometry, bvh) {
4479
+ const point = new Vector311();
4480
+ const direction = new Vector311();
4481
+ const ray = new Ray2(point, direction);
4482
+ const closestTarget = {
4483
+ point: new Vector311(),
4484
+ distance: Infinity,
4485
+ faceIndex: -1
4486
+ };
4487
+ return {
4488
+ geometry,
4489
+ bvh,
4490
+ /**
4491
+ * @param {ArrayLike<number>} value
4492
+ * @param {number=} maxDistance
4493
+ */
4494
+ closestPoint(value, maxDistance = Infinity) {
4495
+ point.set(value[0], value[1], value[2]);
4496
+ const hit = bvh.closestPointToPoint(point, closestTarget, 0, maxDistance);
4497
+ if (!hit || hit.distance === void 0 || hit.faceIndex === void 0 || !hit.point) return null;
4498
+ return {
4499
+ point: [hit.point.x, hit.point.y, hit.point.z],
4500
+ distance: hit.distance,
4501
+ faceIndex: hit.faceIndex
4502
+ };
4503
+ },
4504
+ /**
4505
+ * @param {ArrayLike<number>} origin
4506
+ * @param {ArrayLike<number>} rayDirection
4507
+ * @param {number} near
4508
+ * @param {number} far
4509
+ * @param {'front' | 'back'} side
4510
+ */
4511
+ raycastFirst(origin, rayDirection, near, far, side = "front") {
4512
+ point.set(origin[0], origin[1], origin[2]);
4513
+ direction.set(rayDirection[0], rayDirection[1], rayDirection[2]).normalize();
4514
+ return bvh.raycastFirst(ray, side === "front" ? FrontSide2 : BackSide2, near, far);
4515
+ },
4516
+ dispose() {
4517
+ geometry.dispose();
4518
+ }
4519
+ };
4520
+ }
4521
+
4522
+ // src/rendering/skin-projection.js
4523
+ function mergeSkinGeometry(meshes) {
4524
+ const semantics = new Set(meshes.flatMap((m) => [...m.attributes.keys()]));
4525
+ const count = meshes.reduce((s, m) => s + m.positions.length / 3, 0);
4526
+ const attributes = /* @__PURE__ */ new Map();
4527
+ for (const semantic of semantics) {
4528
+ const size = (
4529
+ /** @type {SkinAttribute} */
4530
+ (meshes.find((m) => m.attributes.has(semantic))?.attributes.get(semantic)).size
4531
+ );
4532
+ const data = new Float32Array(count * size);
4533
+ if (semantic.startsWith("COLOR_")) data.fill(1);
4534
+ let offset = 0;
4535
+ for (const mesh of meshes) {
4536
+ const attribute = mesh.attributes.get(semantic);
4537
+ if (attribute) data.set(attribute.data, offset * size);
4538
+ offset += mesh.positions.length / 3;
4539
+ }
4540
+ attributes.set(semantic, { size, data });
4541
+ }
4542
+ const indices = new Uint32Array(meshes.reduce((s, m) => s + m.indices.length, 0));
4543
+ let vertexOffset = 0, indexOffset = 0;
4544
+ for (const mesh of meshes) {
4545
+ indices.set(mesh.indices.map((i) => i + vertexOffset), indexOffset);
4546
+ indexOffset += mesh.indices.length;
4547
+ vertexOffset += mesh.positions.length / 3;
4548
+ }
4549
+ return { positions: attributes.get("POSITION").data, indices, attributes };
4550
+ }
4551
+ function skinSurface(surface, options = {}) {
4552
+ const query = createSurfaceQuery(surface, { fastBuild: options.fastBuild, geometryOnly: true });
4553
+ const a = new Vector312(), b = new Vector312(), c = new Vector312(), p = new Vector312(), bary = new Vector312();
4554
+ return {
4555
+ dispose: () => query.dispose(),
4556
+ /** @param {ArrayLike<number>} position */
4557
+ closest(position) {
4558
+ const hit = query.closestPoint(position);
4559
+ if (!hit) throw new Error("Cannot project onto an empty surface.");
4560
+ const vertices = Array.from(surface.indices.subarray(hit.faceIndex * 3, hit.faceIndex * 3 + 3));
4561
+ a.fromArray(surface.positions, vertices[0] * 3);
4562
+ b.fromArray(surface.positions, vertices[1] * 3);
4563
+ c.fromArray(surface.positions, vertices[2] * 3);
4564
+ if (!Triangle4.getBarycoord(p.fromArray(hit.point), a, b, c, bary)) {
4565
+ const corners = [a, b, c];
4566
+ let distance = Infinity;
4567
+ for (const [i, j] of [[0, 1], [1, 2], [2, 0]]) {
4568
+ const delta = corners[j].clone().sub(corners[i]);
4569
+ const t = Math.max(0, Math.min(1, p.clone().sub(corners[i]).dot(delta) / (delta.lengthSq() || 1)));
4570
+ const squared = corners[i].clone().addScaledVector(delta, t).distanceToSquared(p);
4571
+ if (squared < distance) {
4572
+ distance = squared;
4573
+ bary.set(0, 0, 0).setComponent(i, 1 - t).setComponent(j, t);
4574
+ }
4575
+ }
4576
+ }
4577
+ return { vertices, bary: bary.toArray(), point: hit.point, face: hit.faceIndex };
4578
+ }
4579
+ };
4580
+ }
4581
+ function projectSkinGeometry(source, target, options = {}) {
4582
+ const query = skinSurface(source), count = target.positions.length / 3;
4583
+ const attributes = new Map([...source.attributes].map(([s, a]) => [s, { size: a.size, data: new Float32Array(count * a.size) }]));
4584
+ const positions = (
4585
+ /** @type {SkinAttribute} */
4586
+ attributes.get("POSITION").data
4587
+ );
4588
+ try {
4589
+ for (let i = 0; i < count; i++) {
4590
+ const hit = query.closest(target.positions.subarray(i * 3, i * 3 + 3));
4591
+ for (const [semantic, dest] of attributes) {
4592
+ if (semantic === "JOINTS_0" || semantic === "WEIGHTS_0") continue;
4593
+ const original = (
4594
+ /** @type {SkinAttribute} */
4595
+ source.attributes.get(semantic)
4596
+ );
4597
+ for (let k = 0; k < dest.size; k++) dest.data[i * dest.size + k] = hit.vertices.reduce((sum, v, j) => sum + hit.bary[j] * original.data[v * dest.size + k], 0);
4598
+ if (semantic === "NORMAL" || semantic === "TANGENT") {
4599
+ const normal = new Vector312().fromArray(dest.data, i * dest.size).normalize();
4600
+ normal.toArray(dest.data, i * dest.size);
4601
+ if (semantic === "TANGENT") dest.data[i * 4 + 3] = dest.data[i * 4 + 3] < 0 ? -1 : 1;
4602
+ }
4603
+ }
4604
+ positions.set(options.snapPositions === false ? target.positions.subarray(i * 3, i * 3 + 3) : hit.point, i * 3);
4605
+ const joints = source.attributes.get("JOINTS_0"), weights = source.attributes.get("WEIGHTS_0");
4606
+ if (joints && weights) {
4607
+ const contributions = /* @__PURE__ */ new Map();
4608
+ hit.vertices.forEach((v, j) => {
4609
+ for (let k = 0; k < 4; k++) {
4610
+ const id = joints.data[v * 4 + k], w = Math.max(0, hit.bary[j]) * weights.data[v * 4 + k];
4611
+ if (w > 0) contributions.set(id, (contributions.get(id) ?? 0) + w);
4612
+ }
4613
+ });
4614
+ const strongest = [...contributions].sort((a, b) => b[1] - a[1]).slice(0, 4);
4615
+ const total = strongest.reduce((s, [, w]) => s + w, 0);
4616
+ if (!(total > 0)) throw new Error("Weight projection produced no joint influence.");
4617
+ strongest.forEach(([id, w], k) => {
4618
+ attributes.get("JOINTS_0").data[i * 4 + k] = id;
4619
+ attributes.get("WEIGHTS_0").data[i * 4 + k] = w / total;
4620
+ });
4621
+ }
4622
+ }
4623
+ } finally {
4624
+ query.dispose();
4625
+ }
4626
+ return { positions, indices: target.indices, attributes };
4627
+ }
4628
+
4629
+ // src/rendering/wrap-skin.js
4630
+ var restMatrices = /* @__PURE__ */ new WeakMap();
4631
+ function captureWrapSkinPose(root) {
4632
+ root.traverse((node) => {
4633
+ node.updateMatrix();
4634
+ restMatrices.set(node, node.matrix.clone());
4635
+ });
4636
+ }
4637
+ function createWrapSkin(original, copy, asset, animate) {
4638
+ const sourceNodes = [];
4639
+ const copyNodes = [];
4640
+ original.traverse((n) => sourceNodes.push(n));
4641
+ copy.traverse((n) => copyNodes.push(n));
4642
+ if (!(animate ?? sourceNodes.some((n) => n instanceof THREE.SkinnedMesh))) return null;
4643
+ const clones = new Map(sourceNodes.map((n, i) => [n, copyNodes[i]]));
4644
+ for (const source of sourceNodes) {
4645
+ const target = clones.get(source), rest = restMatrices.get(source);
4646
+ if (target && rest && source !== original) {
4647
+ target.matrix.copy(rest);
4648
+ target.matrix.decompose(target.position, target.quaternion, target.scale);
4649
+ }
4650
+ }
4651
+ copy.matrixWorld.multiplyMatrices(asset.matrixWorld, copy.matrix);
4652
+ for (const child of copy.children) child.updateMatrixWorld(true);
4653
+ const bones = [], inverses = [], surfaces = [];
4654
+ const boneIds = /* @__PURE__ */ new Map();
4655
+ const worldToAsset = asset.matrixWorld.clone().invert();
4656
+ const p = new THREE.Vector3();
4657
+ for (const source of sourceNodes) {
4658
+ if (!(source instanceof THREE.Mesh) || source.userData.previewWireframeOverlay) continue;
4659
+ const geometry = source.geometry, pos = geometry.getAttribute("position");
4660
+ if (!pos) continue;
4661
+ const posedSource = clones.get(source);
4662
+ if (!(posedSource instanceof THREE.Mesh)) continue;
4663
+ const sourceWorld = posedSource.matrixWorld.clone();
4664
+ const matrix = worldToAsset.clone().multiply(sourceWorld);
4665
+ const positions = new Float32Array(pos.count * 3), ids = new Float32Array(pos.count * 4), weights = new Float32Array(ids.length);
4666
+ const mapping = [];
4667
+ if (source instanceof THREE.SkinnedMesh) {
4668
+ for (let i = 0; i < source.skeleton.bones.length; i++) {
4669
+ const bone = clones.get(source.skeleton.bones[i]);
4670
+ if (!(bone instanceof THREE.Bone)) throw new Error("Source skin references a bone outside its scene.");
4671
+ let id = boneIds.get(bone);
4672
+ if (id === void 0) {
4673
+ id = bones.length;
4674
+ boneIds.set(bone, id);
4675
+ bones.push(bone);
4676
+ inverses.push(bone.matrixWorld.clone().invert());
4677
+ }
4678
+ mapping.push(id);
4679
+ }
4680
+ } else {
4681
+ const bone = new THREE.Bone();
4682
+ clones.get(source)?.add(bone);
4683
+ mapping.push(bones.length);
4684
+ bones.push(bone);
4685
+ inverses.push(sourceWorld.clone().invert());
4686
+ }
4687
+ const j = geometry.getAttribute("skinIndex"), w = geometry.getAttribute("skinWeight");
4688
+ for (let i = 0; i < pos.count; i++) {
4689
+ p.fromBufferAttribute(pos, i).applyMatrix4(matrix).toArray(positions, i * 3);
4690
+ if (posedSource instanceof THREE.SkinnedMesh) posedSource.getVertexPosition(i, p).applyMatrix4(matrix).toArray(positions, i * 3);
4691
+ if (source instanceof THREE.SkinnedMesh && j && w) {
4692
+ for (let k = 0; k < 4; k++) {
4693
+ ids[i * 4 + k] = mapping[j.getComponent(i, k)];
4694
+ weights[i * 4 + k] = w.getComponent(i, k);
4695
+ }
4696
+ } else {
4697
+ ids[i * 4] = mapping[0];
4698
+ weights[i * 4] = 1;
4699
+ }
4700
+ }
4701
+ surfaces.push({ positions, indices: geometry.index ? Uint32Array.from(geometry.index.array) : Uint32Array.from({ length: pos.count }, (_, i) => i), attributes: /* @__PURE__ */ new Map([
4702
+ ["POSITION", { size: 3, data: positions }],
4703
+ ["JOINTS_0", { size: 4, data: ids }],
4704
+ ["WEIGHTS_0", { size: 4, data: weights }]
4705
+ ]) });
4706
+ }
4707
+ const surface = mergeSkinGeometry(surfaces);
4708
+ const skeleton = new THREE.Skeleton(bones, inverses);
4709
+ return {
4710
+ /** @param {THREE.BufferGeometry} geometry @param {THREE.Material | THREE.Material[]} material */
4711
+ mesh(geometry, material) {
4712
+ const position = geometry.getAttribute("position");
4713
+ const positions = Float32Array.from(position.array);
4714
+ const projected = projectSkinGeometry(surface, { positions, indices: new Uint32Array() });
4715
+ const joints = projected.attributes.get("JOINTS_0"), weights = projected.attributes.get("WEIGHTS_0");
4716
+ if (!joints || !weights) throw new Error("Missing projected skin influences.");
4717
+ geometry.setAttribute("skinIndex", new THREE.Uint16BufferAttribute(joints.data, 4));
4718
+ geometry.setAttribute("skinWeight", new THREE.Float32BufferAttribute(weights.data, 4));
4719
+ const mesh = new THREE.SkinnedMesh(geometry, material);
4720
+ mesh.bind(skeleton, asset.matrixWorld);
4721
+ return mesh;
4722
+ },
4723
+ update() {
4724
+ for (const source of sourceNodes) {
4725
+ const target = clones.get(source);
4726
+ if (!target || source === original) continue;
4727
+ target.position.copy(source.position);
4728
+ target.quaternion.copy(source.quaternion);
4729
+ target.scale.copy(source.scale);
4730
+ target.updateMatrix();
4731
+ }
4732
+ copy.updateWorldMatrix(true, true);
4733
+ skeleton.update();
4734
+ },
4735
+ dispose() {
4736
+ skeleton.dispose();
4737
+ const borrowedCopies = new Set(copyNodes.filter((n) => n instanceof THREE.SkinnedMesh).map((n) => n.skeleton));
4738
+ borrowedCopies.forEach((s) => s.dispose());
4739
+ }
4740
+ };
4741
+ }
4742
+ export {
4743
+ captureWrapSkinPose,
4744
+ createWrapSkin
4745
+ };
4746
+ //# sourceMappingURL=wrap-skin.js.map