@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,516 @@
1
+ import { type BufferGeometry, Matrix4, Mesh, Vector3, Vector4 } from "three";
2
+ import {
3
+ Fn,
4
+ If,
5
+ Loop,
6
+ exp,
7
+ instanceIndex,
8
+ instancedArray,
9
+ length,
10
+ uniform,
11
+ uniformArray,
12
+ vec3,
13
+ vertexIndex,
14
+ } from "three/tsl";
15
+ import type {
16
+ ComputeNode,
17
+ Node,
18
+ NodeMaterial,
19
+ StorageBufferNode,
20
+ UniformArrayNode,
21
+ } from "three/webgpu";
22
+ import type { IComputeDriven } from "./compute-driven.js";
23
+ import { GPUReadback, type IGPUReadbackSample } from "./gpu-readback.js";
24
+ import type { IRendererLike } from "./renderer.js";
25
+ import {
26
+ type IClothReferenceOptions,
27
+ type IClothTopology,
28
+ type IClothTopologyOptions,
29
+ buildClothTopology,
30
+ simulateClothReference,
31
+ } from "./softbody-topology.js";
32
+
33
+ export type { IClothReferenceOptions, IClothTopology, IClothTopologyOptions };
34
+ export { buildClothTopology, simulateClothReference };
35
+
36
+ /** Packed collision input supplied by an optional dependency such as `@threenative/physics`. */
37
+ export interface ISoftBodyCollision {
38
+ readonly capacity: number;
39
+ writeBoxes(target: Float32Array, worldToLocal: Matrix4): number;
40
+ }
41
+
42
+ export interface ISoftBody3DOptions extends IClothTopologyOptions {
43
+ /** Spring acceleration per metre of stretch. Required; the game owns the cloth response. */
44
+ readonly stiffness: number;
45
+ /** Exponential velocity decay per second. Required; zero disables damping. */
46
+ readonly damping: number;
47
+ /** Local-space acceleration in metres per second squared. */
48
+ readonly gravity: readonly [number, number, number];
49
+ /** Local-space wind acceleration in metres per second squared. */
50
+ readonly wind: readonly [number, number, number];
51
+ /** Existing physics bodies translated by the physics package; omitted when cloth has no world collision. */
52
+ readonly collision?: ISoftBodyCollision;
53
+ /** Framework fixed-step duration. Defaults to the engine convention of 1/60 second. */
54
+ readonly timeStep?: number;
55
+ /** Throttled GPU position readback for gameplay/proof; zero disables it. */
56
+ readonly readbackEveryFrames?: number;
57
+ }
58
+
59
+ interface IClothBuffers {
60
+ readonly adjacency: StorageBufferNode<"vec2">;
61
+ readonly initial: StorageBufferNode<"vec3">;
62
+ readonly metadata: StorageBufferNode<"uvec2">;
63
+ readonly originalToUnique: StorageBufferNode<"uint">;
64
+ readonly positionsA: StorageBufferNode<"vec3">;
65
+ readonly positionsB: StorageBufferNode<"vec3">;
66
+ readonly velocitiesA: StorageBufferNode<"vec3">;
67
+ readonly velocitiesB: StorageBufferNode<"vec3">;
68
+ }
69
+
70
+ interface IClothCollisionState {
71
+ readonly bounds: UniformArrayNode<"vec4">;
72
+ readonly count: Node<"uint"> & { value: number };
73
+ readonly packed: Float32Array;
74
+ readonly source: ISoftBodyCollision;
75
+ readonly worldToLocal: Matrix4;
76
+ }
77
+
78
+ function finite(name: string, value: number): number {
79
+ if (!Number.isFinite(value)) throw new Error(`SoftBody3D.${name} must be finite.`);
80
+ return value;
81
+ }
82
+
83
+ function positive(name: string, value: number): number {
84
+ finite(name, value);
85
+ if (value <= 0) throw new Error(`SoftBody3D.${name} must be greater than zero.`);
86
+ return value;
87
+ }
88
+
89
+ function nonNegative(name: string, value: number): number {
90
+ finite(name, value);
91
+ if (value < 0) throw new Error(`SoftBody3D.${name} must be non-negative.`);
92
+ return value;
93
+ }
94
+
95
+ function vector(name: string, value: readonly [number, number, number]): Vector3 {
96
+ if (!Array.isArray(value) || value.length !== 3)
97
+ throw new Error(`SoftBody3D.${name} must contain three numbers.`);
98
+ return new Vector3(
99
+ finite(`${name}.x`, value[0]),
100
+ finite(`${name}.y`, value[1]),
101
+ finite(`${name}.z`, value[2]),
102
+ );
103
+ }
104
+
105
+ function nodeMaterial(mesh: Mesh): NodeMaterial {
106
+ if (
107
+ Array.isArray(mesh.material) ||
108
+ (mesh.material as { readonly isNodeMaterial?: boolean }).isNodeMaterial !== true
109
+ )
110
+ throw new Error("SoftBody3D mesh must use one game-owned Three.js node material.");
111
+ return mesh.material.clone() as NodeMaterial;
112
+ }
113
+
114
+ function storageBuffers(topology: IClothTopology): IClothBuffers {
115
+ const zeroVelocities = new Float32Array(topology.positions.length);
116
+ const metadata = new Uint32Array(topology.pinned.length * 2);
117
+ for (let vertex = 0; vertex < topology.pinned.length; vertex += 1) {
118
+ metadata[vertex * 2] = topology.pinned[vertex] ?? 0;
119
+ metadata[vertex * 2 + 1] = topology.neighborCounts[vertex] ?? 0;
120
+ }
121
+ const adjacency = new Float32Array(topology.neighbors.length * 2);
122
+ for (let slot = 0; slot < topology.neighbors.length; slot += 1) {
123
+ adjacency[slot * 2] = topology.neighbors[slot] ?? 0;
124
+ adjacency[slot * 2 + 1] = topology.neighborRestLengths[slot] ?? 0;
125
+ }
126
+ return {
127
+ adjacency: instancedArray(adjacency, "vec2"),
128
+ initial: instancedArray(new Float32Array(topology.positions), "vec3"),
129
+ metadata: instancedArray(metadata, "uvec2"),
130
+ originalToUnique: instancedArray(topology.originalToUnique, "uint"),
131
+ positionsA: instancedArray(new Float32Array(topology.positions), "vec3"),
132
+ positionsB: instancedArray(new Float32Array(topology.positions), "vec3"),
133
+ velocitiesA: instancedArray(zeroVelocities, "vec3"),
134
+ velocitiesB: instancedArray(new Float32Array(zeroVelocities), "vec3"),
135
+ };
136
+ }
137
+
138
+ /** @internal WGSL arrays align vec3 elements to 16 bytes even though the CPU attribute is packed. */
139
+ export function compactClothVec3Readback(data: Float32Array, vertices: number): Float32Array {
140
+ if (data.length === vertices * 3) return new Float32Array(data);
141
+ if (data.length !== vertices * 4)
142
+ throw new Error(
143
+ `SoftBody3D position readback expected ${vertices * 3} packed or ${vertices * 4} padded floats, received ${data.length}.`,
144
+ );
145
+ const compact = new Float32Array(vertices * 3);
146
+ for (let vertex = 0; vertex < vertices; vertex += 1)
147
+ compact.set(data.subarray(vertex * 4, vertex * 4 + 3), vertex * 3);
148
+ return compact;
149
+ }
150
+
151
+ function clothPass(options: {
152
+ readonly name: string;
153
+ readonly vertexCount: number;
154
+ readonly maxNeighbors: number;
155
+ readonly sourcePositions: StorageBufferNode<"vec3">;
156
+ readonly sourceVelocities: StorageBufferNode<"vec3">;
157
+ readonly targetPositions: StorageBufferNode<"vec3">;
158
+ readonly targetVelocities: StorageBufferNode<"vec3">;
159
+ readonly buffers: IClothBuffers;
160
+ readonly forces: UniformArrayNode<"vec4">;
161
+ readonly stiffness: Node<"float">;
162
+ readonly damping: Node<"float">;
163
+ readonly halfStep: Node<"float">;
164
+ readonly collision?: Pick<IClothCollisionState, "bounds" | "count"> & {
165
+ readonly capacity: number;
166
+ };
167
+ }): ComputeNode {
168
+ const pass = Fn(() => {
169
+ const position = options.sourcePositions.element(instanceIndex);
170
+ const force = vec3(0).toVar();
171
+ const metadata = options.buffers.metadata.element(instanceIndex);
172
+ const neighborCount = metadata.y;
173
+ Loop({ type: "uint", start: 0, end: options.maxNeighbors }, ({ i }) => {
174
+ If(i.lessThan(neighborCount), () => {
175
+ const slot = instanceIndex.mul(options.maxNeighbors).add(i);
176
+ const adjacency = options.buffers.adjacency.element(slot);
177
+ const neighbor = adjacency.x.toUint();
178
+ const delta = options.sourcePositions.element(neighbor).sub(position);
179
+ const distance = length(delta);
180
+ If(distance.greaterThan(1e-6), () => {
181
+ const stretch = distance.sub(adjacency.y);
182
+ force.addAssign(delta.mul(stretch.div(distance)).mul(options.stiffness));
183
+ });
184
+ });
185
+ });
186
+ const velocity = options.sourceVelocities
187
+ .element(instanceIndex)
188
+ .add(
189
+ force
190
+ .add(options.forces.element(0).xyz)
191
+ .add(options.forces.element(1).xyz)
192
+ .mul(options.halfStep),
193
+ )
194
+ .mul(exp(options.damping.mul(options.halfStep).negate()))
195
+ .toVar();
196
+ const nextPosition = position.add(velocity.mul(options.halfStep)).toVar();
197
+ const collision = options.collision;
198
+ if (collision !== undefined) {
199
+ Loop({ type: "uint", start: 0, end: collision.capacity }, ({ i }) => {
200
+ If(i.lessThan(collision.count), () => {
201
+ const center = collision.bounds.element(i.mul(2)).xyz;
202
+ const halfExtents = collision.bounds.element(i.mul(2).add(1)).xyz;
203
+ const currentRelative = position.sub(center);
204
+ const relative = nextPosition.sub(center);
205
+ const withinX = relative.x.abs().lessThanEqual(halfExtents.x);
206
+ const withinY = relative.y.abs().lessThanEqual(halfExtents.y);
207
+ const withinZ = relative.z.abs().lessThanEqual(halfExtents.z);
208
+ const crossedNegativeX = currentRelative.x
209
+ .lessThanEqual(halfExtents.x.negate())
210
+ .and(relative.x.greaterThanEqual(halfExtents.x.negate()))
211
+ .and(withinY)
212
+ .and(withinZ);
213
+ const crossedPositiveX = currentRelative.x
214
+ .greaterThanEqual(halfExtents.x)
215
+ .and(relative.x.lessThanEqual(halfExtents.x))
216
+ .and(withinY)
217
+ .and(withinZ);
218
+ const crossedNegativeY = currentRelative.y
219
+ .lessThanEqual(halfExtents.y.negate())
220
+ .and(relative.y.greaterThanEqual(halfExtents.y.negate()))
221
+ .and(withinX)
222
+ .and(withinZ);
223
+ const crossedPositiveY = currentRelative.y
224
+ .greaterThanEqual(halfExtents.y)
225
+ .and(relative.y.lessThanEqual(halfExtents.y))
226
+ .and(withinX)
227
+ .and(withinZ);
228
+ const crossedNegativeZ = currentRelative.z
229
+ .lessThanEqual(halfExtents.z.negate())
230
+ .and(relative.z.greaterThanEqual(halfExtents.z.negate()))
231
+ .and(withinX)
232
+ .and(withinY);
233
+ const crossedPositiveZ = currentRelative.z
234
+ .greaterThanEqual(halfExtents.z)
235
+ .and(relative.z.lessThanEqual(halfExtents.z))
236
+ .and(withinX)
237
+ .and(withinY);
238
+ If(crossedNegativeX, () => {
239
+ nextPosition.x.assign(center.x.sub(halfExtents.x));
240
+ velocity.x.assign(0);
241
+ })
242
+ .ElseIf(crossedPositiveX, () => {
243
+ nextPosition.x.assign(center.x.add(halfExtents.x));
244
+ velocity.x.assign(0);
245
+ })
246
+ .ElseIf(crossedNegativeY, () => {
247
+ nextPosition.y.assign(center.y.sub(halfExtents.y));
248
+ velocity.y.assign(0);
249
+ })
250
+ .ElseIf(crossedPositiveY, () => {
251
+ nextPosition.y.assign(center.y.add(halfExtents.y));
252
+ velocity.y.assign(0);
253
+ })
254
+ .ElseIf(crossedNegativeZ, () => {
255
+ nextPosition.z.assign(center.z.sub(halfExtents.z));
256
+ velocity.z.assign(0);
257
+ })
258
+ .ElseIf(crossedPositiveZ, () => {
259
+ nextPosition.z.assign(center.z.add(halfExtents.z));
260
+ velocity.z.assign(0);
261
+ })
262
+ .ElseIf(relative.abs().lessThanEqual(halfExtents).all(), () => {
263
+ const faceDistance = halfExtents.sub(relative.abs());
264
+ If(
265
+ faceDistance.x
266
+ .lessThanEqual(faceDistance.y)
267
+ .and(faceDistance.x.lessThanEqual(faceDistance.z)),
268
+ () => {
269
+ nextPosition.x.assign(
270
+ center.x.add(halfExtents.x.mul(relative.x.greaterThanEqual(0).select(1, -1))),
271
+ );
272
+ velocity.x.assign(0);
273
+ },
274
+ )
275
+ .ElseIf(faceDistance.y.lessThanEqual(faceDistance.z), () => {
276
+ nextPosition.y.assign(
277
+ center.y.add(halfExtents.y.mul(relative.y.greaterThanEqual(0).select(1, -1))),
278
+ );
279
+ velocity.y.assign(0);
280
+ })
281
+ .Else(() => {
282
+ nextPosition.z.assign(
283
+ center.z.add(halfExtents.z.mul(relative.z.greaterThanEqual(0).select(1, -1))),
284
+ );
285
+ velocity.z.assign(0);
286
+ });
287
+ });
288
+ });
289
+ });
290
+ }
291
+ If(metadata.x.greaterThan(0), () => {
292
+ options.targetPositions
293
+ .element(instanceIndex)
294
+ .assign(options.buffers.initial.element(instanceIndex));
295
+ options.targetVelocities.element(instanceIndex).assign(vec3(0));
296
+ }).Else(() => {
297
+ options.targetPositions.element(instanceIndex).assign(nextPosition);
298
+ options.targetVelocities.element(instanceIndex).assign(velocity);
299
+ });
300
+ })().compute(options.vertexCount);
301
+ pass.setName(options.name);
302
+ return pass;
303
+ }
304
+
305
+ /**
306
+ * Simulate an ordinary game-authored triangle mesh as cloth on the existing fixed-step GPU lane.
307
+ *
308
+ * The mesh supplies every visible choice. This class welds exporter duplicates, owns spring and
309
+ * position buffers, and replaces only the cloned material's position node. It adds no material,
310
+ * colour, texture, wind, stiffness, damping, or pinning default.
311
+ *
312
+ * @situation make a flag, cape, or curtain move as cloth
313
+ * @situation simulate a deforming surface while keeping one edge pinned
314
+ * @situation simulate cloth sails blowing in the wind
315
+ * @situation make cloth sails billow in wind on a ship
316
+ * @constraint the mesh must use one Three.js node material and contain complete triangles
317
+ * @constraint pinned, stiffness, damping, gravity, and wind are required game-owned inputs
318
+ * @constraint Pixel 8 steady upper bound for the shipped 45-vertex pennant with readback every two frames: whole-starter update p95 4.66 ms, render p95 3.56 ms, and GPU timer 0.05 ms across three 300-frame final-rung windows at 552x248 with 4x MSAA; these whole-scene numbers are not isolated solver cost
319
+ * @override timeStep follows the engine 1/60-second convention unless the game overrides it
320
+ * @override readbackEveryFrames enables an explicitly stale CPU position sample; zero disables it
321
+ * @example const flag = new SoftBody3D(flagMesh, { pinned: topEdge, stiffness: 35, damping: 1.8, gravity: [0, -9.81, 0], wind: [1.5, 0, 0.4] });
322
+ */
323
+ export class SoftBody3D extends Mesh<BufferGeometry, NodeMaterial> implements IComputeDriven {
324
+ readonly processCadence = "fixed" as const;
325
+ readonly warmupNodes: readonly ComputeNode[];
326
+ readonly stiffness: number;
327
+ readonly damping: number;
328
+ readonly timeStep: number;
329
+ readonly gravity: Vector3;
330
+ readonly wind: Vector3;
331
+ readonly uniqueVertexCount: number;
332
+ readonly springCount: number;
333
+ readonly #buffers: IClothBuffers;
334
+ readonly #forces: UniformArrayNode<"vec4">;
335
+ readonly #collision: IClothCollisionState | undefined;
336
+ readonly #readback: GPUReadback | undefined;
337
+ readonly #ownedMaterial: NodeMaterial;
338
+ #renderer: IRendererLike | undefined;
339
+ #released = false;
340
+ #steps = 0;
341
+
342
+ constructor(mesh: Mesh, options: ISoftBody3DOptions) {
343
+ const topology = buildClothTopology(mesh.geometry, options);
344
+ const gravity = vector("gravity", options.gravity);
345
+ const wind = vector("wind", options.wind);
346
+ const material = nodeMaterial(mesh);
347
+ const buffers = storageBuffers(topology);
348
+ const forces: UniformArrayNode<"vec4"> = uniformArray(
349
+ [new Vector4(gravity.x, gravity.y, gravity.z, 0), new Vector4(wind.x, wind.y, wind.z, 0)],
350
+ "vec4",
351
+ );
352
+ const collision = options.collision;
353
+ if (
354
+ collision !== undefined &&
355
+ (!Number.isInteger(collision.capacity) || collision.capacity <= 0)
356
+ )
357
+ throw new Error("SoftBody3D collision capacity must be a positive integer.");
358
+ const collisionState: IClothCollisionState | undefined =
359
+ collision === undefined
360
+ ? undefined
361
+ : {
362
+ bounds: uniformArray(
363
+ Array.from({ length: collision.capacity * 2 }, () => new Vector4()),
364
+ "vec4",
365
+ ),
366
+ count: uniform(0, "uint"),
367
+ packed: new Float32Array(collision.capacity * 8),
368
+ source: collision,
369
+ worldToLocal: new Matrix4(),
370
+ };
371
+ material.positionNode = buffers.positionsA.element(
372
+ buffers.originalToUnique.element(vertexIndex),
373
+ );
374
+ super(mesh.geometry, material);
375
+ this.#ownedMaterial = material;
376
+ this.#buffers = buffers;
377
+ this.#forces = forces;
378
+ this.#collision = collisionState;
379
+ this.stiffness = positive("stiffness", options.stiffness);
380
+ this.damping = nonNegative("damping", options.damping);
381
+ this.timeStep = positive("timeStep", options.timeStep ?? 1 / 60);
382
+ this.gravity = gravity;
383
+ this.wind = wind;
384
+ const readbackEveryFrames = options.readbackEveryFrames ?? 0;
385
+ if (!Number.isInteger(readbackEveryFrames) || readbackEveryFrames < 0)
386
+ throw new Error("SoftBody3D.readbackEveryFrames must be a non-negative integer.");
387
+ this.uniqueVertexCount = topology.positions.length / 3;
388
+ this.springCount = topology.springs.length / 2;
389
+ const stiffness = uniform(this.stiffness);
390
+ const damping = uniform(this.damping);
391
+ const halfStep = uniform(this.timeStep / 2);
392
+ const common = {
393
+ buffers,
394
+ ...(collisionState === undefined
395
+ ? {}
396
+ : {
397
+ collision: {
398
+ bounds: collisionState.bounds,
399
+ capacity: collisionState.source.capacity,
400
+ count: collisionState.count,
401
+ },
402
+ }),
403
+ damping,
404
+ forces,
405
+ halfStep,
406
+ maxNeighbors: topology.maxNeighbors,
407
+ stiffness,
408
+ vertexCount: this.uniqueVertexCount,
409
+ };
410
+ const passAtoB = clothPass({
411
+ ...common,
412
+ name: "softbody.a-to-b",
413
+ sourcePositions: buffers.positionsA,
414
+ sourceVelocities: buffers.velocitiesA,
415
+ targetPositions: buffers.positionsB,
416
+ targetVelocities: buffers.velocitiesB,
417
+ });
418
+ const passBtoA = clothPass({
419
+ ...common,
420
+ name: "softbody.b-to-a",
421
+ sourcePositions: buffers.positionsB,
422
+ sourceVelocities: buffers.velocitiesB,
423
+ targetPositions: buffers.positionsA,
424
+ targetVelocities: buffers.velocitiesA,
425
+ });
426
+ this.warmupNodes = [passAtoB, passBtoA];
427
+ this.#readback =
428
+ readbackEveryFrames > 0
429
+ ? new GPUReadback({
430
+ attribute: buffers.positionsA.value,
431
+ everyFrames: readbackEveryFrames,
432
+ })
433
+ : undefined;
434
+ this.frustumCulled = false;
435
+ this.addEventListener("removed", this.#onRemoved);
436
+ }
437
+
438
+ get released(): boolean {
439
+ return this.#released;
440
+ }
441
+
442
+ get steps(): number {
443
+ return this.#steps;
444
+ }
445
+
446
+ /** Latest asynchronous GPU positions and their age, when readback was requested. */
447
+ get sample(): IGPUReadbackSample | undefined {
448
+ const sample = this.#readback?.sample;
449
+ if (sample === undefined) return undefined;
450
+ return {
451
+ data: compactClothVec3Readback(sample.data, this.uniqueVertexCount),
452
+ staleFrames: sample.staleFrames,
453
+ };
454
+ }
455
+
456
+ debug(): Record<string, unknown> {
457
+ return {
458
+ released: this.#released,
459
+ softBodySteps: this.#steps,
460
+ springCount: this.springCount,
461
+ uniqueVertexCount: this.uniqueVertexCount,
462
+ readbackPending: this.#readback?.pending,
463
+ readbackStats: this.#readback?.stats,
464
+ sampleStaleFrames: this.#readback?.staleFrames,
465
+ };
466
+ }
467
+
468
+ attachRenderer(renderer: IRendererLike): void {
469
+ if (this.#released) throw new Error("SoftBody3D cannot be attached after release.");
470
+ if (renderer.kind !== "webgpu") throw new Error("SoftBody3D requires the WebGPU renderer.");
471
+ this.#renderer = renderer;
472
+ }
473
+
474
+ process(renderer = this.#renderer): void {
475
+ if (this.#released) return;
476
+ if (renderer === undefined) throw new Error("SoftBody3D is not attached to a renderer.");
477
+ (this.#forces.array[0] as Vector4).set(this.gravity.x, this.gravity.y, this.gravity.z, 0);
478
+ (this.#forces.array[1] as Vector4).set(this.wind.x, this.wind.y, this.wind.z, 0);
479
+ const collision = this.#collision;
480
+ if (collision !== undefined) {
481
+ this.updateWorldMatrix(true, false);
482
+ collision.worldToLocal.copy(this.matrixWorld).invert();
483
+ const count = collision.source.writeBoxes(collision.packed, collision.worldToLocal);
484
+ if (!Number.isInteger(count) || count < 0 || count > collision.source.capacity)
485
+ throw new Error(
486
+ `SoftBody3D collision source returned ${count}; expected 0..${collision.source.capacity}.`,
487
+ );
488
+ collision.count.value = count;
489
+ for (let index = 0; index < collision.source.capacity * 2; index += 1) {
490
+ const offset = index * 4;
491
+ (collision.bounds.array[index] as Vector4).set(
492
+ collision.packed[offset] as number,
493
+ collision.packed[offset + 1] as number,
494
+ collision.packed[offset + 2] as number,
495
+ collision.packed[offset + 3] as number,
496
+ );
497
+ }
498
+ }
499
+ for (const node of this.warmupNodes) renderer.compute(node);
500
+ this.#steps += 1;
501
+ this.#readback?.request(renderer);
502
+ }
503
+
504
+ detach(): void {
505
+ if (this.#released) return;
506
+ this.removeEventListener("removed", this.#onRemoved);
507
+ this.#renderer = undefined;
508
+ for (const node of this.warmupNodes) node.dispose();
509
+ for (const buffer of Object.values(this.#buffers)) buffer.value.dispose();
510
+ this.#readback?.dispose();
511
+ this.#ownedMaterial.dispose();
512
+ this.#released = true;
513
+ }
514
+
515
+ #onRemoved = (): void => this.detach();
516
+ }