GitHubLoslegen

Die API-Referenz stammt aus den Go-Doc-Kommentaren im Quellcode und ist auf Englisch verfasst.

package skeletal

import "github.com/nsgo-dev/game/pkg/skeletal"

Übersicht

Package skeletal loads, saves and animates 2D skeletal rigs drawn through sprite.Batch.

Format decision

Rigs use an open, versioned YAML format (.skel.yaml, version 1) that Load reads and Encode writes. Choosing an open schema over Spine's export avoids Spine's proprietary runtime license, matches NSGo's screen coordinates directly, and is simple to export from DragonBones, Blender or custom scripts. Like every file a game's author edits, a rig is plain text: one bone, slot, attachment or keyframe per line, so it can be edited by hand and reviewed as a diff. A version-1 rig written as JSON loads too when the JSON is also valid YAML: keys spelled exactly as the schema spells them (matching is case-sensitive) and no `\/` escape, which YAML does not have.

Load is strict: it rejects unknown fields, duplicate keys, trailing documents, unsupported versions and non-finite numbers, as well as every structural error listed on Load.

Coordinates and units

Coordinates match package sprite and core.Drawing: +X points right, +Y points down, and rotations are in radians, clockwise on the screen. Keyframe times and animation durations are written in seconds, at most MaxSeconds, and stored as time.Duration in Go.

Schema (version 1)

