lecodes-sdk 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,482 +1,482 @@
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 (_creator.dynamicBoneCreate) return true
58
- if (!warned) { warned = true; console.warn("DynamicBone needs a newer host (no dynamicBoneCreate) — 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
- /** Only these bones (by name) join the chain — the root always does, a bone left out takes its
138
- * subtree with it. Default: the root's whole subtree. */
139
- bones?: string[]
140
- /** Depth limit under the root (0 = no limit). */
141
- depth = 0
142
- /** Particle radius for the collisions, metres. */
143
- radius: DynamicBoneCurve = 0.02
144
- /** 0..1 — how fast a bone returns to the animated shape (per 1/60 s). 0 = a rope, 1 = rigid. */
145
- stiffness: DynamicBoneCurve = 0.3
146
- /** 0..1 — velocity lost per 1/60 s. 0.02 swings like a rope, 0.1 settles like a tail, 0.3 is honey. */
147
- damping: DynamicBoneCurve = 0.1
148
- /** m/s² downward. A hanging rest pose feels none of it (the bone length cancels it); a pose that
149
- * sticks out droops by as much as `stiffness` lets it. */
150
- gravity: DynamicBoneCurve = 0
151
- /** Max deviation from the animated direction, degrees per bone (0 = free). */
152
- angleLimit: DynamicBoneCurve = 0
153
- /** Relative mass per bone. A bone-length constraint moves its two ends in inverse proportion to
154
- * their masses (the root is kinematic): `[3, 1]` makes a tail's base carry its tip, `1` shares
155
- * evenly like a rope. */
156
- mass: DynamicBoneCurve = 1
157
- /** Bones (by name) that ride the animation exactly while their subtrees still simulate: a sheet's
158
- * several roots under one anchor (a cloak's seven strips under the spine), so ONE chain owns them all
159
- * and `link` ties neighbouring strips — neighbours in THIS order, so list the strips round the ring
160
- * (front-left … back … front-right); the front stays open. */
161
- pinned?: string[]
162
- /** Metres a PINNED bone may be pushed off its animated place by a collider — a soft pin. Its particle
163
- * collides and takes the edge pushes like a free bone (the strip below hangs from where it IS) and is
164
- * drawn back to the animation when the collider leaves; the bone's local translation follows. A hard
165
- * pin (0) at a capsule's edge made the first free bone below it jitter: the edge push on a segment
166
- * with an immovable end is a lever, and a touch near the root threw the child out. 2–3 cm for a
167
- * cloak's roots under a shoulder capsule. */
168
- pinGive = 0
169
- /** 0..1 of the character's travel the chain takes rigidly (0 = the full whip on a dash, 1 = it
170
- * moves with the body and only the pose's own motion swings it). */
171
- follow = 0
172
- /** World wind, m/s². */
173
- wind: Vec3Like = [ 0, 0, 0 ]
174
- /** The BODY'S TURN, ≥ 0. Above 0 the chain lives in the parent bone's ROTATING frame: `damping` acts
175
- * against the body's rigid motion (its travel plus its spin), so a heavily damped cloak RIDES a turn —
176
- * sweeps round with the back — instead of standing in the world while the character spins under it and
177
- * being dragged round after. The turn's inertia comes back as the frame's forces, scaled by this value:
178
- * a centrifugal push `ω² · r` along each bone's animated direction from the axis (the hem, farthest
179
- * from the spine, flies out and, on the chain's length, up). The frame's own physics is built in: the
180
- * whip back when the turn starts and forward when it stops, Coriolis. 1 = the physical push; more = a
181
- * bigger fling. With low damping the frame reproduces a free particle (nothing is counted twice);
182
- * an animation's spine sway is ~1 % of a 900°/s turn. A rotation over 90° in one frame (a respawn
183
- * facing) counts as a snap, not a spin. 0 = the plain translational frame, no turn forces. */
184
- spin = 0
185
- /** With `spin`: the cloth's INERTIA against the body's turn, seconds — the cloth's own rotation follows the
186
- * body's with this time constant. It falls behind when a turn starts (by about ω·τ: 45° at 900°/s and 0.05),
187
- * rides once caught up, and keeps turning past the back when the body stops (the same angle, eased out over
188
- * τ). Smooth by construction. 0 = glued to the turn; large = the cloth stays in the world while the body spins. */
189
- spinInertia = 0
190
- /** 0..1 strength of the ties between neighbouring columns at the same depth (a cloak). */
191
- link = 0
192
- /** 0..1 blend from the animation (0) to the simulation (1). At 0 nothing is simulated and the
193
- * chain re-arms on the animated pose when it comes back. */
194
- weight = 1
195
- /** Substep rate, Hz (≤ 4 substeps per frame). */
196
- rate = 60
197
- /** A root jump longer than this in one frame (metres) resets the chain instead of whipping it. */
198
- teleport = 1
199
- /** What the particles stay above: `'none'`, `'probe'`, a height, or a world point. */
200
- floor: DynamicBoneFloor = "none"
201
- /** The floor plane's normal when `floor` is a point. */
202
- floorNormal: Vec3Like = [ 0, 1, 0 ]
203
- /** Friction against the floor, a Coulomb coefficient: a resting bone's slide loses up to
204
- * `floorFriction · gravity · dt` of speed per substep (0 = ice, 1 = a rubber sole). While a bone
205
- * rests on the floor or a collider, `stiffness` and `angleLimit` let go of it: the surface's
206
- * reaction outranks the spring, or a hem folded on the floor would run away along it. */
207
- floorFriction = 0.5
208
- /** Constraint passes per substep (1..8, default 4). Each pass shares every bone length between its
209
- * ends, so a pull needs passes to travel down a long chain: a long rope may want 8, a short tail is
210
- * fine with 2. */
211
- iterations = 4
212
- /** What the chain collides with (see DynamicBoneColliders). */
213
- colliders: DynamicBoneColliders = "auto"
214
- /** The cloth's outside — makes the colliders one-sided (see DynamicBoneSide). */
215
- side: DynamicBoneSide = "none"
216
- /** How firmly `guide()` targets are HELD through the constraint passes, 0..1. At 0 a guide is applied once
217
- * before the passes and the length / link passes may drag the bone back toward its un-guided neighbours
218
- * within the same frame; at 0.5 it is re-pulled after every pass with half its weight (converges with the
219
- * passes), at 1 with its full weight (a target the bone length cannot reach then jitters). */
220
- guideHold = 0
221
- /** The chain's EDGES collide with the capsules too — every bone segment and every link, not only the bones'
222
- * particles: a capsule thinner than a bone's length (a forearm) no longer passes through the cloth between
223
- * two bones. Off = particles only. */
224
- edges = true
225
-
226
- static fields: FieldMeta<DynamicBone> = {
227
- depth: { min: 0, max: 32, step: 1 },
228
- radius: { min: 0, max: 1, step: 0.005 },
229
- stiffness: { min: 0, max: 1, step: 0.01 },
230
- damping: { min: 0, max: 1, step: 0.01 },
231
- gravity: { min: 0, max: 30, step: 0.1 },
232
- angleLimit: { label: "Angle limit (°)", min: 0, max: 180, step: 1 },
233
- mass: { min: 0.1, max: 10, step: 0.1 },
234
- follow: { min: 0, max: 1, step: 0.01 },
235
- link: { min: 0, max: 1, step: 0.01 },
236
- weight: { min: 0, max: 1, step: 0.01 },
237
- rate: { min: 30, max: 240, step: 10 },
238
- teleport: { min: 0, max: 20, step: 0.1 },
239
- floorFriction: { label: "Floor friction", min: 0, max: 1, step: 0.01 },
240
- iterations: { min: 1, max: 8, step: 1 },
241
- bones: { hidden: true },
242
- pinned: { hidden: true },
243
- pinGive: { label: "Pin give (m)", min: 0, max: 0.2, step: 0.005 },
244
- wind: { hidden: true },
245
- spin: { min: 0, max: 4, step: 0.05 },
246
- spinInertia: { label: "Spin inertia (s)", min: 0, max: 0.3, step: 0.005 },
247
- floor: { hidden: true },
248
- floorNormal: { hidden: true },
249
- colliders: { hidden: true },
250
- side: { hidden: true },
251
- guideHold: { min: 0, max: 1, step: 0.05 },
252
- edges: { hidden: true },
253
- }
254
-
255
- private _id = 0
256
- private _chain: Node[] = []
257
- private _depths: number[] = []
258
- private _blob = new Float32Array(0)
259
- private _sent = new Float32Array(0)
260
- private _floorKey = ""
261
- private _colliderKey = ""
262
- private _collidersDirty = true
263
- private _collidersRef: DynamicBoneColliders | null = null
264
- private _own: number[] = [] // colliders generated for 'humanoid' (destroyed with the aspect)
265
- private _colliderSet: (Node | "auto" | "humanoid" | "none")[] | null = null
266
-
267
- /** The bones of the chain, the root first. */
268
- get chain(): readonly Node[] { return this._chain }
269
-
270
- onAttach(): void {
271
- if (!supported()) return
272
- this._collect()
273
- if (this._chain.length === 0) return
274
- const n = this._chain.length
275
- const bones = new Uint32Array(n)
276
- for (let i = 0; i < n; i++) bones[i] = this._chain[i]!.id
277
- this._blob = new Float32Array(HEADER + n * STRIDE)
278
- this._fill(this._blob)
279
- this._id = _creator.dynamicBoneCreate!(modelOf(this.node).id, bones, this._blob, this._links())
280
- if (!this._id) { console.warn(`DynamicBone: the host refused the chain under '${this.node.name}'`); return }
281
- this._sent = this._blob.slice()
282
- this._floorKey = ""; this._colliderKey = ""; this._collidersDirty = true
283
- this._pushFloor()
284
- this._pushColliders()
285
- }
286
-
287
- onReconfigure(): void { this._sync() }
288
-
289
- /** Every field is live: what changed since the last frame is pushed here, before the engine's stage. */
290
- update(): void { this._sync() }
291
-
292
- onDetach(): void {
293
- if (this._id) { _creator.dynamicBoneDestroy!(this._id); this._id = 0 }
294
- for (const id of this._own) _creator.dynamicBoneColliderDestroy!(id)
295
- this._own = []
296
- this._chain = []
297
- }
298
-
299
- /** Snap the chain onto the animated pose next frame (a teleport, a camera cut). */
300
- reset(): void { if (this._id) _creator.dynamicBoneReset!(this._id) }
301
-
302
- /** GUIDES: world points the bones' particles are drawn to each substep before the constraints —
303
- * weight 1 = there before them, the rest of the chain hangs, collides and links as before (a cape's
304
- * strips riding the arms). Replaces the previous set; an empty list clears. A late-phase script
305
- * (after the animator, before the engine's chain stage) refreshes it every frame. */
306
- guide(rows: readonly { bone: Node, at: Vec3Like, weight: number }[]): void {
307
- if (!this._id) return
308
- const out: number[] = []
309
- for (const r of rows) {
310
- const i = this._chain.indexOf(r.bone)
311
- if (i < 0) continue
312
- out.push(i, cx(r.at), cy(r.at), cz(r.at), r.weight)
313
- }
314
- _creator.dynamicBoneTargets?.(this._id, out.length ? new Float32Array(out) : null)
315
- }
316
-
317
- /** The particles' world positions (the bones, then the leaves' virtual tips) — for a debug draw. */
318
- get particles(): Vec3[] {
319
- if (!this._id) return []
320
- const out = new Float32Array((this._chain.length * 2) * 3)
321
- const n = _creator.dynamicBoneParticles!(this._id, out)
322
- const pts: Vec3[] = []
323
- for (let i = 0; i < n; i++) pts.push(new Vec3(out[i * 3]!, out[i * 3 + 1]!, out[i * 3 + 2]!))
324
- return pts
325
- }
326
-
327
- // ---- internals ----------------------------------------------------------------------------------
328
-
329
- private _collect(): void {
330
- const chain: Node[] = [], depths: number[] = []
331
- const only = this.bones ? new Set(this.bones) : null
332
- const walk = (n: Node, d: number): void => {
333
- chain.push(n); depths.push(d)
334
- if (this.depth > 0 && d >= this.depth) return
335
- for (const c of n.children) {
336
- if (only && !only.has(c.name)) continue
337
- if (c.has(DynamicBone) || c.has(DynamicBoneCollider)) continue // another chain / a body bone
338
- walk(c, d + 1)
339
- }
340
- }
341
- walk(this.node, 0)
342
- this._chain = chain; this._depths = depths
343
- }
344
-
345
- private _fill(b: Float32Array): void {
346
- const n = this._chain.length
347
- let maxDepth = 0
348
- for (const d of this._depths) if (d > maxDepth) maxDepth = d
349
- b[0] = VERSION; b[1] = n; b[2] = STRIDE
350
- b[3] = this.weight; b[4] = this.follow
351
- b[5] = cx(this.wind); b[6] = cy(this.wind); b[7] = cz(this.wind)
352
- b[8] = this.link; b[9] = this.rate; b[10] = this.teleport
353
- 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
354
- b[18] = this.floorFriction
355
- b[19] = Math.max(1, Math.min(8, Math.round(this.iterations)))
356
- const side = this.side
357
- const sideVec = side === "none" || side === "auto" ? null : side
358
- b[20] = side === "none" ? 0 : side === "auto" ? 1 : 2
359
- b[21] = sideVec ? cx(sideVec) : 0; b[22] = sideVec ? cy(sideVec) : 0; b[23] = sideVec ? cz(sideVec) : 0
360
- b[24] = Math.max(0, Math.min(1, this.guideHold))
361
- b[25] = this.edges ? 1 : 0
362
- b[26] = Math.max(0, this.spin)
363
- b[27] = Math.max(0, this.spinInertia)
364
- const pin = this.pinned?.length ? new Set(this.pinned) : null
365
- for (let i = 0; i < n; i++) {
366
- const t = maxDepth > 0 ? this._depths[i]! / maxDepth : 0
367
- const o = HEADER + i * STRIDE
368
- b[o] = at(this.radius, t); b[o + 1] = at(this.stiffness, t); b[o + 2] = at(this.damping, t)
369
- b[o + 3] = at(this.gravity, t); b[o + 4] = at(this.angleLimit, t)
370
- const isPinned = !!pin && i > 0 && pin.has(this._chain[i]!.name)
371
- b[o + 5] = isPinned ? -1 : at(this.mass, t) // mass < 0 = pinned
372
- b[o + 6] = isPinned ? Math.max(0, this.pinGive) : 0
373
- }
374
- }
375
-
376
- /** Neighbour links: the bones at the same depth tied pairwise, the columns in the order of `pinned` (a cloak's
377
- * strips listed round the ring) — columns not listed there follow in tree order. Tree order alone is the
378
- * engine's child order, which for a GLB is the file's node order REVERSED (Filament prepends each child), so
379
- * strips added to a rig later were tied across the body instead of to their neighbours: the ermine's cloak
380
- * had one true neighbour pair out of eight, the rest were rods through the chest. */
381
- private _links(): Uint16Array | undefined {
382
- if (this.link <= 0) return undefined
383
- const index = new Map<Node, number>(this._chain.map((n, i) => [ n, i ]))
384
- const column = new Int32Array(this._chain.length).fill(-1) // per bone: the chain index of its depth-1 ancestor
385
- for (let i = 1; i < this._chain.length; i++) {
386
- const p = index.get(this._chain[i]!.parent!) ?? 0
387
- column[i] = this._depths[i] === 1 ? i : column[p]!
388
- }
389
- const ring = this.pinned ?? []
390
- const key = (i: number): number => { const k = ring.indexOf(this._chain[column[i]!]!.name); return k < 0 ? ring.length + column[i]! : k }
391
- const byDepth = new Map<number, number[]>()
392
- this._depths.forEach((d, i) => { if (d > 0) (byDepth.get(d) ?? byDepth.set(d, []).get(d)!).push(i) })
393
- const pairs: number[] = []
394
- for (const row of byDepth.values()) {
395
- row.sort((a, b) => key(a) - key(b))
396
- for (let k = 0; k + 1 < row.length; k++) pairs.push(row[k]!, row[k + 1]!)
397
- }
398
- return pairs.length ? new Uint16Array(pairs) : undefined
399
- }
400
-
401
- private _sync(): void {
402
- if (!this._id) return
403
- this._fill(this._blob)
404
- let changed = false
405
- for (let i = 0; i < this._blob.length; i++) if (this._blob[i] !== this._sent[i]) { changed = true; break }
406
- if (changed) { _creator.dynamicBoneSet!(this._id, this._blob); this._sent.set(this._blob) }
407
- this._pushFloor()
408
- this._pushColliders()
409
- }
410
-
411
- private _pushFloor(): void {
412
- const f = this.floor
413
- let key: string, mode: 0 | 1 | 2 = FLOOR_NONE, x = 0, y = 0, z = 0, nx = 0, ny = 1, nz = 0
414
- if (f === "probe") { mode = FLOOR_PROBE; key = "probe" }
415
- else if (f === "none" || f === undefined || f === null) { key = "none" }
416
- else if (typeof f === "number") { mode = FLOOR_PLANE; y = f; key = `y${f}` }
417
- else {
418
- mode = FLOOR_PLANE; x = cx(f); y = cy(f); z = cz(f)
419
- nx = cx(this.floorNormal); ny = cy(this.floorNormal); nz = cz(this.floorNormal)
420
- key = `p${x},${y},${z},${nx},${ny},${nz}`
421
- }
422
- if (key === this._floorKey) return
423
- this._floorKey = key
424
- _creator.dynamicBoneSetFloor!(this._id, mode, x, y, z, nx, ny, nz)
425
- }
426
-
427
- private _pushColliders(): void {
428
- // re-listed only when a collider came or went, or the field was reassigned (per frame otherwise)
429
- if (!this._collidersDirty && this._collidersRef === this.colliders) return
430
- this._collidersDirty = false
431
- this._collidersRef = this.colliders
432
- const ids: number[] = []
433
- const model = modelOf(this.node)
434
- const c = this.colliders
435
- if (c === "auto" || c === "humanoid") {
436
- for (const col of Aspect.all(DynamicBoneCollider)) if (col._colliderId && modelOf(col.node) === model) ids.push(col._colliderId)
437
- if (c === "humanoid") { if (this._own.length === 0) this._makeHumanoid(model); ids.push(...this._own) }
438
- } else if (Array.isArray(c)) {
439
- for (const n of c) {
440
- const col = n.get(DynamicBoneCollider)
441
- if (col?._colliderId) ids.push(col._colliderId)
442
- }
443
- }
444
- const key = ids.join(",")
445
- if (key === this._colliderKey) return
446
- this._colliderKey = key
447
- _creator.dynamicBoneSetColliders!(this._id, new Uint32Array(ids))
448
- }
449
-
450
- /** Capsules on the standard humanoid bones, sized like the Ragdoll's parts. */
451
- private _makeHumanoid(model: Node): void {
452
- const find = (role: string): string | null => {
453
- for (const name of HUMANOID[role] ?? []) if (model.bone(name)) return name
454
- return null
455
- }
456
- let parts: ReturnType<typeof humanoidParts>
457
- try { parts = humanoidParts(find) } catch { return } // no hips: not a humanoid, nothing generated
458
- for (const p of parts) {
459
- const bone = model.bone(p.bone)
460
- if (!bone) continue
461
- const inv = bone.worldMatrix.invert()
462
- let end: Vec3
463
- const to = p.to ? model.bone(p.to) : null
464
- if (to) end = inv.transformPoint(to.worldPosition)
465
- else {
466
- // a leaf: along the line from the parent part's origin through this bone
467
- const parentBone = p.parent ? model.bone(p.parent) : null
468
- const dir = parentBone ? bone.worldPosition.sub(parentBone.worldPosition) : new Vec3(0, 1, 0)
469
- const local = inv.transformDirection(dir)
470
- const len = local.length()
471
- end = len > 1e-6 ? local.scale((p.length ?? 0.2) / len) : new Vec3(0, p.length ?? 0.2, 0)
472
- }
473
- const id = _creator.dynamicBoneColliderCreate!(bone.id, 0, 0, 0, end.x, end.y, end.z, p.radius ?? 0.05, 0)
474
- if (id) this._own.push(id)
475
- }
476
- }
477
-
478
- /** @internal a collider attached / detached: every chain that collects them re-lists. */
479
- static _collidersChanged(): void {
480
- for (const d of Aspect.all(DynamicBone)) if (d._id && (d.colliders === "auto" || d.colliders === "humanoid")) { d._collidersDirty = true; d._pushColliders() }
481
- }
482
- }
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 (_creator.dynamicBoneCreate) return true
58
+ if (!warned) { warned = true; console.warn("DynamicBone needs a newer host (no dynamicBoneCreate) — 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
+ /** Only these bones (by name) join the chain — the root always does, a bone left out takes its
138
+ * subtree with it. Default: the root's whole subtree. */
139
+ bones?: string[]
140
+ /** Depth limit under the root (0 = no limit). */
141
+ depth = 0
142
+ /** Particle radius for the collisions, metres. */
143
+ radius: DynamicBoneCurve = 0.02
144
+ /** 0..1 — how fast a bone returns to the animated shape (per 1/60 s). 0 = a rope, 1 = rigid. */
145
+ stiffness: DynamicBoneCurve = 0.3
146
+ /** 0..1 — velocity lost per 1/60 s. 0.02 swings like a rope, 0.1 settles like a tail, 0.3 is honey. */
147
+ damping: DynamicBoneCurve = 0.1
148
+ /** m/s² downward. A hanging rest pose feels none of it (the bone length cancels it); a pose that
149
+ * sticks out droops by as much as `stiffness` lets it. */
150
+ gravity: DynamicBoneCurve = 0
151
+ /** Max deviation from the animated direction, degrees per bone (0 = free). */
152
+ angleLimit: DynamicBoneCurve = 0
153
+ /** Relative mass per bone. A bone-length constraint moves its two ends in inverse proportion to
154
+ * their masses (the root is kinematic): `[3, 1]` makes a tail's base carry its tip, `1` shares
155
+ * evenly like a rope. */
156
+ mass: DynamicBoneCurve = 1
157
+ /** Bones (by name) that ride the animation exactly while their subtrees still simulate: a sheet's
158
+ * several roots under one anchor (a cloak's seven strips under the spine), so ONE chain owns them all
159
+ * and `link` ties neighbouring strips — neighbours in THIS order, so list the strips round the ring
160
+ * (front-left … back … front-right); the front stays open. */
161
+ pinned?: string[]
162
+ /** Metres a PINNED bone may be pushed off its animated place by a collider — a soft pin. Its particle
163
+ * collides and takes the edge pushes like a free bone (the strip below hangs from where it IS) and is
164
+ * drawn back to the animation when the collider leaves; the bone's local translation follows. A hard
165
+ * pin (0) at a capsule's edge made the first free bone below it jitter: the edge push on a segment
166
+ * with an immovable end is a lever, and a touch near the root threw the child out. 2–3 cm for a
167
+ * cloak's roots under a shoulder capsule. */
168
+ pinGive = 0
169
+ /** 0..1 of the character's travel the chain takes rigidly (0 = the full whip on a dash, 1 = it
170
+ * moves with the body and only the pose's own motion swings it). */
171
+ follow = 0
172
+ /** World wind, m/s². */
173
+ wind: Vec3Like = [ 0, 0, 0 ]
174
+ /** The BODY'S TURN, ≥ 0. Above 0 the chain lives in the parent bone's ROTATING frame: `damping` acts
175
+ * against the body's rigid motion (its travel plus its spin), so a heavily damped cloak RIDES a turn —
176
+ * sweeps round with the back — instead of standing in the world while the character spins under it and
177
+ * being dragged round after. The turn's inertia comes back as the frame's forces, scaled by this value:
178
+ * a centrifugal push `ω² · r` along each bone's animated direction from the axis (the hem, farthest
179
+ * from the spine, flies out and, on the chain's length, up). The frame's own physics is built in: the
180
+ * whip back when the turn starts and forward when it stops, Coriolis. 1 = the physical push; more = a
181
+ * bigger fling. With low damping the frame reproduces a free particle (nothing is counted twice);
182
+ * an animation's spine sway is ~1 % of a 900°/s turn. A rotation over 90° in one frame (a respawn
183
+ * facing) counts as a snap, not a spin. 0 = the plain translational frame, no turn forces. */
184
+ spin = 0
185
+ /** With `spin`: the cloth's INERTIA against the body's turn, seconds — the cloth's own rotation follows the
186
+ * body's with this time constant. It falls behind when a turn starts (by about ω·τ: 45° at 900°/s and 0.05),
187
+ * rides once caught up, and keeps turning past the back when the body stops (the same angle, eased out over
188
+ * τ). Smooth by construction. 0 = glued to the turn; large = the cloth stays in the world while the body spins. */
189
+ spinInertia = 0
190
+ /** 0..1 strength of the ties between neighbouring columns at the same depth (a cloak). */
191
+ link = 0
192
+ /** 0..1 blend from the animation (0) to the simulation (1). At 0 nothing is simulated and the
193
+ * chain re-arms on the animated pose when it comes back. */
194
+ weight = 1
195
+ /** Substep rate, Hz (≤ 4 substeps per frame). */
196
+ rate = 60
197
+ /** A root jump longer than this in one frame (metres) resets the chain instead of whipping it. */
198
+ teleport = 1
199
+ /** What the particles stay above: `'none'`, `'probe'`, a height, or a world point. */
200
+ floor: DynamicBoneFloor = "none"
201
+ /** The floor plane's normal when `floor` is a point. */
202
+ floorNormal: Vec3Like = [ 0, 1, 0 ]
203
+ /** Friction against the floor, a Coulomb coefficient: a resting bone's slide loses up to
204
+ * `floorFriction · gravity · dt` of speed per substep (0 = ice, 1 = a rubber sole). While a bone
205
+ * rests on the floor or a collider, `stiffness` and `angleLimit` let go of it: the surface's
206
+ * reaction outranks the spring, or a hem folded on the floor would run away along it. */
207
+ floorFriction = 0.5
208
+ /** Constraint passes per substep (1..8, default 4). Each pass shares every bone length between its
209
+ * ends, so a pull needs passes to travel down a long chain: a long rope may want 8, a short tail is
210
+ * fine with 2. */
211
+ iterations = 4
212
+ /** What the chain collides with (see DynamicBoneColliders). */
213
+ colliders: DynamicBoneColliders = "auto"
214
+ /** The cloth's outside — makes the colliders one-sided (see DynamicBoneSide). */
215
+ side: DynamicBoneSide = "none"
216
+ /** How firmly `guide()` targets are HELD through the constraint passes, 0..1. At 0 a guide is applied once
217
+ * before the passes and the length / link passes may drag the bone back toward its un-guided neighbours
218
+ * within the same frame; at 0.5 it is re-pulled after every pass with half its weight (converges with the
219
+ * passes), at 1 with its full weight (a target the bone length cannot reach then jitters). */
220
+ guideHold = 0
221
+ /** The chain's EDGES collide with the capsules too — every bone segment and every link, not only the bones'
222
+ * particles: a capsule thinner than a bone's length (a forearm) no longer passes through the cloth between
223
+ * two bones. Off = particles only. */
224
+ edges = true
225
+
226
+ static fields: FieldMeta<DynamicBone> = {
227
+ depth: { min: 0, max: 32, step: 1 },
228
+ radius: { min: 0, max: 1, step: 0.005 },
229
+ stiffness: { min: 0, max: 1, step: 0.01 },
230
+ damping: { min: 0, max: 1, step: 0.01 },
231
+ gravity: { min: 0, max: 30, step: 0.1 },
232
+ angleLimit: { label: "Angle limit (°)", min: 0, max: 180, step: 1 },
233
+ mass: { min: 0.1, max: 10, step: 0.1 },
234
+ follow: { min: 0, max: 1, step: 0.01 },
235
+ link: { min: 0, max: 1, step: 0.01 },
236
+ weight: { min: 0, max: 1, step: 0.01 },
237
+ rate: { min: 30, max: 240, step: 10 },
238
+ teleport: { min: 0, max: 20, step: 0.1 },
239
+ floorFriction: { label: "Floor friction", min: 0, max: 1, step: 0.01 },
240
+ iterations: { min: 1, max: 8, step: 1 },
241
+ bones: { hidden: true },
242
+ pinned: { hidden: true },
243
+ pinGive: { label: "Pin give (m)", min: 0, max: 0.2, step: 0.005 },
244
+ wind: { hidden: true },
245
+ spin: { min: 0, max: 4, step: 0.05 },
246
+ spinInertia: { label: "Spin inertia (s)", min: 0, max: 0.3, step: 0.005 },
247
+ floor: { hidden: true },
248
+ floorNormal: { hidden: true },
249
+ colliders: { hidden: true },
250
+ side: { hidden: true },
251
+ guideHold: { min: 0, max: 1, step: 0.05 },
252
+ edges: { hidden: true },
253
+ }
254
+
255
+ private _id = 0
256
+ private _chain: Node[] = []
257
+ private _depths: number[] = []
258
+ private _blob = new Float32Array(0)
259
+ private _sent = new Float32Array(0)
260
+ private _floorKey = ""
261
+ private _colliderKey = ""
262
+ private _collidersDirty = true
263
+ private _collidersRef: DynamicBoneColliders | null = null
264
+ private _own: number[] = [] // colliders generated for 'humanoid' (destroyed with the aspect)
265
+ private _colliderSet: (Node | "auto" | "humanoid" | "none")[] | null = null
266
+
267
+ /** The bones of the chain, the root first. */
268
+ get chain(): readonly Node[] { return this._chain }
269
+
270
+ onAttach(): void {
271
+ if (!supported()) return
272
+ this._collect()
273
+ if (this._chain.length === 0) return
274
+ const n = this._chain.length
275
+ const bones = new Uint32Array(n)
276
+ for (let i = 0; i < n; i++) bones[i] = this._chain[i]!.id
277
+ this._blob = new Float32Array(HEADER + n * STRIDE)
278
+ this._fill(this._blob)
279
+ this._id = _creator.dynamicBoneCreate!(modelOf(this.node).id, bones, this._blob, this._links())
280
+ if (!this._id) { console.warn(`DynamicBone: the host refused the chain under '${this.node.name}'`); return }
281
+ this._sent = this._blob.slice()
282
+ this._floorKey = ""; this._colliderKey = ""; this._collidersDirty = true
283
+ this._pushFloor()
284
+ this._pushColliders()
285
+ }
286
+
287
+ onReconfigure(): void { this._sync() }
288
+
289
+ /** Every field is live: what changed since the last frame is pushed here, before the engine's stage. */
290
+ update(): void { this._sync() }
291
+
292
+ onDetach(): void {
293
+ if (this._id) { _creator.dynamicBoneDestroy!(this._id); this._id = 0 }
294
+ for (const id of this._own) _creator.dynamicBoneColliderDestroy!(id)
295
+ this._own = []
296
+ this._chain = []
297
+ }
298
+
299
+ /** Snap the chain onto the animated pose next frame (a teleport, a camera cut). */
300
+ reset(): void { if (this._id) _creator.dynamicBoneReset!(this._id) }
301
+
302
+ /** GUIDES: world points the bones' particles are drawn to each substep before the constraints —
303
+ * weight 1 = there before them, the rest of the chain hangs, collides and links as before (a cape's
304
+ * strips riding the arms). Replaces the previous set; an empty list clears. A late-phase script
305
+ * (after the animator, before the engine's chain stage) refreshes it every frame. */
306
+ guide(rows: readonly { bone: Node, at: Vec3Like, weight: number }[]): void {
307
+ if (!this._id) return
308
+ const out: number[] = []
309
+ for (const r of rows) {
310
+ const i = this._chain.indexOf(r.bone)
311
+ if (i < 0) continue
312
+ out.push(i, cx(r.at), cy(r.at), cz(r.at), r.weight)
313
+ }
314
+ _creator.dynamicBoneTargets?.(this._id, out.length ? new Float32Array(out) : null)
315
+ }
316
+
317
+ /** The particles' world positions (the bones, then the leaves' virtual tips) — for a debug draw. */
318
+ get particles(): Vec3[] {
319
+ if (!this._id) return []
320
+ const out = new Float32Array((this._chain.length * 2) * 3)
321
+ const n = _creator.dynamicBoneParticles!(this._id, out)
322
+ const pts: Vec3[] = []
323
+ for (let i = 0; i < n; i++) pts.push(new Vec3(out[i * 3]!, out[i * 3 + 1]!, out[i * 3 + 2]!))
324
+ return pts
325
+ }
326
+
327
+ // ---- internals ----------------------------------------------------------------------------------
328
+
329
+ private _collect(): void {
330
+ const chain: Node[] = [], depths: number[] = []
331
+ const only = this.bones ? new Set(this.bones) : null
332
+ const walk = (n: Node, d: number): void => {
333
+ chain.push(n); depths.push(d)
334
+ if (this.depth > 0 && d >= this.depth) return
335
+ for (const c of n.children) {
336
+ if (only && !only.has(c.name)) continue
337
+ if (c.has(DynamicBone) || c.has(DynamicBoneCollider)) continue // another chain / a body bone
338
+ walk(c, d + 1)
339
+ }
340
+ }
341
+ walk(this.node, 0)
342
+ this._chain = chain; this._depths = depths
343
+ }
344
+
345
+ private _fill(b: Float32Array): void {
346
+ const n = this._chain.length
347
+ let maxDepth = 0
348
+ for (const d of this._depths) if (d > maxDepth) maxDepth = d
349
+ b[0] = VERSION; b[1] = n; b[2] = STRIDE
350
+ b[3] = this.weight; b[4] = this.follow
351
+ b[5] = cx(this.wind); b[6] = cy(this.wind); b[7] = cz(this.wind)
352
+ b[8] = this.link; b[9] = this.rate; b[10] = this.teleport
353
+ 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
354
+ b[18] = this.floorFriction
355
+ b[19] = Math.max(1, Math.min(8, Math.round(this.iterations)))
356
+ const side = this.side
357
+ const sideVec = side === "none" || side === "auto" ? null : side
358
+ b[20] = side === "none" ? 0 : side === "auto" ? 1 : 2
359
+ b[21] = sideVec ? cx(sideVec) : 0; b[22] = sideVec ? cy(sideVec) : 0; b[23] = sideVec ? cz(sideVec) : 0
360
+ b[24] = Math.max(0, Math.min(1, this.guideHold))
361
+ b[25] = this.edges ? 1 : 0
362
+ b[26] = Math.max(0, this.spin)
363
+ b[27] = Math.max(0, this.spinInertia)
364
+ const pin = this.pinned?.length ? new Set(this.pinned) : null
365
+ for (let i = 0; i < n; i++) {
366
+ const t = maxDepth > 0 ? this._depths[i]! / maxDepth : 0
367
+ const o = HEADER + i * STRIDE
368
+ b[o] = at(this.radius, t); b[o + 1] = at(this.stiffness, t); b[o + 2] = at(this.damping, t)
369
+ b[o + 3] = at(this.gravity, t); b[o + 4] = at(this.angleLimit, t)
370
+ const isPinned = !!pin && i > 0 && pin.has(this._chain[i]!.name)
371
+ b[o + 5] = isPinned ? -1 : at(this.mass, t) // mass < 0 = pinned
372
+ b[o + 6] = isPinned ? Math.max(0, this.pinGive) : 0
373
+ }
374
+ }
375
+
376
+ /** Neighbour links: the bones at the same depth tied pairwise, the columns in the order of `pinned` (a cloak's
377
+ * strips listed round the ring) — columns not listed there follow in tree order. Tree order alone is the
378
+ * engine's child order, which for a GLB is the file's node order REVERSED (Filament prepends each child), so
379
+ * strips added to a rig later were tied across the body instead of to their neighbours: the ermine's cloak
380
+ * had one true neighbour pair out of eight, the rest were rods through the chest. */
381
+ private _links(): Uint16Array | undefined {
382
+ if (this.link <= 0) return undefined
383
+ const index = new Map<Node, number>(this._chain.map((n, i) => [ n, i ]))
384
+ const column = new Int32Array(this._chain.length).fill(-1) // per bone: the chain index of its depth-1 ancestor
385
+ for (let i = 1; i < this._chain.length; i++) {
386
+ const p = index.get(this._chain[i]!.parent!) ?? 0
387
+ column[i] = this._depths[i] === 1 ? i : column[p]!
388
+ }
389
+ const ring = this.pinned ?? []
390
+ const key = (i: number): number => { const k = ring.indexOf(this._chain[column[i]!]!.name); return k < 0 ? ring.length + column[i]! : k }
391
+ const byDepth = new Map<number, number[]>()
392
+ this._depths.forEach((d, i) => { if (d > 0) (byDepth.get(d) ?? byDepth.set(d, []).get(d)!).push(i) })
393
+ const pairs: number[] = []
394
+ for (const row of byDepth.values()) {
395
+ row.sort((a, b) => key(a) - key(b))
396
+ for (let k = 0; k + 1 < row.length; k++) pairs.push(row[k]!, row[k + 1]!)
397
+ }
398
+ return pairs.length ? new Uint16Array(pairs) : undefined
399
+ }
400
+
401
+ private _sync(): void {
402
+ if (!this._id) return
403
+ this._fill(this._blob)
404
+ let changed = false
405
+ for (let i = 0; i < this._blob.length; i++) if (this._blob[i] !== this._sent[i]) { changed = true; break }
406
+ if (changed) { _creator.dynamicBoneSet!(this._id, this._blob); this._sent.set(this._blob) }
407
+ this._pushFloor()
408
+ this._pushColliders()
409
+ }
410
+
411
+ private _pushFloor(): void {
412
+ const f = this.floor
413
+ let key: string, mode: 0 | 1 | 2 = FLOOR_NONE, x = 0, y = 0, z = 0, nx = 0, ny = 1, nz = 0
414
+ if (f === "probe") { mode = FLOOR_PROBE; key = "probe" }
415
+ else if (f === "none" || f === undefined || f === null) { key = "none" }
416
+ else if (typeof f === "number") { mode = FLOOR_PLANE; y = f; key = `y${f}` }
417
+ else {
418
+ mode = FLOOR_PLANE; x = cx(f); y = cy(f); z = cz(f)
419
+ nx = cx(this.floorNormal); ny = cy(this.floorNormal); nz = cz(this.floorNormal)
420
+ key = `p${x},${y},${z},${nx},${ny},${nz}`
421
+ }
422
+ if (key === this._floorKey) return
423
+ this._floorKey = key
424
+ _creator.dynamicBoneSetFloor!(this._id, mode, x, y, z, nx, ny, nz)
425
+ }
426
+
427
+ private _pushColliders(): void {
428
+ // re-listed only when a collider came or went, or the field was reassigned (per frame otherwise)
429
+ if (!this._collidersDirty && this._collidersRef === this.colliders) return
430
+ this._collidersDirty = false
431
+ this._collidersRef = this.colliders
432
+ const ids: number[] = []
433
+ const model = modelOf(this.node)
434
+ const c = this.colliders
435
+ if (c === "auto" || c === "humanoid") {
436
+ for (const col of Aspect.all(DynamicBoneCollider)) if (col._colliderId && modelOf(col.node) === model) ids.push(col._colliderId)
437
+ if (c === "humanoid") { if (this._own.length === 0) this._makeHumanoid(model); ids.push(...this._own) }
438
+ } else if (Array.isArray(c)) {
439
+ for (const n of c) {
440
+ const col = n.get(DynamicBoneCollider)
441
+ if (col?._colliderId) ids.push(col._colliderId)
442
+ }
443
+ }
444
+ const key = ids.join(",")
445
+ if (key === this._colliderKey) return
446
+ this._colliderKey = key
447
+ _creator.dynamicBoneSetColliders!(this._id, new Uint32Array(ids))
448
+ }
449
+
450
+ /** Capsules on the standard humanoid bones, sized like the Ragdoll's parts. */
451
+ private _makeHumanoid(model: Node): void {
452
+ const find = (role: string): string | null => {
453
+ for (const name of HUMANOID[role] ?? []) if (model.bone(name)) return name
454
+ return null
455
+ }
456
+ let parts: ReturnType<typeof humanoidParts>
457
+ try { parts = humanoidParts(find) } catch { return } // no hips: not a humanoid, nothing generated
458
+ for (const p of parts) {
459
+ const bone = model.bone(p.bone)
460
+ if (!bone) continue
461
+ const inv = bone.worldMatrix.invert()
462
+ let end: Vec3
463
+ const to = p.to ? model.bone(p.to) : null
464
+ if (to) end = inv.transformPoint(to.worldPosition)
465
+ else {
466
+ // a leaf: along the line from the parent part's origin through this bone
467
+ const parentBone = p.parent ? model.bone(p.parent) : null
468
+ const dir = parentBone ? bone.worldPosition.sub(parentBone.worldPosition) : new Vec3(0, 1, 0)
469
+ const local = inv.transformDirection(dir)
470
+ const len = local.length()
471
+ end = len > 1e-6 ? local.scale((p.length ?? 0.2) / len) : new Vec3(0, p.length ?? 0.2, 0)
472
+ }
473
+ const id = _creator.dynamicBoneColliderCreate!(bone.id, 0, 0, 0, end.x, end.y, end.z, p.radius ?? 0.05, 0)
474
+ if (id) this._own.push(id)
475
+ }
476
+ }
477
+
478
+ /** @internal a collider attached / detached: every chain that collects them re-lists. */
479
+ static _collidersChanged(): void {
480
+ for (const d of Aspect.all(DynamicBone)) if (d._id && (d.colliders === "auto" || d.colliders === "humanoid")) { d._collidersDirty = true; d._pushColliders() }
481
+ }
482
+ }