@threenative/core 0.3.4 → 0.3.6

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-Jz4Fdoeb.d.ts} +114 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12437 -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 +57 -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 +2408 -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 +574 -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 +850 -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,353 @@
1
+ /**
2
+ * The terrain block merge and the seam bridge strip, as pure attribute arithmetic.
3
+ *
4
+ * Two hosts run these two bodies: the main thread, inline, and a module worker. Nothing here reads
5
+ * a scene, a material, a field or a sampler — the inputs are typed arrays plus the numbers that
6
+ * place them, the outputs are the merged arrays — so both hosts compute from one function and
7
+ * cannot disagree. `TerrainTiles` keeps the GPU uploads and the scene-graph edits; this is the part
8
+ * that moves (PRD-478 Phase 3).
9
+ *
10
+ * Buffers go to the worker by structured clone and come back transferred: a level's own attribute
11
+ * arrays stay owned by its geometry, because a dissolved block restores that mesh, so they are
12
+ * never detached underneath it.
13
+ */
14
+
15
+ /** Which edge of a level a sample row runs along. */
16
+ export type TerrainEdgeSide = "east" | "north" | "south" | "west";
17
+
18
+ /** Where a tile or a block sits, in world metres. */
19
+ export interface ITerrainJobOrigin {
20
+ readonly x: number;
21
+ readonly z: number;
22
+ }
23
+
24
+ /** One tile level's attributes, exactly as the merge reads them. */
25
+ export interface ITerrainPartAttributes {
26
+ readonly indices: Uint16Array | Uint32Array;
27
+ readonly normals: Float32Array;
28
+ readonly positions: Float32Array;
29
+ }
30
+
31
+ export interface ITerrainMergeJob {
32
+ readonly blockOrigin: ITerrainJobOrigin;
33
+ readonly kind: "merge";
34
+ readonly parts: readonly (ITerrainPartAttributes & { readonly origin: ITerrainJobOrigin })[];
35
+ }
36
+
37
+ export interface ITerrainMergeResult extends ITerrainPartAttributes {
38
+ readonly indices: Uint32Array;
39
+ readonly kind: "merge";
40
+ }
41
+
42
+ /** One level's edge: the row's own sample heights and the field rectangle they sit on. */
43
+ export interface ITerrainEdgeJob {
44
+ readonly depth: number;
45
+ readonly origin: ITerrainJobOrigin;
46
+ /** The edge's vertex heights, copied out of the level that still owns them. */
47
+ readonly samples: Float32Array;
48
+ readonly side: TerrainEdgeSide;
49
+ readonly width: number;
50
+ }
51
+
52
+ export interface ITerrainFineEdgeJob extends ITerrainEdgeJob {
53
+ /** How many pairs the strip carries; the coarse side is sampled at the fine side's rate. */
54
+ readonly resolution: number;
55
+ }
56
+
57
+ export interface ITerrainSeamJob {
58
+ readonly kind: "seam";
59
+ readonly pairs: readonly {
60
+ readonly coarse: ITerrainEdgeJob;
61
+ readonly fine: ITerrainFineEdgeJob;
62
+ }[];
63
+ }
64
+
65
+ export interface ITerrainBridgeAttributes {
66
+ readonly coverageDepth: number;
67
+ readonly indices: Uint32Array;
68
+ readonly normals: Float32Array;
69
+ readonly positions: Float32Array;
70
+ }
71
+
72
+ export interface ITerrainSeamResult {
73
+ readonly bridges: readonly ITerrainBridgeAttributes[];
74
+ readonly kind: "seam";
75
+ }
76
+
77
+ export type ITerrainJob = ITerrainMergeJob | ITerrainSeamJob;
78
+ export type ITerrainJobResult = ITerrainMergeResult | ITerrainSeamResult;
79
+
80
+ /**
81
+ * Concatenate each part's `position`/`normal`/`index` into one block, every vertex translated from
82
+ * its own tile origin to the block origin. The vertices land on the world positions they already
83
+ * occupied, so the same surface material samples the same heights and normals. Skirts come along
84
+ * unchanged because they are part of the level geometry, and each survivor keeps its tile's
85
+ * perimeter skirt: a block edge only ever exposes a tile that was already on the block's perimeter,
86
+ * whose outward skirt is already there.
87
+ */
88
+ export function mergeBlockAttributes(job: ITerrainMergeJob): ITerrainMergeResult {
89
+ let vertexCount = 0;
90
+ let indexCount = 0;
91
+ for (const part of job.parts) {
92
+ vertexCount += part.positions.length / 3;
93
+ indexCount += part.indices.length;
94
+ }
95
+ const positions = new Float32Array(vertexCount * 3);
96
+ const normals = new Float32Array(vertexCount * 3);
97
+ const indices = new Uint32Array(indexCount);
98
+ let vertexOffset = 0;
99
+ let indexOffset = 0;
100
+ for (const part of job.parts) {
101
+ const dx = part.origin.x - job.blockOrigin.x;
102
+ const dz = part.origin.z - job.blockOrigin.z;
103
+ const count = part.positions.length / 3;
104
+ for (let vertex = 0; vertex < count; vertex += 1) {
105
+ const at = (vertexOffset + vertex) * 3;
106
+ const from = vertex * 3;
107
+ positions[at] = (part.positions[from] as number) + dx;
108
+ positions[at + 1] = part.positions[from + 1] as number;
109
+ positions[at + 2] = (part.positions[from + 2] as number) + dz;
110
+ normals[at] = part.normals[from] as number;
111
+ normals[at + 1] = part.normals[from + 1] as number;
112
+ normals[at + 2] = part.normals[from + 2] as number;
113
+ }
114
+ for (let element = 0; element < part.indices.length; element += 1)
115
+ indices[indexOffset + element] = (part.indices[element] as number) + vertexOffset;
116
+ vertexOffset += count;
117
+ indexOffset += part.indices.length;
118
+ }
119
+ return { indices, kind: "merge", normals, positions };
120
+ }
121
+
122
+ /**
123
+ * The strip's height along one edge: the retained samples read at a normalized position, clamped to
124
+ * the row's own ends.
125
+ */
126
+ export function interpolatedEdgeSample(
127
+ samples: Float32Array,
128
+ normalized: number,
129
+ name: string,
130
+ ): number {
131
+ const position = Math.max(0, Math.min(1, normalized)) * (samples.length - 1);
132
+ const lower = Math.floor(position);
133
+ const upper = Math.min(samples.length - 1, lower + 1);
134
+ const mix = position - lower;
135
+ const lowerValue = samples[lower] as number;
136
+ const upperValue = samples[upper] as number;
137
+ if (!Number.isFinite(lowerValue) || !Number.isFinite(upperValue))
138
+ throw new Error(`TerrainTiles retained ${name} edge sample must be finite.`);
139
+ return lowerValue * (1 - mix) + upperValue * mix;
140
+ }
141
+
142
+ /** The rectangle and side one edge's point is read against; a field's own numbers, no samples. */
143
+ export type ITerrainEdgeFrame = Pick<ITerrainEdgeJob, "depth" | "origin" | "side" | "width">;
144
+
145
+ /** Where one edge's point at a normalized position sits in the world. */
146
+ export function edgeWorldPoint(
147
+ edge: ITerrainEdgeFrame,
148
+ normalized: number,
149
+ height: number,
150
+ ): [number, number, number] {
151
+ const minimumX = edge.origin.x - edge.width / 2;
152
+ const minimumZ = edge.origin.z - edge.depth / 2;
153
+ const x =
154
+ edge.side === "west"
155
+ ? minimumX
156
+ : edge.side === "east"
157
+ ? minimumX + edge.width
158
+ : minimumX + normalized * edge.width;
159
+ const z =
160
+ edge.side === "north"
161
+ ? minimumZ
162
+ : edge.side === "south"
163
+ ? minimumZ + edge.depth
164
+ : minimumZ + normalized * edge.depth;
165
+ return [x, height, z];
166
+ }
167
+
168
+ /**
169
+ * One bridge's strip: a quad per fine vertex between the fine edge's height and the coarse edge's,
170
+ * plus the deepest gap between them, which is the coverage the bridge has to hide.
171
+ */
172
+ export function stitchBridgeAttributes(
173
+ fine: ITerrainFineEdgeJob,
174
+ coarse: ITerrainEdgeJob,
175
+ ): ITerrainBridgeAttributes {
176
+ const positions = new Float32Array(fine.resolution * 6);
177
+ const normals = new Float32Array(fine.resolution * 6);
178
+ const indices = new Uint32Array((fine.resolution - 1) * 12);
179
+ let coverageDepth = 0;
180
+ for (let index = 0; index < fine.resolution; index += 1) {
181
+ const normalized = index / (fine.resolution - 1);
182
+ const fineHeight = interpolatedEdgeSample(
183
+ fine.samples,
184
+ normalized,
185
+ `${fine.side} of finer LOD`,
186
+ );
187
+ const coarseHeight = interpolatedEdgeSample(
188
+ coarse.samples,
189
+ normalized,
190
+ `${coarse.side} of coarser LOD`,
191
+ );
192
+ coverageDepth = Math.max(coverageDepth, Math.abs(fineHeight - coarseHeight));
193
+ const at = index * 6;
194
+ const finePoint = edgeWorldPoint(fine, normalized, fineHeight);
195
+ const coarsePoint = edgeWorldPoint(coarse, normalized, coarseHeight);
196
+ positions[at] = finePoint[0];
197
+ positions[at + 1] = finePoint[1];
198
+ positions[at + 2] = finePoint[2];
199
+ positions[at + 3] = coarsePoint[0];
200
+ positions[at + 4] = coarsePoint[1];
201
+ positions[at + 5] = coarsePoint[2];
202
+ normals[at] = 0;
203
+ normals[at + 1] = 1;
204
+ normals[at + 2] = 0;
205
+ normals[at + 3] = 0;
206
+ normals[at + 4] = 1;
207
+ normals[at + 5] = 0;
208
+ }
209
+ for (let index = 0; index < fine.resolution - 1; index += 1) {
210
+ const fine2 = index * 2;
211
+ const coarse2 = fine2 + 1;
212
+ const nextFine = fine2 + 2;
213
+ const nextCoarse = coarse2 + 2;
214
+ const at = index * 12;
215
+ indices[at] = fine2;
216
+ indices[at + 1] = coarse2;
217
+ indices[at + 2] = nextFine;
218
+ indices[at + 3] = nextFine;
219
+ indices[at + 4] = coarse2;
220
+ indices[at + 5] = nextCoarse;
221
+ indices[at + 6] = nextFine;
222
+ indices[at + 7] = coarse2;
223
+ indices[at + 8] = fine2;
224
+ indices[at + 9] = nextCoarse;
225
+ indices[at + 10] = coarse2;
226
+ indices[at + 11] = nextFine;
227
+ }
228
+ return { coverageDepth, indices, normals, positions };
229
+ }
230
+
231
+ export function runTerrainJob(job: ITerrainMergeJob): ITerrainMergeResult;
232
+ export function runTerrainJob(job: ITerrainSeamJob): ITerrainSeamResult;
233
+ export function runTerrainJob(job: ITerrainJob): ITerrainJobResult;
234
+ /** The one body both hosts run; the worker entry is a message handler around this call. */
235
+ export function runTerrainJob(job: ITerrainJob): ITerrainJobResult {
236
+ if (job.kind === "merge") return mergeBlockAttributes(job);
237
+ return {
238
+ bridges: job.pairs.map(({ coarse, fine }) => stitchBridgeAttributes(fine, coarse)),
239
+ kind: "seam",
240
+ };
241
+ }
242
+
243
+ /** The buffers a result owns, so the reply transfers them instead of copying them back. */
244
+ export function terrainJobTransfers(result: ITerrainJobResult): Transferable[] {
245
+ if (result.kind === "merge")
246
+ return [result.positions.buffer, result.normals.buffer, result.indices.buffer];
247
+ return result.bridges.flatMap((bridge) => [
248
+ bridge.positions.buffer,
249
+ bridge.normals.buffer,
250
+ bridge.indices.buffer,
251
+ ]);
252
+ }
253
+
254
+ /**
255
+ * Where the terrain jobs run.
256
+ *
257
+ * `offThread` is `true` only when a worker is really there: the runner keeps the same function
258
+ * inline whenever `Worker` is missing (node, a native script scope) or refuses a module source, and
259
+ * it falls back to this thread if a worker dies mid-job, so a broken worker costs the main thread
260
+ * the work and nothing else. `inlineReason` names which of those it is.
261
+ *
262
+ * One worker, one job at a time, which is what keeps a block's older merge from answering after its
263
+ * newer one: replies come back in the order the jobs were sent.
264
+ */
265
+ export interface ITerrainJobRunner {
266
+ dispose(): void;
267
+ /** Why this host runs the jobs on its own thread, or `undefined` while a worker has them. */
268
+ readonly inlineReason: string | undefined;
269
+ readonly offThread: boolean;
270
+ merge(job: ITerrainMergeJob): ITerrainMergeResult | Promise<ITerrainMergeResult>;
271
+ seam(job: ITerrainSeamJob): ITerrainSeamResult | Promise<ITerrainSeamResult>;
272
+ }
273
+
274
+ interface IPendingJob {
275
+ readonly compute: () => ITerrainJobResult;
276
+ readonly resolve: (result: ITerrainJobResult) => void;
277
+ }
278
+
279
+ /**
280
+ * The module worker next to this file, and why there may not be one.
281
+ *
282
+ * The native host is the host that answers here: its shim installs a `Worker` that admits a classic
283
+ * Blob source only and refuses a module source by name (`TN_NATIVE_WORKER_MODULE_UNSUPPORTED`, see
284
+ * `runtime-native/src/runtime-scripts/url-worker-polyfill.js`), and the native bundle rewrites
285
+ * `import.meta.url` before Vite can inline a sibling worker, so there is no packaged module to load
286
+ * there. Both refusals are reported as a reason and every job runs inline from the same function.
287
+ */
288
+ function spawnTerrainWorker(): { reason: string | undefined; worker: Worker | undefined } {
289
+ if (typeof Worker === "undefined") return { reason: "no Worker on this host", worker: undefined };
290
+ try {
291
+ const worker = new Worker(new URL("./terrain-jobs-worker.js", import.meta.url), {
292
+ type: "module",
293
+ });
294
+ return { reason: undefined, worker };
295
+ } catch (error) {
296
+ const message = error instanceof Error ? error.message : String(error);
297
+ return { reason: `module worker refused: ${message}`, worker: undefined };
298
+ }
299
+ }
300
+
301
+ export function createTerrainJobRunner(): ITerrainJobRunner {
302
+ const pending = new Map<number, IPendingJob>();
303
+ let nextId = 0;
304
+ const spawned = spawnTerrainWorker();
305
+ let worker = spawned.worker;
306
+ const abandon = (): void => {
307
+ for (const [, job] of pending) job.resolve(job.compute());
308
+ pending.clear();
309
+ worker?.terminate();
310
+ worker = undefined;
311
+ };
312
+ if (worker !== undefined) {
313
+ worker.onmessage = (event: MessageEvent): void => {
314
+ const reply = event.data as { id: number; result: ITerrainJobResult };
315
+ pending.get(reply.id)?.resolve(reply.result);
316
+ pending.delete(reply.id);
317
+ };
318
+ worker.onerror = abandon;
319
+ }
320
+ const dispatch = <T extends ITerrainJobResult>(
321
+ job: ITerrainJob,
322
+ compute: () => T,
323
+ ): T | Promise<T> => {
324
+ const active = worker;
325
+ if (active === undefined) return compute();
326
+ const id = nextId;
327
+ nextId += 1;
328
+ const sent = new Promise<T>((resolve) => {
329
+ pending.set(id, {
330
+ compute: compute as () => ITerrainJobResult,
331
+ resolve: resolve as (result: ITerrainJobResult) => void,
332
+ });
333
+ });
334
+ try {
335
+ active.postMessage({ id, job });
336
+ } catch {
337
+ pending.delete(id);
338
+ return compute();
339
+ }
340
+ return sent;
341
+ };
342
+ return {
343
+ dispose: () => {
344
+ pending.clear();
345
+ worker?.terminate();
346
+ worker = undefined;
347
+ },
348
+ inlineReason: spawned.reason,
349
+ merge: (job) => dispatch(job, () => runTerrainJob(job)),
350
+ offThread: worker !== undefined,
351
+ seam: (job) => dispatch(job, () => runTerrainJob(job)),
352
+ };
353
+ }
@@ -0,0 +1,39 @@
1
+ import { DataTexture, RGBAFormat, UnsignedByteType } from "three";
2
+
3
+ /**
4
+ * A soft round sprite, built as pixel data rather than by painting a canvas.
5
+ *
6
+ * Canvas-drawn images sample black under `WebGPURenderer` — a documented trap that cost a shipped
7
+ * game real debugging time — so sprite images are written straight into pixel data. A radial alpha
8
+ * falloff is also the whole difference between a puff and a rectangle: a flat quad reads as a grey
9
+ * box, the same quad with this alpha reads as smoke.
10
+ *
11
+ * @param size edge length in pixels
12
+ * @param hardness 0 fades from the very centre, 1 keeps a solid core out to the rim
13
+ */
14
+ export function softCircleDataTexture(size = 64, hardness = 0.25): DataTexture {
15
+ if (!Number.isInteger(size) || size <= 0)
16
+ throw new Error("softCircleDataTexture size must be a positive integer.");
17
+ if (!Number.isFinite(hardness) || hardness < 0 || hardness > 1)
18
+ throw new Error("softCircleDataTexture hardness must be between 0 and 1.");
19
+ const data = new Uint8Array(size * size * 4);
20
+ const centre = (size - 1) / 2;
21
+ for (let y = 0; y < size; y += 1) {
22
+ for (let x = 0; x < size; x += 1) {
23
+ const dx = (x - centre) / centre;
24
+ const dy = (y - centre) / centre;
25
+ const distance = Math.sqrt(dx * dx + dy * dy);
26
+ // 1 at the centre, 0 at the rim, with a flat core when hardness is raised.
27
+ const falloff =
28
+ distance >= 1 ? 0 : hardness >= 1 ? 1 : Math.min(1, (1 - distance) / (1 - hardness)) ** 1.6;
29
+ const index = (y * size + x) * 4;
30
+ data[index] = 255;
31
+ data[index + 1] = 255;
32
+ data[index + 2] = 255;
33
+ data[index + 3] = Math.round(falloff * 255);
34
+ }
35
+ }
36
+ const texture = new DataTexture(data, size, size, RGBAFormat, UnsignedByteType);
37
+ texture.needsUpdate = true;
38
+ return texture;
39
+ }
package/src/tracers.ts ADDED
@@ -0,0 +1,237 @@
1
+ import {
2
+ type BufferGeometry,
3
+ CylinderGeometry,
4
+ type Material,
5
+ Mesh,
6
+ type Object3D,
7
+ Quaternion,
8
+ Vector3,
9
+ } from "three";
10
+
11
+ const UP = new Vector3(0, 1, 0);
12
+ /** Below this the round stopped inside the muzzle; a streak that short reads as a flash, not a shot. */
13
+ const MIN_DISTANCE = 0.05;
14
+ /** How far in front of `from` the segment starts, so the streak clears the weapon that fired it. */
15
+ const MAX_LEAD = 0.16;
16
+
17
+ function validateSpawnOptions(options: ITracerSpawnOptions): void {
18
+ const { lifetime, segmentLength, widthScale } = options;
19
+ if (widthScale !== undefined && (!Number.isFinite(widthScale) || widthScale <= 0)) {
20
+ throw new Error("TracerPool3D.spawn widthScale must be a positive finite number.");
21
+ }
22
+ if (segmentLength !== undefined && (!Number.isFinite(segmentLength) || segmentLength <= 0)) {
23
+ throw new Error("TracerPool3D.spawn segmentLength must be a positive finite number.");
24
+ }
25
+ if (lifetime !== undefined && (!Number.isFinite(lifetime) || lifetime <= 0)) {
26
+ throw new Error("TracerPool3D.spawn lifetime must be a positive finite number.");
27
+ }
28
+ }
29
+
30
+ function streakGeometry(): BufferGeometry {
31
+ // Unit-length along +Y with the base at the origin: scaling y stretches the streak forward.
32
+ const geometry = new CylinderGeometry(0.012, 0.012, 1, 6, 1, true);
33
+ geometry.translate(0, 0.5, 0);
34
+ return geometry;
35
+ }
36
+
37
+ interface ITracerSlot {
38
+ direction: Vector3;
39
+ life: number;
40
+ lifetime: number;
41
+ maxTravel: number;
42
+ mesh: Mesh;
43
+ travel: number;
44
+ }
45
+
46
+ export interface ITracerPool3DOptions {
47
+ /** Slots in the pool. Shots over the count recycle the oldest streak. Default 12. */
48
+ readonly count?: number;
49
+ /**
50
+ * The streak's shape, supplied by the game. The default is a neutral unit-length cylinder
51
+ * along +Y with its base at the origin — the pool stretches it along y, so any geometry laid
52
+ * out the same way works. Override it to change the streak's cross-section or silhouette.
53
+ */
54
+ readonly geometry?: BufferGeometry;
55
+ /**
56
+ * The streak's surface, supplied by the game and cloned per slot so each can fade
57
+ * independently. Required: pooling, travel and fading are the engine's; what the streak
58
+ * looks like never is. Set `opacity` to the peak brightness and pass a transparent,
59
+ * additive surface for the usual bright-fade look.
60
+ */
61
+ readonly material: Material;
62
+ /** Longest streak in metres; shorter shots get a shorter streak. Default 3.2. */
63
+ readonly segmentLength?: number;
64
+ /** Travel speed in metres per second. Default 360. */
65
+ readonly speed?: number;
66
+ /** Seconds a streak lives before fading out fully. Default 0.11. */
67
+ readonly lifetime?: number;
68
+ }
69
+
70
+ /**
71
+ * Per-shot overrides a game passes to {@link TracerPool3D.spawn} — shot-to-shot variation
72
+ * keeps two rounds from reading as one drawn line. The values are the game's (usually from
73
+ * its seeded random so replays stay identical); the pool only applies them.
74
+ */
75
+ export interface ITracerSpawnOptions {
76
+ /** Longest streak for this shot, in metres. Defaults to the pool's `segmentLength`. */
77
+ readonly segmentLength?: number;
78
+ /** Seconds this streak lives before fading out fully. Defaults to the pool's `lifetime`. */
79
+ readonly lifetime?: number;
80
+ /** Multiplier on this streak's cross-section (x/z scale). Default 1. */
81
+ readonly widthScale?: number;
82
+ }
83
+
84
+ /**
85
+ * Pooled travelling bullet streaks for hitscan shots.
86
+ *
87
+ * A hitscan round leaves nothing to see, so a shot is only a sound and a number — you cannot tell
88
+ * where it went or who is firing. The pool draws a short bright segment that travels from the
89
+ * muzzle toward the point reached and fades out. Segments are stretched cylinders rather than
90
+ * `Line`s, because line width is not portable across backends and a one-pixel line is invisible at
91
+ * thirty metres.
92
+ *
93
+ * Every member starts visible at zero opacity, so the whole pool doubles as a pipeline prewarm
94
+ * surface (`prewarm(tracers)`); nothing is created while firing. Call {@link update} once per
95
+ * frame and {@link dispose} with the owning scene.
96
+ */
97
+ export class TracerPool3D {
98
+ #cursor = 0;
99
+ readonly #direction = new Vector3();
100
+ #disposed = false;
101
+ readonly #geometry: BufferGeometry;
102
+ readonly #lifetime: number;
103
+ readonly #ownsGeometry: boolean;
104
+ readonly #parent: Object3D;
105
+ readonly #peakOpacity: number;
106
+ readonly #quaternion = new Quaternion();
107
+ readonly #segmentLength: number;
108
+ #settled = false;
109
+ readonly #slots: readonly ITracerSlot[];
110
+ readonly #speed: number;
111
+
112
+ constructor(parent: Object3D, options: ITracerPool3DOptions) {
113
+ const { count = 12, lifetime = 0.11, segmentLength = 3.2, speed = 360 } = options;
114
+ if (!Number.isInteger(count) || count <= 0)
115
+ throw new Error("TracerPool3D.count must be a positive integer.");
116
+ if (options.material === undefined) throw new Error("TracerPool3D.material is required.");
117
+ if (!Number.isFinite(segmentLength) || segmentLength <= 0)
118
+ throw new Error("TracerPool3D.segmentLength must be a positive finite number.");
119
+ if (!Number.isFinite(speed) || speed <= 0)
120
+ throw new Error("TracerPool3D.speed must be a positive finite number.");
121
+ if (!Number.isFinite(lifetime) || lifetime <= 0)
122
+ throw new Error("TracerPool3D.lifetime must be a positive finite number.");
123
+
124
+ this.#parent = parent;
125
+ this.#lifetime = lifetime;
126
+ this.#segmentLength = segmentLength;
127
+ this.#speed = speed;
128
+ // Fading animates `opacity`, which only renders on a transparent surface.
129
+ options.material.transparent = true;
130
+ this.#peakOpacity = options.material.opacity;
131
+ this.#ownsGeometry = options.geometry === undefined;
132
+ this.#geometry = options.geometry ?? streakGeometry();
133
+ this.#slots = Array.from({ length: count }, () => {
134
+ const mesh = new Mesh(this.#geometry, options.material.clone());
135
+ // Zero-opacity members ride along in render passes from load time, warming the backend's
136
+ // pipeline cache so the first real shot costs no compile stall (see `prewarm`).
137
+ (mesh.material as Material).opacity = 0;
138
+ mesh.visible = true;
139
+ mesh.frustumCulled = false;
140
+ parent.add(mesh);
141
+ return {
142
+ direction: new Vector3(),
143
+ life: 0,
144
+ lifetime,
145
+ maxTravel: 0,
146
+ mesh,
147
+ travel: 0,
148
+ };
149
+ });
150
+ }
151
+
152
+ /**
153
+ * Stop submitting the slots that are not carrying a shot.
154
+ *
155
+ * The pool is resident from construction at zero opacity so its pipeline compiles during
156
+ * loading; the cost is a draw per dead streak every frame forever, and on a phone the draw call
157
+ * is the expensive part, not the triangles. Once compiled the pipeline is cached, so `spawn`
158
+ * re-showing a slot is free. Call this a second or two into the scene, after `prewarm` — not on
159
+ * the first frame, or the compile this exists to force will not have happened yet.
160
+ */
161
+ settle(): void {
162
+ this.#settled = true;
163
+ for (const slot of this.#slots) {
164
+ if (slot.life <= 0) slot.mesh.visible = false;
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Draw one round travelling from `from` along `direction` for `distance` metres.
170
+ * `options` carries the game's per-shot variation; omit it for the pool defaults.
171
+ */
172
+ spawn(
173
+ from: Vector3,
174
+ direction: Vector3,
175
+ distance: number,
176
+ options: ITracerSpawnOptions = {},
177
+ ): void {
178
+ if (this.#disposed) throw new Error("TracerPool3D cannot spawn after dispose.");
179
+ const squaredLength = direction.lengthSq();
180
+ if (!Number.isFinite(squaredLength) || squaredLength <= 0)
181
+ throw new Error("TracerPool3D.spawn direction must be a non-zero finite vector.");
182
+ if (!Number.isFinite(distance))
183
+ throw new Error("TracerPool3D.spawn distance must be a finite number.");
184
+ validateSpawnOptions(options);
185
+ const shotLifetime = options.lifetime ?? this.#lifetime;
186
+ const shotSegmentLength = options.segmentLength ?? this.#segmentLength;
187
+ const widthScale = options.widthScale ?? 1;
188
+ const slot = this.#slots[this.#cursor % this.#slots.length];
189
+ this.#cursor += 1;
190
+ if (slot === undefined || distance < MIN_DISTANCE) return;
191
+
192
+ this.#direction.copy(direction).normalize();
193
+ this.#quaternion.setFromUnitVectors(UP, this.#direction);
194
+ const segmentLength = Math.min(shotSegmentLength, distance);
195
+ const lead = Math.min(MAX_LEAD, Math.max(0, distance - segmentLength));
196
+ slot.direction.copy(this.#direction);
197
+ slot.travel = lead;
198
+ slot.maxTravel = Math.max(lead, distance - segmentLength);
199
+ slot.mesh.position.copy(from).addScaledVector(this.#direction, lead);
200
+ slot.mesh.quaternion.copy(this.#quaternion);
201
+ slot.mesh.scale.set(widthScale, segmentLength, widthScale);
202
+ if (this.#settled) slot.mesh.visible = true;
203
+ (slot.mesh.material as Material).opacity = this.#peakOpacity;
204
+ slot.life = shotLifetime;
205
+ slot.lifetime = shotLifetime;
206
+ }
207
+
208
+ /** Advance every live streak; call once per frame with the frame's delta seconds. */
209
+ update(dt: number): void {
210
+ for (const slot of this.#slots) {
211
+ if (slot.life <= 0) continue;
212
+ slot.life -= dt;
213
+ const movement = Math.min(dt * this.#speed, slot.maxTravel - slot.travel);
214
+ slot.travel += movement;
215
+ slot.mesh.position.addScaledVector(slot.direction, movement);
216
+ if (slot.life <= 0 || slot.travel >= slot.maxTravel) {
217
+ slot.life = 0;
218
+ (slot.mesh.material as Material).opacity = 0;
219
+ if (this.#settled) slot.mesh.visible = false;
220
+ continue;
221
+ }
222
+ (slot.mesh.material as Material).opacity =
223
+ this.#peakOpacity * Math.min(1, slot.life / slot.lifetime);
224
+ }
225
+ }
226
+
227
+ /** Remove every mesh from the parent and release pooled surfaces. Game-owned geometry survives. */
228
+ dispose(): void {
229
+ if (this.#disposed) return;
230
+ this.#disposed = true;
231
+ for (const slot of this.#slots) {
232
+ this.#parent.remove(slot.mesh);
233
+ (slot.mesh.material as Material).dispose();
234
+ }
235
+ if (this.#ownsGeometry) this.#geometry.dispose();
236
+ }
237
+ }