A rig file is a YAML mapping with:

  • version (int, required): must be 1.
  • name (string, optional): rig name.
  • bones (sequence): bone hierarchy in bind pose. Each bone has name (required, unique), optional parent (another bone's name), local offset x and y, local rotation in radians, local scaleX and scaleY (default 1), and optional length for tooling. Cycles and missing parents are rejected.
  • slots (sequence): draw-ordered list, back to front. Each slot has name (required, unique), bone (required, an existing bone's name), optional attachment (default atlas frame name), and alpha in [0, 1] (default 1).
  • skins (mapping): maps skin name (default "default") to a mapping of slot name to an attachment {frame, x, y, rotation, scaleX, scaleY, originX, originY}. scaleX and scaleY default to 1. Slots missing from the active skin fall back to "default". An empty frame hides the slot.
  • animations (mapping): maps animation name to {duration, loop, bones, slots}. duration is in seconds (derived from the last keyframe when omitted). Each bone timeline has optional translate [{time, x, y, curve, bezier}], rotate [{time, angle, curve, bezier}] and scale [{time, x, y, curve, bezier}], applied relative to bind pose (translate and rotate add; scale multiplies). Each slot timeline has optional attachment [{time, frame}] and alpha [{time, value, curve, bezier}]. curve is "linear" (default), "stepped", or "bezier" with bezier: [cx1, cy1, cx2, cy2] where cx1, cx2 lie in [0, 1]; bezier is rejected on other curves.

Canonical form

Encode writes one canonical form: keys in schema order, skins, attachments, animations and timelines sorted by name in plain byte order (as sort.Strings sorts them), each bone, slot, attachment and keyframe as a one-line flow mapping, fields equal to their defaults left out, except that keyframes always write their time and values and animations their duration, and numbers in plain decimal notation, never with an exponent. Loading a canonical file and encoding it gives the same bytes back, and loading what Encode wrote gives the same rig. Comments and anchors are not kept.

Sample

version: 1
name: runner
bones:
  - {name: root}
  - {name: torso, parent: root, y: -18, length: 16}
  - {name: head, parent: torso, y: -16, length: 12}
slots:
  - {name: torso, bone: torso}
  - {name: head, bone: head}
skins:
  default:
    head: {frame: head, originX: 6, originY: 12}
    torso: {frame: torso, originX: 6, originY: 16}
animations:
  idle:
    duration: 1
    loop: true
    bones:
      torso:
        translate:
          - {time: 0, x: 0, y: 0, curve: bezier, bezier: [0.25, 0.1, 0.25, 1]}
          - {time: 0.5, x: 0, y: -2}
          - {time: 1, x: 0, y: 0}

Index

Konstanten

const FormatVersion = 1

FormatVersion is the schema version that Load reads and Encode writes.

const MaxSeconds = 1_000_000

MaxSeconds is the longest keyframe time or animation duration, in seconds, that a rig may hold. Within it, a time written in seconds by Encode loads back to the same nanosecond.

Funktionen

func Encode(sd *SkeletonData) ([]byte, error)

Encode serializes sd as a version-1 .skel.yaml document and checks that the result loads.

The output is deterministic: keys follow the schema's order, skins, attachments, animations and timelines are sorted by name in byte order, numbers are written in plain decimal notation without an exponent, every bone, slot, attachment and keyframe sits on one line in flow style, and values equal to their defaults are left out, except that keyframes always spell out their time and values and animations their duration. Encoding the result of Load gives the same bytes back for a file already in this form, and loading the result of Encode gives data equal to sd.

Encode reports an error, and writes nothing, when sd would not load: a missing or dangling name, a cycle, an unknown curve, a non-finite number, a time outside [0, MaxSeconds], Bezier control points on a curve that is not CurveBezier, an Animation whose Name differs from its key in Animations, or any other rule Load enforces. It does not modify sd.

Typen

type Animation struct {
	// Name is the animation's key in SkeletonData.Animations.
	Name string
	// Duration is the length of one pass of the animation.
	Duration time.Duration
	// Loop is the file's default looping preference for this animation.
	Loop bool
	// Bones maps bone names to their transform timelines.
	Bones map[string]BoneTimeline
	// Slots maps slot names to their attachment and alpha timelines.
	Slots map[string]SlotTimeline
	// contains filtered or unexported fields
}

Animation holds the bone and slot timelines for one named motion.

type Attachment struct {
	// Frame is the atlas frame name to draw; empty hides the slot.
	Frame string
	// X and Y are the attachment's offset in its bone's local space.
	X, Y float32
	// Rotation is the attachment's local rotation in radians, clockwise on the screen.
	Rotation float32
	// ScaleX and ScaleY are the attachment's local scales, 1 when omitted in the file.
	ScaleX, ScaleY float32
	// OriginX and OriginY are the pivot point of the untrimmed atlas frame, matching sprite.Sprite.
	OriginX, OriginY float32
}

Attachment places one atlas frame on a slot, relative to the slot's bone.

type AttachmentKeyframe struct {
	Time  time.Duration
	Frame string
}

AttachmentKeyframe swaps a slot's atlas frame at Time; an empty Frame hides the slot.

type BoneData struct {
	// Name uniquely identifies the bone in the skeleton.
	Name string
	// Parent is the parent bone's Name, or empty for a root bone.
	Parent string
	// X and Y are the bone's bind-pose offset in its parent's space.
	X, Y float32
	// Rotation is the bone's bind-pose rotation in radians, clockwise on the screen.
	Rotation float32
	// ScaleX and ScaleY are the bone's bind-pose scales, 1 when omitted in the file.
	ScaleX, ScaleY float32
	// Length is an optional bone length for editors and debug overlays.
	Length float32
}

BoneData describes one bone's bind pose relative to its parent.

type BoneTimeline struct {
	Translate []Vec2Keyframe
	Rotate    []FloatKeyframe
	Scale     []Vec2Keyframe
}

BoneTimeline holds the optional transform tracks for one bone, applied relative to its bind pose: Translate and Rotate add; Scale multiplies.

type BoneTransform struct {
	X, Y           float32
	Rotation       float32
	ScaleX, ScaleY float32
}

BoneTransform is a bone's position, rotation and scale in a drawing's coordinates.

type CurveType uint8

CurveType selects how a keyframe interpolates to the next keyframe.

const (
	// CurveLinear interpolates evenly between keyframes.
	CurveLinear CurveType = iota
	// CurveStepped holds the keyframe's value until the next keyframe's time.
	CurveStepped
	// CurveBezier eases with a cubic Bezier curve defined by [cx1, cy1, cx2, cy2].
	CurveBezier
)
type FloatKeyframe struct {
	Time   time.Duration
	Value  float32
	Curve  CurveType
	Bezier [4]float32
}

FloatKeyframe is a scalar keyframe (rotation angle in radians or slot alpha).

type Skeleton struct {
	// X and Y place the skeleton's root origin in the drawing.
	X, Y float32
	// Rotation turns the skeleton about its root origin, in radians, clockwise on the screen.
	Rotation float32
	// ScaleX and ScaleY scale the skeleton about its root origin; a negative value mirrors it.
	ScaleX, ScaleY float32
	// FlipX and FlipY mirror the skeleton across its root axes before Rotation.
	FlipX, FlipY bool
	// Alpha multiplies every slot's opacity, from 0 (draws nothing) to 1.
	Alpha float32
	// Z is passed to each sprite drawn by Draw.
	Z int
	// contains filtered or unexported fields
}

Skeleton is a live instance of a SkeletonData rig: its root placement, active skin, per-slot attachment overrides, animation playback and computed bone transforms.

NewSkeleton returns a skeleton at full size and opacity in bind pose, with the "default" skin active when the rig defines one.

func NewSkeleton(data *SkeletonData, atlas *sprite.Atlas) *Skeleton

NewSkeleton returns a skeleton for data drawing frames from atlas, at full scale and opacity in its bind pose. If data defines a "default" skin, it is active initially.

NewSkeleton panics when data does not compile, such as a hand-built SkeletonData with a duplicate bone name, an unknown parent or a cycle: an invalid rig would otherwise render every bone at the drawing's origin and report nothing.

func (s *Skeleton) Animation() string

Animation returns the name of the active (or incoming) animation, or empty when no animation is playing.

func (s *Skeleton) Blending() bool

Blending reports whether a crossfade is currently in progress.

func (s *Skeleton) ClearAttachment(slot string)

ClearAttachment removes any manual override set on slot by SetAttachment, returning it to the active animation or skin attachment.

func (s *Skeleton) Crossfade(anim string, duration time.Duration, loop bool) error

Crossfade smoothly blends from the current pose into the named animation over duration, using shortest-angle rotation blending and linear translation, scale and alpha blending. If duration <= 0, Crossfade switches immediately like Play.

func (s *Skeleton) Data() *SkeletonData

Data returns the immutable SkeletonData this skeleton was created from.

func (s *Skeleton) Done() bool

Done reports whether a non-looping animation has reached its end.

func (s *Skeleton) Draw(d *core.Drawing)

Draw updates world transforms and draws every visible slot into d in slot draw order through a reusable sprite.Batch.

func (s *Skeleton) Play(anim string, loop bool) error

Play starts playing the named animation from time 0, cancelling any active crossfade, applies its initial pose and updates world transforms.

func (s *Skeleton) ResetToBindPose()

ResetToBindPose restores every bone and slot to its bind pose, clears any active animation or crossfade, and updates world transforms.

func (s *Skeleton) SetAttachment(slot, frame string)

SetAttachment overrides the atlas frame drawn by slot. An empty frame hides the slot. Unknown slot names are ignored.

func (s *Skeleton) SetSkin(name string) error

SetSkin switches the active skin to name. Slots missing from name fall back to the "default" skin. It returns an error if data does not define name.

func (s *Skeleton) Skin() string

Skin returns the name of the active skin, or empty if none is active.

func (s *Skeleton) Update(dt time.Duration)

Update advances the active animation (and any ongoing crossfade) by dt and updates every bone's world transform. Call it from a game.Loop's fixed-step Update callback for deterministic playback.

func (s *Skeleton) UpdateWorldTransforms()

UpdateWorldTransforms computes every bone's world transform down the parent-child tree from the skeleton's root transform and current local pose.

func (s *Skeleton) WorldBone(name string) (BoneTransform, bool)

WorldBone returns the last computed world transform of the named bone. Call UpdateWorldTransforms (or Update) after changing root fields before reading it for attachments, hitboxes or particles.

type SkeletonData struct {
	// Version is the schema version of the rig, FormatVersion.
	Version int
	// Name is the rig's name, if the file gave one.
	Name string
	// Bones are the rig's bones in bind pose.
	Bones []BoneData
	// Slots are the rig's slots in draw order, back to front.
	Slots []SlotData
	// Skins maps each skin's name to the attachments it places on slots.
	Skins map[string]Skin
	// Animations maps each animation's name to its timelines.
	Animations map[string]*Animation
	// contains filtered or unexported fields
}

SkeletonData is the immutable description of a 2D skeletal rig: its bones, draw-ordered slots, skins and animations. Share one SkeletonData across as many Skeleton instances as need it.

func Load(data []byte) (*SkeletonData, error)

Load parses and validates a version-1 skeletal rig from YAML (.skel.yaml).

It rejects empty input, unknown fields, duplicate keys, trailing YAML documents, unknown schema versions, non-finite numbers, duplicate bone or slot names, missing parents, cycles in the bone hierarchy, slots or skins referencing missing bones or slots, and animations with unknown targets, unsorted or out-of-range keyframes, or invalid curves. A version-1 rig written as JSON loads too when the JSON is also valid YAML: keys spelled exactly as the schema spells them (matching is case-sensitive) and no `\/` escape, which YAML does not have.

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 (sd *SkeletonData) Compile() error

Compile validates cross-references in a hand-built SkeletonData and builds the dense lookup indices and topological bone evaluation order its runtime needs. Data loaded from a document is compiled already, and calling Compile again is harmless.

type Skin map[string]Attachment

Skin maps slot names to their attachments.

type SlotData struct {
	// Name uniquely identifies the slot in the skeleton.
	Name string
	// Bone is the name of the bone whose transform the slot follows.
	Bone string
	// Attachment is an optional default atlas frame name when no skin supplies one.
	Attachment string
	// Alpha is the slot's bind-pose opacity in [0, 1], 1 when omitted in the file.
	Alpha float32
}

SlotData describes one draw slot attached to a bone.

type SlotTimeline struct {
	Attachment []AttachmentKeyframe
	Alpha      []FloatKeyframe
}

SlotTimeline holds the optional attachment and opacity tracks for one slot.

type Vec2Keyframe struct {
	Time   time.Duration
	X, Y   float32
	Curve  CurveType
	Bezier [4]float32
}

Vec2Keyframe is a two-component keyframe (translation offset or scale factor).