@threenative/core 0.3.4 → 0.3.5

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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12423 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +47 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2390 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +564 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +839 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,812 @@
1
+ import {
2
+ BufferAttribute,
3
+ BufferGeometry,
4
+ Color,
5
+ type ColorRepresentation,
6
+ type InstancedMesh,
7
+ type InterleavedBufferAttribute,
8
+ type Material,
9
+ Matrix3,
10
+ Matrix4,
11
+ Mesh,
12
+ Object3D,
13
+ } from "three";
14
+ import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
15
+
16
+ /**
17
+ * One piece on its way into a merged buffer.
18
+ *
19
+ * A `Mesh` is already one of these — pass the meshes straight in and their own transforms are
20
+ * used. Every value here is the game's: the shape, where it sits, and what colour it is.
21
+ */
22
+ export interface IMergePart {
23
+ /** The piece's own colour, written flat across its vertices. Omit it on every part for none. */
24
+ readonly color?: ColorRepresentation;
25
+ /** The shape. It is cloned before anything is done to it, so the game's copy is untouched. */
26
+ readonly geometry: BufferGeometry;
27
+ /** Where the piece sits. A `Mesh` brings its own; identity when there is none. */
28
+ readonly matrix?: Matrix4;
29
+ }
30
+
31
+ export interface IMergePartsOptions {
32
+ /** Named in the error when the merge is refused. Say what was being built. */
33
+ readonly label: string;
34
+ /**
35
+ * Channels to keep from each part besides `position`. Absent or empty keeps today's
36
+ * position-only merge, whose normals are recomputed from the merged result.
37
+ *
38
+ * `"normal"` keeps each part's authored normals, transformed by the part's placement matrix
39
+ * (the inverse-transpose normal matrix) and **never** recomputed. `"uv"` keeps each part's
40
+ * texture coordinates verbatim — the placement matrix moves position and normal, so UV values
41
+ * are retained unchanged. A part that does not carry a listed channel refuses the merge.
42
+ */
43
+ readonly preserve?: readonly ("uv" | "normal")[];
44
+ }
45
+
46
+ export interface IMergeByMaterialOptions {
47
+ /** Named in the error when a group's merge is refused. Say what was being built. */
48
+ readonly label: string;
49
+ /**
50
+ * Leaves one mesh out of its material's group and out of the result — a piece that moves at run
51
+ * time, or one a capture script addresses by name.
52
+ */
53
+ readonly skip?: (mesh: Mesh) => boolean;
54
+ /**
55
+ * An `InstancedMesh` is baked into its material's group as one part per instance matrix while that
56
+ * group stays at or below this many triangles. Above it — or absent, which is the old behaviour —
57
+ * it comes back in the result untouched, because one instanced draw is already cheaper than the
58
+ * triangles it expands into.
59
+ */
60
+ readonly expandInstancedUnderTriangles?: number;
61
+ /**
62
+ * Vertices one merged group may hold before the rest of its material's parts start a second mesh.
63
+ *
64
+ * One merged group is one upload on the frame that first draws it, and that upload is the frame's
65
+ * whole cost: measured in a browser, a streamed world created 826 GPU buffers totalling 228.8 MB
66
+ * out of `createAttribute`, 33 of them over 1 MB, and the first draw of the largest chunk meshes
67
+ * took up to 230 ms. Splitting a material group in traversal order — which keeps the pieces
68
+ * adjacent to the pieces they were placed beside — bounds each of those uploads instead of
69
+ * trading one draw for a single enormous buffer. See `CHUNK_MERGE_MAX_VERTICES`.
70
+ */
71
+ readonly maxGroupVertices?: number;
72
+ }
73
+
74
+ /** The channels `mergeByMaterial` keeps, in the order it asks `mergeParts` for them. */
75
+ const MERGEABLE_CHANNELS = ["normal", "uv"] as const;
76
+
77
+ /** One material's parts that will become one mesh, and what that costs. */
78
+ interface IMergeGroup {
79
+ readonly parts: IMergePart[];
80
+ triangles: number;
81
+ vertices: number;
82
+ }
83
+
84
+ /**
85
+ * Triangles an `InstancedMesh`'s own shape may hold before the repeats are baked into the merge.
86
+ *
87
+ * Expanding trades one instanced draw for `count` copies of the shape, so the shape has to be worth
88
+ * repeating: a box, a fence post, a kerb. A detailed prop is already one cheap draw whatever the
89
+ * count, and baking it produces a merged buffer of the same detail per instance — the 228.8 MB of
90
+ * triangle soup this whole path used to produce. 2,048 triangles is about where a repeated shape
91
+ * stops being cheaper instanced than it is merged.
92
+ */
93
+ const INSTANCED_REPEAT_MAX_TRIANGLES = 2048;
94
+
95
+ /**
96
+ * Triangles one geometry submits: its index, or its vertex count where it carries none.
97
+ */
98
+ function trianglesOf(geometry: BufferGeometry): number {
99
+ const drawn = geometry.index?.count ?? geometry.getAttribute("position")?.count ?? 0;
100
+ return Math.floor(drawn / 3);
101
+ }
102
+
103
+ /** Vertices one part contributes to a merged group: its own, de-indexed or not. */
104
+ function verticesOf(geometry: BufferGeometry): number {
105
+ return geometry.getAttribute("position")?.count ?? 0;
106
+ }
107
+
108
+ function placementMatrix(part: IMergePart): Matrix4 | undefined {
109
+ if (!(part instanceof Object3D)) return part.matrix;
110
+ if (!part.matrixAutoUpdate) return part.matrix;
111
+ return new Matrix4().compose(part.position, part.quaternion, part.scale);
112
+ }
113
+
114
+ /**
115
+ * Three's `denormalize` divisor for an array's type, or `-1` for a type it does not know.
116
+ *
117
+ * `denormalize` divides by it and clamps at `-1`; `normalize` multiplies by the same number and
118
+ * rounds. A float channel's divisor is `0`, because both are the identity there and the copy skips
119
+ * them. One number covers both directions because three switches on the same array constructor for
120
+ * each.
121
+ */
122
+ function divisorOf(array: IRawNumbers): number {
123
+ if (array instanceof Float32Array) return 0;
124
+ if (array instanceof Int8Array) return 127;
125
+ if (array instanceof Uint8Array) return 255;
126
+ if (array instanceof Int16Array) return 32767;
127
+ if (array instanceof Uint16Array) return 65535;
128
+ if (array instanceof Int32Array) return 2147483647;
129
+ if (array instanceof Uint32Array) return 4294967295;
130
+ return -1;
131
+ }
132
+
133
+ /**
134
+ * Where one channel's raw components live, addressed for a copy loop.
135
+ *
136
+ * A cooked model's channels are quantized and interleaved (`KHR_mesh_quantization`: normalized Int8
137
+ * normals inside a shared stride), so three reaches them through `getX`/`setXYZ`, which denormalizes,
138
+ * multiplies and renormalizes one component at a time through a `Vector3`, and a `clone()` of such a
139
+ * channel de-interleaves it first through a boxed `Array`. Read straight out of the array the same
140
+ * arithmetic is three additions and a divide, and nothing is copied five times to get there.
141
+ */
142
+ interface IChannel {
143
+ /** Components one vertex holds. */
144
+ readonly itemSize: number;
145
+ /** Vertices the part contributes: its own, or its index count where the group de-indexes. */
146
+ readonly count: number;
147
+ /** Components between two vertices: the interleaved stride, or `itemSize` for a plain attribute. */
148
+ readonly stride: number;
149
+ /** Where this channel sits inside a vertex. */
150
+ readonly offset: number;
151
+ /** The raw numbers: an interleaved buffer's array, or a plain attribute's. */
152
+ readonly array: IRawNumbers;
153
+ /** {@link divisorOf} for this channel's array, or `-1` when this path cannot read it. */
154
+ readonly scale: number;
155
+ }
156
+
157
+ /** Raw components, addressed by index: any typed array three reads a channel out of. */
158
+ interface IRawNumbers {
159
+ readonly [component: number]: number;
160
+ }
161
+
162
+ /** The channel a kept attribute reads as, or `undefined` for a type this path cannot read. */
163
+ function channelOf(attribute: BufferAttribute, count: number): IChannel | undefined {
164
+ if (Reflect.get(attribute, "isFloat16BufferAttribute") === true) return undefined;
165
+ // quality-allow: three types a geometry attribute as BufferAttribute; the flag below tells them apart.
166
+ const interleaved = attribute as unknown as InterleavedBufferAttribute | undefined;
167
+ const data = interleaved?.isInterleavedBufferAttribute === true ? interleaved.data : undefined;
168
+ const array = (data?.array ?? attribute.array) as IRawNumbers;
169
+ const scale = divisorOf(array);
170
+ if (scale < 0) return undefined;
171
+ return {
172
+ array,
173
+ count,
174
+ itemSize: attribute.itemSize,
175
+ offset: data === undefined ? 0 : (interleaved?.offset ?? 0),
176
+ scale,
177
+ stride: data?.stride ?? attribute.itemSize,
178
+ };
179
+ }
180
+
181
+ /** The index a de-indexing part reads its vertices through, or `null` when it reads them in order. */
182
+ function indexOf(part: IMergePart, deindex: boolean): Uint16Array | Uint32Array | null {
183
+ if (!deindex) return null;
184
+ const index = part.geometry.getIndex();
185
+ if (index === null) return null;
186
+ const array = index.array;
187
+ if (array instanceof Uint16Array) return array;
188
+ if (array instanceof Uint32Array) return array;
189
+ return null;
190
+ }
191
+
192
+ /** The 16 elements of a placement, read once so the loop below reads locals. */
193
+ type PlacementElements = readonly [
194
+ number,
195
+ number,
196
+ number,
197
+ number,
198
+ number,
199
+ number,
200
+ number,
201
+ number,
202
+ number,
203
+ number,
204
+ number,
205
+ number,
206
+ number,
207
+ number,
208
+ number,
209
+ number,
210
+ ];
211
+
212
+ /** The 9 elements of an inverse transpose, read once so the loop below reads locals. */
213
+ type NormalElements = readonly [
214
+ number,
215
+ number,
216
+ number,
217
+ number,
218
+ number,
219
+ number,
220
+ number,
221
+ number,
222
+ number,
223
+ ];
224
+
225
+ /**
226
+ * Positions of one part, placed, written into `values` at `at`.
227
+ *
228
+ * The expression is three's `Vector3.applyMatrix4` term for term over the same elements in the same
229
+ * order, including its homogeneous divide, so a merged buffer holds the values it held before. The
230
+ * second half of it is what `setXYZ` wrote back into the part's own typed array before the
231
+ * de-quantizing copy read it again: `normalize` rounds into the channel's own range — the scratch
232
+ * store keeps a value outside that range wrapping exactly as three's store did — and `denormalize`
233
+ * reads it back as a float.
234
+ */
235
+ function writePosition(
236
+ channel: IChannel,
237
+ indices: Uint16Array | Uint32Array | null,
238
+ elements: PlacementElements | null,
239
+ scratch: IScratch | null,
240
+ values: Float32Array,
241
+ at: number,
242
+ ): void {
243
+ const { array, count, offset, scale, stride } = channel;
244
+ for (let vertex = 0; vertex < count; vertex += 1) {
245
+ const base = (indices === null ? vertex : (indices[vertex] as number)) * stride + offset;
246
+ const raw = array as { [component: number]: number | undefined };
247
+ const x = scale === 0 ? (raw[base] as number) : Math.max((raw[base] as number) / scale, -1);
248
+ const y =
249
+ scale === 0 ? (raw[base + 1] as number) : Math.max((raw[base + 1] as number) / scale, -1);
250
+ const z =
251
+ scale === 0 ? (raw[base + 2] as number) : Math.max((raw[base + 2] as number) / scale, -1);
252
+ let px: number;
253
+ let py: number;
254
+ let pz: number;
255
+ if (elements === null) {
256
+ px = x;
257
+ py = y;
258
+ pz = z;
259
+ } else {
260
+ const e = elements;
261
+ const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
262
+ px = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
263
+ py = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
264
+ pz = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
265
+ }
266
+ const out = at + vertex * 3;
267
+ if (scratch !== null) {
268
+ scratch[0] = Math.round(px * scale);
269
+ scratch[1] = Math.round(py * scale);
270
+ scratch[2] = Math.round(pz * scale);
271
+ px = Math.max((scratch[0] as number) / scale, -1);
272
+ py = Math.max((scratch[1] as number) / scale, -1);
273
+ pz = Math.max((scratch[2] as number) / scale, -1);
274
+ }
275
+ values[out] = px;
276
+ values[out + 1] = py;
277
+ values[out + 2] = pz;
278
+ }
279
+ }
280
+
281
+ /**
282
+ * Normals of one part, placed by the inverse transpose, written into `values` at `at`. Three's
283
+ * `applyNormalMatrix`, term for term, quantized back to the channel's own range exactly as
284
+ * {@link writePosition} does.
285
+ */
286
+ function writeNormal(
287
+ channel: IChannel,
288
+ indices: Uint16Array | Uint32Array | null,
289
+ elements: NormalElements | null,
290
+ scratch: IScratch | null,
291
+ values: Float32Array,
292
+ at: number,
293
+ ): void {
294
+ const { array, count, offset, scale, stride } = channel;
295
+ const e = elements;
296
+ for (let vertex = 0; vertex < count; vertex += 1) {
297
+ const base = (indices === null ? vertex : (indices[vertex] as number)) * stride + offset;
298
+ const raw = array as { [component: number]: number | undefined };
299
+ const x = scale === 0 ? (raw[base] as number) : Math.max((raw[base] as number) / scale, -1);
300
+ const y =
301
+ scale === 0 ? (raw[base + 1] as number) : Math.max((raw[base + 1] as number) / scale, -1);
302
+ const z =
303
+ scale === 0 ? (raw[base + 2] as number) : Math.max((raw[base + 2] as number) / scale, -1);
304
+ let px: number;
305
+ let py: number;
306
+ let pz: number;
307
+ if (e === null) {
308
+ px = x;
309
+ py = y;
310
+ pz = z;
311
+ } else {
312
+ px = e[0] * x + e[3] * y + e[6] * z;
313
+ py = e[1] * x + e[4] * y + e[7] * z;
314
+ pz = e[2] * x + e[5] * y + e[8] * z;
315
+ // `Vector3.applyNormalMatrix` ends in `normalize()`, so a placed normal is a unit normal and
316
+ // not the scaled vector the matrix produced — the same three terms, then its `length()` and
317
+ // its `multiplyScalar(1 / length)`.
318
+ const by = 1 / (Math.sqrt(px * px + py * py + pz * pz) || 1);
319
+ px *= by;
320
+ py *= by;
321
+ pz *= by;
322
+ }
323
+ const out = at + vertex * 3;
324
+ if (scratch !== null) {
325
+ scratch[0] = Math.round(px * scale);
326
+ scratch[1] = Math.round(py * scale);
327
+ scratch[2] = Math.round(pz * scale);
328
+ px = Math.max((scratch[0] as number) / scale, -1);
329
+ py = Math.max((scratch[1] as number) / scale, -1);
330
+ pz = Math.max((scratch[2] as number) / scale, -1);
331
+ }
332
+ values[out] = px;
333
+ values[out + 1] = py;
334
+ values[out + 2] = pz;
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Every other kept channel of one part, copied through as three's de-quantizing copy read it, and one
340
+ * part's flat colour written over `count` vertices.
341
+ */
342
+ function writeThrough(
343
+ channel: IChannel,
344
+ indices: Uint16Array | Uint32Array | null,
345
+ values: Float32Array,
346
+ at: number,
347
+ ): void {
348
+ const { array, count, itemSize, offset, scale, stride } = channel;
349
+ if (scale === 0) {
350
+ for (let vertex = 0; vertex < count; vertex += 1) {
351
+ const from = (indices === null ? vertex : (indices[vertex] as number)) * stride + offset;
352
+ const out = at + vertex * itemSize;
353
+ for (let component = 0; component < itemSize; component += 1)
354
+ values[out + component] = array[from + component] as number;
355
+ }
356
+ return;
357
+ }
358
+ for (let vertex = 0; vertex < count; vertex += 1) {
359
+ const from = (indices === null ? vertex : (indices[vertex] as number)) * stride + offset;
360
+ const out = at + vertex * itemSize;
361
+ for (let component = 0; component < itemSize; component += 1)
362
+ values[out + component] = Math.max((array[from + component] as number) / scale, -1);
363
+ }
364
+ }
365
+
366
+ /** One part's flat colour, written across every vertex it contributes. */
367
+ function writeColour(values: Float32Array, at: number, count: number, tone: Color): void {
368
+ for (let vertex = 0; vertex < count; vertex += 1) {
369
+ const out = at + vertex * 3;
370
+ values[out] = tone.r;
371
+ values[out + 1] = tone.g;
372
+ values[out + 2] = tone.b;
373
+ }
374
+ }
375
+
376
+ /**
377
+ * A three-component scratch array of one channel's own type, standing in for the in-place
378
+ * quantization `setXYZ` did on the part three had cloned.
379
+ */
380
+ interface IScratch {
381
+ [component: number]: number;
382
+ }
383
+
384
+ /** A scratch array of one channel's own type, where `setXYZ` would have quantized in place. */
385
+ function scratchOf(array: IRawNumbers): IScratch | null {
386
+ if (array instanceof Int8Array) return new Int8Array(3);
387
+ if (array instanceof Int16Array) return new Int16Array(3);
388
+ if (array instanceof Int32Array) return new Int32Array(3);
389
+ if (array instanceof Uint8Array) return new Uint8Array(3);
390
+ if (array instanceof Uint16Array) return new Uint16Array(3);
391
+ if (array instanceof Uint32Array) return new Uint32Array(3);
392
+ return null;
393
+ }
394
+
395
+ function flatten(
396
+ part: IMergePart,
397
+ paint: boolean,
398
+ preserve: readonly ("uv" | "normal")[],
399
+ deindex: boolean,
400
+ ): BufferGeometry {
401
+ const placed = part.geometry.clone();
402
+ const matrix = placementMatrix(part);
403
+ if (matrix !== undefined) placed.applyMatrix4(matrix);
404
+ const flat = deindex && placed.index !== null ? placed.toNonIndexed() : placed;
405
+ if (flat !== placed) placed.dispose();
406
+ const keep = new Set<string>(["position", ...preserve]);
407
+ for (const name of Object.keys(flat.attributes)) {
408
+ if (!keep.has(name)) flat.deleteAttribute(name);
409
+ }
410
+ flat.morphAttributes = {};
411
+ flat.morphTargetsRelative = false;
412
+ // A cooked model's attributes are quantized (`KHR_mesh_quantization`: normalized Int16 uv,
413
+ // Int8 normals, interleaved buffers), and `mergeGeometries` refuses parts whose arrays differ in
414
+ // type. Every kept channel is merged as plain float, read through the attribute's own accessors
415
+ // so normalization and interleaving resolve to the values three would have drawn.
416
+ for (const name of Object.keys(flat.attributes)) {
417
+ const attribute = flat.getAttribute(name);
418
+ if (
419
+ attribute.array instanceof Float32Array &&
420
+ !attribute.normalized &&
421
+ !("isInterleavedBufferAttribute" in attribute)
422
+ )
423
+ continue;
424
+ const values = new Float32Array(attribute.count * attribute.itemSize);
425
+ for (let index = 0; index < attribute.count; index += 1)
426
+ for (let component = 0; component < attribute.itemSize; component += 1)
427
+ values[index * attribute.itemSize + component] = attribute.getComponent(index, component);
428
+ flat.setAttribute(name, new BufferAttribute(values, attribute.itemSize));
429
+ }
430
+ const position = flat.getAttribute("position");
431
+ if (!paint || position === undefined) return flat;
432
+ const tone = new Color(part.color);
433
+ const painted = new Float32Array(position.count * 3);
434
+ for (let vertex = 0; vertex < position.count; vertex += 1) {
435
+ painted[vertex * 3] = tone.r;
436
+ painted[vertex * 3 + 1] = tone.g;
437
+ painted[vertex * 3 + 2] = tone.b;
438
+ }
439
+ flat.setAttribute("color", new BufferAttribute(painted, 3));
440
+ return flat;
441
+ }
442
+
443
+ /**
444
+ * Merge game-authored pieces into one buffer, keeping each piece's own colour and, when asked,
445
+ * its uv and authored normals.
446
+ *
447
+ * Two things go wrong every time an agent bakes a building, a ship or a character out of
448
+ * primitives, and neither is about how any of it looks. `mergeGeometries` returns `null` on
449
+ * mismatched inputs instead of throwing, and the usual mismatch — one non-indexed extrusion among
450
+ * a hundred indexed primitives — is invisible until the whole scene is missing; and a merged
451
+ * buffer draws with one surface, so per-piece colour is gone unless every piece carries a flat
452
+ * `color` attribute written before the merge. Writing that attribute is mechanical. The colours
453
+ * are entirely the game's, one per part, and changing them changes nothing here. By default the
454
+ * merged normals are recomputed from the merged buffer; `preserve` keeps the authored normals and
455
+ * texture coordinates instead so an imported model's shading survives the bake.
456
+ *
457
+ * A group whose parts are all indexed merges indexed — the sum of their vertex counts, not three
458
+ * times their triangles — and only a mixed group falls back to the de-indexed soup. One crossing
459
+ * 65,535 vertices gets a 32-bit index, because a 16-bit one cannot name the vertex.
460
+ */
461
+ export function mergeParts(
462
+ parts: Iterable<IMergePart>,
463
+ options: IMergePartsOptions,
464
+ ): BufferGeometry {
465
+ const list = [...parts];
466
+ const { label } = options;
467
+ const preserve = options.preserve ?? [];
468
+ if (list.length === 0) throw new Error(`mergeParts(${label}): the part list is empty.`);
469
+ const coloured = list.filter((part) => part.color !== undefined).length;
470
+ if (coloured !== 0 && coloured !== list.length) {
471
+ const reason = "A merged buffer needs the attribute on every part or on none of them.";
472
+ throw new Error(
473
+ `mergeParts(${label}): ${coloured} of ${list.length} parts name a colour. ${reason}`,
474
+ );
475
+ }
476
+ list.forEach((part, index) => {
477
+ for (const channel of preserve) {
478
+ if (part.geometry.getAttribute(channel) === undefined) {
479
+ throw new Error(
480
+ `mergeParts(${label}): part ${index} has no ${channel} to preserve. Prepare the missing channel in the part's own data first.`,
481
+ );
482
+ }
483
+ }
484
+ });
485
+ // One indexed part among non-indexed ones is what `mergeGeometries` refuses, so a mixed group
486
+ // de-indexes and an all-indexed group keeps its index and a third of its vertices.
487
+ const deindex = !list.every((part) => part.geometry.index !== null);
488
+ const merged = fusable(list, preserve, deindex)
489
+ ? concatenate(list, coloured !== 0, preserve, deindex, label)
490
+ : mergeThroughThree(list, coloured !== 0, preserve, deindex, label);
491
+ if (!preserve.includes("normal")) merged.computeVertexNormals();
492
+ return merged;
493
+ }
494
+
495
+ /** The channels a group keeps, in the order the first part carries them — a merged buffer's own order. */
496
+ function keptChannels(first: IMergePart, preserve: readonly ("uv" | "normal")[]): string[] {
497
+ const keep = new Set<string>(["position", ...preserve]);
498
+ return Object.keys(first.geometry.attributes).filter((name) => keep.has(name));
499
+ }
500
+
501
+ /** Vertices one part contributes: its index count where the group de-indexes, else its own. */
502
+ function contributes(part: IMergePart, deindex: boolean): number {
503
+ const index = part.geometry.getIndex();
504
+ if (!deindex || index === null) return part.geometry.getAttribute("position")?.count ?? 0;
505
+ return index.count;
506
+ }
507
+
508
+ /**
509
+ * Whether {@link concatenate} can read every channel this group keeps. It cannot for a type three's
510
+ * `normalize`/`denormalize` do not describe (half floats) or for a position that is not three
511
+ * components, and those groups take the path that was always here.
512
+ */
513
+ function fusable(
514
+ list: readonly IMergePart[],
515
+ preserve: readonly ("uv" | "normal")[],
516
+ deindex: boolean,
517
+ ): boolean {
518
+ if (!preserve.every((channel) => channel === "uv" || channel === "normal")) return false;
519
+ const names = keptChannels(list[0] as IMergePart, preserve);
520
+ return list.every((part) => fusablePart(part, names, deindex));
521
+ }
522
+
523
+ /** One part's answer to {@link fusable}, per kept channel. */
524
+ function fusablePart(part: IMergePart, names: readonly string[], deindex: boolean): boolean {
525
+ const index = part.geometry.getIndex();
526
+ if (deindex && index !== null && indexOf(part, deindex) === null) return false;
527
+ const count = contributes(part, deindex);
528
+ return names.every((name) => {
529
+ const attribute = part.geometry.getAttribute(name);
530
+ if (attribute === undefined) return false;
531
+ // A channel whose vertex count is not the part's own would merge at a length of its own, which
532
+ // is a buffer three had already stopped being able to draw; that part takes the three path.
533
+ if (attribute.count !== count) return false;
534
+ if (attribute.itemSize !== 3 && (name === "position" || name === "normal")) return false;
535
+ return channelOf(attribute as BufferAttribute, count) !== undefined;
536
+ });
537
+ }
538
+
539
+ /**
540
+ * Every part's channels, placed and de-quantized, written straight into one buffer.
541
+ *
542
+ * This is what `flatten` and `mergeGeometries` did between them, without the intermediates: no
543
+ * `clone()` (which de-interleaves a quantized channel through a boxed `Array`), no `toNonIndexed()`,
544
+ * no per-channel re-quantizing copy, no second copy into the merged attributes, and no index built
545
+ * one `Array.push` at a time. Each byte of a part is read once and lands once, which is the whole of
546
+ * a 5.5 ms/MB merge becoming a fraction of that.
547
+ */
548
+ function concatenate(
549
+ list: readonly IMergePart[],
550
+ paint: boolean,
551
+ preserve: readonly ("uv" | "normal")[],
552
+ deindex: boolean,
553
+ label: string,
554
+ ): BufferGeometry {
555
+ const names = keptChannels(list[0] as IMergePart, preserve);
556
+ if (paint) names.push("color");
557
+ const counts = list.map((part) => contributes(part, deindex));
558
+ const vertices = counts.reduce((total, count) => total + count, 0);
559
+ const geometry = new BufferGeometry();
560
+ for (const name of names) {
561
+ const itemSize =
562
+ name === "color" ? 3 : ((list[0] as IMergePart).geometry.getAttribute(name)?.itemSize ?? 3);
563
+ const values = new Float32Array(vertices * itemSize);
564
+ let at = 0;
565
+ for (let part = 0; part < list.length; part += 1) {
566
+ const count = counts[part] as number;
567
+ if (name === "color") writeColour(values, at, count, new Color(list[part]?.color));
568
+ else writeChannel(name, list[part] as IMergePart, count, deindex, label, values, at);
569
+ at += count * itemSize;
570
+ }
571
+ geometry.setAttribute(name, new BufferAttribute(values, itemSize));
572
+ }
573
+ geometry.setIndex(deindex ? null : new BufferAttribute(mergeIndex(list, vertices), 1));
574
+ return geometry;
575
+ }
576
+
577
+ /** One part's one kept channel, placed and de-quantized into `values` at `at`. */
578
+ function writeChannel(
579
+ name: string,
580
+ part: IMergePart,
581
+ count: number,
582
+ deindex: boolean,
583
+ label: string,
584
+ values: Float32Array,
585
+ at: number,
586
+ ): void {
587
+ const channel = channelOf(part.geometry.getAttribute(name) as BufferAttribute, count);
588
+ if (channel === undefined)
589
+ throw new Error(`mergeParts(${label}): a part has no ${name} this path can read.`);
590
+ const indices = indexOf(part, deindex);
591
+ const matrix = placementMatrix(part);
592
+ if (name === "position") {
593
+ writePosition(
594
+ channel,
595
+ indices,
596
+ // quality-allow: Matrix4.elements is number[] in three's types and always 16 long.
597
+ matrix === undefined ? null : (matrix.elements as unknown as PlacementElements),
598
+ scratchOf(channel.array),
599
+ values,
600
+ at,
601
+ );
602
+ return;
603
+ }
604
+ if (name === "normal") {
605
+ writeNormal(
606
+ channel,
607
+ indices,
608
+ matrix === undefined
609
+ ? null
610
+ : // quality-allow: Matrix3.elements is number[] in three's types and always 9 long.
611
+ (new Matrix3().getNormalMatrix(matrix).elements as unknown as NormalElements),
612
+ scratchOf(channel.array),
613
+ values,
614
+ at,
615
+ );
616
+ return;
617
+ }
618
+ writeThrough(channel, indices, values, at);
619
+ }
620
+
621
+ /**
622
+ * One index for the whole group, each part's offset by the vertices before it — a 32-bit one past
623
+ * 65,535 vertices, because a 16-bit one cannot name the vertex, which is the same rule `widenIndex`
624
+ * applied to a merged index three had already built.
625
+ */
626
+ function mergeIndex(list: readonly IMergePart[], vertices: number): Uint16Array | Uint32Array {
627
+ let total = 0;
628
+ for (const part of list) total += part.geometry.getIndex()?.count ?? 0;
629
+ const merged = vertices > 65_535 ? new Uint32Array(total) : new Uint16Array(total);
630
+ let at = 0;
631
+ let offset = 0;
632
+ for (const part of list) {
633
+ const source = part.geometry.getIndex();
634
+ if (source === null) continue;
635
+ const values = source.array as Uint16Array | Uint32Array;
636
+ for (let entry = 0; entry < source.count; entry += 1)
637
+ merged[at + entry] = (values[entry] as number) + offset;
638
+ at += source.count;
639
+ offset += part.geometry.getAttribute("position")?.count ?? 0;
640
+ }
641
+ return merged;
642
+ }
643
+
644
+ /**
645
+ * The path that was always here: `flatten` each part and hand the lot to `mergeGeometries`. It is
646
+ * what a group whose channels this file cannot read directly — a half-float channel, a position that
647
+ * is not three components — takes, and the refusals it raises are the ones a caller already handles.
648
+ */
649
+ function mergeThroughThree(
650
+ list: readonly IMergePart[],
651
+ paint: boolean,
652
+ preserve: readonly ("uv" | "normal")[],
653
+ deindex: boolean,
654
+ label: string,
655
+ ): BufferGeometry {
656
+ const flattened: BufferGeometry[] = [];
657
+ let merged: BufferGeometry | null;
658
+ try {
659
+ for (const part of list) flattened.push(flatten(part, paint, preserve, deindex));
660
+ merged = mergeGeometries(flattened, false);
661
+ } finally {
662
+ for (const geometry of flattened) geometry.dispose();
663
+ }
664
+ if (merged === null) {
665
+ const reason = "three.js refused the merge and reported why on the console.";
666
+ const requirement =
667
+ "Every part needs a position attribute, and morph targets do not survive a merge.";
668
+ throw new Error(`mergeParts(${label}): ${reason} Tried ${list.length} parts. ${requirement}`);
669
+ }
670
+ if (!deindex) widenIndex(merged);
671
+ return merged;
672
+ }
673
+
674
+ /**
675
+ * A 16-bit index cannot name a vertex past 65,535, so a merge that crosses that is unreadable.
676
+ * Three picks the type from the inputs, so one widened here is the only place it can be wrong.
677
+ */
678
+ function widenIndex(geometry: BufferGeometry): void {
679
+ const index = geometry.getIndex();
680
+ const vertices = geometry.getAttribute("position")?.count ?? 0;
681
+ if (index === null || index.array instanceof Uint32Array || vertices <= 65_535) return;
682
+ const widened = new Uint32Array(index.count);
683
+ for (let at = 0; at < index.count; at += 1) widened[at] = index.getX(at);
684
+ geometry.setIndex(new BufferAttribute(widened, 1));
685
+ }
686
+
687
+ /**
688
+ * Bake a hierarchy's static meshes into one mesh per material, transforms and all.
689
+ *
690
+ * A building or a ship is dozens of boxes and cylinders that never move relative to each other, and
691
+ * every one of them is a draw call. Grouping by material and merging each group is the ordinary
692
+ * fix, and the ordinary fix is thirty lines an agent rewrites in every game, each time slightly
693
+ * differently: walk the tree, group by material, bake `matrixWorld` into the vertices, hand the
694
+ * group to `mergeParts`, build a mesh on the game's own material. The parts here are the same
695
+ * `IMergePart` list, so a game that already merges by hand gets the same refusals — a group that
696
+ * cannot merge throws naming `label:material`, not silently vanishing.
697
+ *
698
+ * Nothing here decides how anything looks: the material is the game's own instance, the geometry is
699
+ * exactly what was authored, and the group split follows the materials the game already made.
700
+ *
701
+ * `normal` survives when every mesh in a group carries it and is recomputed otherwise. `uv` survives
702
+ * when any mesh carries it, so a group where only some do is the refusal `mergeParts` raises, never
703
+ * a texture silently left unmapped. Skinned meshes are left alone — their vertices are posed per
704
+ * frame — and an instanced one is left alone unless `expandInstancedUnderTriangles` names a cap its
705
+ * group fits under and its own shape is small enough to be worth repeating, which bakes every
706
+ * instance matrix into the merge.
707
+ *
708
+ * `maxGroupVertices` bounds a single group, and a material whose parts cross it is merged into
709
+ * several meshes in traversal order — more draws, none of them carrying a buffer big enough to stall
710
+ * the frame that first submits it.
711
+ */
712
+ export function mergeByMaterial(root: Object3D, options: IMergeByMaterialOptions): Mesh[] {
713
+ root.updateMatrixWorld(true);
714
+ const toRoot = new Matrix4().copy(root.matrixWorld).invert();
715
+ const byMaterial = new Map<Material, IMergeGroup[]>();
716
+ const kept: Mesh[] = [];
717
+ /** The group a part joins: the last one, or a new one once that one has taken its vertex budget. */
718
+ const groupFor = (material: Material, part: IMergePart): IMergeGroup => {
719
+ let groups = byMaterial.get(material);
720
+ if (groups === undefined) {
721
+ groups = [];
722
+ byMaterial.set(material, groups);
723
+ }
724
+ const open = groups[groups.length - 1];
725
+ const vertices = verticesOf(part.geometry);
726
+ if (
727
+ open === undefined ||
728
+ open.vertices + vertices > (options.maxGroupVertices ?? Number.POSITIVE_INFINITY)
729
+ ) {
730
+ const started: IMergeGroup = { parts: [], triangles: 0, vertices: 0 };
731
+ groups.push(started);
732
+ return started;
733
+ }
734
+ return open;
735
+ };
736
+ const add = (material: Material, part: IMergePart, triangles: number): IMergeGroup => {
737
+ const group = groupFor(material, part);
738
+ group.parts.push(part);
739
+ group.triangles += triangles;
740
+ group.vertices += verticesOf(part.geometry);
741
+ return group;
742
+ };
743
+ root.traverse((object) => {
744
+ // three's own discriminators, read structurally the way `assets.ts` reads `isTexture`.
745
+ const renderable = object as Mesh & { isInstancedMesh?: boolean; isSkinnedMesh?: boolean };
746
+ if (!renderable.isMesh || renderable.isSkinnedMesh) return;
747
+ if (Array.isArray(renderable.material) || options.skip?.(renderable) === true) return;
748
+ const place = toRoot.clone().multiply(renderable.matrixWorld);
749
+ if (renderable.isInstancedMesh !== true) {
750
+ add(
751
+ renderable.material,
752
+ { geometry: renderable.geometry, matrix: place },
753
+ trianglesOf(renderable.geometry),
754
+ );
755
+ return;
756
+ }
757
+ const instanced = renderable as InstancedMesh;
758
+ const shape = trianglesOf(instanced.geometry);
759
+ const cost = instanced.count * shape;
760
+ const cap = options.expandInstancedUnderTriangles;
761
+ // The group the repeats would join, which a shape too big to repeat never gets to: expanding a
762
+ // detailed prop repeats its detail per instance, and one instanced draw of it beats a merged
763
+ // buffer of the expanded soup by everything the expansion costs.
764
+ const target = groupFor(renderable.material, {
765
+ geometry: instanced.geometry,
766
+ matrix: place,
767
+ });
768
+ if (
769
+ cap === undefined ||
770
+ shape > INSTANCED_REPEAT_MAX_TRIANGLES ||
771
+ target.triangles + cost > cap
772
+ ) {
773
+ kept.push(instanced);
774
+ return;
775
+ }
776
+ const instance = new Matrix4();
777
+ for (let index = 0; index < instanced.count; index += 1) {
778
+ instanced.getMatrixAt(index, instance);
779
+ add(
780
+ renderable.material,
781
+ { geometry: instanced.geometry, matrix: place.clone().multiply(instance) },
782
+ shape,
783
+ );
784
+ }
785
+ });
786
+ const merged: Mesh[] = [];
787
+ [...byMaterial].forEach(([material, groups], index) => {
788
+ groups.forEach((group, part) => {
789
+ // A group of nothing is an instanced mesh of zero instances: nothing to draw, nothing to refuse.
790
+ if (group.parts.length === 0) return;
791
+ // A normal missing from one piece is recomputed; a uv missing from one piece is a refusal, since
792
+ // dropping it would leave the group's texture unmapped without a word.
793
+ const has = (piece: IMergePart, channel: "normal" | "uv") =>
794
+ piece.geometry.getAttribute(channel) !== undefined;
795
+ const preserve = MERGEABLE_CHANNELS.filter((channel) =>
796
+ channel === "uv"
797
+ ? group.parts.some((piece) => has(piece, channel))
798
+ : group.parts.every((piece) => has(piece, channel)),
799
+ );
800
+ merged.push(
801
+ new Mesh(
802
+ mergeParts(group.parts, {
803
+ label: `${options.label}:${material.name || index}${part === 0 ? "" : `#${part}`}`,
804
+ preserve,
805
+ }),
806
+ material,
807
+ ),
808
+ );
809
+ });
810
+ });
811
+ return [...merged, ...kept];
812
+ }