Documentation
¶
Overview ¶
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 LoadEventsFromGLTFExtras(gltfJSON []byte) (map[string][]ClipEvent, error)
- func LoadEventsSidecar(data []byte) (map[string][]ClipEvent, error)
- func MarshalEventsSidecar(clips map[string][]ClipEvent) ([]byte, error)
- 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 AnimLayer
- 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 BoneMask
- 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 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 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 PoseSampler
- type QuatKeyframe
- type RootMotion
- type RootMotionOptions
- type State
- type StateMachine
- func (sm *StateMachine) AddState(state State)
- func (sm *StateMachine) AddTransition(tr Transition)
- func (sm *StateMachine) BlendProgress() float32
- 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) Update(dt time.Duration) Pose
- type Transition
- 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.
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 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 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 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 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 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 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 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 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 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 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 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) 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.
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. It returns false if name is not a registered state.
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 Transition ¶
Transition defines a conditional crossfade between two states in a StateMachine. An empty From string matches any state other than To.