API リファレンスはソースコード内の Go ドキュメントコメントから生成されており、英語で記述されています。
package anim3d
import "github.com/nsgo-dev/game/pkg/anim3d"概要
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.
目次
- 変数
- 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 NewBlendSpace1D(samples ...BlendSample1D) *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 NewBlendSpace2D(samples ...BlendSample2D) *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
- func ClipFromGLTF(doc *gltf.Document, animIndex int) (*Clip, error)
- func ClipsFromGLTF(doc *gltf.Document) ([]*Clip, error)
- func (c *Clip) AddEvent(ev ClipEvent)
- func (c *Clip) NormalizeTime(t time.Duration) time.Duration
- func (c *Clip) Sample(t time.Duration) Pose
- func (c *Clip) SampleJoint(jointIndex int, t time.Duration) math3d.Transform
- type ClipEvent
- type EventDispatcher
- func NewEventDispatcher() *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 NewLayerStack(jointCount int) *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 NewPlayer(doc *gltf.Document) (*Player, error)
- 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
- func (p Pose) Clone() Pose
- type PoseSampler
- type QuatKeyframe
- type RootMotion
- type RootMotionOptions
- type State
- type StateMachine
- func NewStateMachine(initialState string) *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
変数
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.
関数
func ApplyRootMotion(world math3d.Transform, rm RootMotion) math3d.TransformApplyRootMotion advances a character's world transform by rm, transforming rm.DeltaPos by world's current orientation and scale and composing rm.DeltaRot.
func LoadEventsFromGLTFExtras(gltfJSON []byte) (map[string][]ClipEvent, error)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>".
Its errors are *loaderr.Error values that give the line of the problem and how to fix it; a caller that read the document from a file names it with loaderr.WithFile.
func LoadEventsSidecar(data []byte) (map[string][]ClipEvent, error)LoadEventsSidecar parses a JSON sidecar file produced by MarshalEventsSidecar ({"version": 1, "clips": {...}}) or a flat {"clipName": [...]} map into per-clip event slices sorted by ascending Time.
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(clips map[string][]ClipEvent) ([]byte, error)MarshalEventsSidecar serializes per-clip event lists into a formatted JSON sidecar document ({"version": 1, "clips": {...}}) with each clip's events sorted by ascending Time.
func SolveFABRIK(joints []math3d.Vec3, target math3d.Vec3, iterations int, tolerance float32) []math3d.Vec3SolveFABRIK 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.
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
func SortClipEvents(events []ClipEvent)SortClipEvents stably sorts events in place by ascending Time.
型
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 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 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 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.
func NewBlendSpace1D(samples ...BlendSample1D) *BlendSpace1DNewBlendSpace1D creates a 1D blend space with samples sorted by ascending Param.
func (bs *BlendSpace1D) CycleSpeed(param float32) float32CycleSpeed returns the weighted normalized cycle speed sum(w_i / dur_i) in cycles per second at param.
func (bs *BlendSpace1D) Evaluate(param float32, phase float32) PoseEvaluate samples the blend space at param and normalized phase without mutating internal state.
func (bs *BlendSpace1D) Param() float32Param returns the current scalar parameter.
func (bs *BlendSpace1D) Phase() float32Phase returns the current normalized cycle phase in [0, 1).
func (bs *BlendSpace1D) Pose() PosePose evaluates the blend space at its current Param and Phase without advancing time.
func (bs *BlendSpace1D) Reset()Reset resets the normalized cycle phase back to 0.
func (bs *BlendSpace1D) Samples() []BlendSample1DSamples returns a copy of the sorted samples in the blend space.
func (bs *BlendSpace1D) SetParam(value float32)SetParam updates the active scalar parameter used by Update and Pose.
func (bs *BlendSpace1D) SetPhase(phase float32)SetPhase sets the normalized cycle phase (wrapped into [0, 1)).
func (bs *BlendSpace1D) Update(dt time.Duration) PoseUpdate advances the synchronized foot phase by dt using the weighted cycle speed at the current Param and returns the evaluated Pose.
func (bs *BlendSpace1D) Weights(param float32) []float32Weights computes the normalized blend weights for param (clamped at endpoints). Samples that share the same Param split that position's weight equally.
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(samples ...BlendSample2D) *BlendSpace2DNewBlendSpace2D creates a 2D blend space from the given samples.
func (bs *BlendSpace2D) CycleSpeed(x, y float32) float32CycleSpeed returns the weighted normalized cycle speed sum(w_i / dur_i) in cycles per second at (x, y).
func (bs *BlendSpace2D) Evaluate(x, y, phase float32) PoseEvaluate samples the 2D blend space at (x, y) and normalized phase without mutating internal state.
func (bs *BlendSpace2D) Params() (x, y float32)Params returns the current (X, Y) coordinates.
func (bs *BlendSpace2D) Phase() float32Phase returns the current normalized cycle phase in [0, 1).
func (bs *BlendSpace2D) Pose() PosePose evaluates the 2D blend space at its current (X, Y) and Phase without advancing time.
func (bs *BlendSpace2D) Reset()Reset resets the normalized cycle phase back to 0.
func (bs *BlendSpace2D) Samples() []BlendSample2DSamples returns a copy of the samples in the 2D blend space.
func (bs *BlendSpace2D) SetParams(x, y float32)SetParams updates the active (X, Y) coordinates used by Update and Pose.
func (bs *BlendSpace2D) SetPhase(phase float32)SetPhase sets the normalized cycle phase (wrapped into [0, 1)).
func (bs *BlendSpace2D) Update(dt time.Duration) PoseUpdate advances the synchronized foot phase by dt using the weighted cycle speed at the current (X, Y) and returns the evaluated Pose.
func (bs *BlendSpace2D) Weights(x, y float32) []float32Weights 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 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).
func NewBoneMask(jointCount int, defaultWeight float32) *BoneMaskNewBoneMask creates a BoneMask for jointCount joints initialized to defaultWeight (clamped to [0, 1]).
func (m *BoneMask) Clone() *BoneMaskClone returns a deep copy of m, or nil if m is nil.
func (m *BoneMask) SetBranch(parents []int, rootJoint int, weight float32)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).
func (m *BoneMask) SetJoint(idx int, weight float32)SetJoint sets the blend weight for a single joint, clamped to [0, 1]. Out-of-range indices are ignored.
func (m *BoneMask) Weight(idx int) float32Weight returns the clamped blend weight for joint idx. A nil BoneMask represents an unmasked weight of 1.0 for every joint. Out-of-range indices on a non-nil mask return 0.
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(doc *gltf.Document, animIndex int) (*Clip, error)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. Loop defaults to false.
func ClipsFromGLTF(doc *gltf.Document) ([]*Clip, error)ClipsFromGLTF converts every animation in doc into an anim3d.Clip in document order.
func (c *Clip) AddEvent(ev ClipEvent)AddEvent appends ev to the clip's Events slice and keeps Events sorted by Time.
func (c *Clip) NormalizeTime(t time.Duration) time.DurationNormalizeTime maps t into the clip's playable range: wrapped into [0, Duration) when Loop is true, or clamped to [0, Duration] otherwise.
func (c *Clip) Sample(t time.Duration) PoseSample evaluates the clip at time t and returns the resulting Pose. Translations and scales are linearly interpolated; rotations use Quat.Slerp.
func (c *Clip) SampleJoint(jointIndex int, t time.Duration) math3d.TransformSampleJoint evaluates a single joint's local transform at time t (normalized according to the clip's Loop setting).
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(events []ClipEvent, prevTime, nextTime, duration float32, loop bool) []ClipEventCollectClipEvents 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).
type EventDispatcher struct {
// contains filtered or unexported fields
}EventDispatcher collects FiredEvents and dispatches them to registered callbacks and an internal queue drained via Drain.
func NewEventDispatcher() *EventDispatcherNewEventDispatcher creates an empty EventDispatcher.
func (d *EventDispatcher) Clear()Clear discards all queued FiredEvents.
func (d *EventDispatcher) DispatchClip(clip *Clip, stateName string, prevTime, nextTime, weight float32) []FiredEventDispatchClip 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 (d *EventDispatcher) Drain() []FiredEventDrain returns all queued FiredEvents since the last Drain and clears the queue.
func (d *EventDispatcher) Emit(ev FiredEvent)Emit appends ev to the pending queue and notifies all registered listeners.
func (d *EventDispatcher) OnEvent(fn func(FiredEvent))OnEvent registers a listener invoked synchronously whenever an event is emitted.
func (d *EventDispatcher) Pending() []FiredEventPending returns a copy of queued FiredEvents without clearing the queue.
type FiredEvent struct {
Event ClipEvent
State string
Clip string
Weight float32
}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 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 intLayerBlendMode 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 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.
func NewLayerStack(jointCount int) *LayerStackNewLayerStack creates an empty LayerStack targeting skeletons with jointCount joints.
func (ls *LayerStack) AddLayer(layer AnimLayer)AddLayer appends a layer to the top of the stack.
func (ls *LayerStack) Evaluate() PoseEvaluate composes all active layers at their current times without advancing playback.
func (ls *LayerStack) Layer(name string) *AnimLayerLayer returns a pointer to the first layer matching name, or nil if not found.
func (ls *LayerStack) LayerWeight(name string) float32LayerWeight returns the current Weight of the named layer, or 0 if not found.
func (ls *LayerStack) Pose() PosePose evaluates the composed layer stack without advancing time (implements PoseSampler).
func (ls *LayerStack) RemoveLayer(name string) boolRemoveLayer removes the first layer matching name. It returns true if removed.
func (ls *LayerStack) SetLayerWeight(name string, weight float32) boolSetLayerWeight updates the Weight of the named layer (clamped to [0, 1]). It returns false if no layer with name exists.
func (ls *LayerStack) Update(dt time.Duration) PoseUpdate advances all layers by dt and returns the composed Pose.
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.
func NewPlayer(doc *gltf.Document) (*Player, error)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 (p *Player) AnimationIndex() intAnimationIndex returns the active animation index, or -1 if doc has no animations.
func (p *Player) AnimationName() stringAnimationName returns the name of the active animation, or "" if none is active or the animation is unnamed.
func (p *Player) ApplyToNodes(nodes []*scene3d.Node) intApplyToNodes 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 (p *Player) ApplyToScene(scene *scene3d.Scene) intApplyToScene 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 (p *Player) Crossfade(animIndex int, duration time.Duration) errorCrossfade 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. Interrupting an in-progress crossfade snapshots the current blended pose so transitions never pop.
func (p *Player) CrossfadeByName(name string, duration time.Duration) errorCrossfadeByName finds the first animation in doc whose Name equals name and calls Crossfade on it over duration.
func (p *Player) CrossfadeProgress() float32CrossfadeProgress returns the normalized crossfade blend weight in [0, 1], or 1 when no crossfade is active.
func (p *Player) Duration() time.DurationDuration returns the duration of the active animation, or 0 if none is active.
func (p *Player) IsCrossfading() boolIsCrossfading reports whether a crossfade transition is in progress.
func (p *Player) LocalTransform(nodeIndex int) math3d.TransformLocalTransform returns the current local TRS transform for nodeIndex, or TransformIdentity if nodeIndex is out of range.
func (p *Player) LocalTransforms() []math3d.TransformLocalTransforms returns a copy of every node's current local TRS transform.
func (p *Player) Loop() boolLoop reports whether playback wraps at animation boundaries.
func (p *Player) MorphWeights(nodeIndex int) []float32MorphWeights 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 (p *Player) NodeCount() intNodeCount returns the number of nodes tracked by the player.
func (p *Player) Pause()Pause halts playback while keeping the current Time, pose, and world transforms intact.
func (p *Player) Play(animIndex int) errorPlay starts or resumes playback of doc.Animations[animIndex].
Switching to a different animation resets Time to 0 and cancels any active crossfade. Calling Play with the already-selected animation resumes from the current Time if paused, or replays from the start if a non-looping clip has already finished. The pose and world transforms are evaluated immediately.
func (p *Player) PlayByName(name string) errorPlayByName finds the first animation in doc whose Name equals name and calls Play on it.
func (p *Player) Playing() boolPlaying reports whether the player is actively advancing on Step calls.
func (p *Player) Pose() PosePose returns a snapshot of every node's current local TRS transform.
func (p *Player) Seek(t time.Duration)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 (p *Player) SetLoop(loop bool)SetLoop controls whether playback wraps at animation boundaries (true) or clamps and stops at the end (false).
func (p *Player) SetSpeed(speed float32)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.
func (p *Player) SkinMatrices(skinIndex int) ([]math3d.Mat4, error)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 (p *Player) SkinMatricesForNode(meshNodeIndex int) ([]math3d.Mat4, error)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 (p *Player) Speed() float32Speed returns the current playback speed multiplier.
func (p *Player) Step(dt time.Duration)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 (p *Player) Stop()Stop halts playback, resets Time to 0, cancels any active crossfade, and restores all nodes to their rest (bind) pose.
func (p *Player) Time() time.DurationTime returns the current playback timestamp of the active animation.
func (p *Player) Update(dt time.Duration) PoseUpdate advances playback by dt and returns the resulting node local Pose, implementing PoseSampler.
func (p *Player) WorldTransform(nodeIndex int) math3d.Mat4WorldTransform returns the current world-space 4x4 matrix for nodeIndex, or Mat4Identity if nodeIndex is out of range.
func (p *Player) WorldTransforms() []math3d.Mat4WorldTransforms returns a copy of every node's current world-space 4x4 transformation matrix.
type Pose struct {
Joints []math3d.Transform
}Pose holds local TRS transforms for each joint in a skeleton.
func ApplyAdditivePose(base Pose, additive Pose, strength float32, mask *BoneMask) PoseApplyAdditivePose 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(a, b Pose, t float32) PoseBlendPoses 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(base, overlay Pose, weight float32, mask *BoneMask) PoseBlendPosesMasked 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(poses []Pose, weights []float32) PoseBlendPosesWeighted 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(target Pose, reference Pose) PoseMakeAdditivePose 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 NewPose(jointCount int) PoseNewPose returns a Pose with jointCount joints initialized to identity transforms.
func StripRootMotion(pose Pose, opts RootMotionOptions) PoseStripRootMotion 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 interface {
Update(dt time.Duration) Pose
Pose() Pose
}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 struct {
Time time.Duration
Value math3d.Quat
}QuatKeyframe is a timed rotation sample for a joint orientation channel.
type RootMotion struct {
DeltaPos math3d.Vec3
DeltaRot math3d.Quat
}RootMotion holds the per-step root displacement extracted from an animation clip.
func ExtractRootMotion(clip *Clip, prevTime, currTime time.Duration, opts RootMotionOptions) RootMotionExtractRootMotion 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.
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 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 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.
func NewStateMachine(initialState string) *StateMachineNewStateMachine creates a StateMachine starting in initialState.
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.
func (sm *StateMachine) AddTransition(tr Transition)AddTransition appends a conditional transition evaluated in registration order.
func (sm *StateMachine) BlendProgress() float32BlendProgress returns the normalized crossfade weight in [0, 1]. It returns 1 when no crossfade is active.
func (sm *StateMachine) CurrentState() stringCurrentState returns the name of the active (or target, while blending) state.
func (sm *StateMachine) CurrentTime() time.DurationCurrentTime returns the playback time of the current state's clip.
func (sm *StateMachine) DrainEvents() []FiredEventDrainEvents returns all FiredEvents collected since the last DrainEvents call and clears the internal event buffer.
func (sm *StateMachine) EventWeightThreshold() float32EventWeightThreshold returns the configured minimum blend weight threshold for event firing.
func (sm *StateMachine) IsBlending() boolIsBlending reports whether a crossfade transition is currently in progress.
func (sm *StateMachine) OnEvent(fn func(FiredEvent))OnEvent registers a callback invoked synchronously whenever an animation event fires during Update.
func (sm *StateMachine) Param(name string) float32Param returns the value of the named float32 parameter, or 0 if unset.
func (sm *StateMachine) Pose() PosePose evaluates the current state's pose (or blended pose during a crossfade) without advancing time.
func (sm *StateMachine) PreviousState() stringPreviousState returns the name of the state being blended out of, or "" when not blending.
func (sm *StateMachine) Restart(name string, blendDuration time.Duration) boolRestart replays a state from its beginning, crossfading from itself when name is the current state and blendDuration is positive.
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 (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 (sm *StateMachine) SetState(name string, blendDuration time.Duration) boolSetState transitions directly to name over blendDuration. It returns false if name is not a registered state.
func (sm *StateMachine) Update(dt time.Duration) PoseUpdate 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 struct {
From string
To string
BlendDuration time.Duration
When func() bool
}Transition defines a conditional crossfade between two states in a StateMachine. An empty From string matches any state other than To.
type Vec3Keyframe struct {
Time time.Duration
Value math3d.Vec3
}Vec3Keyframe is a timed 3D vector sample for a translation or scale channel.