Documentation
¶
Overview ¶
Package anim3d is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package anim3d provides 3D skeletal animation playback for glTF 2.0 models, state machines, 1D/2D blend spaces with foot-phase synchronization, layered bone-masked and additive blending, timed animation events, inverse kinematics solvers, and root motion extraction for NSGo 3D games.
All transforms, vectors, and quaternions follow package math3d's right-handed Y-up conventions (+X right, +Y up, -Z forward). Time advances in fixed time.Duration steps matching game.Loop.Update.
Index ¶
- Constants
- Variables
- func ApplyRootMotion(world math3d.Transform, rm RootMotion) math3d.Transform
- func EncodeBoneMap(m BoneMap) ([]byte, error)
- func LoadEventsFromGLTFExtras(gltfJSON []byte) (map[string][]ClipEvent, error)
- func LoadEventsSidecar(data []byte) (map[string][]ClipEvent, error)
- func MarshalEventsSidecar(clips map[string][]ClipEvent) ([]byte, error)
- func SolveCCD(joints []math3d.Vec3, target math3d.Vec3, iterations int, tolerance float32) []math3d.Vec3
- func SolveFABRIK(joints []math3d.Vec3, target math3d.Vec3, iterations int, tolerance float32) []math3d.Vec3
- func SolveTwoBoneIK(root, mid, end, target, pole math3d.Vec3) (newMid, newEnd math3d.Vec3, rootRot, midRot math3d.Quat)
- func SortClipEvents(events []ClipEvent)
- type AddNode
- type AnimLayer
- type BlendNode
- type BlendSample1D
- type BlendSample2D
- type BlendSpace1D
- func (bs *BlendSpace1D) CycleSpeed(param float32) float32
- func (bs *BlendSpace1D) Evaluate(param float32, phase float32) Pose
- func (bs *BlendSpace1D) Param() float32
- func (bs *BlendSpace1D) Phase() float32
- func (bs *BlendSpace1D) Pose() Pose
- func (bs *BlendSpace1D) Reset()
- func (bs *BlendSpace1D) Samples() []BlendSample1D
- func (bs *BlendSpace1D) SetParam(value float32)
- func (bs *BlendSpace1D) SetPhase(phase float32)
- func (bs *BlendSpace1D) Update(dt time.Duration) Pose
- func (bs *BlendSpace1D) Weights(param float32) []float32
- type BlendSpace2D
- func (bs *BlendSpace2D) CycleSpeed(x, y float32) float32
- func (bs *BlendSpace2D) Evaluate(x, y, phase float32) Pose
- func (bs *BlendSpace2D) Params() (x, y float32)
- func (bs *BlendSpace2D) Phase() float32
- func (bs *BlendSpace2D) Pose() Pose
- func (bs *BlendSpace2D) Reset()
- func (bs *BlendSpace2D) Samples() []BlendSample2D
- func (bs *BlendSpace2D) SetParams(x, y float32)
- func (bs *BlendSpace2D) SetPhase(phase float32)
- func (bs *BlendSpace2D) Update(dt time.Duration) Pose
- func (bs *BlendSpace2D) Weights(x, y float32) []float32
- type BoneDesc
- type BoneMap
- type BoneMask
- type CapsuleCollider
- type ChainIK
- type Clip
- type ClipEvent
- type EventDispatcher
- func (d *EventDispatcher) Clear()
- func (d *EventDispatcher) DispatchClip(clip *Clip, stateName string, prevTime, nextTime, weight float32) []FiredEvent
- func (d *EventDispatcher) Drain() []FiredEvent
- func (d *EventDispatcher) Emit(ev FiredEvent)
- func (d *EventDispatcher) OnEvent(fn func(FiredEvent))
- func (d *EventDispatcher) Pending() []FiredEvent
- type FiredEvent
- type FootConfig
- type FootPlacement
- type Graph
- func (g *Graph) ApplyModifiers(pose Pose, modelWorld math3d.Mat4, dt time.Duration) Pose
- func (g *Graph) Bool(name string) bool
- func (g *Graph) CurrentState() string
- func (g *Graph) DrainEvents() []FiredEvent
- func (g *Graph) Float(name string) float32
- func (g *Graph) LayerStack() *LayerStack
- func (g *Graph) LayerState(layer string) string
- func (g *Graph) Machine(layer string) *StateMachine
- func (g *Graph) Modifiers() *ModifierStack
- func (g *Graph) OnEvent(fn func(FiredEvent))
- func (g *Graph) Pose() Pose
- func (g *Graph) Resource() *resource.AnimGraph
- func (g *Graph) Rig() *Rig
- func (g *Graph) SetBool(name string, value bool)
- func (g *Graph) SetFloat(name string, value float32)
- func (g *Graph) SetFootPlacementRay(fn RayFunc)
- func (g *Graph) SetModifierInfluence(index int, weight float32)
- func (g *Graph) SetModifierPoleTarget(bone string, poleWorld math3d.Vec3)
- func (g *Graph) SetModifierTarget(bone string, targetWorld math3d.Vec3)
- func (g *Graph) SetSpringWind(wind math3d.Vec3)
- func (g *Graph) Travel(state string) bool
- func (g *Graph) TravelLayer(layer, state string) bool
- func (g *Graph) Trigger(name string)
- func (g *Graph) Update(dt time.Duration) Pose
- type IKSolver
- type JointLimit
- type JointTrack
- type LayerBlendMode
- type LayerStack
- func (ls *LayerStack) AddLayer(layer AnimLayer)
- func (ls *LayerStack) Evaluate() Pose
- func (ls *LayerStack) Layer(name string) *AnimLayer
- func (ls *LayerStack) LayerWeight(name string) float32
- func (ls *LayerStack) Pose() Pose
- func (ls *LayerStack) RemoveLayer(name string) bool
- func (ls *LayerStack) SetLayerWeight(name string, weight float32) bool
- func (ls *LayerStack) Update(dt time.Duration) Pose
- type LookAt
- type Modifier
- type ModifierContext
- func (c *ModifierContext) DeltaTime() float32
- func (c *ModifierContext) MarkDirty()
- func (c *ModifierContext) ModelWorld() math3d.Mat4
- func (c *ModifierContext) PoleTarget(boneIndex int) (math3d.Vec3, bool)
- func (c *ModifierContext) Rig() *Rig
- func (c *ModifierContext) Target(boneIndex int) (math3d.Vec3, bool)
- func (c *ModifierContext) TargetByName(bone string) (math3d.Vec3, bool)
- func (c *ModifierContext) WorldMatrix(pose *Pose, boneIndex int) math3d.Mat4
- func (c *ModifierContext) WorldPosition(pose *Pose, boneIndex int) math3d.Vec3
- func (c *ModifierContext) WorldRotation(pose *Pose, boneIndex int) math3d.Quat
- type ModifierStack
- func (s *ModifierStack) Apply(pose Pose, modelWorld math3d.Mat4) Pose
- func (s *ModifierStack) ApplyStep(pose Pose, modelWorld math3d.Mat4, dt float32) Pose
- func (s *ModifierStack) ClearPoleTarget(bone string)
- func (s *ModifierStack) ClearTarget(bone string)
- func (s *ModifierStack) Influence(index int) float32
- func (s *ModifierStack) Reset()
- func (s *ModifierStack) Rig() *Rig
- func (s *ModifierStack) SetDeltaTime(dt float32)
- func (s *ModifierStack) SetInfluence(index int, weight float32)
- func (s *ModifierStack) SetPoleTarget(bone string, poleWorld math3d.Vec3)
- func (s *ModifierStack) SetStepDuration(d time.Duration)
- func (s *ModifierStack) SetTarget(bone string, targetWorld math3d.Vec3)
- type OneShot
- type PlaneCollider
- type Player
- func (p *Player) AnimationIndex() int
- func (p *Player) AnimationName() string
- func (p *Player) ApplyToNodes(nodes []*scene3d.Node) int
- func (p *Player) ApplyToScene(scene *scene3d.Scene) int
- func (p *Player) Crossfade(animIndex int, duration time.Duration) error
- func (p *Player) CrossfadeByName(name string, duration time.Duration) error
- func (p *Player) CrossfadeProgress() float32
- func (p *Player) Duration() time.Duration
- func (p *Player) IsCrossfading() bool
- func (p *Player) LocalTransform(nodeIndex int) math3d.Transform
- func (p *Player) LocalTransforms() []math3d.Transform
- func (p *Player) Loop() bool
- func (p *Player) MorphWeights(nodeIndex int) []float32
- func (p *Player) NodeCount() int
- func (p *Player) Pause()
- func (p *Player) Play(animIndex int) error
- func (p *Player) PlayByName(name string) error
- func (p *Player) Playing() bool
- func (p *Player) Pose() Pose
- func (p *Player) Seek(t time.Duration)
- func (p *Player) SetLoop(loop bool)
- func (p *Player) SetSpeed(speed float32)
- func (p *Player) SkinMatrices(skinIndex int) ([]math3d.Mat4, error)
- func (p *Player) SkinMatricesForNode(meshNodeIndex int) ([]math3d.Mat4, error)
- func (p *Player) Speed() float32
- func (p *Player) Step(dt time.Duration)
- func (p *Player) Stop()
- func (p *Player) Time() time.Duration
- func (p *Player) Update(dt time.Duration) Pose
- func (p *Player) WorldTransform(nodeIndex int) math3d.Mat4
- func (p *Player) WorldTransforms() []math3d.Mat4
- type Pose
- func ApplyAdditivePose(base Pose, additive Pose, strength float32, mask *BoneMask) Pose
- func BlendPoses(a, b Pose, t float32) Pose
- func BlendPosesMasked(base, overlay Pose, weight float32, mask *BoneMask) Pose
- func BlendPosesWeighted(poses []Pose, weights []float32) Pose
- func MakeAdditivePose(target Pose, reference Pose) Pose
- func NewPose(jointCount int) Pose
- func StripRootMotion(pose Pose, opts RootMotionOptions) Pose
- type PoseModifierFunc
- type PoseSampler
- type QuatKeyframe
- type RayFunc
- type Rig
- func (r *Rig) BoneIndex(name string) (int, bool)
- func (r *Rig) BoneName(index int) string
- func (r *Rig) Chain(rootName, tipName string) ([]int, bool)
- func (r *Rig) IsDescendant(ancestor, descendant int) bool
- func (r *Rig) JointCount() int
- func (r *Rig) Parent(index int) int
- func (r *Rig) RestPose() Pose
- func (r *Rig) RestTransform(index int) math3d.Transform
- type RootMotion
- type RootMotionOptions
- type SphereCollider
- type SpringBones
- func (s *SpringBones) AddChain(chain SpringChain)
- func (s *SpringBones) AddCollider(c SpringCollider)
- func (s *SpringBones) AddColliderGroup(group string, colliders ...SpringCollider)
- func (s *SpringBones) Apply(pose Pose, modelWorld math3d.Mat4, dt float32) Pose
- func (s *SpringBones) Modifier() Modifier
- func (s *SpringBones) Reset()
- func (s *SpringBones) Rig() *Rig
- func (s *SpringBones) SetWind(wind math3d.Vec3)
- func (s *SpringBones) Wind() math3d.Vec3
- type SpringChain
- type SpringCollider
- type SpringJoint
- type State
- type StateMachine
- func (sm *StateMachine) AddState(state State)
- func (sm *StateMachine) AddTransition(tr Transition)
- func (sm *StateMachine) BlendProgress() float32
- func (sm *StateMachine) CancelTravel()
- func (sm *StateMachine) CurrentState() string
- func (sm *StateMachine) CurrentTime() time.Duration
- func (sm *StateMachine) DrainEvents() []FiredEvent
- func (sm *StateMachine) EventWeightThreshold() float32
- func (sm *StateMachine) IsBlending() bool
- func (sm *StateMachine) OnEvent(fn func(FiredEvent))
- func (sm *StateMachine) Param(name string) float32
- func (sm *StateMachine) Pose() Pose
- func (sm *StateMachine) PreviousState() string
- func (sm *StateMachine) Restart(name string, blendDuration time.Duration) bool
- func (sm *StateMachine) SetEventWeightThreshold(minWeight float32)
- func (sm *StateMachine) SetParam(name string, value float32)
- func (sm *StateMachine) SetState(name string, blendDuration time.Duration) bool
- func (sm *StateMachine) Travel(target string) bool
- func (sm *StateMachine) TravelTarget() string
- func (sm *StateMachine) Update(dt time.Duration) Pose
- type TimeScale
- type TimeSeek
- type Transition
- type TwoBoneIK
- type Vec3Keyframe
Examples ¶
Constants ¶
const EventsSidecarVersion = 1
EventsSidecarVersion is the schema version of the JSON clip events sidecar format written by MarshalEventsSidecar and read by LoadEventsSidecar.
Variables ¶
var ( // ErrNilDocument is returned when a nil *gltf.Document is passed. ErrNilDocument = errors.New("anim3d: nil gltf document") // ErrInvalidAnimation is returned when an animation index is out of range. ErrInvalidAnimation = errors.New("anim3d: animation index out of range") // ErrAnimationNotFound is returned when no animation matches the given name. ErrAnimationNotFound = errors.New("anim3d: animation not found") // ErrInvalidSkin is returned when a skin index or skinned node is out of range. ErrInvalidSkin = errors.New("anim3d: skin index out of range") )
Playback errors returned by glTF clip conversion and Player operations.
var HumanoidBones = []string{"Hips", "Spine", "Chest", "Neck", "Head", "LeftUpperArm", "LeftLowerArm", "LeftHand", "RightUpperArm", "RightLowerArm", "RightHand", "LeftUpperLeg", "LeftLowerLeg", "LeftFoot", "RightUpperLeg", "RightLowerLeg", "RightFoot"}
HumanoidBones names the standard humanoid profile.
Functions ¶
func ApplyRootMotion ¶
func ApplyRootMotion(world math3d.Transform, rm RootMotion) math3d.Transform
ApplyRootMotion advances a character's world transform by rm, transforming rm.DeltaPos by world's current orientation and scale and composing rm.DeltaRot.
func EncodeBoneMap ¶
EncodeBoneMap validates m and writes it as canonical YAML with two-space indentation.
func LoadEventsFromGLTFExtras ¶
LoadEventsFromGLTFExtras parses animation events from a glTF 2.0 JSON document's animations[i].extras.events and/or animations[i].extras.nsgo_events arrays. Each clip's events are returned sorted by ascending Time. Animations without a name fall back to "animation_<index>".
Per glTF 2.0, absent, null, or non-object extras and unrelated keys inside an object extras are ignored. When "events" or "nsgo_events" is present and malformed (wrong type, unknown event field, or duplicate event key), an error is returned instead of dropping the clip's events.
Its errors are *loaderr.Error values that give the line and field (including the animation index) of the problem and how to fix it; a caller that read the document from a file names it with loaderr.WithFile.
func LoadEventsSidecar ¶
LoadEventsSidecar parses a versioned JSON sidecar file produced by MarshalEventsSidecar ({"version": 1, "clips": {...}}) into per-clip event slices sorted by ascending Time.
It requires version == EventsSidecarVersion (1) and refuses unknown fields, duplicate keys, trailing data, and the legacy unversioned flat-map shape.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.
func MarshalEventsSidecar ¶
MarshalEventsSidecar serializes per-clip event lists into a formatted JSON sidecar document ({"version": 1, "clips": {...}}) with each clip's events sorted by ascending Time.
Example ¶
MarshalEventsSidecar writes clip events as a JSON sidecar that LoadEventsSidecar reads back.
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/nsgo-dev/game/pkg/anim3d"
)
func main() {
data, err := anim3d.MarshalEventsSidecar(map[string][]anim3d.ClipEvent{
"walk": {{Time: 0.5, Name: "footstep"}, {Time: 0, Name: "start"}},
})
if err != nil {
fmt.Println(err)
return
}
var compact bytes.Buffer
if err := json.Compact(&compact, data); err != nil {
fmt.Println(err)
return
}
fmt.Println(compact.String())
clips, err := anim3d.LoadEventsSidecar(data)
fmt.Println(len(clips["walk"]), err)
}
Output: {"version":1,"clips":{"walk":[{"time":0,"name":"start"},{"time":0.5,"name":"footstep"}]}} 2 <nil>
func SolveCCD ¶
func SolveCCD(joints []math3d.Vec3, target math3d.Vec3, iterations int, tolerance float32) []math3d.Vec3
SolveCCD solves a multi-joint inverse kinematics chain using Cyclic Coordinate Descent (CCD), sweeping from the joint closest to the end effector back to the root on each iteration.
The root joint joints[0] stays fixed and every bone segment length |joints[i+1] - joints[i]| is preserved. The input slice is not mutated. If iterations <= 0 it defaults to 10; if tolerance <= 0 it defaults to 1e-4.
func SolveFABRIK ¶
func SolveFABRIK(joints []math3d.Vec3, target math3d.Vec3, iterations int, tolerance float32) []math3d.Vec3
SolveFABRIK solves a multi-joint inverse kinematics chain using the iterative FABRIK (Forward And Backward Reaching Inverse Kinematics) algorithm.
The root joint joints[0] stays fixed and every bone segment length |joints[i+1] - joints[i]| is preserved exactly. The input slice is not mutated. If iterations <= 0 it defaults to 10; if tolerance <= 0 it defaults to 1e-4.
Example ¶
SolveFABRIK moves a chain of any length toward a target while its root stays put.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/anim3d"
"github.com/nsgo-dev/game/pkg/math3d"
)
func main() {
chain := []math3d.Vec3{{}, {X: 1}, {X: 2}, {X: 3}}
solved := anim3d.SolveFABRIK(chain, math3d.Vec3{X: 1, Y: 2}, 20, 1e-4)
last := solved[len(solved)-1]
fmt.Printf("root (%.0f, %.0f) tip (%.2f, %.2f)\n", solved[0].X, solved[0].Y, last.X, last.Y)
}
Output: root (0, 0) tip (1.00, 2.00)
func SolveTwoBoneIK ¶
func SolveTwoBoneIK(root, mid, end, target, pole math3d.Vec3) (newMid, newEnd math3d.Vec3, rootRot, midRot math3d.Quat)
SolveTwoBoneIK analytically solves a two-bone inverse kinematics chain (root -> mid -> end) to place the end effector as close as possible to target while bending the hinge joint toward the pole target position in the root-target-pole plane.
Bone lengths |mid - root| and |end - mid| are preserved exactly. Unreachable targets (farther than l1+l2 or closer than |l1-l2|) are clamped cleanly along the root-to-target axis without NaN or stretching. When one bone has zero length the other bone alone is aimed at the target; when both do, the chain is returned unchanged.
Returned delta rotations satisfy:
- root.Add(rootRot.RotateVec3(mid.Sub(root))) == newMid
- newMid.Add(midRot.Mul(rootRot).RotateVec3(end.Sub(mid))) == newEnd
Example ¶
SolveTwoBoneIK bends an arm or leg so its end reaches the target, keeping both bone lengths.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/anim3d"
"github.com/nsgo-dev/game/pkg/math3d"
)
func main() {
root := math3d.Vec3Zero()
mid := math3d.Vec3{Y: -1}
end := math3d.Vec3{Y: -2}
target := math3d.Vec3{X: 1, Y: -1}
pole := math3d.Vec3{Z: -1} // the knee bends forward
newMid, newEnd, _, _ := anim3d.SolveTwoBoneIK(root, mid, end, target, pole)
fmt.Printf("end (%.2f, %.2f)\n", newEnd.X, newEnd.Y)
fmt.Printf("bones %.2f %.2f\n", newMid.Dist(root), newEnd.Dist(newMid))
}
Output: end (1.00, -1.00) bones 1.00 1.00
func SortClipEvents ¶
func SortClipEvents(events []ClipEvent)
SortClipEvents stably sorts events in place by ascending Time.
Types ¶
type AddNode ¶
type AddNode struct {
Base PoseSampler
Add PoseSampler
Clip *Clip
ReferencePose *Pose
Amount float32
Mask *BoneMask
Loop bool
Speed float32 // playback speed multiplier when using Clip; 0 defaults to 1.0
// contains filtered or unexported fields
}
AddNode applies an additive pose (from Add or Clip, optionally made relative to ReferencePose via MakeAdditivePose) on top of Base at Amount in [0, 1], optionally restricted by Mask. When Base is nil, AddNode evaluates to the additive delta pose itself so it can be placed inside an additive LayerStack layer.
func NewAddNode ¶
func NewAddNode(base, add PoseSampler, ref *Pose, amount float32) *AddNode
NewAddNode creates an AddNode that applies add (relative to ref when non-nil) onto base at amount in [0, 1].
func (*AddNode) Reset ¶
func (a *AddNode) Reset()
Reset rewinds Clip playback and resets Base and Add if they implement Reset.
type AnimLayer ¶
type AnimLayer struct {
Name string
Mode LayerBlendMode
Weight float32
Mask *BoneMask
Clip *Clip
ReferencePose *Pose
Sampler PoseSampler
Time float32 // playback time in seconds when using Clip
Loop bool
Speed float32 // playback speed multiplier; 0 defaults to 1.0
}
AnimLayer configures a single layer inside a LayerStack.
If Sampler is non-nil, it drives the layer's pose and time advancement; otherwise Clip is sampled at Time (in seconds) with Loop and Speed. For LayerAdditive layers, if ReferencePose is non-nil, MakeAdditivePose is computed relative to ReferencePose; if nil, the sampled pose is treated as an already-delta additive pose (equivalently, relative to identity).
When a layer plays a Clip, only the joints the clip has a track for take part: an override layer leaves the other joints at the pose below it, and an additive layer adds nothing to them.
type BlendNode ¶
type BlendNode struct {
A PoseSampler
B PoseSampler
Weight float32
Mask *BoneMask
}
BlendNode blends two PoseSamplers A and B by Weight in [0, 1], optionally restricted per joint by Mask.
func NewBlendNode ¶
func NewBlendNode(a, b PoseSampler, weight float32) *BlendNode
NewBlendNode creates a BlendNode interpolating from a (weight 0) to b (weight 1).
type BlendSample1D ¶
type BlendSample1D struct {
Param float32
Clip *Clip
FootPhaseOffset float32 // normalized in [0, 1)
}
BlendSample1D binds a clip and normalized foot-phase offset to a scalar parameter position in a BlendSpace1D.
type BlendSample2D ¶
type BlendSample2D struct {
X, Y float32
Clip *Clip
FootPhaseOffset float32 // normalized in [0, 1)
}
BlendSample2D binds a clip and normalized foot-phase offset to a 2D point (e.g. speed/direction or strafe/forward) in a BlendSpace2D.
type BlendSpace1D ¶
type BlendSpace1D struct {
// ParamName optionally names a StateMachine parameter to read when attached
// to a State without an explicit State.ParamName.
ParamName string
// Speed multiplies phase progression rate; 0 defaults to 1.0.
Speed float32
// contains filtered or unexported fields
}
BlendSpace1D blends N clips sorted along a single scalar parameter with foot-phase synchronization across clips of different durations.
Example ¶
A BlendSpace1D weighs the clips on either side of its parameter, here walk and run by speed.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/anim3d"
"github.com/nsgo-dev/game/pkg/math3d"
)
// slide returns a one-joint clip that moves joint 0 along +X from 0 to dist over d.
func slide(name string, d time.Duration, dist float32, loop bool) *anim3d.Clip {
return &anim3d.Clip{
Name: name, Duration: d, Loop: loop, JointCount: 1,
Tracks: []anim3d.JointTrack{{
JointIndex: 0,
Translations: []anim3d.Vec3Keyframe{
{Time: 0, Value: math3d.Vec3Zero()},
{Time: d, Value: math3d.Vec3{X: dist}},
},
}},
}
}
func main() {
bs := anim3d.NewBlendSpace1D(
anim3d.BlendSample1D{Param: 0, Clip: slide("idle", time.Second, 0, true)},
anim3d.BlendSample1D{Param: 2, Clip: slide("walk", time.Second, 1, true)},
anim3d.BlendSample1D{Param: 6, Clip: slide("run", 500*time.Millisecond, 1, true)},
)
for _, speed := range []float32{1, 2, 4} {
fmt.Printf("speed %v: %.2f\n", speed, bs.Weights(speed))
}
}
Output: speed 1: [0.50 0.50 0.00] speed 2: [0.00 1.00 0.00] speed 4: [0.00 0.50 0.50]
func NewBlendSpace1D ¶
func NewBlendSpace1D(samples ...BlendSample1D) *BlendSpace1D
NewBlendSpace1D creates a 1D blend space with samples sorted by ascending Param.
func (*BlendSpace1D) CycleSpeed ¶
func (bs *BlendSpace1D) CycleSpeed(param float32) float32
CycleSpeed returns the weighted normalized cycle speed sum(w_i / dur_i) in cycles per second at param.
func (*BlendSpace1D) Evaluate ¶
func (bs *BlendSpace1D) Evaluate(param float32, phase float32) Pose
Evaluate samples the blend space at param and normalized phase without mutating internal state.
func (*BlendSpace1D) Param ¶
func (bs *BlendSpace1D) Param() float32
Param returns the current scalar parameter.
func (*BlendSpace1D) Phase ¶
func (bs *BlendSpace1D) Phase() float32
Phase returns the current normalized cycle phase in [0, 1).
func (*BlendSpace1D) Pose ¶
func (bs *BlendSpace1D) Pose() Pose
Pose evaluates the blend space at its current Param and Phase without advancing time.
func (*BlendSpace1D) Reset ¶
func (bs *BlendSpace1D) Reset()
Reset resets the normalized cycle phase back to 0.
func (*BlendSpace1D) Samples ¶
func (bs *BlendSpace1D) Samples() []BlendSample1D
Samples returns a copy of the sorted samples in the blend space.
func (*BlendSpace1D) SetParam ¶
func (bs *BlendSpace1D) SetParam(value float32)
SetParam updates the active scalar parameter used by Update and Pose.
func (*BlendSpace1D) SetPhase ¶
func (bs *BlendSpace1D) SetPhase(phase float32)
SetPhase sets the normalized cycle phase (wrapped into [0, 1)).
func (*BlendSpace1D) Update ¶
func (bs *BlendSpace1D) Update(dt time.Duration) Pose
Update advances the synchronized foot phase by dt using the weighted cycle speed at the current Param and returns the evaluated Pose.
func (*BlendSpace1D) Weights ¶
func (bs *BlendSpace1D) Weights(param float32) []float32
Weights computes the normalized blend weights for param (clamped at endpoints). Samples that share the same Param split that position's weight equally.
type BlendSpace2D ¶
type BlendSpace2D struct {
// ParamXName and ParamYName optionally name StateMachine parameters to read
// when attached to a State without explicit State.ParamXName / ParamYName.
ParamXName string
ParamYName string
// Speed multiplies phase progression rate; 0 defaults to 1.0.
Speed float32
// contains filtered or unexported fields
}
BlendSpace2D blends N clips in a 2D parameter space using Cartesian gradient-band interpolation with normalized weights and foot-phase synchronization.
func NewBlendSpace2D ¶
func NewBlendSpace2D(samples ...BlendSample2D) *BlendSpace2D
NewBlendSpace2D creates a 2D blend space from the given samples.
func (*BlendSpace2D) CycleSpeed ¶
func (bs *BlendSpace2D) CycleSpeed(x, y float32) float32
CycleSpeed returns the weighted normalized cycle speed sum(w_i / dur_i) in cycles per second at (x, y).
func (*BlendSpace2D) Evaluate ¶
func (bs *BlendSpace2D) Evaluate(x, y, phase float32) Pose
Evaluate samples the 2D blend space at (x, y) and normalized phase without mutating internal state.
func (*BlendSpace2D) Params ¶
func (bs *BlendSpace2D) Params() (x, y float32)
Params returns the current (X, Y) coordinates.
func (*BlendSpace2D) Phase ¶
func (bs *BlendSpace2D) Phase() float32
Phase returns the current normalized cycle phase in [0, 1).
func (*BlendSpace2D) Pose ¶
func (bs *BlendSpace2D) Pose() Pose
Pose evaluates the 2D blend space at its current (X, Y) and Phase without advancing time.
func (*BlendSpace2D) Reset ¶
func (bs *BlendSpace2D) Reset()
Reset resets the normalized cycle phase back to 0.
func (*BlendSpace2D) Samples ¶
func (bs *BlendSpace2D) Samples() []BlendSample2D
Samples returns a copy of the samples in the 2D blend space.
func (*BlendSpace2D) SetParams ¶
func (bs *BlendSpace2D) SetParams(x, y float32)
SetParams updates the active (X, Y) coordinates used by Update and Pose.
func (*BlendSpace2D) SetPhase ¶
func (bs *BlendSpace2D) SetPhase(phase float32)
SetPhase sets the normalized cycle phase (wrapped into [0, 1)).
func (*BlendSpace2D) Update ¶
func (bs *BlendSpace2D) Update(dt time.Duration) Pose
Update advances the synchronized foot phase by dt using the weighted cycle speed at the current (X, Y) and returns the evaluated Pose.
func (*BlendSpace2D) Weights ¶
func (bs *BlendSpace2D) Weights(x, y float32) []float32
Weights computes smooth normalized Cartesian gradient-band weights summing to 1 for query point (x, y). At any sample's exact position, that sample receives weight 1 (or equal shares if duplicate sample coordinates exist).
type BoneDesc ¶
type BoneDesc struct {
// Name is the bone's unique lookup name. Unnamed bones are allowed and still
// participate in the hierarchy by index.
Name string
// Parent is the parent joint's index, or -1 for a root joint.
Parent int
// Rest is the joint's local rest (bind) TRS transform. A zero Scale or zero
// Rotation defaults to identity when NewRigFromBones normalizes the rig.
Rest math3d.Transform
}
BoneDesc describes one joint when constructing a Rig programmatically without a glTF document (see NewRigFromBones).
type BoneMap ¶
type BoneMap struct {
Type string `yaml:"type"`
Version int `yaml:"version"`
Profile string `yaml:"profile"`
Bones map[string]string `yaml:"bones"`
}
BoneMap maps the bones of a humanoid profile, by role name such as "Hips" or "LeftHand", to the bone names of one model's rig, so animations authored for the profile drive the model. It is a YAML file of type boneMap and version 1.
func DecodeBoneMap ¶
DecodeBoneMap reads a bone map from YAML, refusing unknown fields and a second document, and validates it. Its errors are *loaderr.Error values with the line and field at fault.
func GuessBoneMap ¶
GuessBoneMap proposes a humanoid map from bone names such as Mixamo's ("mixamorig:LeftHand") or side-suffixed ones ("hand_l", "Hand.R"), and reports the profile's roles it could not map, sorted. A role is mapped only to a bone on the same side, a bone whose name equals the role is preferred to one that merely contains it, and otherwise the first matching name wins.
type BoneMask ¶
type BoneMask struct {
Weights []float32
}
BoneMask stores per-joint blend weights in [0, 1] used to restrict an animation layer or additive pose to a subset of joints (e.g. upper body).
Example ¶
A BoneMask limits a blend to a branch of the skeleton, such as the upper body.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/anim3d"
"github.com/nsgo-dev/game/pkg/math3d"
)
func main() {
// Joint 0 is the hips; 1 the spine and 2 the arm under it; 3 a leg.
parents := []int{-1, 0, 1, 0}
mask := anim3d.NewBoneMask(4, 0)
mask.SetBranch(parents, 1, 1)
base := anim3d.NewPose(4)
wave := anim3d.NewPose(4)
for i := range wave.Joints {
wave.Joints[i].Pos = math3d.Vec3{Y: 1}
}
out := anim3d.BlendPosesMasked(base, wave, 1, mask)
for i, j := range out.Joints {
fmt.Printf("joint %d: y=%.0f\n", i, j.Pos.Y)
}
}
Output: joint 0: y=0 joint 1: y=1 joint 2: y=1 joint 3: y=0
func NewBoneMask ¶
NewBoneMask creates a BoneMask for jointCount joints initialized to defaultWeight (clamped to [0, 1]).
func (*BoneMask) SetBranch ¶
SetBranch sets the blend weight (clamped to [0, 1]) for rootJoint and all of its descendants according to parents, where parents[j] is the parent joint index of joint j (or < 0 for root joints).
type CapsuleCollider ¶
type CapsuleCollider struct {
Bone string
Offset math3d.Vec3
Tail math3d.Vec3
Radius float32
Inside bool
// Group assigns this collider to a named collider group. When empty, the
// collider is global and collides with every chain.
Group string
}
CapsuleCollider is a capsule segment from Offset to Tail in Bone's local space (or the model root when Bone is empty). When Inside is true, joints are kept inside the capsule rather than pushed outside it.
type ChainIK ¶
type ChainIK struct {
// Root names the fixed ancestor bone at the base of the chain.
Root string
// Tip names the end-effector bone to pull toward its target.
Tip string
// Solver selects FABRIK (default) or CCD.
Solver IKSolver
// Iterations is the maximum number of solver sweeps (defaults to 10 when <= 0).
Iterations int
// Tolerance stops early once the tip is within this world-space distance of
// the target (defaults to 1e-4 when <= 0).
Tolerance float32
// Limits specifies optional per-bone rotation limits relative to rest pose.
Limits []JointLimit
// contains filtered or unexported fields
}
ChainIK solves an arbitrary ancestor-to-descendant chain (Root .. Tip) using FABRIK or CCD with optional per-joint angular limits, writing local rotations that preserve bone twist.
Set the end-effector target via ModifierStack.SetTarget(Tip, targetWorld).
func (*ChainIK) Apply ¶
func (c *ChainIK) Apply(pose *Pose, ctx *ModifierContext)
Apply solves the chain toward the target set on Tip.
type Clip ¶
type Clip struct {
Name string
Duration time.Duration
Loop bool
JointCount int
Tracks []JointTrack
Events []ClipEvent
}
Clip is a keyframed 3D skeletal animation clip.
func ClipFromGLTF ¶
ClipFromGLTF converts doc.Animations[animIndex] into an anim3d.Clip whose JointTrack indices match doc.Nodes indices (0..len(doc.Nodes)-1).
For every node targeted by the animation, any TRS component not driven by a channel is seeded from that node's rest transform in doc so sampling preserves bone offsets and bind orientations. Untargeted nodes are omitted from Tracks so BoneMask and LayerStack overrides leave them untouched.
CUBICSPLINE channels extract their keyframe values; use Player directly when exact STEP or CUBICSPLINE interpolation, morph target weights, or per-node world and skin joint matrices are needed. Any timed events stored in the animation's glTF extras (see LoadEventsFromGLTFExtras) are attached to the returned Clip; malformed "events" or "nsgo_events" entries return a *loaderr.Error instead of being dropped. Loop defaults to false.
func ClipsFromGLTF ¶
ClipsFromGLTF converts every animation in doc into an anim3d.Clip in document order.
func (*Clip) AddEvent ¶
AddEvent appends ev to the clip's Events slice and keeps Events sorted by Time.
func (*Clip) NormalizeTime ¶
NormalizeTime maps t into the clip's playable range: wrapped into [0, Duration) when Loop is true, or clamped to [0, Duration] otherwise.
func (*Clip) Sample ¶
Sample evaluates the clip at time t and returns the resulting Pose. Translations and scales are linearly interpolated; rotations use Quat.Slerp.
Example ¶
A Clip is sampled at any time; translations between keyframes are interpolated.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/anim3d"
"github.com/nsgo-dev/game/pkg/math3d"
)
// slide returns a one-joint clip that moves joint 0 along +X from 0 to dist over d.
func slide(name string, d time.Duration, dist float32, loop bool) *anim3d.Clip {
return &anim3d.Clip{
Name: name, Duration: d, Loop: loop, JointCount: 1,
Tracks: []anim3d.JointTrack{{
JointIndex: 0,
Translations: []anim3d.Vec3Keyframe{
{Time: 0, Value: math3d.Vec3Zero()},
{Time: d, Value: math3d.Vec3{X: dist}},
},
}},
}
}
func main() {
clip := slide("walk", time.Second, 2, true)
for _, t := range []time.Duration{0, 250 * time.Millisecond, 1250 * time.Millisecond} {
pose := clip.Sample(t)
fmt.Printf("%v: x=%.2f\n", t, pose.Joints[0].Pos.X)
}
}
Output: 0s: x=0.00 250ms: x=0.50 1.25s: x=0.50
type ClipEvent ¶
type ClipEvent struct {
Time float32 `json:"time"`
Name string `json:"name"`
Payload string `json:"payload,omitempty"`
Data map[string]any `json:"data,omitempty"`
}
ClipEvent marks a named gameplay or audio event at a specific time (in seconds) within an animation Clip.
func CollectClipEvents ¶
func CollectClipEvents(events []ClipEvent, prevTime, nextTime, duration float32, loop bool) []ClipEvent
CollectClipEvents returns all events from events that trigger while advancing clip playback from prevTime to nextTime (both in seconds) for a clip of length duration (in seconds).
Events fire strictly once per playback across normal steps, multi-frame skips (including spans exceeding duration), and loop wrap-arounds. Both wrapped playback timestamps (nextTime < prevTime when loop is true) and unwrapped monotonic timestamps (nextTime >= duration) are handled cleanly.
Boundary semantics prevent double-firing at loop seams:
- Events at Time == 0 fire on [prev, next) (i.e. at loop start when playback advances past 0 or crosses a loop boundary into the new loop).
- Events at 0 < Time <= duration fire on (prev, next] (i.e. on the step that reaches or crosses Time, including Time == duration at loop end).
Example ¶
CollectClipEvents finds the events crossed by one playback step, including across a loop's end.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/anim3d"
)
func main() {
events := []anim3d.ClipEvent{{Time: 0.25, Name: "left"}, {Time: 0.75, Name: "right"}}
for _, e := range anim3d.CollectClipEvents(events, 0.6, 1.3, 1, true) {
fmt.Println(e.Name)
}
}
Output: right left
type EventDispatcher ¶
type EventDispatcher struct {
// contains filtered or unexported fields
}
EventDispatcher collects FiredEvents and dispatches them to registered callbacks and an internal queue drained via Drain.
Example ¶
An EventDispatcher queues fired events for the game to drain each frame.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/anim3d"
"github.com/nsgo-dev/game/pkg/math3d"
)
// slide returns a one-joint clip that moves joint 0 along +X from 0 to dist over d.
func slide(name string, d time.Duration, dist float32, loop bool) *anim3d.Clip {
return &anim3d.Clip{
Name: name, Duration: d, Loop: loop, JointCount: 1,
Tracks: []anim3d.JointTrack{{
JointIndex: 0,
Translations: []anim3d.Vec3Keyframe{
{Time: 0, Value: math3d.Vec3Zero()},
{Time: d, Value: math3d.Vec3{X: dist}},
},
}},
}
}
func main() {
clip := slide("attack", time.Second, 0, false)
clip.AddEvent(anim3d.ClipEvent{Time: 0.4, Name: "hit", Payload: "sword"})
d := anim3d.NewEventDispatcher()
d.DispatchClip(clip, "attack", 0, 0.5, 1)
for _, e := range d.Drain() {
fmt.Println(e.Clip, e.Event.Name, e.Event.Payload)
}
fmt.Println(len(d.Pending()))
}
Output: attack hit sword 0
func NewEventDispatcher ¶
func NewEventDispatcher() *EventDispatcher
NewEventDispatcher creates an empty EventDispatcher.
func (*EventDispatcher) Clear ¶
func (d *EventDispatcher) Clear()
Clear discards all queued FiredEvents.
func (*EventDispatcher) DispatchClip ¶
func (d *EventDispatcher) DispatchClip(clip *Clip, stateName string, prevTime, nextTime, weight float32) []FiredEvent
DispatchClip collects events on clip in the interval [prevTime, nextTime] (in seconds), wraps each as a FiredEvent with stateName and weight, emits them through d, and returns the fired slice.
func (*EventDispatcher) Drain ¶
func (d *EventDispatcher) Drain() []FiredEvent
Drain returns all queued FiredEvents since the last Drain and clears the queue.
func (*EventDispatcher) Emit ¶
func (d *EventDispatcher) Emit(ev FiredEvent)
Emit appends ev to the pending queue and notifies all registered listeners.
func (*EventDispatcher) OnEvent ¶
func (d *EventDispatcher) OnEvent(fn func(FiredEvent))
OnEvent registers a listener invoked synchronously whenever an event is emitted.
func (*EventDispatcher) Pending ¶
func (d *EventDispatcher) Pending() []FiredEvent
Pending returns a copy of queued FiredEvents without clearing the queue.
type FiredEvent ¶
FiredEvent records a ClipEvent emitted during animation playback along with the state name, clip name, and active blend weight at the time it fired.
type FootConfig ¶
type FootConfig struct {
// Foot names the ankle/foot tip bone.
Foot string
// UpperLeg optionally names the thigh/hip bone. If empty, inferred as the
// grandparent of Foot in the rig.
UpperLeg string
// LowerLeg optionally names the shin/knee bone. If empty, inferred as the
// parent of Foot in the rig.
LowerLeg string
// PoleBone optionally names the knee pole bone.
PoleBone string
// FootHeight is the vertical offset from ground surface to the Foot bone
// pivot. When zero, FootPlacement.FootHeight is used.
FootHeight float32
}
FootConfig configures one foot/leg chain inside a multi-foot FootPlacement.
type FootPlacement ¶
type FootPlacement struct {
// Foot names a single foot bone. For multi-foot characters sharing one
// pelvis offset, populate Feet (if both are set, Foot is evaluated first).
Foot string
// Feet configures multiple foot chains sharing one pelvis adjustment.
Feet []FootConfig
// Pelvis names the pelvis/hips bone to raise or lower. If empty, it is
// inferred from the parent of the leg root bone(s).
Pelvis string
// UpperLeg and LowerLeg optionally specify the two-bone chain for Foot.
// If empty, they are inferred as grandparent and parent of Foot.
UpperLeg string
LowerLeg string
// PoleBone optionally names the knee pole bone for Foot.
PoleBone string
// Ray casts a world-space segment from above each foot to below it and
// returns (hitPoint, surfaceNormal, hit).
Ray RayFunc
// RayUp is the distance above the animated foot where the ray begins.
// Defaults to 0.5 when <= 0.
RayUp float32
// RayDown is the distance below the animated foot that the ray extends.
// Defaults to 0.5 when <= 0.
RayDown float32
// FootHeight is the default vertical offset from the ground surface to the
// foot bone pivot.
FootHeight float32
// MaxPelvisOffset limits how far the pelvis shifts vertically (world units).
// Defaults to 0.5 when <= 0.
MaxPelvisOffset float32
// MaxFootTilt limits how far each foot tilts to match the surface normal
// (radians). Defaults to 0.7 (~40 degrees) when <= 0.
MaxFootTilt float32
// Up is the world up direction. Defaults to math3d.Vec3Up() when zero.
Up math3d.Vec3
// contains filtered or unexported fields
}
FootPlacement adapts a character's pelvis height, legs, and feet to uneven ground (stairs, slopes, ledges) using a caller-provided Ray callback, with no dependency on physics3d.
func (*FootPlacement) Apply ¶
func (fp *FootPlacement) Apply(pose *Pose, ctx *ModifierContext)
Apply casts ground rays for each foot, adjusts pelvis height, solves leg IK, and aligns each foot's orientation to the ground surface normal.
type Graph ¶
type Graph struct {
// contains filtered or unexported fields
}
Graph is a runtime 3D animation graph instantiated from a *resource.AnimGraph and bound to a *gltf.Document's animations and skin hierarchy.
Parameters can be set by their declared name ("speed", "airborne", "attack") or by path ("parameters/speed", "parameters/locomotion/blend_position", "parameters/upper/weight", "parameters/upper/fire").
func BuildGraph ¶
BuildGraph validates ag and binds it to doc's clips and skeleton. Errors are *loaderr.Error values naming the field path at fault.
func LoadGraph ¶
LoadGraph loads the animgraph resource at path from lib, resolves every clip by glTF animation name and every bone mask through doc's skin (or node hierarchy when doc has no skins), compiles transition conditions with animclip.CompileCondition, and returns the ready-to-update Graph.
Any schema, clip, bone, or parameter error is returned as a *loaderr.Error naming path and the line and column of the offending field when available.
func ParseGraph ¶
ParseGraph parses raw YAML bytes as an animgraph resource and binds it to doc, locating any schema, clip, bone, or parameter error to its line and column in data.
func (*Graph) ApplyModifiers ¶
ApplyModifiers synchronizes modifier influence parameters and applies the graph's modifier stack to pose under modelWorld for step dt. If the graph declares no modifiers, pose is returned unchanged.
func (*Graph) Bool ¶
Bool returns the current value of bool parameter name, or false when unset or unknown.
func (*Graph) CurrentState ¶
CurrentState returns the active state of the first machine layer, or "" when the graph has no machine layers.
func (*Graph) DrainEvents ¶
func (g *Graph) DrainEvents() []FiredEvent
DrainEvents returns all FiredEvents collected across all machine layers since the last DrainEvents call.
func (*Graph) Float ¶
Float returns the current value of float parameter name (or path), or 0 when unset or unknown.
func (*Graph) LayerStack ¶
func (g *Graph) LayerStack() *LayerStack
LayerStack returns the underlying *LayerStack evaluated by the graph.
func (*Graph) LayerState ¶
LayerState returns the active state of the named machine layer, or "".
func (*Graph) Machine ¶
func (g *Graph) Machine(layer string) *StateMachine
Machine returns the underlying *StateMachine for the named layer, or nil.
func (*Graph) Modifiers ¶
func (g *Graph) Modifiers() *ModifierStack
Modifiers returns the *ModifierStack instantiated from the graph's optional modifiers section, or nil when the graph declares no modifiers.
func (*Graph) OnEvent ¶
func (g *Graph) OnEvent(fn func(FiredEvent))
OnEvent registers a callback invoked synchronously whenever any machine layer fires an animation event during Update.
func (*Graph) SetBool ¶
SetBool sets a declared bool parameter by name (or "parameters/<name>"). Unknown or non-bool names are ignored.
func (*Graph) SetFloat ¶
SetFloat sets a float parameter by its declared name (e.g. "speed") or by path (e.g. "parameters/speed", "parameters/locomotion/blend_position", "parameters/locomotion/blend_position.x", "parameters/upper/weight", "parameters/base/time_scale", "parameters/base/time_seek", "parameters/recoil/add_amount", "parameters/mix/blend_amount"). Non-finite values and unknown names are ignored.
func (*Graph) SetFootPlacementRay ¶
SetFootPlacementRay attaches a ground ray-cast callback to every FootPlacement modifier declared in the graph.
func (*Graph) SetModifierInfluence ¶
SetModifierInfluence overrides the influence weight of modifier index on the graph's modifier stack, taking precedence over any YAML influenceParam.
func (*Graph) SetModifierPoleTarget ¶
SetModifierPoleTarget assigns an explicit world-space pole position to bone on the graph's modifier stack. It is a no-op if the graph has no modifiers.
func (*Graph) SetModifierTarget ¶
SetModifierTarget assigns a world-space target position to bone on the graph's modifier stack. It is a no-op if the graph has no modifiers.
func (*Graph) SetSpringWind ¶
SetSpringWind sets the external world-space wind force vector on every SpringBones modifier declared in the graph.
func (*Graph) Travel ¶
Travel requests the first machine layer containing state to travel along its shortest transition path to state. It returns false if no machine layer has a transition path to state.
func (*Graph) TravelLayer ¶
TravelLayer requests the named machine layer to travel to state along its shortest transition path.
func (*Graph) Trigger ¶
Trigger pulses a declared trigger parameter by name (or "parameters/<name>" or "parameters/<layer>/fire"). Triggers are consumed by transitions and one-shot layers on the next Update(dt) with dt > 0, then cleared automatically.
type IKSolver ¶
type IKSolver int
IKSolver selects the multi-joint solver used by ChainIK.
const ( // FABRIK solves the chain using Forward And Backward Reaching Inverse // Kinematics (SolveFABRIK math) and converts solved positions to local // rotations preserving bone twist. FABRIK IKSolver = iota // CCD solves the chain using Cyclic Coordinate Descent directly on local // rotations, enforcing JointLimit constraints at every iteration. CCD )
type JointLimit ¶
type JointLimit struct {
// Bone names the constrained joint inside the ChainIK chain.
Bone string
// Axis optionally specifies a local hinge axis. When non-zero, the joint's
// rotation around Axis is clamped to [MinAngle, MaxAngle] (pure hinge).
// When zero, the total swing angle from rest is clamped to [max(0, MinAngle), MaxAngle].
Axis math3d.Vec3
// MinAngle is the minimum rotation angle in radians.
MinAngle float32
// MaxAngle is the maximum rotation angle in radians.
MaxAngle float32
}
JointLimit restricts a joint's local rotation relative to its rest rotation in a ChainIK modifier.
type JointTrack ¶
type JointTrack struct {
JointIndex int
Translations []Vec3Keyframe
Rotations []QuatKeyframe
Scales []Vec3Keyframe
}
JointTrack stores keyframed local TRS channels for a single joint. Keyframes in each channel must be ordered by ascending Time. Any empty channel falls back to the corresponding identity component.
type LayerBlendMode ¶
type LayerBlendMode int
LayerBlendMode controls how an AnimLayer combines with lower layers in a LayerStack.
const ( // LayerOverride blends the layer pose over the accumulated pose using // linear interpolation for translation/scale and Slerp for rotation. LayerOverride LayerBlendMode = iota // LayerAdditive applies the layer pose as an additive delta over the // accumulated pose. LayerAdditive )
type LayerStack ¶
type LayerStack struct {
// contains filtered or unexported fields
}
LayerStack composes multiple ordered AnimLayers (base locomotion, masked upper-body overrides, and parameterized additive layers) into a single Pose.
Example ¶
A LayerStack composes a base layer with weighted layers above it.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/anim3d"
"github.com/nsgo-dev/game/pkg/math3d"
)
// slide returns a one-joint clip that moves joint 0 along +X from 0 to dist over d.
func slide(name string, d time.Duration, dist float32, loop bool) *anim3d.Clip {
return &anim3d.Clip{
Name: name, Duration: d, Loop: loop, JointCount: 1,
Tracks: []anim3d.JointTrack{{
JointIndex: 0,
Translations: []anim3d.Vec3Keyframe{
{Time: 0, Value: math3d.Vec3Zero()},
{Time: d, Value: math3d.Vec3{X: dist}},
},
}},
}
}
func main() {
stack := anim3d.NewLayerStack(1)
stack.AddLayer(anim3d.AnimLayer{Name: "base", Weight: 1, Clip: slide("walk", time.Second, 2, true), Loop: true})
stack.AddLayer(anim3d.AnimLayer{Name: "lean", Mode: anim3d.LayerAdditive, Weight: 0.5, Clip: slide("lean", time.Second, 1, false)})
stack.Update(500 * time.Millisecond)
fmt.Printf("x=%.2f\n", stack.Pose().Joints[0].Pos.X)
stack.SetLayerWeight("lean", 0)
fmt.Printf("x=%.2f\n", stack.Evaluate().Joints[0].Pos.X)
}
Output: x=1.25 x=1.00
func NewLayerStack ¶
func NewLayerStack(jointCount int) *LayerStack
NewLayerStack creates an empty LayerStack targeting skeletons with jointCount joints.
func (*LayerStack) AddLayer ¶
func (ls *LayerStack) AddLayer(layer AnimLayer)
AddLayer appends a layer to the top of the stack.
func (*LayerStack) Evaluate ¶
func (ls *LayerStack) Evaluate() Pose
Evaluate composes all active layers at their current times without advancing playback.
func (*LayerStack) Layer ¶
func (ls *LayerStack) Layer(name string) *AnimLayer
Layer returns a pointer to the first layer matching name, or nil if not found.
func (*LayerStack) LayerWeight ¶
func (ls *LayerStack) LayerWeight(name string) float32
LayerWeight returns the current Weight of the named layer, or 0 if not found.
func (*LayerStack) Pose ¶
func (ls *LayerStack) Pose() Pose
Pose evaluates the composed layer stack without advancing time (implements PoseSampler).
func (*LayerStack) RemoveLayer ¶
func (ls *LayerStack) RemoveLayer(name string) bool
RemoveLayer removes the first layer matching name. It returns true if removed.
func (*LayerStack) SetLayerWeight ¶
func (ls *LayerStack) SetLayerWeight(name string, weight float32) bool
SetLayerWeight updates the Weight of the named layer (clamped to [0, 1]). It returns false if no layer with name exists.
type LookAt ¶
type LookAt struct {
// Bone names the skeleton joint to aim (e.g. "Head" or "Turret").
Bone string
// Forward is the bone's local forward direction. Defaults to
// math3d.Vec3Forward() (0, 0, -1) when zero or non-finite.
Forward math3d.Vec3
// Up is the bone's local reference up direction for yaw/pitch decomposition.
// Defaults to math3d.Vec3Up() (0, 1, 0) orthogonalized against Forward.
Up math3d.Vec3
// MaxYaw is the maximum horizontal rotation in radians around the bone's up
// axis (in (0, π]). A value <= 0 imposes no yaw limit.
MaxYaw float32
// MaxPitch is the maximum vertical elevation in radians (in (0, π/2]). A
// value <= 0 imposes no pitch limit.
MaxPitch float32
// Smooth is the exponential damping rate in 1/s for smooth tracking.
// A value <= 0 snaps immediately to the clamped aim direction.
Smooth float32
// contains filtered or unexported fields
}
LookAt rotates a single bone so its local Forward axis aims toward the world-space target assigned via ModifierStack.SetTarget(Bone, targetWorld), clamped to MaxYaw and MaxPitch while preserving bone twist.
func (*LookAt) Apply ¶
func (l *LookAt) Apply(pose *Pose, ctx *ModifierContext)
Apply rotates l.Bone toward its world-space target within MaxYaw and MaxPitch.
type Modifier ¶
type Modifier interface {
Apply(pose *Pose, ctx *ModifierContext)
}
Modifier applies a post-animation pose correction using the rig, world-space forward kinematics cache, targets, and step delta provided by ctx.
type ModifierContext ¶
type ModifierContext struct {
// contains filtered or unexported fields
}
ModifierContext provides read/write access to the rig, cached world-space joint transforms, targets, model transform, and step delta time during ModifierStack evaluation.
ModifierContext is owned by ModifierStack and reused across Apply calls.
func (*ModifierContext) DeltaTime ¶
func (c *ModifierContext) DeltaTime() float32
DeltaTime returns the step duration in seconds for the current Apply call.
func (*ModifierContext) MarkDirty ¶
func (c *ModifierContext) MarkDirty()
MarkDirty invalidates the cached world-space forward kinematics so the next query or modifier recomputes world transforms from the updated Pose.
func (*ModifierContext) ModelWorld ¶
func (c *ModifierContext) ModelWorld() math3d.Mat4
ModelWorld returns the character's world-space root matrix passed to Apply.
func (*ModifierContext) PoleTarget ¶
func (c *ModifierContext) PoleTarget(boneIndex int) (math3d.Vec3, bool)
PoleTarget returns the explicit world-space pole target assigned to joint boneIndex, if any.
func (*ModifierContext) Rig ¶
func (c *ModifierContext) Rig() *Rig
Rig returns the skeleton Rig bound to the ModifierStack, or nil.
func (*ModifierContext) Target ¶
func (c *ModifierContext) Target(boneIndex int) (math3d.Vec3, bool)
Target returns the world-space target assigned to joint boneIndex, if any.
func (*ModifierContext) TargetByName ¶
func (c *ModifierContext) TargetByName(bone string) (math3d.Vec3, bool)
TargetByName returns the world-space target assigned to the named bone, if any.
func (*ModifierContext) WorldMatrix ¶
func (c *ModifierContext) WorldMatrix(pose *Pose, boneIndex int) math3d.Mat4
WorldMatrix returns the cached world-space 4x4 matrix of boneIndex, recomputing forward kinematics first if marked dirty.
func (*ModifierContext) WorldPosition ¶
func (c *ModifierContext) WorldPosition(pose *Pose, boneIndex int) math3d.Vec3
WorldPosition returns the cached world-space position of boneIndex.
func (*ModifierContext) WorldRotation ¶
func (c *ModifierContext) WorldRotation(pose *Pose, boneIndex int) math3d.Quat
WorldRotation returns the cached world-space rotation of boneIndex.
type ModifierStack ¶
type ModifierStack struct {
// contains filtered or unexported fields
}
ModifierStack applies skeleton pose modifiers in declaration order after animation sampling (StateMachine, LayerStack, or Graph).
All scratch buffers (output pose, blend snapshot, forward kinematics tables, target tables, and per-modifier solver state) are preallocated at construction so Apply and ApplyStep perform zero heap allocations per step. The Pose returned by Apply and ApplyStep aliases an internal buffer owned by the stack and remains valid until the next Apply/ApplyStep call; call Pose.Clone to retain a snapshot across steps. One ModifierStack is not safe for concurrent use.
func NewModifierStack ¶
func NewModifierStack(rig *Rig, modifiers ...Modifier) *ModifierStack
NewModifierStack creates a deterministic, allocation-free post-animation modifier stack bound to rig. Each modifier starts with influence 1.
Passing rig == nil is permitted when using custom PoseModifierFunc modifiers that do not query a Rig; bone-name modifiers safely no-op when rig is nil.
func (*ModifierStack) Apply ¶
func (s *ModifierStack) Apply(pose Pose, modelWorld math3d.Mat4) Pose
Apply evaluates all enabled modifiers in declaration order against pose under modelWorld using the stack's configured step duration (default 1/60s). The input pose is never modified.
func (*ModifierStack) ApplyStep ¶
ApplyStep evaluates all enabled modifiers in declaration order against pose under modelWorld using step delta dt (in seconds). The input pose is never modified.
func (*ModifierStack) ClearPoleTarget ¶
func (s *ModifierStack) ClearPoleTarget(bone string)
ClearPoleTarget removes any explicit pole target assigned to the named bone.
func (*ModifierStack) ClearTarget ¶
func (s *ModifierStack) ClearTarget(bone string)
ClearTarget removes any world-space target assigned to the named bone.
func (*ModifierStack) Influence ¶
func (s *ModifierStack) Influence(index int) float32
Influence returns modifier index's current blend weight, or 0 if out of range.
func (*ModifierStack) Reset ¶
func (s *ModifierStack) Reset()
Reset clears temporal smoothing state on all modifiers (for example after a character teleport or respawn).
func (*ModifierStack) Rig ¶
func (s *ModifierStack) Rig() *Rig
Rig returns the Rig bound to the stack, or nil.
func (*ModifierStack) SetDeltaTime ¶
func (s *ModifierStack) SetDeltaTime(dt float32)
SetDeltaTime sets the fixed step duration (in seconds) used by Apply for stateful modifiers such as smoothed LookAt. Non-finite or negative values are clamped to 0.
func (*ModifierStack) SetInfluence ¶
func (s *ModifierStack) SetInfluence(index int, weight float32)
SetInfluence sets modifier index's blend weight, clamped to [0, 1]. Influence 0 skips the modifier completely, 1 applies its full correction, and values in between blend each joint from the pre-modifier pose toward its result. NaN is treated as 0; out-of-range indices are ignored.
func (*ModifierStack) SetPoleTarget ¶
func (s *ModifierStack) SetPoleTarget(bone string, poleWorld math3d.Vec3)
SetPoleTarget assigns an explicit world-space pole position for the TwoBoneIK modifier targeting the named tip bone, overriding PoleBone. Unknown bone names and non-finite coordinates are ignored.
func (*ModifierStack) SetStepDuration ¶
func (s *ModifierStack) SetStepDuration(d time.Duration)
SetStepDuration sets the fixed step duration used by Apply. Negative durations are clamped to 0.
type OneShot ¶
type OneShot struct {
Base PoseSampler
Clip *Clip
FadeIn time.Duration
FadeOut time.Duration
Speed float32 // playback speed multiplier; 0 defaults to 1.0
Mask *BoneMask
Mode LayerBlendMode
ReferencePose *Pose
// contains filtered or unexported fields
}
OneShot plays a Clip once on demand with smooth FadeIn and FadeOut ramps and returns to inactive (Weight == 0) automatically when the clip finishes.
OneShot implements PoseSampler and works in two ways:
- Standalone with Base set: Update advances both Base and the one-shot clip, and Pose blends the one-shot over Base using Mask, Mode, ReferencePose and Weight, returning Base unchanged once finished.
- Inside a LayerStack (Base == nil): LayerStack multiplies the layer's Weight by OneShot.Weight() and leaves joints untouched when the clip has no track for them or when the one-shot is inactive.
func NewOneShot ¶
NewOneShot creates a OneShot node that plays clip once with the given fade-in and fade-out durations.
func (*OneShot) Abort ¶
func (o *OneShot) Abort()
Abort immediately stops an active one-shot and resets its elapsed time to 0.
func (*OneShot) Fire ¶
func (o *OneShot) Fire()
Fire starts playing the one-shot from time 0. Calling Fire while already active restarts it from 0. A nil or zero-duration clip remains inactive.
func (*OneShot) Reset ¶
func (o *OneShot) Reset()
Reset stops the one-shot and resets Base if it implements Reset.
func (*OneShot) Time ¶
Time returns the elapsed playback time of the current one-shot, or 0 when inactive.
type PlaneCollider ¶
type PlaneCollider struct {
Bone string
Offset math3d.Vec3
Normal math3d.Vec3
// Group assigns this collider to a named collider group. When empty, the
// collider is global and collides with every chain.
Group string
}
PlaneCollider is a half-space plane passing through Offset with outward unit Normal in Bone's local space (or the model root when Bone is empty). A zero Normal defaults to +Y (0, 1, 0).
type Player ¶
type Player struct {
// contains filtered or unexported fields
}
Player drives glTF 2.0 node animation playback on fixed time.Duration steps matching game.Loop.Update.
Player evaluates translation, rotation (shortest-path quaternion Slerp for LINEAR and Hermite spline normalization for CUBICSPLINE), scale, and morph target weight channels across STEP, LINEAR, and CUBICSPLINE interpolation modes. It maintains its own per-instance node transforms and world matrices without mutating the underlying *gltf.Document, allowing multiple Players to animate the same loaded asset independently.
Player also implements PoseSampler via Update and Pose.
Example ¶
A Player advances a glTF document's translation, rotation, and scale channels on fixed steps without mutating the document.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/anim3d"
"github.com/nsgo-dev/game/pkg/gltf"
"github.com/nsgo-dev/game/pkg/math3d"
)
func main() {
doc := &gltf.Document{
Nodes: []gltf.Node{{
Name: "hips",
Parent: -1,
Translation: math3d.Vec3Zero(),
Rotation: math3d.QuatIdentity(),
Scale: math3d.Vec3One(),
}},
Animations: []gltf.Animation{{
Name: "Walk",
Duration: 1.0,
Channels: []gltf.AnimationChannel{{
TargetNode: 0,
Path: gltf.PathTranslation,
Interpolation: gltf.InterpolationLinear,
Times: []float32{0, 1},
Values: []float32{0, 0, 0, 0, 2, 0},
Stride: 3,
}},
}},
}
player, err := anim3d.NewPlayer(doc)
if err != nil {
fmt.Println(err)
return
}
_ = player.PlayByName("Walk")
player.Step(250 * time.Millisecond)
fmt.Printf("t=%v y=%.2f\n", player.Time(), player.LocalTransform(0).Pos.Y)
}
Output: t=250ms y=0.50
func NewPlayer ¶
NewPlayer creates a Player bound to doc's node hierarchy, skins, and animations. The player validates the node hierarchy (rejecting out-of-range children, multiple parents, and cycles), initializes all node transforms to doc's bind pose, and computes initial world matrices without mutating doc.
Loop defaults to true and Speed defaults to 1.0. If doc contains animations, animation 0 is selected in the stopped state until Play or Crossfade is called.
func (*Player) AnimationIndex ¶
AnimationIndex returns the active animation index, or -1 if doc has no animations.
func (*Player) AnimationName ¶
AnimationName returns the name of the active animation, or "" if none is active or the animation is unnamed.
func (*Player) ApplyToNodes ¶
ApplyToNodes copies current local TRS transforms by index onto nodes (where nodes[i] corresponds to doc.Nodes[i]) and returns the number of non-nil nodes updated.
func (*Player) ApplyToScene ¶
ApplyToScene copies current local TRS transforms onto nodes in scene whose Name matches a named node in the glTF document, refreshes scene transforms, and returns the number of scene nodes updated.
func (*Player) Crossfade ¶
Crossfade smoothly blends from the current pose into doc.Animations[animIndex] over duration.
If duration <= 0, no animation is active yet, or animIndex is already the active animation, Crossfade switches immediately and resets Time to 0 (or Duration when Loop is false and Speed is negative). Interrupting an in-progress crossfade snapshots the current blended pose so transitions never pop.
func (*Player) CrossfadeByName ¶
CrossfadeByName finds the first animation in doc whose Name equals name and calls Crossfade on it over duration.
func (*Player) CrossfadeProgress ¶
CrossfadeProgress returns the normalized crossfade blend weight in [0, 1], or 1 when no crossfade is active.
func (*Player) Duration ¶
Duration returns the duration of the active animation, or 0 if none is active.
func (*Player) IsCrossfading ¶
IsCrossfading reports whether a crossfade transition is in progress.
func (*Player) LocalTransform ¶
LocalTransform returns the current local TRS transform for nodeIndex, or TransformIdentity if nodeIndex is out of range.
func (*Player) LocalTransforms ¶
LocalTransforms returns a copy of every node's current local TRS transform.
func (*Player) MorphWeights ¶
MorphWeights returns a copy of the current morph target weights for nodeIndex, or nil if nodeIndex has no morph weights or is out of range.
func (*Player) Pause ¶
func (p *Player) Pause()
Pause halts playback while keeping the current Time, pose, and world transforms intact.
func (*Player) Play ¶
Play starts or resumes playback of doc.Animations[animIndex].
Switching to a different animation resets Time to 0 (or to the animation's Duration when Loop is false and Speed is negative) and cancels any active crossfade. Calling Play with the already-selected animation resumes from the current Time if paused, or replays from the start (Duration when reversing a non-looping clip) if a non-looping clip has already finished. The pose and world transforms are evaluated immediately.
func (*Player) PlayByName ¶
PlayByName finds the first animation in doc whose Name equals name and calls Play on it.
func (*Player) Seek ¶
Seek moves playback to t (wrapped into [0, Duration) when Loop is true, or clamped to [0, Duration] otherwise) and immediately re-evaluates node transforms and world matrices without changing Playing.
func (*Player) SetLoop ¶
SetLoop controls whether playback wraps at animation boundaries (true) or clamps and stops at the end (false).
func (*Player) SetSpeed ¶
SetSpeed sets the playback speed multiplier. Negative values play in reverse; 0 freezes animation time while leaving crossfades able to finish. Non-finite values are ignored. When playing a non-looping animation parked at a clamped end (0 when flipping negative, or Duration when flipping positive), Time jumps to the opposite end and the pose is re-evaluated.
func (*Player) SkinMatrices ¶
SkinMatrices computes the glTF 2.0 joint skinning matrices for doc.Skins[skinIndex]:
jointMatrix[i] = inverse(worldMatrix[meshNode]) * worldMatrix[joint[i]] * inverseBindMatrix[i]
where meshNode is the first node in doc.Nodes referencing skinIndex. If no node references skinIndex (or the mesh node's world matrix is singular), inverse(worldMatrix[meshNode]) is omitted and worldMatrix[joint[i]] * inverseBindMatrix[i] is returned directly.
Use SkinMatricesForNode when multiple mesh nodes share the same skin index.
func (*Player) SkinMatricesForNode ¶
SkinMatricesForNode computes the glTF 2.0 joint skinning matrices for the skin attached to doc.Nodes[meshNodeIndex], normalizing joint world matrices by inverse(worldMatrix[meshNodeIndex]).
func (*Player) Step ¶
Step advances playback and any active crossfade by dt (matching game.Loop.Update) and recomputes local node transforms and world matrices.
When paused, stopped, or given dt <= 0, Step is a no-op.
func (*Player) Stop ¶
func (p *Player) Stop()
Stop halts playback, resets Time to 0, cancels any active crossfade, and restores all nodes to their rest (bind) pose.
func (*Player) Update ¶
Update advances playback by dt and returns the resulting node local Pose, implementing PoseSampler.
func (*Player) WorldTransform ¶
WorldTransform returns the current world-space 4x4 matrix for nodeIndex, or Mat4Identity if nodeIndex is out of range.
func (*Player) WorldTransforms ¶
WorldTransforms returns a copy of every node's current world-space 4x4 transformation matrix.
type Pose ¶
Pose holds local TRS transforms for each joint in a skeleton.
func ApplyAdditivePose ¶
ApplyAdditivePose applies an additive delta pose onto base, scaled by strength (clamped to [0, 1]) and multiplied per joint by mask (if non-nil).
- Pos: base.Pos + additive.Pos * w
- Rot: Slerp(Identity, additive.Rot, w) * base.Rot
- Scale: base.Scale * Lerp(Vec3One, additive.Scale, w)
func BlendPoses ¶
BlendPoses interpolates between poses a (t=0) and b (t=1), clamping t to [0, 1]. Translation and scale are linearly interpolated; rotations use shortest-path Slerp. If a and b have different joint counts, missing joints default to TransformIdentity.
func BlendPosesMasked ¶
BlendPosesMasked blends overlay over base by weight (clamped to [0, 1]) multiplied per joint by mask (if non-nil). A joint that overlay does not have (past len(overlay.Joints)) keeps the base transform rather than blending toward identity.
func BlendPosesWeighted ¶
BlendPosesWeighted blends poses using the corresponding non-negative weights. Weights are normalized internally so their sum equals 1. Translation and scale are linearly weighted; rotations use hemisphere-aligned normalized quaternion blending so the result is smooth and order-independent.
func MakeAdditivePose ¶
MakeAdditivePose computes the exact additive delta pose transforming reference into target:
- Pos: target.Pos - reference.Pos
- Rot: target.Rot * reference.Rot.Conj() (normalized)
- Scale: component-wise target.Scale / reference.Scale (1 when reference scale is 0)
A joint that target does not have (past len(target.Joints)) gets the identity delta, so it leaves the base pose unchanged instead of applying the negated reference.
func StripRootMotion ¶
func StripRootMotion(pose Pose, opts RootMotionOptions) Pose
StripRootMotion returns a copy of pose with the configured root translation and/or rotation channels removed from opts.RootJoint so world-space movement is driven exclusively by the extracted RootMotion.
type PoseModifierFunc ¶
type PoseModifierFunc func(pose *Pose, ctx *ModifierContext)
PoseModifierFunc adapts a function into a Modifier.
func (PoseModifierFunc) Apply ¶
func (f PoseModifierFunc) Apply(pose *Pose, ctx *ModifierContext)
Apply calls f with pose and ctx when f is non-nil.
type PoseSampler ¶
PoseSampler is implemented by animated pose sources that advance with dt and evaluate to a Pose (such as BlendSpace1D, BlendSpace2D, LayerStack, and StateMachine).
type QuatKeyframe ¶
QuatKeyframe is a timed rotation sample for a joint orientation channel.
type RayFunc ¶
RayFunc casts a world-space ray segment from from to to and returns the hit position, surface normal, and whether a surface was hit.
type Rig ¶
type Rig struct {
// contains filtered or unexported fields
}
Rig stores a skeleton's immutable joint hierarchy, rest pose, topological evaluation order, and bone-name index for pose modifiers and IK solvers.
Joint indices match doc.Nodes (0..len(doc.Nodes)-1) for rigs built with NewRig, aligning directly with Pose.Joints from ClipFromGLTF, StateMachine, LayerStack, Player, and Graph.
func NewRig ¶
NewRig builds a Rig from doc's node hierarchy and skinIndex.
When doc defines one or more skins, skinIndex must be in [0, len(doc.Skins)) and only nodes listed in that skin's Joints (plus its Skeleton root, when set) are registered in the bone-name index, preventing non-skin mesh nodes from being addressed as bones. When doc has no skins, skinIndex must be 0 and all named nodes are registered.
func NewRigFromBones ¶
NewRigFromBones builds a Rig from an explicit slice of BoneDesc entries. Parent indices must be -1 (root) or in [0, len(bones)), and the hierarchy must be acyclic.
func (*Rig) BoneIndex ¶
BoneIndex looks up a bone by name and returns its joint index and true, or (-1, false) when not found.
func (*Rig) Chain ¶
Chain returns the ordered slice of joint indices from rootName down to tipName inclusive ([root, ..., tip]), or (nil, false) if either name is unknown or tipName is not equal to or a descendant of rootName.
func (*Rig) IsDescendant ¶
IsDescendant reports whether descendant is a strict descendant of ancestor in the rig's hierarchy.
func (*Rig) JointCount ¶
JointCount returns the total number of joints in the rig.
func (*Rig) Parent ¶
Parent returns the parent joint index of index, or -1 for roots or out-of-range indices.
type RootMotion ¶
RootMotion holds the per-step root displacement extracted from an animation clip.
func ExtractRootMotion ¶
func ExtractRootMotion(clip *Clip, prevTime, currTime time.Duration, opts RootMotionOptions) RootMotion
ExtractRootMotion extracts the root joint's translation delta (DeltaPos) and rotation delta (DeltaRot) across the interval [prevTime, currTime].
For looping clips, loop wrap-around is handled cleanly without backward jumps whether the caller passes already-wrapped playback times (currTime < prevTime) or monotonic unwrapped times (currTime >= clip.Duration). A step that crosses one or more loop boundaries is split at each boundary and the pieces are composed in playback order, so its DeltaRot equals the rotation of applying the pieces one after another with ApplyRootMotion, also for clips that pitch and yaw at once.
Example ¶
ExtractRootMotion reads how far the root joint moved in a step, and ApplyRootMotion moves the character's world transform by it.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/anim3d"
"github.com/nsgo-dev/game/pkg/math3d"
)
// slide returns a one-joint clip that moves joint 0 along +X from 0 to dist over d.
func slide(name string, d time.Duration, dist float32, loop bool) *anim3d.Clip {
return &anim3d.Clip{
Name: name, Duration: d, Loop: loop, JointCount: 1,
Tracks: []anim3d.JointTrack{{
JointIndex: 0,
Translations: []anim3d.Vec3Keyframe{
{Time: 0, Value: math3d.Vec3Zero()},
{Time: d, Value: math3d.Vec3{X: dist}},
},
}},
}
}
func main() {
clip := slide("walk", time.Second, 2, true)
opts := anim3d.RootMotionOptions{StripRootXZ: true}
rm := anim3d.ExtractRootMotion(clip, 0, 500*time.Millisecond, opts)
world := math3d.TransformIdentity()
world.Rot = math3d.QuatFromAxisAngle(math3d.Vec3Up(), math3d.DegToRad(90))
world = anim3d.ApplyRootMotion(world, rm)
fmt.Printf("delta x=%.2f; world z=%.2f\n", rm.DeltaPos.X, world.Pos.Z)
stripped := anim3d.StripRootMotion(clip.Sample(500*time.Millisecond), opts)
fmt.Printf("skeleton x=%.2f\n", stripped.Joints[0].Pos.X)
}
Output: delta x=1.00; world z=-1.00 skeleton x=0.00
type RootMotionOptions ¶
type RootMotionOptions struct {
// RootJoint is the joint index carrying root motion (default 0).
RootJoint int
// ExtractYawOnly projects DeltaRot onto the world +Y yaw axis so pitch and
// roll remain purely visual on the animated skeleton.
ExtractYawOnly bool
// StripRootXZ zeroes the root joint's X and Z translation in StripRootMotion
// (keeping Y vertical motion on the skeleton) so characters can drive their
// world transform from DeltaPos without double-translating.
StripRootXZ bool
// StripRootY zeroes the root joint's Y translation in StripRootMotion.
StripRootY bool
// StripRootRot removes the extracted root rotation from the root joint in
// StripRootMotion.
StripRootRot bool
}
RootMotionOptions configures root motion extraction and pose stripping.
type SphereCollider ¶
type SphereCollider struct {
Bone string
Offset math3d.Vec3
Radius float32
Inside bool
// Group assigns this collider to a named collider group. When empty, the
// collider is global and collides with every chain.
Group string
}
SphereCollider is a sphere attached to Bone (or the model root when Bone is empty). When Inside is true, joints are kept inside the sphere rather than pushed outside it.
type SpringBones ¶
type SpringBones struct {
Chains []SpringChain
Colliders []SpringCollider
// contains filtered or unexported fields
}
SpringBones simulates secondary motion for hair, tails, ears, capes, and soft accessories using deterministic fixed-step Verlet integration with sphere, capsule, and plane colliders.
All scratch buffers and per-segment state are preallocated so Apply performs zero heap allocations per step. The Pose returned by Apply aliases an internal buffer owned by SpringBones and remains valid until the next Apply call; call Pose.Clone to retain a snapshot. One SpringBones instance is not safe for concurrent use.
func NewSpringBones ¶
func NewSpringBones(rig *Rig, chains ...SpringChain) *SpringBones
NewSpringBones creates a spring-bone simulator bound to rig for chains. Unknown bone names or invalid chains are ignored safely without panicking.
func SpringBonesFromGLTF ¶
func SpringBonesFromGLTF(doc *gltf.Document) (*SpringBones, error)
SpringBonesFromGLTF reads VRMC_springBone directly from doc and returns a SpringBones simulator bound to doc's skeleton with no intermediate conversion.
When doc carries no VRMC_springBone extension (and no unsupported legacy VRM extension), it returns an empty *SpringBones bound to doc's rig. Unsupported extension versions (including legacy VRM 0.x) and malformed extension data return a clear error.
func (*SpringBones) AddChain ¶
func (s *SpringBones) AddChain(chain SpringChain)
AddChain appends a spring-bone chain to s and binds it to s's Rig. It does nothing on a nil receiver.
func (*SpringBones) AddCollider ¶
func (s *SpringBones) AddCollider(c SpringCollider)
AddCollider adds a SphereCollider, CapsuleCollider, or PlaneCollider. Colliders with an empty Group collide with every chain; colliders with a non-empty Group collide with chains that list that group in ColliderGroups. It does nothing on a nil receiver or nil collider.
func (*SpringBones) AddColliderGroup ¶
func (s *SpringBones) AddColliderGroup(group string, colliders ...SpringCollider)
AddColliderGroup adds colliders assigned to the named collider group. Any collider with an empty Group inherits group.
func (*SpringBones) Apply ¶
Apply advances all spring chains by dt seconds under modelWorld and returns the resulting Pose without mutating pose.
Apply performs zero heap allocations per step when pose matches the bound rig's joint count. The returned Pose aliases an internal buffer owned by s until the next Apply call.
func (*SpringBones) Modifier ¶
func (s *SpringBones) Modifier() Modifier
Modifier returns a Modifier adapter that runs s inside a ModifierStack. ModifierStack.Reset resets s as well.
func (*SpringBones) Reset ¶
func (s *SpringBones) Reset()
Reset clears accumulated velocity and simulation state so the next Apply starts every chain at rest in the new pose and world transform (for example after a character teleport). It does nothing on a nil receiver.
func (*SpringBones) Rig ¶
func (s *SpringBones) Rig() *Rig
Rig returns the skeleton Rig bound to s, or nil.
func (*SpringBones) SetWind ¶
func (s *SpringBones) SetWind(wind math3d.Vec3)
SetWind sets an external world-space wind force applied to every spring joint on subsequent steps. Non-finite vectors are ignored.
func (*SpringBones) Wind ¶
func (s *SpringBones) Wind() math3d.Vec3
Wind returns the current external world-space wind force vector.
type SpringChain ¶
type SpringChain struct {
Name string
Root, Tip string
Center string
Stiffness float32
Drag float32
Gravity math3d.Vec3
Radius float32
RotationAxis math3d.Vec3
Joints []SpringJoint
ColliderGroups []string
}
SpringChain describes a named secondary-motion bone chain.
Specify either Root and Tip (expanding every joint along the rig hierarchy using the chain-level defaults, optionally refined by per-joint entries in Joints) or an explicit ordered Joints slice (as loaded from VRMC_springBone).
type SpringCollider ¶
type SpringCollider interface {
// contains filtered or unexported methods
}
SpringCollider is a collision volume attached to a bone that constrains spring-bone joints. Built-in shapes are SphereCollider, CapsuleCollider, and PlaneCollider.
type SpringJoint ¶
type SpringJoint struct {
// Bone names the skeleton joint.
Bone string
// Stiffness is the restoring force toward the animated/rest pose (>= 0).
Stiffness float32
// Drag is the per-step velocity damping factor in [0, 1].
Drag float32
// Gravity is the world-space gravity acceleration vector.
Gravity math3d.Vec3
// Radius is the joint's collision hit radius (>= 0).
Radius float32
// RotationAxis optionally constrains this joint to hinge around a local-space
// axis. A zero vector allows unconstrained 3D swing.
RotationAxis math3d.Vec3
}
SpringJoint configures per-joint secondary-motion parameters within a SpringChain.
type State ¶
type State struct {
Name string
Clip *Clip
Blend1D *BlendSpace1D
Blend2D *BlendSpace2D
Sampler PoseSampler
ParamName string // optional StateMachine parameter name for Blend1D
ParamXName string // optional StateMachine X parameter name for Blend2D
ParamYName string // optional StateMachine Y parameter name for Blend2D
Speed float32 // playback speed multiplier; 0 defaults to 1.0
}
State binds a named state in a StateMachine to an animation Clip, a BlendSpace1D, a BlendSpace2D, or a custom PoseSampler.
Resolution priority when more than one pose source is populated is: Blend1D > Blend2D > Sampler > Clip.
type StateMachine ¶
type StateMachine struct {
// contains filtered or unexported fields
}
StateMachine drives 3D skeletal clip and blend-space playback, event dispatch, and smooth crossfades between named animation states on fixed Update steps.
Example ¶
A StateMachine crossfades between named states when a Transition's condition holds, and fires the clips' events as playback crosses them.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/anim3d"
"github.com/nsgo-dev/game/pkg/math3d"
)
// slide returns a one-joint clip that moves joint 0 along +X from 0 to dist over d.
func slide(name string, d time.Duration, dist float32, loop bool) *anim3d.Clip {
return &anim3d.Clip{
Name: name, Duration: d, Loop: loop, JointCount: 1,
Tracks: []anim3d.JointTrack{{
JointIndex: 0,
Translations: []anim3d.Vec3Keyframe{
{Time: 0, Value: math3d.Vec3Zero()},
{Time: d, Value: math3d.Vec3{X: dist}},
},
}},
}
}
func main() {
idle := slide("idle", time.Second, 0, true)
walk := slide("walk", time.Second, 2, true)
walk.AddEvent(anim3d.ClipEvent{Time: 0.5, Name: "footstep"})
sm := anim3d.NewStateMachine("idle")
sm.AddState(anim3d.State{Name: "idle", Clip: idle})
sm.AddState(anim3d.State{Name: "walk", Clip: walk})
sm.AddTransition(anim3d.Transition{
From: "idle", To: "walk", BlendDuration: 200 * time.Millisecond,
When: func() bool { return sm.Param("speed") > 0.1 },
})
sm.OnEvent(func(e anim3d.FiredEvent) { fmt.Println("event:", e.Event.Name, "in", e.State) })
sm.SetParam("speed", 1)
sm.Update(100 * time.Millisecond)
fmt.Println(sm.CurrentState(), sm.IsBlending())
for range 6 {
sm.Update(100 * time.Millisecond)
}
fmt.Println(sm.CurrentState(), sm.IsBlending())
}
Output: walk true event: footstep in walk walk false
func NewStateMachine ¶
func NewStateMachine(initialState string) *StateMachine
NewStateMachine creates a StateMachine starting in initialState.
func (*StateMachine) AddState ¶
func (sm *StateMachine) AddState(state State)
AddState registers or replaces a named state. If the machine has no active state yet, state.Name becomes the current state. When registering the active state for the first time, playback starts at Duration for a non-looping clip with negative Speed and at 0 otherwise. When replacing the active state, if a non-looping clip's effective speed changes sign while parked at a clamped end, playback jumps to the opposite end so it plays instead of staying clamped.
func (*StateMachine) AddTransition ¶
func (sm *StateMachine) AddTransition(tr Transition)
AddTransition appends a conditional transition evaluated in registration order.
func (*StateMachine) BlendProgress ¶
func (sm *StateMachine) BlendProgress() float32
BlendProgress returns the normalized crossfade weight in [0, 1]. It returns 1 when no crossfade is active.
func (*StateMachine) CancelTravel ¶
func (sm *StateMachine) CancelTravel()
CancelTravel stops advancing along any queued Travel path without interrupting the current state or active crossfade.
func (*StateMachine) CurrentState ¶
func (sm *StateMachine) CurrentState() string
CurrentState returns the name of the active (or target, while blending) state.
func (*StateMachine) CurrentTime ¶
func (sm *StateMachine) CurrentTime() time.Duration
CurrentTime returns the playback time of the current state's clip.
func (*StateMachine) DrainEvents ¶
func (sm *StateMachine) DrainEvents() []FiredEvent
DrainEvents returns all FiredEvents collected since the last DrainEvents call and clears the internal event buffer.
func (*StateMachine) EventWeightThreshold ¶
func (sm *StateMachine) EventWeightThreshold() float32
EventWeightThreshold returns the configured minimum blend weight threshold for event firing.
func (*StateMachine) IsBlending ¶
func (sm *StateMachine) IsBlending() bool
IsBlending reports whether a crossfade transition is currently in progress.
func (*StateMachine) OnEvent ¶
func (sm *StateMachine) OnEvent(fn func(FiredEvent))
OnEvent registers a callback invoked synchronously whenever an animation event fires during Update.
func (*StateMachine) Param ¶
func (sm *StateMachine) Param(name string) float32
Param returns the value of the named float32 parameter, or 0 if unset.
func (*StateMachine) Pose ¶
func (sm *StateMachine) Pose() Pose
Pose evaluates the current state's pose (or blended pose during a crossfade) without advancing time.
func (*StateMachine) PreviousState ¶
func (sm *StateMachine) PreviousState() string
PreviousState returns the name of the state being blended out of, or "" when not blending.
func (*StateMachine) Restart ¶
func (sm *StateMachine) Restart(name string, blendDuration time.Duration) bool
Restart replays a state from its beginning, crossfading from itself when name is the current state and blendDuration is positive, and cancels any active Travel path.
func (*StateMachine) SetEventWeightThreshold ¶
func (sm *StateMachine) SetEventWeightThreshold(minWeight float32)
SetEventWeightThreshold configures the minimum active blend weight in [0, 1] required for a state (or blend-space clip) to fire events during crossfades. A threshold of 0 (the default) fires events for any clip with weight > 0.
func (*StateMachine) SetParam ¶
func (sm *StateMachine) SetParam(name string, value float32)
SetParam sets a named float32 parameter on the state machine. Blend-space states bound to that parameter name automatically read it during Update and Pose.
func (*StateMachine) SetState ¶
func (sm *StateMachine) SetState(name string, blendDuration time.Duration) bool
SetState transitions directly to name over blendDuration and cancels any active Travel path. It returns false if name is not a registered state.
func (*StateMachine) Travel ¶
func (sm *StateMachine) Travel(target string) bool
Travel follows the shortest path of registered transitions from the current state to target, crossfading along each transition's BlendDuration. Automatic conditional transitions are paused until the travel finishes or is cancelled by SetState, Restart, or CancelTravel.
Travel returns false without changing state when target is not a registered state or no transition path leads from the current state to target. Asking to travel to the already-current state cancels any active travel and returns true.
func (*StateMachine) TravelTarget ¶
func (sm *StateMachine) TravelTarget() string
TravelTarget returns the destination state of an in-progress Travel, or "" when no travel is active.
func (*StateMachine) Update ¶
func (sm *StateMachine) Update(dt time.Duration) Pose
Update evaluates conditional transitions, advances clip and blend-space playback and any active crossfade by dt, dispatches triggered animation events, and returns the resulting Pose.
Update(0) is a paused step: it re-evaluates the pose but neither advances time nor starts conditional transitions, so a paused character does not change state. During a crossfade both states fire events at their crossfade weights at the midpoint of the part of the step that lies inside the crossfade, so the step that completes a crossfade still fires the outgoing state's events. When both states of a crossfade are driven by the same blend space or sampler, it is advanced once per step, not twice.
type TimeScale ¶
type TimeScale struct {
Source PoseSampler
Scale float32
}
TimeScale wraps a PoseSampler and scales its Update step duration by Scale. A Scale of 0 pauses the wrapped sampler without losing its pose.
func NewTimeScale ¶
func NewTimeScale(source PoseSampler, scale float32) *TimeScale
NewTimeScale creates a TimeScale wrapping source at the given non-negative playback scale.
type TimeSeek ¶
type TimeSeek struct {
Clip *Clip
Source PoseSampler
Loop bool
// contains filtered or unexported fields
}
TimeSeek wraps a Clip or PoseSampler with explicit playback-time seeking.
func NewTimeSeek ¶
NewTimeSeek creates a TimeSeek node driving clip with explicit Seek support.
func NewTimeSeekSampler ¶
func NewTimeSeekSampler(source PoseSampler) *TimeSeek
NewTimeSeekSampler creates a TimeSeek node wrapping source.
func (*TimeSeek) Seek ¶
Seek moves playback to pos (clamped to >= 0). When wrapping a Clip, pos is normalized on evaluation; when wrapping a PoseSampler, Seek delegates to a Seek(time.Duration) method if present, or calls Reset followed by Update(pos).
type Transition ¶
Transition defines a conditional crossfade between two states in a StateMachine. An empty From string matches any state other than To.
type TwoBoneIK ¶
type TwoBoneIK struct {
// Root is the upper bone (e.g. "UpperLeg.L" or "UpperArm.R").
Root string
// Mid is the hinge bone (e.g. "LowerLeg.L" or "Forearm.R").
Mid string
// Tip is the end-effector bone (e.g. "Foot.L" or "Hand.R").
Tip string
// PoleBone optionally names a bone whose world position steers the hinge
// bend plane (e.g. "Knee.L"). Overridden by ModifierStack.SetPoleTarget.
PoleBone string
// contains filtered or unexported fields
}
TwoBoneIK analytically solves a two-bone inverse kinematics chain (Root -> Mid -> Tip) using SolveTwoBoneIK and writes local rotations back to Root and Mid while preserving bone twist.
Set the end-effector target via ModifierStack.SetTarget(Tip, targetWorld).
func (*TwoBoneIK) Apply ¶
func (ik *TwoBoneIK) Apply(pose *Pose, ctx *ModifierContext)
Apply solves two-bone IK for Root -> Mid -> Tip toward the target set on Tip.