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

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