lecodes-sdk 2.3.0 → 2.3.1

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.
@@ -1,486 +1,486 @@
1
- // DynamicBone — secondary motion for tails, ears, hair, ropes and cloaks, simulated in the engine.
2
- // Attach to the ROOT bone of a chain; the bone's whole subtree becomes Verlet particle chains that
3
- // swing, lag and settle under gravity, wind and the character's motion, pulled back toward the pose
4
- // the animation gives them, kept out of the body by capsule colliders and above the floor.
5
- //
6
- // const tail = fox.bone('tail')!
7
- // tail.aspect(DynamicBone, { stiffness: [0.6, 0.15], damping: 0.15, gravity: 2, angleLimit: 50 })
8
- // fox.bone('earend')!.aspect(DynamicBone, { stiffness: 0.8, angleLimit: 25 })
9
- // fox.bone('Hips')!.aspect(DynamicBoneCollider, { radius: 0.12, to: 'chest' }) // a capsule the tail can't enter
10
- // tail.dynamicBone.weight = cutscene ? 0 : 1 // blend to the animation
11
- // tail.dynamicBone.floor = hit.point // the ground under it
12
- // tail.dynamicBone.reset() // after a teleport
13
- //
14
- // Per-bone values (`radius`, `stiffness`, `damping`, `gravity`, `angleLimit`) take one number for the
15
- // whole chain or a `[root, tip]` pair interpolated down the chain — a tail is stiff at the base and
16
- // loose at the tip. A cloak is one aspect on the common parent of its columns with `link` > 0: the
17
- // bones at the same depth of neighbouring columns are tied at their rest distance.
18
- //
19
- // The simulation runs natively in a stage of its own after the late phase and before the skin flush
20
- // (docs/parity: gl-dynamic-bones): the animator, an active ragdoll and late-phase aspects (IK) are
21
- // its input; every field of this aspect is live — the values are pushed when they change.
22
-
23
- import { Aspect } from "../../core/Aspect"
24
- import type { FieldMeta } from "../../core/fields"
25
- import { Vec3, cx, cy, cz, type Vec3Like } from "../../math/vec"
26
- import { Node } from "../Node"
27
- import { Model } from "../Model"
28
- import { HUMANOID, humanoidParts } from "../physics/Ragdoll"
29
-
30
- /** One value for the chain, or `[root, tip]` interpolated down it by depth. */
31
- export type DynamicBoneCurve = number | readonly [root: number, tip: number]
32
- /** `'none'`, `'probe'` (a ray from the chain root down against the physics world, every frame), a
33
- * height (a horizontal plane at that world y) or a world point (a plane through it, `floorNormal` up). */
34
- export type DynamicBoneFloor = "none" | "probe" | number | Vec3Like
35
- /** `'auto'` = every DynamicBoneCollider under the model; `'humanoid'` = those plus capsules generated
36
- * on the standard humanoid bones (hips, spine, head, limbs — the Ragdoll's layout); `'none'`; or the
37
- * nodes carrying the colliders to use. */
38
- export type DynamicBoneColliders = "auto" | "humanoid" | "none" | Node[]
39
- /** The cloth's SIDE of every collider marked `oneSided`: `'none'` = no side, every collider pushes a bone to
40
- * its nearest surface (tails, ropes); `'auto'` = away from the root bone's own axis (a cloak's strips round
41
- * a spine face out from it); a vector = a fixed direction in the root bone's frame (a cape hanging BEHIND
42
- * the arms: the body's backward). A one-sided collider that is moving AWAY from that side — an arm swinging
43
- * forward under the cape — puts a bone it has run into over to the side instead of carrying it: the arm
44
- * passes through the cloth and the cape hangs behind it again, instead of being dragged round the body.
45
- * Still, or moving toward the cloth, it pushes like any other collider, so cloth draped on an arm at rest
46
- * stays where it is. Two-sided colliders (the body's) never read the side. */
47
- export type DynamicBoneSide = "none" | "auto" | Vec3Like
48
-
49
- const VERSION = 1
50
- const PARAMS = 25 // CANIM_DYN_COUNT
51
- const HEADER = 3 + PARAMS
52
- const STRIDE = 7 // CANIM_DYN_BONE_STRIDE
53
- const FLOOR_NONE = 0, FLOOR_PLANE = 1, FLOOR_PROBE = 2
54
-
55
- let warned = false
56
- const supported = (): boolean => {
57
- if (DynamicBone.supported) return true
58
- if (!warned) { warned = true; console.warn("DynamicBone: this host has no dynamic bones (DynamicBone.supported is false) — the animation shows as is") }
59
- return false
60
- }
61
-
62
- const at = (c: DynamicBoneCurve, t: number): number => typeof c === "number" ? c : c[0] + (c[1] - c[0]) * t
63
-
64
- /** The model a bone belongs to: the topmost Model ancestor, else the topmost ancestor. */
65
- const modelOf = (n: Node): Node => {
66
- let top: Node = n, model: Node | null = null
67
- for (let p: Node | null = n; p; p = p.parent) { top = p; if (p instanceof Model) model = p }
68
- return model ?? top
69
- }
70
-
71
- /** A capsule (or a sphere) riding a bone — what dynamic bones stay out of. Attach to a body bone:
72
- * `hips.aspect(DynamicBoneCollider, { radius: 0.12, to: 'Spine' })`. The capsule runs from
73
- * `offset` (the bone's origin by default) to the `to` bone's origin, or to `end` (both in the bone's
74
- * local space); neither = a sphere at `offset`. Picked up by every DynamicBone on the same model
75
- * with `colliders: 'auto'` / `'humanoid'`, or listed explicitly. */
76
- export class DynamicBoneCollider extends Aspect<"dynamicBoneCollider", Node> {
77
- static readonly aspect = "dynamicBoneCollider"
78
-
79
- /** Radius in metres, in the world: the bone's scale does not touch it (`offset` / `end` are in the bone's own units). */
80
- radius = 0.1
81
- /** Start of the capsule in the bone's local space (default: the bone's origin). */
82
- offset: Vec3Like = [ 0, 0, 0 ]
83
- /** End of the capsule in the bone's local space (a sphere when neither `end` nor `to` is set). */
84
- end?: Vec3Like
85
- /** The bone the capsule reaches (its origin), instead of `end`. */
86
- to?: string
87
- /** ONE-SIDED: the cloth belongs on the chain's `side` of this capsule (see DynamicBone.side). While the capsule
88
- * moves away from that side it puts a bone it has run into over to the side instead of carrying it — an arm
89
- * under a cape may push the cape back, never drag it forward round the body. Needs a `side` on the DynamicBone. */
90
- oneSided = false
91
-
92
- static fields: FieldMeta<DynamicBoneCollider> = {
93
- radius: { min: 0, max: 2, step: 0.005 },
94
- offset: { hidden: true },
95
- end: { hidden: true },
96
- to: { hidden: true },
97
- oneSided: { label: "One-sided" },
98
- }
99
-
100
- private _id = 0
101
-
102
- /** @internal the engine's collider id (0 when the host has none). */
103
- get _colliderId(): number { return this._id }
104
-
105
- private _segment(): [Vec3, Vec3] {
106
- const a = new Vec3(this.offset)
107
- if (this.to) {
108
- const target = modelOf(this.node).bone(this.to)
109
- if (!target) throw new Error(`DynamicBoneCollider: no bone '${this.to}' (the 'to' of '${this.node.name}')`)
110
- const b = this.node.worldMatrix.invert().transformPoint(target.worldPosition)
111
- return [ a, b ]
112
- }
113
- return [ a, this.end ? new Vec3(this.end) : a ]
114
- }
115
-
116
- onAttach(): void {
117
- if (!supported()) return
118
- const [ a, b ] = this._segment()
119
- this._id = _creator.dynamicBoneColliderCreate!(this.node.id, a.x, a.y, a.z, b.x, b.y, b.z, this.radius, this.oneSided ? 1 : 0)
120
- DynamicBone._collidersChanged()
121
- }
122
-
123
- onReconfigure(): void {
124
- if (!this._id) return
125
- const [ a, b ] = this._segment()
126
- _creator.dynamicBoneColliderSet!(this._id, a.x, a.y, a.z, b.x, b.y, b.z, this.radius, this.oneSided ? 1 : 0)
127
- }
128
-
129
- onDetach(): void {
130
- if (this._id) { _creator.dynamicBoneColliderDestroy!(this._id); this._id = 0; DynamicBone._collidersChanged() }
131
- }
132
- }
133
-
134
- export class DynamicBone extends Aspect<"dynamicBone", Node> {
135
- static readonly aspect = "dynamicBone"
136
-
137
- /** Whether this host simulates dynamic bones. False, never a throw, on Web Lite and in headless
138
- * tests; there the aspect attaches, warns once, and `chain` stays empty. */
139
- static get supported(): boolean { return typeof _creator !== "undefined" && !!_creator && typeof _creator.dynamicBoneCreate === "function" }
140
-
141
- /** Only these bones (by name) join the chain — the root always does, a bone left out takes its
142
- * subtree with it. Default: the root's whole subtree. */
143
- bones?: string[]
144
- /** Depth limit under the root (0 = no limit). */
145
- depth = 0
146
- /** Particle radius for the collisions, metres. */
147
- radius: DynamicBoneCurve = 0.02
148
- /** 0..1 — how fast a bone returns to the animated shape (per 1/60 s). 0 = a rope, 1 = rigid. */
149
- stiffness: DynamicBoneCurve = 0.3
150
- /** 0..1 — velocity lost per 1/60 s. 0.02 swings like a rope, 0.1 settles like a tail, 0.3 is honey. */
151
- damping: DynamicBoneCurve = 0.1
152
- /** m/s² downward. A hanging rest pose feels none of it (the bone length cancels it); a pose that
153
- * sticks out droops by as much as `stiffness` lets it. */
154
- gravity: DynamicBoneCurve = 0
155
- /** Max deviation from the animated direction, degrees per bone (0 = free). */
156
- angleLimit: DynamicBoneCurve = 0
157
- /** Relative mass per bone. A bone-length constraint moves its two ends in inverse proportion to
158
- * their masses (the root is kinematic): `[3, 1]` makes a tail's base carry its tip, `1` shares
159
- * evenly like a rope. */
160
- mass: DynamicBoneCurve = 1
161
- /** Bones (by name) that ride the animation exactly while their subtrees still simulate: a sheet's
162
- * several roots under one anchor (a cloak's seven strips under the spine), so ONE chain owns them all
163
- * and `link` ties neighbouring strips — neighbours in THIS order, so list the strips round the ring
164
- * (front-left … back … front-right); the front stays open. */
165
- pinned?: string[]
166
- /** Metres a PINNED bone may be pushed off its animated place by a collider — a soft pin. Its particle
167
- * collides and takes the edge pushes like a free bone (the strip below hangs from where it IS) and is
168
- * drawn back to the animation when the collider leaves; the bone's local translation follows. A hard
169
- * pin (0) at a capsule's edge made the first free bone below it jitter: the edge push on a segment
170
- * with an immovable end is a lever, and a touch near the root threw the child out. 2–3 cm for a
171
- * cloak's roots under a shoulder capsule. */
172
- pinGive = 0
173
- /** 0..1 of the character's travel the chain takes rigidly (0 = the full whip on a dash, 1 = it
174
- * moves with the body and only the pose's own motion swings it). */
175
- follow = 0
176
- /** World wind, m/s². */
177
- wind: Vec3Like = [ 0, 0, 0 ]
178
- /** The BODY'S TURN, ≥ 0. Above 0 the chain lives in the parent bone's ROTATING frame: `damping` acts
179
- * against the body's rigid motion (its travel plus its spin), so a heavily damped cloak RIDES a turn —
180
- * sweeps round with the back — instead of standing in the world while the character spins under it and
181
- * being dragged round after. The turn's inertia comes back as the frame's forces, scaled by this value:
182
- * a centrifugal push `ω² · r` along each bone's animated direction from the axis (the hem, farthest
183
- * from the spine, flies out and, on the chain's length, up). The frame's own physics is built in: the
184
- * whip back when the turn starts and forward when it stops, Coriolis. 1 = the physical push; more = a
185
- * bigger fling. With low damping the frame reproduces a free particle (nothing is counted twice);
186
- * an animation's spine sway is ~1 % of a 900°/s turn. A rotation over 90° in one frame (a respawn
187
- * facing) counts as a snap, not a spin. 0 = the plain translational frame, no turn forces. */
188
- spin = 0
189
- /** With `spin`: the cloth's INERTIA against the body's turn, seconds — the cloth's own rotation follows the
190
- * body's with this time constant. It falls behind when a turn starts (by about ω·τ: 45° at 900°/s and 0.05),
191
- * rides once caught up, and keeps turning past the back when the body stops (the same angle, eased out over
192
- * τ). Smooth by construction. 0 = glued to the turn; large = the cloth stays in the world while the body spins. */
193
- spinInertia = 0
194
- /** 0..1 strength of the ties between neighbouring columns at the same depth (a cloak). */
195
- link = 0
196
- /** 0..1 blend from the animation (0) to the simulation (1). At 0 nothing is simulated and the
197
- * chain re-arms on the animated pose when it comes back. */
198
- weight = 1
199
- /** Substep rate, Hz (≤ 4 substeps per frame). */
200
- rate = 60
201
- /** A root jump longer than this in one frame (metres) resets the chain instead of whipping it. */
202
- teleport = 1
203
- /** What the particles stay above: `'none'`, `'probe'`, a height, or a world point. */
204
- floor: DynamicBoneFloor = "none"
205
- /** The floor plane's normal when `floor` is a point. */
206
- floorNormal: Vec3Like = [ 0, 1, 0 ]
207
- /** Friction against the floor, a Coulomb coefficient: a resting bone's slide loses up to
208
- * `floorFriction · gravity · dt` of speed per substep (0 = ice, 1 = a rubber sole). While a bone
209
- * rests on the floor or a collider, `stiffness` and `angleLimit` let go of it: the surface's
210
- * reaction outranks the spring, or a hem folded on the floor would run away along it. */
211
- floorFriction = 0.5
212
- /** Constraint passes per substep (1..8, default 4). Each pass shares every bone length between its
213
- * ends, so a pull needs passes to travel down a long chain: a long rope may want 8, a short tail is
214
- * fine with 2. */
215
- iterations = 4
216
- /** What the chain collides with (see DynamicBoneColliders). */
217
- colliders: DynamicBoneColliders = "auto"
218
- /** The cloth's outside — makes the colliders one-sided (see DynamicBoneSide). */
219
- side: DynamicBoneSide = "none"
220
- /** How firmly `guide()` targets are HELD through the constraint passes, 0..1. At 0 a guide is applied once
221
- * before the passes and the length / link passes may drag the bone back toward its un-guided neighbours
222
- * within the same frame; at 0.5 it is re-pulled after every pass with half its weight (converges with the
223
- * passes), at 1 with its full weight (a target the bone length cannot reach then jitters). */
224
- guideHold = 0
225
- /** The chain's EDGES collide with the capsules too — every bone segment and every link, not only the bones'
226
- * particles: a capsule thinner than a bone's length (a forearm) no longer passes through the cloth between
227
- * two bones. Off = particles only. */
228
- edges = true
229
-
230
- static fields: FieldMeta<DynamicBone> = {
231
- depth: { min: 0, max: 32, step: 1 },
232
- radius: { min: 0, max: 1, step: 0.005 },
233
- stiffness: { min: 0, max: 1, step: 0.01 },
234
- damping: { min: 0, max: 1, step: 0.01 },
235
- gravity: { min: 0, max: 30, step: 0.1 },
236
- angleLimit: { label: "Angle limit (°)", min: 0, max: 180, step: 1 },
237
- mass: { min: 0.1, max: 10, step: 0.1 },
238
- follow: { min: 0, max: 1, step: 0.01 },
239
- link: { min: 0, max: 1, step: 0.01 },
240
- weight: { min: 0, max: 1, step: 0.01 },
241
- rate: { min: 30, max: 240, step: 10 },
242
- teleport: { min: 0, max: 20, step: 0.1 },
243
- floorFriction: { label: "Floor friction", min: 0, max: 1, step: 0.01 },
244
- iterations: { min: 1, max: 8, step: 1 },
245
- bones: { hidden: true },
246
- pinned: { hidden: true },
247
- pinGive: { label: "Pin give (m)", min: 0, max: 0.2, step: 0.005 },
248
- wind: { hidden: true },
249
- spin: { min: 0, max: 4, step: 0.05 },
250
- spinInertia: { label: "Spin inertia (s)", min: 0, max: 0.3, step: 0.005 },
251
- floor: { hidden: true },
252
- floorNormal: { hidden: true },
253
- colliders: { hidden: true },
254
- side: { hidden: true },
255
- guideHold: { min: 0, max: 1, step: 0.05 },
256
- edges: { hidden: true },
257
- }
258
-
259
- private _id = 0
260
- private _chain: Node[] = []
261
- private _depths: number[] = []
262
- private _blob = new Float32Array(0)
263
- private _sent = new Float32Array(0)
264
- private _floorKey = ""
265
- private _colliderKey = ""
266
- private _collidersDirty = true
267
- private _collidersRef: DynamicBoneColliders | null = null
268
- private _own: number[] = [] // colliders generated for 'humanoid' (destroyed with the aspect)
269
- private _colliderSet: (Node | "auto" | "humanoid" | "none")[] | null = null
270
-
271
- /** The bones of the chain, the root first. */
272
- get chain(): readonly Node[] { return this._chain }
273
-
274
- onAttach(): void {
275
- if (!supported()) return
276
- this._collect()
277
- if (this._chain.length === 0) return
278
- const n = this._chain.length
279
- const bones = new Uint32Array(n)
280
- for (let i = 0; i < n; i++) bones[i] = this._chain[i]!.id
281
- this._blob = new Float32Array(HEADER + n * STRIDE)
282
- this._fill(this._blob)
283
- this._id = _creator.dynamicBoneCreate!(modelOf(this.node).id, bones, this._blob, this._links())
284
- if (!this._id) { console.warn(`DynamicBone: the host refused the chain under '${this.node.name}'`); return }
285
- this._sent = this._blob.slice()
286
- this._floorKey = ""; this._colliderKey = ""; this._collidersDirty = true
287
- this._pushFloor()
288
- this._pushColliders()
289
- }
290
-
291
- onReconfigure(): void { this._sync() }
292
-
293
- /** Every field is live: what changed since the last frame is pushed here, before the engine's stage. */
294
- update(): void { this._sync() }
295
-
296
- onDetach(): void {
297
- if (this._id) { _creator.dynamicBoneDestroy!(this._id); this._id = 0 }
298
- for (const id of this._own) _creator.dynamicBoneColliderDestroy!(id)
299
- this._own = []
300
- this._chain = []
301
- }
302
-
303
- /** Snap the chain onto the animated pose next frame (a teleport, a camera cut). */
304
- reset(): void { if (this._id) _creator.dynamicBoneReset!(this._id) }
305
-
306
- /** GUIDES: world points the bones' particles are drawn to each substep before the constraints —
307
- * weight 1 = there before them, the rest of the chain hangs, collides and links as before (a cape's
308
- * strips riding the arms). Replaces the previous set; an empty list clears. A late-phase script
309
- * (after the animator, before the engine's chain stage) refreshes it every frame. */
310
- guide(rows: readonly { bone: Node, at: Vec3Like, weight: number }[]): void {
311
- if (!this._id) return
312
- const out: number[] = []
313
- for (const r of rows) {
314
- const i = this._chain.indexOf(r.bone)
315
- if (i < 0) continue
316
- out.push(i, cx(r.at), cy(r.at), cz(r.at), r.weight)
317
- }
318
- _creator.dynamicBoneTargets?.(this._id, out.length ? new Float32Array(out) : null)
319
- }
320
-
321
- /** The particles' world positions (the bones, then the leaves' virtual tips) — for a debug draw. */
322
- get particles(): Vec3[] {
323
- if (!this._id) return []
324
- const out = new Float32Array((this._chain.length * 2) * 3)
325
- const n = _creator.dynamicBoneParticles!(this._id, out)
326
- const pts: Vec3[] = []
327
- for (let i = 0; i < n; i++) pts.push(new Vec3(out[i * 3]!, out[i * 3 + 1]!, out[i * 3 + 2]!))
328
- return pts
329
- }
330
-
331
- // ---- internals ----------------------------------------------------------------------------------
332
-
333
- private _collect(): void {
334
- const chain: Node[] = [], depths: number[] = []
335
- const only = this.bones ? new Set(this.bones) : null
336
- const walk = (n: Node, d: number): void => {
337
- chain.push(n); depths.push(d)
338
- if (this.depth > 0 && d >= this.depth) return
339
- for (const c of n.children) {
340
- if (only && !only.has(c.name)) continue
341
- if (c.has(DynamicBone) || c.has(DynamicBoneCollider)) continue // another chain / a body bone
342
- walk(c, d + 1)
343
- }
344
- }
345
- walk(this.node, 0)
346
- this._chain = chain; this._depths = depths
347
- }
348
-
349
- private _fill(b: Float32Array): void {
350
- const n = this._chain.length
351
- let maxDepth = 0
352
- for (const d of this._depths) if (d > maxDepth) maxDepth = d
353
- b[0] = VERSION; b[1] = n; b[2] = STRIDE
354
- b[3] = this.weight; b[4] = this.follow
355
- b[5] = cx(this.wind); b[6] = cy(this.wind); b[7] = cz(this.wind)
356
- b[8] = this.link; b[9] = this.rate; b[10] = this.teleport
357
- b[11] = 0; b[12] = 0; b[13] = 0; b[14] = 0; b[15] = 0; b[16] = 1; b[17] = 0 // the floor goes through setFloor
358
- b[18] = this.floorFriction
359
- b[19] = Math.max(1, Math.min(8, Math.round(this.iterations)))
360
- const side = this.side
361
- const sideVec = side === "none" || side === "auto" ? null : side
362
- b[20] = side === "none" ? 0 : side === "auto" ? 1 : 2
363
- b[21] = sideVec ? cx(sideVec) : 0; b[22] = sideVec ? cy(sideVec) : 0; b[23] = sideVec ? cz(sideVec) : 0
364
- b[24] = Math.max(0, Math.min(1, this.guideHold))
365
- b[25] = this.edges ? 1 : 0
366
- b[26] = Math.max(0, this.spin)
367
- b[27] = Math.max(0, this.spinInertia)
368
- const pin = this.pinned?.length ? new Set(this.pinned) : null
369
- for (let i = 0; i < n; i++) {
370
- const t = maxDepth > 0 ? this._depths[i]! / maxDepth : 0
371
- const o = HEADER + i * STRIDE
372
- b[o] = at(this.radius, t); b[o + 1] = at(this.stiffness, t); b[o + 2] = at(this.damping, t)
373
- b[o + 3] = at(this.gravity, t); b[o + 4] = at(this.angleLimit, t)
374
- const isPinned = !!pin && i > 0 && pin.has(this._chain[i]!.name)
375
- b[o + 5] = isPinned ? -1 : at(this.mass, t) // mass < 0 = pinned
376
- b[o + 6] = isPinned ? Math.max(0, this.pinGive) : 0
377
- }
378
- }
379
-
380
- /** Neighbour links: the bones at the same depth tied pairwise, the columns in the order of `pinned` (a cloak's
381
- * strips listed round the ring) — columns not listed there follow in tree order. Tree order alone is the
382
- * engine's child order, which for a GLB is the file's node order REVERSED (Filament prepends each child), so
383
- * strips added to a rig later were tied across the body instead of to their neighbours: the ermine's cloak
384
- * had one true neighbour pair out of eight, the rest were rods through the chest. */
385
- private _links(): Uint16Array | undefined {
386
- if (this.link <= 0) return undefined
387
- const index = new Map<Node, number>(this._chain.map((n, i) => [ n, i ]))
388
- const column = new Int32Array(this._chain.length).fill(-1) // per bone: the chain index of its depth-1 ancestor
389
- for (let i = 1; i < this._chain.length; i++) {
390
- const p = index.get(this._chain[i]!.parent!) ?? 0
391
- column[i] = this._depths[i] === 1 ? i : column[p]!
392
- }
393
- const ring = this.pinned ?? []
394
- const key = (i: number): number => { const k = ring.indexOf(this._chain[column[i]!]!.name); return k < 0 ? ring.length + column[i]! : k }
395
- const byDepth = new Map<number, number[]>()
396
- this._depths.forEach((d, i) => { if (d > 0) (byDepth.get(d) ?? byDepth.set(d, []).get(d)!).push(i) })
397
- const pairs: number[] = []
398
- for (const row of byDepth.values()) {
399
- row.sort((a, b) => key(a) - key(b))
400
- for (let k = 0; k + 1 < row.length; k++) pairs.push(row[k]!, row[k + 1]!)
401
- }
402
- return pairs.length ? new Uint16Array(pairs) : undefined
403
- }
404
-
405
- private _sync(): void {
406
- if (!this._id) return
407
- this._fill(this._blob)
408
- let changed = false
409
- for (let i = 0; i < this._blob.length; i++) if (this._blob[i] !== this._sent[i]) { changed = true; break }
410
- if (changed) { _creator.dynamicBoneSet!(this._id, this._blob); this._sent.set(this._blob) }
411
- this._pushFloor()
412
- this._pushColliders()
413
- }
414
-
415
- private _pushFloor(): void {
416
- const f = this.floor
417
- let key: string, mode: 0 | 1 | 2 = FLOOR_NONE, x = 0, y = 0, z = 0, nx = 0, ny = 1, nz = 0
418
- if (f === "probe") { mode = FLOOR_PROBE; key = "probe" }
419
- else if (f === "none" || f === undefined || f === null) { key = "none" }
420
- else if (typeof f === "number") { mode = FLOOR_PLANE; y = f; key = `y${f}` }
421
- else {
422
- mode = FLOOR_PLANE; x = cx(f); y = cy(f); z = cz(f)
423
- nx = cx(this.floorNormal); ny = cy(this.floorNormal); nz = cz(this.floorNormal)
424
- key = `p${x},${y},${z},${nx},${ny},${nz}`
425
- }
426
- if (key === this._floorKey) return
427
- this._floorKey = key
428
- _creator.dynamicBoneSetFloor!(this._id, mode, x, y, z, nx, ny, nz)
429
- }
430
-
431
- private _pushColliders(): void {
432
- // re-listed only when a collider came or went, or the field was reassigned (per frame otherwise)
433
- if (!this._collidersDirty && this._collidersRef === this.colliders) return
434
- this._collidersDirty = false
435
- this._collidersRef = this.colliders
436
- const ids: number[] = []
437
- const model = modelOf(this.node)
438
- const c = this.colliders
439
- if (c === "auto" || c === "humanoid") {
440
- for (const col of Aspect.all(DynamicBoneCollider)) if (col._colliderId && modelOf(col.node) === model) ids.push(col._colliderId)
441
- if (c === "humanoid") { if (this._own.length === 0) this._makeHumanoid(model); ids.push(...this._own) }
442
- } else if (Array.isArray(c)) {
443
- for (const n of c) {
444
- const col = n.get(DynamicBoneCollider)
445
- if (col?._colliderId) ids.push(col._colliderId)
446
- }
447
- }
448
- const key = ids.join(",")
449
- if (key === this._colliderKey) return
450
- this._colliderKey = key
451
- _creator.dynamicBoneSetColliders!(this._id, new Uint32Array(ids))
452
- }
453
-
454
- /** Capsules on the standard humanoid bones, sized like the Ragdoll's parts. */
455
- private _makeHumanoid(model: Node): void {
456
- const find = (role: string): string | null => {
457
- for (const name of HUMANOID[role] ?? []) if (model.bone(name)) return name
458
- return null
459
- }
460
- let parts: ReturnType<typeof humanoidParts>
461
- try { parts = humanoidParts(find) } catch { return } // no hips: not a humanoid, nothing generated
462
- for (const p of parts) {
463
- const bone = model.bone(p.bone)
464
- if (!bone) continue
465
- const inv = bone.worldMatrix.invert()
466
- let end: Vec3
467
- const to = p.to ? model.bone(p.to) : null
468
- if (to) end = inv.transformPoint(to.worldPosition)
469
- else {
470
- // a leaf: along the line from the parent part's origin through this bone
471
- const parentBone = p.parent ? model.bone(p.parent) : null
472
- const dir = parentBone ? bone.worldPosition.sub(parentBone.worldPosition) : new Vec3(0, 1, 0)
473
- const local = inv.transformDirection(dir)
474
- const len = local.length()
475
- end = len > 1e-6 ? local.scale((p.length ?? 0.2) / len) : new Vec3(0, p.length ?? 0.2, 0)
476
- }
477
- const id = _creator.dynamicBoneColliderCreate!(bone.id, 0, 0, 0, end.x, end.y, end.z, p.radius ?? 0.05, 0)
478
- if (id) this._own.push(id)
479
- }
480
- }
481
-
482
- /** @internal a collider attached / detached: every chain that collects them re-lists. */
483
- static _collidersChanged(): void {
484
- for (const d of Aspect.all(DynamicBone)) if (d._id && (d.colliders === "auto" || d.colliders === "humanoid")) { d._collidersDirty = true; d._pushColliders() }
485
- }
486
- }
1
+ // DynamicBone — secondary motion for tails, ears, hair, ropes and cloaks, simulated in the engine.
2
+ // Attach to the ROOT bone of a chain; the bone's whole subtree becomes Verlet particle chains that
3
+ // swing, lag and settle under gravity, wind and the character's motion, pulled back toward the pose
4
+ // the animation gives them, kept out of the body by capsule colliders and above the floor.
5
+ //
6
+ // const tail = fox.bone('tail')!
7
+ // tail.aspect(DynamicBone, { stiffness: [0.6, 0.15], damping: 0.15, gravity: 2, angleLimit: 50 })
8
+ // fox.bone('earend')!.aspect(DynamicBone, { stiffness: 0.8, angleLimit: 25 })
9
+ // fox.bone('Hips')!.aspect(DynamicBoneCollider, { radius: 0.12, to: 'chest' }) // a capsule the tail can't enter
10
+ // tail.dynamicBone.weight = cutscene ? 0 : 1 // blend to the animation
11
+ // tail.dynamicBone.floor = hit.point // the ground under it
12
+ // tail.dynamicBone.reset() // after a teleport
13
+ //
14
+ // Per-bone values (`radius`, `stiffness`, `damping`, `gravity`, `angleLimit`) take one number for the
15
+ // whole chain or a `[root, tip]` pair interpolated down the chain — a tail is stiff at the base and
16
+ // loose at the tip. A cloak is one aspect on the common parent of its columns with `link` > 0: the
17
+ // bones at the same depth of neighbouring columns are tied at their rest distance.
18
+ //
19
+ // The simulation runs natively in a stage of its own after the late phase and before the skin flush
20
+ // (docs/parity: gl-dynamic-bones): the animator, an active ragdoll and late-phase aspects (IK) are
21
+ // its input; every field of this aspect is live — the values are pushed when they change.
22
+
23
+ import { Aspect } from "../../core/Aspect"
24
+ import type { FieldMeta } from "../../core/fields"
25
+ import { Vec3, cx, cy, cz, type Vec3Like } from "../../math/vec"
26
+ import { Node } from "../Node"
27
+ import { Model } from "../Model"
28
+ import { HUMANOID, humanoidParts } from "../physics/Ragdoll"
29
+
30
+ /** One value for the chain, or `[root, tip]` interpolated down it by depth. */
31
+ export type DynamicBoneCurve = number | readonly [root: number, tip: number]
32
+ /** `'none'`, `'probe'` (a ray from the chain root down against the physics world, every frame), a
33
+ * height (a horizontal plane at that world y) or a world point (a plane through it, `floorNormal` up). */
34
+ export type DynamicBoneFloor = "none" | "probe" | number | Vec3Like
35
+ /** `'auto'` = every DynamicBoneCollider under the model; `'humanoid'` = those plus capsules generated
36
+ * on the standard humanoid bones (hips, spine, head, limbs — the Ragdoll's layout); `'none'`; or the
37
+ * nodes carrying the colliders to use. */
38
+ export type DynamicBoneColliders = "auto" | "humanoid" | "none" | Node[]
39
+ /** The cloth's SIDE of every collider marked `oneSided`: `'none'` = no side, every collider pushes a bone to
40
+ * its nearest surface (tails, ropes); `'auto'` = away from the root bone's own axis (a cloak's strips round
41
+ * a spine face out from it); a vector = a fixed direction in the root bone's frame (a cape hanging BEHIND
42
+ * the arms: the body's backward). A one-sided collider that is moving AWAY from that side — an arm swinging
43
+ * forward under the cape — puts a bone it has run into over to the side instead of carrying it: the arm
44
+ * passes through the cloth and the cape hangs behind it again, instead of being dragged round the body.
45
+ * Still, or moving toward the cloth, it pushes like any other collider, so cloth draped on an arm at rest
46
+ * stays where it is. Two-sided colliders (the body's) never read the side. */
47
+ export type DynamicBoneSide = "none" | "auto" | Vec3Like
48
+
49
+ const VERSION = 1
50
+ const PARAMS = 25 // CANIM_DYN_COUNT
51
+ const HEADER = 3 + PARAMS
52
+ const STRIDE = 7 // CANIM_DYN_BONE_STRIDE
53
+ const FLOOR_NONE = 0, FLOOR_PLANE = 1, FLOOR_PROBE = 2
54
+
55
+ let warned = false
56
+ const supported = (): boolean => {
57
+ if (DynamicBone.supported) return true
58
+ if (!warned) { warned = true; console.warn("DynamicBone: this host has no dynamic bones (DynamicBone.supported is false) — the animation shows as is") }
59
+ return false
60
+ }
61
+
62
+ const at = (c: DynamicBoneCurve, t: number): number => typeof c === "number" ? c : c[0] + (c[1] - c[0]) * t
63
+
64
+ /** The model a bone belongs to: the topmost Model ancestor, else the topmost ancestor. */
65
+ const modelOf = (n: Node): Node => {
66
+ let top: Node = n, model: Node | null = null
67
+ for (let p: Node | null = n; p; p = p.parent) { top = p; if (p instanceof Model) model = p }
68
+ return model ?? top
69
+ }
70
+
71
+ /** A capsule (or a sphere) riding a bone — what dynamic bones stay out of. Attach to a body bone:
72
+ * `hips.aspect(DynamicBoneCollider, { radius: 0.12, to: 'Spine' })`. The capsule runs from
73
+ * `offset` (the bone's origin by default) to the `to` bone's origin, or to `end` (both in the bone's
74
+ * local space); neither = a sphere at `offset`. Picked up by every DynamicBone on the same model
75
+ * with `colliders: 'auto'` / `'humanoid'`, or listed explicitly. */
76
+ export class DynamicBoneCollider extends Aspect<"dynamicBoneCollider", Node> {
77
+ static readonly aspect = "dynamicBoneCollider"
78
+
79
+ /** Radius in metres, in the world: the bone's scale does not touch it (`offset` / `end` are in the bone's own units). */
80
+ radius = 0.1
81
+ /** Start of the capsule in the bone's local space (default: the bone's origin). */
82
+ offset: Vec3Like = [ 0, 0, 0 ]
83
+ /** End of the capsule in the bone's local space (a sphere when neither `end` nor `to` is set). */
84
+ end?: Vec3Like
85
+ /** The bone the capsule reaches (its origin), instead of `end`. */
86
+ to?: string
87
+ /** ONE-SIDED: the cloth belongs on the chain's `side` of this capsule (see DynamicBone.side). While the capsule
88
+ * moves away from that side it puts a bone it has run into over to the side instead of carrying it — an arm
89
+ * under a cape may push the cape back, never drag it forward round the body. Needs a `side` on the DynamicBone. */
90
+ oneSided = false
91
+
92
+ static fields: FieldMeta<DynamicBoneCollider> = {
93
+ radius: { min: 0, max: 2, step: 0.005 },
94
+ offset: { hidden: true },
95
+ end: { hidden: true },
96
+ to: { hidden: true },
97
+ oneSided: { label: "One-sided" },
98
+ }
99
+
100
+ private _id = 0
101
+
102
+ /** @internal the engine's collider id (0 when the host has none). */
103
+ get _colliderId(): number { return this._id }
104
+
105
+ private _segment(): [Vec3, Vec3] {
106
+ const a = new Vec3(this.offset)
107
+ if (this.to) {
108
+ const target = modelOf(this.node).bone(this.to)
109
+ if (!target) throw new Error(`DynamicBoneCollider: no bone '${this.to}' (the 'to' of '${this.node.name}')`)
110
+ const b = this.node.worldMatrix.invert().transformPoint(target.worldPosition)
111
+ return [ a, b ]
112
+ }
113
+ return [ a, this.end ? new Vec3(this.end) : a ]
114
+ }
115
+
116
+ onAttach(): void {
117
+ if (!supported()) return
118
+ const [ a, b ] = this._segment()
119
+ this._id = _creator.dynamicBoneColliderCreate!(this.node.id, a.x, a.y, a.z, b.x, b.y, b.z, this.radius, this.oneSided ? 1 : 0)
120
+ DynamicBone._collidersChanged()
121
+ }
122
+
123
+ onReconfigure(): void {
124
+ if (!this._id) return
125
+ const [ a, b ] = this._segment()
126
+ _creator.dynamicBoneColliderSet!(this._id, a.x, a.y, a.z, b.x, b.y, b.z, this.radius, this.oneSided ? 1 : 0)
127
+ }
128
+
129
+ onDetach(): void {
130
+ if (this._id) { _creator.dynamicBoneColliderDestroy!(this._id); this._id = 0; DynamicBone._collidersChanged() }
131
+ }
132
+ }
133
+
134
+ export class DynamicBone extends Aspect<"dynamicBone", Node> {
135
+ static readonly aspect = "dynamicBone"
136
+
137
+ /** Whether this host simulates dynamic bones. False, never a throw, on Web Lite and in headless
138
+ * tests; there the aspect attaches, warns once, and `chain` stays empty. */
139
+ static get supported(): boolean { return typeof _creator !== "undefined" && !!_creator && typeof _creator.dynamicBoneCreate === "function" }
140
+
141
+ /** Only these bones (by name) join the chain — the root always does, a bone left out takes its
142
+ * subtree with it. Default: the root's whole subtree. */
143
+ bones?: string[]
144
+ /** Depth limit under the root (0 = no limit). */
145
+ depth = 0
146
+ /** Particle radius for the collisions, metres. */
147
+ radius: DynamicBoneCurve = 0.02
148
+ /** 0..1 — how fast a bone returns to the animated shape (per 1/60 s). 0 = a rope, 1 = rigid. */
149
+ stiffness: DynamicBoneCurve = 0.3
150
+ /** 0..1 — velocity lost per 1/60 s. 0.02 swings like a rope, 0.1 settles like a tail, 0.3 is honey. */
151
+ damping: DynamicBoneCurve = 0.1
152
+ /** m/s² downward. A hanging rest pose feels none of it (the bone length cancels it); a pose that
153
+ * sticks out droops by as much as `stiffness` lets it. */
154
+ gravity: DynamicBoneCurve = 0
155
+ /** Max deviation from the animated direction, degrees per bone (0 = free). */
156
+ angleLimit: DynamicBoneCurve = 0
157
+ /** Relative mass per bone. A bone-length constraint moves its two ends in inverse proportion to
158
+ * their masses (the root is kinematic): `[3, 1]` makes a tail's base carry its tip, `1` shares
159
+ * evenly like a rope. */
160
+ mass: DynamicBoneCurve = 1
161
+ /** Bones (by name) that ride the animation exactly while their subtrees still simulate: a sheet's
162
+ * several roots under one anchor (a cloak's seven strips under the spine), so ONE chain owns them all
163
+ * and `link` ties neighbouring strips — neighbours in THIS order, so list the strips round the ring
164
+ * (front-left … back … front-right); the front stays open. */
165
+ pinned?: string[]
166
+ /** Metres a PINNED bone may be pushed off its animated place by a collider — a soft pin. Its particle
167
+ * collides and takes the edge pushes like a free bone (the strip below hangs from where it IS) and is
168
+ * drawn back to the animation when the collider leaves; the bone's local translation follows. A hard
169
+ * pin (0) at a capsule's edge made the first free bone below it jitter: the edge push on a segment
170
+ * with an immovable end is a lever, and a touch near the root threw the child out. 2–3 cm for a
171
+ * cloak's roots under a shoulder capsule. */
172
+ pinGive = 0
173
+ /** 0..1 of the character's travel the chain takes rigidly (0 = the full whip on a dash, 1 = it
174
+ * moves with the body and only the pose's own motion swings it). */
175
+ follow = 0
176
+ /** World wind, m/s². */
177
+ wind: Vec3Like = [ 0, 0, 0 ]
178
+ /** The BODY'S TURN, ≥ 0. Above 0 the chain lives in the parent bone's ROTATING frame: `damping` acts
179
+ * against the body's rigid motion (its travel plus its spin), so a heavily damped cloak RIDES a turn —
180
+ * sweeps round with the back — instead of standing in the world while the character spins under it and
181
+ * being dragged round after. The turn's inertia comes back as the frame's forces, scaled by this value:
182
+ * a centrifugal push `ω² · r` along each bone's animated direction from the axis (the hem, farthest
183
+ * from the spine, flies out and, on the chain's length, up). The frame's own physics is built in: the
184
+ * whip back when the turn starts and forward when it stops, Coriolis. 1 = the physical push; more = a
185
+ * bigger fling. With low damping the frame reproduces a free particle (nothing is counted twice);
186
+ * an animation's spine sway is ~1 % of a 900°/s turn. A rotation over 90° in one frame (a respawn
187
+ * facing) counts as a snap, not a spin. 0 = the plain translational frame, no turn forces. */
188
+ spin = 0
189
+ /** With `spin`: the cloth's INERTIA against the body's turn, seconds — the cloth's own rotation follows the
190
+ * body's with this time constant. It falls behind when a turn starts (by about ω·τ: 45° at 900°/s and 0.05),
191
+ * rides once caught up, and keeps turning past the back when the body stops (the same angle, eased out over
192
+ * τ). Smooth by construction. 0 = glued to the turn; large = the cloth stays in the world while the body spins. */
193
+ spinInertia = 0
194
+ /** 0..1 strength of the ties between neighbouring columns at the same depth (a cloak). */
195
+ link = 0
196
+ /** 0..1 blend from the animation (0) to the simulation (1). At 0 nothing is simulated and the
197
+ * chain re-arms on the animated pose when it comes back. */
198
+ weight = 1
199
+ /** Substep rate, Hz (≤ 4 substeps per frame). */
200
+ rate = 60
201
+ /** A root jump longer than this in one frame (metres) resets the chain instead of whipping it. */
202
+ teleport = 1
203
+ /** What the particles stay above: `'none'`, `'probe'`, a height, or a world point. */
204
+ floor: DynamicBoneFloor = "none"
205
+ /** The floor plane's normal when `floor` is a point. */
206
+ floorNormal: Vec3Like = [ 0, 1, 0 ]
207
+ /** Friction against the floor, a Coulomb coefficient: a resting bone's slide loses up to
208
+ * `floorFriction · gravity · dt` of speed per substep (0 = ice, 1 = a rubber sole). While a bone
209
+ * rests on the floor or a collider, `stiffness` and `angleLimit` let go of it: the surface's
210
+ * reaction outranks the spring, or a hem folded on the floor would run away along it. */
211
+ floorFriction = 0.5
212
+ /** Constraint passes per substep (1..8, default 4). Each pass shares every bone length between its
213
+ * ends, so a pull needs passes to travel down a long chain: a long rope may want 8, a short tail is
214
+ * fine with 2. */
215
+ iterations = 4
216
+ /** What the chain collides with (see DynamicBoneColliders). */
217
+ colliders: DynamicBoneColliders = "auto"
218
+ /** The cloth's outside — makes the colliders one-sided (see DynamicBoneSide). */
219
+ side: DynamicBoneSide = "none"
220
+ /** How firmly `guide()` targets are HELD through the constraint passes, 0..1. At 0 a guide is applied once
221
+ * before the passes and the length / link passes may drag the bone back toward its un-guided neighbours
222
+ * within the same frame; at 0.5 it is re-pulled after every pass with half its weight (converges with the
223
+ * passes), at 1 with its full weight (a target the bone length cannot reach then jitters). */
224
+ guideHold = 0
225
+ /** The chain's EDGES collide with the capsules too — every bone segment and every link, not only the bones'
226
+ * particles: a capsule thinner than a bone's length (a forearm) no longer passes through the cloth between
227
+ * two bones. Off = particles only. */
228
+ edges = true
229
+
230
+ static fields: FieldMeta<DynamicBone> = {
231
+ depth: { min: 0, max: 32, step: 1 },
232
+ radius: { min: 0, max: 1, step: 0.005 },
233
+ stiffness: { min: 0, max: 1, step: 0.01 },
234
+ damping: { min: 0, max: 1, step: 0.01 },
235
+ gravity: { min: 0, max: 30, step: 0.1 },
236
+ angleLimit: { label: "Angle limit (°)", min: 0, max: 180, step: 1 },
237
+ mass: { min: 0.1, max: 10, step: 0.1 },
238
+ follow: { min: 0, max: 1, step: 0.01 },
239
+ link: { min: 0, max: 1, step: 0.01 },
240
+ weight: { min: 0, max: 1, step: 0.01 },
241
+ rate: { min: 30, max: 240, step: 10 },
242
+ teleport: { min: 0, max: 20, step: 0.1 },
243
+ floorFriction: { label: "Floor friction", min: 0, max: 1, step: 0.01 },
244
+ iterations: { min: 1, max: 8, step: 1 },
245
+ bones: { hidden: true },
246
+ pinned: { hidden: true },
247
+ pinGive: { label: "Pin give (m)", min: 0, max: 0.2, step: 0.005 },
248
+ wind: { hidden: true },
249
+ spin: { min: 0, max: 4, step: 0.05 },
250
+ spinInertia: { label: "Spin inertia (s)", min: 0, max: 0.3, step: 0.005 },
251
+ floor: { hidden: true },
252
+ floorNormal: { hidden: true },
253
+ colliders: { hidden: true },
254
+ side: { hidden: true },
255
+ guideHold: { min: 0, max: 1, step: 0.05 },
256
+ edges: { hidden: true },
257
+ }
258
+
259
+ private _id = 0
260
+ private _chain: Node[] = []
261
+ private _depths: number[] = []
262
+ private _blob = new Float32Array(0)
263
+ private _sent = new Float32Array(0)
264
+ private _floorKey = ""
265
+ private _colliderKey = ""
266
+ private _collidersDirty = true
267
+ private _collidersRef: DynamicBoneColliders | null = null
268
+ private _own: number[] = [] // colliders generated for 'humanoid' (destroyed with the aspect)
269
+ private _colliderSet: (Node | "auto" | "humanoid" | "none")[] | null = null
270
+
271
+ /** The bones of the chain, the root first. */
272
+ get chain(): readonly Node[] { return this._chain }
273
+
274
+ onAttach(): void {
275
+ if (!supported()) return
276
+ this._collect()
277
+ if (this._chain.length === 0) return
278
+ const n = this._chain.length
279
+ const bones = new Uint32Array(n)
280
+ for (let i = 0; i < n; i++) bones[i] = this._chain[i]!.id
281
+ this._blob = new Float32Array(HEADER + n * STRIDE)
282
+ this._fill(this._blob)
283
+ this._id = _creator.dynamicBoneCreate!(modelOf(this.node).id, bones, this._blob, this._links())
284
+ if (!this._id) { console.warn(`DynamicBone: the host refused the chain under '${this.node.name}'`); return }
285
+ this._sent = this._blob.slice()
286
+ this._floorKey = ""; this._colliderKey = ""; this._collidersDirty = true
287
+ this._pushFloor()
288
+ this._pushColliders()
289
+ }
290
+
291
+ onReconfigure(): void { this._sync() }
292
+
293
+ /** Every field is live: what changed since the last frame is pushed here, before the engine's stage. */
294
+ update(): void { this._sync() }
295
+
296
+ onDetach(): void {
297
+ if (this._id) { _creator.dynamicBoneDestroy!(this._id); this._id = 0 }
298
+ for (const id of this._own) _creator.dynamicBoneColliderDestroy!(id)
299
+ this._own = []
300
+ this._chain = []
301
+ }
302
+
303
+ /** Snap the chain onto the animated pose next frame (a teleport, a camera cut). */
304
+ reset(): void { if (this._id) _creator.dynamicBoneReset!(this._id) }
305
+
306
+ /** GUIDES: world points the bones' particles are drawn to each substep before the constraints —
307
+ * weight 1 = there before them, the rest of the chain hangs, collides and links as before (a cape's
308
+ * strips riding the arms). Replaces the previous set; an empty list clears. A late-phase script
309
+ * (after the animator, before the engine's chain stage) refreshes it every frame. */
310
+ guide(rows: readonly { bone: Node, at: Vec3Like, weight: number }[]): void {
311
+ if (!this._id) return
312
+ const out: number[] = []
313
+ for (const r of rows) {
314
+ const i = this._chain.indexOf(r.bone)
315
+ if (i < 0) continue
316
+ out.push(i, cx(r.at), cy(r.at), cz(r.at), r.weight)
317
+ }
318
+ _creator.dynamicBoneTargets?.(this._id, out.length ? new Float32Array(out) : null)
319
+ }
320
+
321
+ /** The particles' world positions (the bones, then the leaves' virtual tips) — for a debug draw. */
322
+ get particles(): Vec3[] {
323
+ if (!this._id) return []
324
+ const out = new Float32Array((this._chain.length * 2) * 3)
325
+ const n = _creator.dynamicBoneParticles!(this._id, out)
326
+ const pts: Vec3[] = []
327
+ for (let i = 0; i < n; i++) pts.push(new Vec3(out[i * 3]!, out[i * 3 + 1]!, out[i * 3 + 2]!))
328
+ return pts
329
+ }
330
+
331
+ // ---- internals ----------------------------------------------------------------------------------
332
+
333
+ private _collect(): void {
334
+ const chain: Node[] = [], depths: number[] = []
335
+ const only = this.bones ? new Set(this.bones) : null
336
+ const walk = (n: Node, d: number): void => {
337
+ chain.push(n); depths.push(d)
338
+ if (this.depth > 0 && d >= this.depth) return
339
+ for (const c of n.children) {
340
+ if (only && !only.has(c.name)) continue
341
+ if (c.has(DynamicBone) || c.has(DynamicBoneCollider)) continue // another chain / a body bone
342
+ walk(c, d + 1)
343
+ }
344
+ }
345
+ walk(this.node, 0)
346
+ this._chain = chain; this._depths = depths
347
+ }
348
+
349
+ private _fill(b: Float32Array): void {
350
+ const n = this._chain.length
351
+ let maxDepth = 0
352
+ for (const d of this._depths) if (d > maxDepth) maxDepth = d
353
+ b[0] = VERSION; b[1] = n; b[2] = STRIDE
354
+ b[3] = this.weight; b[4] = this.follow
355
+ b[5] = cx(this.wind); b[6] = cy(this.wind); b[7] = cz(this.wind)
356
+ b[8] = this.link; b[9] = this.rate; b[10] = this.teleport
357
+ b[11] = 0; b[12] = 0; b[13] = 0; b[14] = 0; b[15] = 0; b[16] = 1; b[17] = 0 // the floor goes through setFloor
358
+ b[18] = this.floorFriction
359
+ b[19] = Math.max(1, Math.min(8, Math.round(this.iterations)))
360
+ const side = this.side
361
+ const sideVec = side === "none" || side === "auto" ? null : side
362
+ b[20] = side === "none" ? 0 : side === "auto" ? 1 : 2
363
+ b[21] = sideVec ? cx(sideVec) : 0; b[22] = sideVec ? cy(sideVec) : 0; b[23] = sideVec ? cz(sideVec) : 0
364
+ b[24] = Math.max(0, Math.min(1, this.guideHold))
365
+ b[25] = this.edges ? 1 : 0
366
+ b[26] = Math.max(0, this.spin)
367
+ b[27] = Math.max(0, this.spinInertia)
368
+ const pin = this.pinned?.length ? new Set(this.pinned) : null
369
+ for (let i = 0; i < n; i++) {
370
+ const t = maxDepth > 0 ? this._depths[i]! / maxDepth : 0
371
+ const o = HEADER + i * STRIDE
372
+ b[o] = at(this.radius, t); b[o + 1] = at(this.stiffness, t); b[o + 2] = at(this.damping, t)
373
+ b[o + 3] = at(this.gravity, t); b[o + 4] = at(this.angleLimit, t)
374
+ const isPinned = !!pin && i > 0 && pin.has(this._chain[i]!.name)
375
+ b[o + 5] = isPinned ? -1 : at(this.mass, t) // mass < 0 = pinned
376
+ b[o + 6] = isPinned ? Math.max(0, this.pinGive) : 0
377
+ }
378
+ }
379
+
380
+ /** Neighbour links: the bones at the same depth tied pairwise, the columns in the order of `pinned` (a cloak's
381
+ * strips listed round the ring) — columns not listed there follow in tree order. Tree order alone is the
382
+ * engine's child order, which for a GLB is the file's node order REVERSED (Filament prepends each child), so
383
+ * strips added to a rig later were tied across the body instead of to their neighbours: the ermine's cloak
384
+ * had one true neighbour pair out of eight, the rest were rods through the chest. */
385
+ private _links(): Uint16Array | undefined {
386
+ if (this.link <= 0) return undefined
387
+ const index = new Map<Node, number>(this._chain.map((n, i) => [ n, i ]))
388
+ const column = new Int32Array(this._chain.length).fill(-1) // per bone: the chain index of its depth-1 ancestor
389
+ for (let i = 1; i < this._chain.length; i++) {
390
+ const p = index.get(this._chain[i]!.parent!) ?? 0
391
+ column[i] = this._depths[i] === 1 ? i : column[p]!
392
+ }
393
+ const ring = this.pinned ?? []
394
+ const key = (i: number): number => { const k = ring.indexOf(this._chain[column[i]!]!.name); return k < 0 ? ring.length + column[i]! : k }
395
+ const byDepth = new Map<number, number[]>()
396
+ this._depths.forEach((d, i) => { if (d > 0) (byDepth.get(d) ?? byDepth.set(d, []).get(d)!).push(i) })
397
+ const pairs: number[] = []
398
+ for (const row of byDepth.values()) {
399
+ row.sort((a, b) => key(a) - key(b))
400
+ for (let k = 0; k + 1 < row.length; k++) pairs.push(row[k]!, row[k + 1]!)
401
+ }
402
+ return pairs.length ? new Uint16Array(pairs) : undefined
403
+ }
404
+
405
+ private _sync(): void {
406
+ if (!this._id) return
407
+ this._fill(this._blob)
408
+ let changed = false
409
+ for (let i = 0; i < this._blob.length; i++) if (this._blob[i] !== this._sent[i]) { changed = true; break }
410
+ if (changed) { _creator.dynamicBoneSet!(this._id, this._blob); this._sent.set(this._blob) }
411
+ this._pushFloor()
412
+ this._pushColliders()
413
+ }
414
+
415
+ private _pushFloor(): void {
416
+ const f = this.floor
417
+ let key: string, mode: 0 | 1 | 2 = FLOOR_NONE, x = 0, y = 0, z = 0, nx = 0, ny = 1, nz = 0
418
+ if (f === "probe") { mode = FLOOR_PROBE; key = "probe" }
419
+ else if (f === "none" || f === undefined || f === null) { key = "none" }
420
+ else if (typeof f === "number") { mode = FLOOR_PLANE; y = f; key = `y${f}` }
421
+ else {
422
+ mode = FLOOR_PLANE; x = cx(f); y = cy(f); z = cz(f)
423
+ nx = cx(this.floorNormal); ny = cy(this.floorNormal); nz = cz(this.floorNormal)
424
+ key = `p${x},${y},${z},${nx},${ny},${nz}`
425
+ }
426
+ if (key === this._floorKey) return
427
+ this._floorKey = key
428
+ _creator.dynamicBoneSetFloor!(this._id, mode, x, y, z, nx, ny, nz)
429
+ }
430
+
431
+ private _pushColliders(): void {
432
+ // re-listed only when a collider came or went, or the field was reassigned (per frame otherwise)
433
+ if (!this._collidersDirty && this._collidersRef === this.colliders) return
434
+ this._collidersDirty = false
435
+ this._collidersRef = this.colliders
436
+ const ids: number[] = []
437
+ const model = modelOf(this.node)
438
+ const c = this.colliders
439
+ if (c === "auto" || c === "humanoid") {
440
+ for (const col of Aspect.all(DynamicBoneCollider)) if (col._colliderId && modelOf(col.node) === model) ids.push(col._colliderId)
441
+ if (c === "humanoid") { if (this._own.length === 0) this._makeHumanoid(model); ids.push(...this._own) }
442
+ } else if (Array.isArray(c)) {
443
+ for (const n of c) {
444
+ const col = n.get(DynamicBoneCollider)
445
+ if (col?._colliderId) ids.push(col._colliderId)
446
+ }
447
+ }
448
+ const key = ids.join(",")
449
+ if (key === this._colliderKey) return
450
+ this._colliderKey = key
451
+ _creator.dynamicBoneSetColliders!(this._id, new Uint32Array(ids))
452
+ }
453
+
454
+ /** Capsules on the standard humanoid bones, sized like the Ragdoll's parts. */
455
+ private _makeHumanoid(model: Node): void {
456
+ const find = (role: string): string | null => {
457
+ for (const name of HUMANOID[role] ?? []) if (model.bone(name)) return name
458
+ return null
459
+ }
460
+ let parts: ReturnType<typeof humanoidParts>
461
+ try { parts = humanoidParts(find) } catch { return } // no hips: not a humanoid, nothing generated
462
+ for (const p of parts) {
463
+ const bone = model.bone(p.bone)
464
+ if (!bone) continue
465
+ const inv = bone.worldMatrix.invert()
466
+ let end: Vec3
467
+ const to = p.to ? model.bone(p.to) : null
468
+ if (to) end = inv.transformPoint(to.worldPosition)
469
+ else {
470
+ // a leaf: along the line from the parent part's origin through this bone
471
+ const parentBone = p.parent ? model.bone(p.parent) : null
472
+ const dir = parentBone ? bone.worldPosition.sub(parentBone.worldPosition) : new Vec3(0, 1, 0)
473
+ const local = inv.transformDirection(dir)
474
+ const len = local.length()
475
+ end = len > 1e-6 ? local.scale((p.length ?? 0.2) / len) : new Vec3(0, p.length ?? 0.2, 0)
476
+ }
477
+ const id = _creator.dynamicBoneColliderCreate!(bone.id, 0, 0, 0, end.x, end.y, end.z, p.radius ?? 0.05, 0)
478
+ if (id) this._own.push(id)
479
+ }
480
+ }
481
+
482
+ /** @internal a collider attached / detached: every chain that collects them re-lists. */
483
+ static _collidersChanged(): void {
484
+ for (const d of Aspect.all(DynamicBone)) if (d._id && (d.colliders === "auto" || d.colliders === "humanoid")) { d._collidersDirty = true; d._pushColliders() }
485
+ }
486
+ }