La referencia de API proviene de los comentarios de documentación de Go en el código fuente y está redactada en inglés.
package resource
import "github.com/nsgo-dev/game/pkg/resource"Resumen
Package resource is experimental: its API and documented formats may change in a minor release. See the API stability policy. reads, validates and writes shared resource files: reusable data that scenes and code reference by path instead of repeating it.
Files
A resource file is one YAML document that starts with a common header, the resource's type, the schema version and an optional uid, followed by the fields of that type:
type: material version: 1 baseColor: "#8a8f99" opacity: 0.75 blend: multiply
The uid (Header.UID) is the file's stable ID, made once by NewUID, which stays the same when the file is renamed or moved so that package refs can find it again.
The types are material (Material), curve (Curve), gradient (Gradient), animation (Animation), theme (Theme), busLayout (BusLayout), physicsMaterial (PhysicsMaterial), animgraph (AnimGraph), sound (Sound) and music (Music). Parse reads any of them and returns the matching type; it refuses an unknown type, a version other than CurrentVersion, unknown fields, trailing documents and values out of range. Encode writes deterministic 2-space YAML with fields in a fixed order, so a file that Encode wrote reads back with Parse and encodes to the same bytes.
Sharing
A Library loads resource files from an fs.FS by slash-separated path and keeps one value per path, so every scene and every piece of code that loads the same path holds the same pointer. Library.Reload replaces a loaded resource's contents in place, so an edit to one file reaches everything that uses it; hotreload.Watcher.WatchResources calls it when a file changes on disk.
sceneformat objects reference a material by path (ObjectDoc.Material) and resolve it through a resolver such as a Library, so two scenes that use one material file both change when it is edited.
Índice
- Constantes
- func BlendModes() []string
- func Encode(r Resource) ([]byte, error)
- func LoadAs[T Resource](l *Library, path string) (T, error)
- func NewUID(r io.Reader) (string, error)
- func ParseAs[T Resource](data []byte) (T, error)
- func ValidUID(s string) bool
- type AlphaSettings
- type AnimGraph
- type AnimGraphBlend1D
- type AnimGraphLayer
- type AnimGraphMachine
- type AnimGraphMask
- type AnimGraphOneShot
- type AnimGraphParam
- type AnimGraphRoot
- type AnimGraphSample
- type AnimGraphState
- type AnimGraphTransition
- type Animation
- type BandFilterEffect
- type BitcrushEffect
- type Bus
- type BusEffect
- type BusLayout
- type ChorusEffect
- type ClipKey
- type CompressorEffect
- type Curve
- type DelayEffect
- type DepthSettings
- type DistortionEffect
- type EQBandEffect
- type EQEffect
- type Event
- type FilterEffect
- type FrameKey
- type GainEffect
- type GainFilterEffect
- type Gradient
- type GradientStop
- type Header
- type Interp
- type Key
- type Kind
- type Library
- func NewLibrary(fsys fs.FS) *Library
- func (l *Library) Animation(path string) (*Animation, error)
- func (l *Library) Load(path string) (Resource, error)
- func (l *Library) Loaded(path string) bool
- func (l *Library) Material(path string) (*Material, error)
- func (l *Library) Paths() []string
- func (l *Library) PhysicsMaterial(path string) (*PhysicsMaterial, error)
- func (l *Library) Reload(path string, data []byte) (bool, error)
- func (l *Library) ReloadFile(path string) (int64, bool, error)
- func (l *Library) Revision() uint64
- type LimiterEffect
- type Material
- type Music
- type MusicClip
- type MusicPlaylist
- type MusicTransition
- type PannerEffect
- type PhaserEffect
- type PhysicsMaterial
- type PitchShiftEffect
- type Resource
- type ReverbEffect
- type ShaderParams
- type Sound
- type SoundCone
- type SoundKey
- type SoundSpatial
- type SoundVariant
- type StereoWidthEffect
- type StyleBorder
- type StyleBox
- type TextureMap
- type Theme
- type ThemeColors
- type ThemeFont
- type ThemeVariation
- type ToonSettings
- type Track
- type UVSettings
- type WidgetStyle
Constantes
const CurrentVersion = 1CurrentVersion is the resource schema version this package reads and writes.
Funciones
func BlendModes() []stringBlendModes returns the names Material.Blend accepts, sorted: the canvas composite operations in camel case, such as "sourceOver", "multiply" and "lighter".
func Encode(r Resource) ([]byte, error)Encode validates r and writes it as deterministic 2-space YAML: the header first, then the type's fields in declaration order, omitting fields left at their defaults.
func LoadAs[T Resource](l *Library, path string) (T, error)LoadAs loads the resource at path from l and returns it as T, failing when the file holds another type.
func NewUID(r io.Reader) (string, error)NewUID returns a new UID, UIDLength characters of uidAlphabet that carry 65 random bits read from r, or from crypto/rand when r is nil. A UID is the stable ID a scene or resource file keeps in its header (SceneDoc.UID in sceneformat, Header.UID here), which stays the same when the file is renamed or moved, so the tools can find a moved file again (see package refs).
func ParseAs[T Resource](data []byte) (T, error)ParseAs parses data and returns it as T, failing when the file holds another type.
func ValidUID(s string) boolValidUID reports whether s has the form NewUID returns: UIDLength characters, each a digit or a lower-case letter other than i, l, o and u.
Tipos
type AlphaSettings struct {
// Mode is opaque, cutout, hash or blend; empty is opaque.
Mode string `yaml:"mode,omitempty"`
// Cutoff is the alpha below which a cutout surface is discarded, from 0 to 1.
Cutoff *float32 `yaml:"cutoff,omitempty"`
}AlphaSettings controls alpha interpretation for a 3D material.
type AnimGraph struct {
Header `yaml:",inline"`
Name string `yaml:"name,omitempty"`
Model string `yaml:"model"`
Params []AnimGraphParam `yaml:"params,omitempty"`
Root AnimGraphRoot `yaml:"root"`
}AnimGraph is a text-authored 3D animation graph with layers and state machines.
func (a *AnimGraph) Validate() errorValidate checks the header, the model path, that parameters have unique names and a type of float, bool or trigger, and that layers have unique names and exactly one of a machine and a one-shot whose states, transitions, blends, parameters, masks and modes are consistent, returning a *loaderr.Error naming the field at fault.
type AnimGraphBlend1D struct {
Param string `yaml:"param"`
Samples []AnimGraphSample `yaml:"samples"`
}AnimGraphBlend1D blends the clips of Samples by the value of the parameter Param.
type AnimGraphLayer struct {
Name string `yaml:"name"`
Machine *AnimGraphMachine `yaml:"machine,omitempty"`
OneShot *AnimGraphOneShot `yaml:"oneShot,omitempty"`
Mask *AnimGraphMask `yaml:"mask,omitempty"`
Mode string `yaml:"mode,omitempty"`
}AnimGraphLayer is one layer of the graph: a state machine or a one-shot clip, optionally masked to a branch of the skeleton, combined with the layers below it by Mode.
type AnimGraphMachine struct {
Entry string `yaml:"entry"`
States []AnimGraphState `yaml:"states"`
Transitions []AnimGraphTransition `yaml:"transitions,omitempty"`
}AnimGraphMachine is a state machine that starts in Entry and moves between States along Transitions.
type AnimGraphMask struct {
Branch string `yaml:"branch"`
Weight float32 `yaml:"weight,omitempty"`
}AnimGraphMask limits a layer to the skeleton branch rooted at Branch, at Weight.
type AnimGraphOneShot struct {
Clip string `yaml:"clip"`
Fire string `yaml:"fire"`
FadeIn float32 `yaml:"fadeIn,omitempty"`
FadeOut float32 `yaml:"fadeOut,omitempty"`
}AnimGraphOneShot plays a clip once when its fire parameter is set, fading in and out over the given seconds.
type AnimGraphParam struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
}AnimGraphParam declares one parameter the game sets to drive the graph, by name and type.
type AnimGraphRoot struct {
Layers []AnimGraphLayer `yaml:"layers"`
}AnimGraphRoot is the graph's layers, blended in order.
type AnimGraphSample struct {
At float32 `yaml:"at"`
Clip string `yaml:"clip"`
}AnimGraphSample places a clip at the value At of a blend's parameter.
type AnimGraphState struct {
Name string `yaml:"name"`
Clip string `yaml:"clip,omitempty"`
Blend1D *AnimGraphBlend1D `yaml:"blend1d,omitempty"`
}AnimGraphState is one state of a machine, playing a clip or a one-dimensional blend of clips.
type AnimGraphTransition struct {
From string `yaml:"from"`
To string `yaml:"to"`
When string `yaml:"when,omitempty"`
XFade float32 `yaml:"xfade,omitempty"`
}AnimGraphTransition moves a machine from one state to another when its condition holds, cross-fading over XFade seconds.
type Animation struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Length is the clip's length in seconds; it must be positive.
Length float32 `yaml:"length"`
// Loop plays the clip again from the start when it ends.
Loop bool `yaml:"loop,omitempty"`
// Tracks are the clip's keyed properties; each target and property pair appears once.
Tracks []Track `yaml:"tracks,omitempty"`
// Events are named cues on the clip's timeline in time order, such as a footstep sound, which a player reports as playback crosses them.
Events []Event `yaml:"events,omitempty"`
// Sounds are sound resources played at times on the clip's timeline, in non-decreasing time order.
Sounds []SoundKey `yaml:"sounds,omitempty"`
// Clips are animation clips started on targets at times on the clip's timeline, in non-decreasing time order.
Clips []ClipKey `yaml:"clips,omitempty"`
}Animation is a clip of property tracks keyed over its length, played on a scene object or node.
func (a *Animation) ClipTime(t float32) float32ClipTime maps a play time t in seconds to a time within the clip: wrapped into [0, Length) when Loop is set, clamped to [0, Length] otherwise.
func (a *Animation) Sample(t float32, set func(target, property string, value float32))Sample evaluates every numeric track at play time t (mapped through ClipTime) and calls set with each track's target, property and value, in track order. Discrete frame tracks are skipped; use SampleFrames for them.
func (a *Animation) SampleFrames(t float32, set func(target, property, frame string))SampleFrames evaluates every discrete frame track at play time t (mapped through ClipTime) and calls set with each track's target, property and frame name, in track order.
func (a *Animation) Validate() errorValidate checks the header, the length, every track, every event and its arguments, and every sound and clip key.
type BandFilterEffect struct {
// Hz is the band center in hertz; it must be positive.
Hz float64 `yaml:"hz"`
// Q is the filter's resonance; 0 is Butterworth (1/sqrt(2)).
Q float64 `yaml:"q,omitempty"`
}BandFilterEffect is a band-pass or notch filter around Hz.
type BitcrushEffect struct {
// Bits is the bit depth from 1 to 15.
Bits int `yaml:"bits"`
// Downsample holds every Downsample-th frame; 0 or 1 does not downsample.
Downsample int `yaml:"downsample,omitempty"`
}BitcrushEffect quantizes samples and holds frames for a lo-fi sound.
type Bus struct {
// Name is the mixer group's name, such as "music" or "effects".
Name string `yaml:"name"`
// Effects is the bus's effect chain, applied in order.
Effects []BusEffect `yaml:"effects,omitempty"`
}Bus is one sound bus: a sound.Mixer group and its effects, applied in order.
func (bus *Bus) Chain() sound.EffectChainChain returns the bus's effects as a sound.EffectChain, in order.
type BusEffect struct {
// LowPass attenuates frequencies above its cutoff (sound.LowPass).
LowPass *FilterEffect `yaml:"lowPass,omitempty"`
// HighPass attenuates frequencies below its cutoff (sound.HighPass).
HighPass *FilterEffect `yaml:"highPass,omitempty"`
// Delay is a feedback echo (sound.Delay).
Delay *DelayEffect `yaml:"delay,omitempty"`
// Reverb is a room reverb (sound.Reverb).
Reverb *ReverbEffect `yaml:"reverb,omitempty"`
// Gain scales every sample (sound.Gain).
Gain *GainEffect `yaml:"gain,omitempty"`
// Bitcrush lowers bit depth and sample rate (sound.Bitcrush).
Bitcrush *BitcrushEffect `yaml:"bitcrush,omitempty"`
// BandPass keeps the band around its frequency (sound.BandPass).
BandPass *BandFilterEffect `yaml:"bandPass,omitempty"`
// Notch cuts the band around its frequency (sound.Notch).
Notch *BandFilterEffect `yaml:"notch,omitempty"`
// PeakingEQ boosts or cuts one band by gain (sound.PeakingEQ).
PeakingEQ *GainFilterEffect `yaml:"peakingEq,omitempty"`
// LowShelf raises or lowers everything below its frequency (sound.LowShelf).
LowShelf *GainFilterEffect `yaml:"lowShelf,omitempty"`
// HighShelf raises or lowers everything above its frequency (sound.HighShelf).
HighShelf *GainFilterEffect `yaml:"highShelf,omitempty"`
// EQ shapes several peaking bands in order (sound.EQ).
EQ *EQEffect `yaml:"eq,omitempty"`
// Compressor compresses levels above its threshold (sound.Compressor).
Compressor *CompressorEffect `yaml:"compressor,omitempty"`
// Limiter clips every sample to its ceiling (sound.Limiter).
Limiter *LimiterEffect `yaml:"limiter,omitempty"`
// Distortion shapes a driven signal (sound.Distortion).
Distortion *DistortionEffect `yaml:"distortion,omitempty"`
// Chorus adds a modulated delay copy (sound.Chorus).
Chorus *ChorusEffect `yaml:"chorus,omitempty"`
// Phaser sweeps all-pass stages with feedback (sound.Phaser).
Phaser *PhaserEffect `yaml:"phaser,omitempty"`
// PitchShift retunes by semitones without changing duration (sound.PitchShift).
PitchShift *PitchShiftEffect `yaml:"pitchShift,omitempty"`
// Panner moves a stereo signal between channels (sound.Panner).
Panner *PannerEffect `yaml:"panner,omitempty"`
// StereoWidth narrows or widens a stereo signal (sound.StereoWidth).
StereoWidth *StereoWidthEffect `yaml:"stereoWidth,omitempty"`
}BusEffect is one effect on a bus. Exactly one field must be set.
func (e *BusEffect) Effect() sound.BusEffectEffect returns the sound.BusEffect the entry describes, or nil when no field is set.
type BusLayout struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Buses are the layout's buses, each name once.
Buses []Bus `yaml:"buses,omitempty"`
}BusLayout lays out a game's sound buses: the groups a sound.Mixer plays through and the DSP effect chain on each.
func (b *BusLayout) Apply(m *sound.Mixer)Apply sets each bus's effect chain on m with sound.Mixer.SetGroupEffects; a bus with no effects clears its group's chain. Groups the layout does not name keep their chains, and volumes are left to the player's settings.
func (b *BusLayout) Validate() errorValidate checks the header, bus names and every effect's parameters.
type ChorusEffect struct {
// RateHz is the sweep rate; it must be positive.
RateHz float64 `yaml:"rateHz"`
// DepthMs is the sweep depth around 20ms in milliseconds.
DepthMs float64 `yaml:"depthMs,omitempty"`
// Mix is the dry/wet mix from 0 to 1.
Mix float64 `yaml:"mix,omitempty"`
}ChorusEffect is a modulated-delay chorus.
type ClipKey struct {
// Time is where the clip starts, from 0 to the clip's Length.
Time float32 `yaml:"time"`
// Target names the object that plays the clip; empty is the animated object itself.
Target string `yaml:"target,omitempty"`
// Clip is the project-relative path of the animation resource to start.
Clip string `yaml:"clip"`
}ClipKey starts a clip on a target at a time on the Animation's timeline; an empty target is the animated object itself.
type CompressorEffect struct {
// ThresholdDB is the level above which the compressor acts.
ThresholdDB float64 `yaml:"thresholdDb"`
// Ratio is how much the level above the threshold is compressed; it must be above 1.
Ratio float64 `yaml:"ratio"`
// AttackMs and ReleaseMs are the envelope times in milliseconds; 0 reacts at once.
AttackMs float64 `yaml:"attackMs,omitempty"`
ReleaseMs float64 `yaml:"releaseMs,omitempty"`
}CompressorEffect is a feed-forward peak compressor.
type Curve struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Keys are the curve's keys in strictly increasing Time order; there must be at least one.
Keys []Key `yaml:"keys"`
}Curve is a value keyed over time, such as an easing, a particle's size over its life or damage over distance.
func (c *Curve) Eval(t float32) float32Eval returns the curve's value at t, holding the first and last keys' values before and after them. Its method value fits tween.EaseFunc.
func (c *Curve) Validate() errorValidate checks the header and that the keys are finite, ordered and use a known interp.
type DelayEffect struct {
// Seconds is the echo spacing; it must be positive.
Seconds float64 `yaml:"seconds"`
// Feedback is how much of each echo feeds the next, from 0 to 0.99.
Feedback float64 `yaml:"feedback,omitempty"`
// Wet is the dry/wet mix from 0 to 1.
Wet float64 `yaml:"wet"`
}DelayEffect is a feedback delay line.
type DepthSettings struct {
// Write is auto, on or off; empty is auto.
Write string `yaml:"write,omitempty"`
// Test turns depth testing on or off; nil is on.
Test *bool `yaml:"test,omitempty"`
}DepthSettings controls depth testing and writes.
type DistortionEffect struct {
// Shape is clip, tanh or fold.
Shape string `yaml:"shape"`
// DriveDB is how much the signal is driven before shaping, in dB.
DriveDB float64 `yaml:"driveDb,omitempty"`
// Mix is the dry/wet mix from 0 to 1.
Mix float64 `yaml:"mix,omitempty"`
}DistortionEffect drives a signal and shapes it with a transfer curve.
type EQBandEffect struct {
// Hz is the band center in hertz; it must be positive.
Hz float64 `yaml:"hz"`
// GainDB is the boost or cut in dB.
GainDB float64 `yaml:"gainDb"`
// Q is the band's resonance; 0 is Butterworth (1/sqrt(2)).
Q float64 `yaml:"q,omitempty"`
}EQBandEffect is one peaking band of EQ.
type EQEffect struct {
// Bands are the peaking bands, each with a center frequency, a gain and an optional resonance.
Bands []EQBandEffect `yaml:"bands"`
}EQEffect is the peaking bands EQ applies in order.
type Event struct {
// Time is where the event sits, from 0 to the clip's Length; events must be in non-decreasing Time order.
Time float32 `yaml:"time"`
// Name says what happens, such as "footstep"; it must not be empty.
Name string `yaml:"name"`
// Args are named scalar values (strings, numbers or booleans) passed with the event to gameplay callbacks.
Args map[string]any `yaml:"args,omitempty"`
}Event is one named cue on an Animation's timeline.
type FilterEffect struct {
// CutoffHz is the cutoff frequency in hertz; it must be positive.
CutoffHz float64 `yaml:"cutoffHz"`
// Q is the filter's resonance; 0 is Butterworth (1/sqrt(2)).
Q float64 `yaml:"q,omitempty"`
}FilterEffect is a low-pass or high-pass biquad filter.
type FrameKey struct {
// Time is where the frame starts, from 0 to the clip's Length; frame keys must be in strictly increasing Time order.
Time float32 `yaml:"time"`
// Frame is the atlas frame name shown from Time until the next key; it must not be empty.
Frame string `yaml:"frame"`
}FrameKey is one discrete sprite frame key on an animation Track, holding an atlas frame name from Time until the next key without interpolation.
type GainEffect struct {
// Factor is the scale; it must be finite and non-negative.
Factor float64 `yaml:"factor"`
}GainEffect scales every sample by Factor.
type GainFilterEffect struct {
// Hz is the band center in hertz for a peaking filter, or the shelf corner; it must be positive.
Hz float64 `yaml:"hz"`
// GainDB is the boost or cut in dB.
GainDB float64 `yaml:"gainDb"`
// Q is the filter's resonance; 0 is Butterworth (1/sqrt(2)).
Q float64 `yaml:"q,omitempty"`
}GainFilterEffect is a peaking or shelf filter around Hz with GainDB.
type Gradient struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Stops are the gradient's colors in non-decreasing Offset order; two stops at one offset make a hard edge. There must be at least one.
Stops []GradientStop `yaml:"stops"`
}Gradient is a run of colors keyed over offsets from 0 to 1, such as a particle's color over its life or a sky's color over the day.
func (g *Gradient) At(t float32) core.ColorAt returns the gradient's color at t, mixing each channel linearly between the stops around it and holding the end colors beyond them.
func (g *Gradient) CoreStops() []core.GradientStopCoreStops returns the stops as core.GradientStop values for a canvas gradient. A stop whose color does not parse is transparent.
func (g *Gradient) Validate() errorValidate checks the header and that the stops are in order with valid colors.
type GradientStop struct {
// Offset is where the color sits, from 0 to 1.
Offset float32 `yaml:"offset"`
// Color is a CSS color parsed with core.ParseColor.
Color string `yaml:"color"`
}GradientStop is one color of a Gradient.
type Header struct {
// Type names the resource's type; it must match the Go type holding it.
Type Kind `yaml:"type"`
// Version is the schema version; it must equal CurrentVersion (1).
Version int `yaml:"version"`
// UID is the file's stable ID, which stays the same when the file is renamed or moved so the tools can find it again (see package refs); empty until a tool such as game index gives it one. When set it must be a UID as NewUID returns it.
UID string `yaml:"uid,omitempty"`
}Header is the common start of every resource file: its type, schema version and stable ID. Every resource type embeds it, so Type, Version and UID are the first fields of each file.
func NewHeader(kind Kind) HeaderNewHeader returns the header for a resource of kind at CurrentVersion.
type Interp stringInterp is how a key's value moves to the next key's.
const (
// InterpLinear moves in a straight line; it is the default when a key leaves interp empty.
InterpLinear Interp = "linear"
// InterpStep holds the key's value until the next key.
InterpStep Interp = "step"
// InterpSmooth eases in and out with a smoothstep.
InterpSmooth Interp = "smooth"
)type Key struct {
// Time is where the key sits; keys must be in strictly increasing Time order.
Time float32 `yaml:"time"`
// Value is the value at Time.
Value float32 `yaml:"value"`
// Interp is how the value moves from this key to the next; empty is InterpLinear.
Interp Interp `yaml:"interp,omitempty"`
}Key is one keyed value on a Curve or a numeric animation Track.
type Kind stringKind is a resource file's type, written in its header's type field.
const (
// KindMaterial is a Material: surface color, texture, opacity and blending.
KindMaterial Kind = "material"
// KindCurve is a Curve: a value keyed over time.
KindCurve Kind = "curve"
// KindGradient is a Gradient: colors keyed over offsets from 0 to 1.
KindGradient Kind = "gradient"
// KindAnimation is an Animation: property tracks keyed over a clip's length.
KindAnimation Kind = "animation"
// KindTheme is a Theme: colors, spacing and font for gameui.
KindTheme Kind = "theme"
// KindBusLayout is a BusLayout: sound buses and their effect chains.
KindBusLayout Kind = "busLayout"
// KindPhysicsMaterial is a PhysicsMaterial: friction, bounce and damping for rigid bodies.
KindPhysicsMaterial Kind = "physicsMaterial"
// KindAnimGraph is an AnimGraph: a 3D model's animation layers, state machines, one-shots and bone masks.
KindAnimGraph Kind = "animgraph"
// KindSound is a Sound: a sound cue's weighted variants, bus, ranges and attenuation.
KindSound Kind = "sound"
// KindMusic is Music: an adaptive piece's clips, stems, transitions and playlist.
KindMusic Kind = "music"
)func Kinds() []KindKinds returns every resource type this package reads, in a fixed order.
type Library struct {
// contains filtered or unexported fields
}Library loads resource files from a file system and shares them: every Load of one path returns the same pointer, so the scenes and code that use a resource all see one value, and Reload changes that value in place.
Paths are slash-separated and relative to the file system's root, as fs.ValidPath requires, such as "materials/stone.material.yaml".
Load and Reload are safe to call from any goroutine, but Reload writes the shared value that readers hold, so call it on the goroutine that reads resources, usually the engine's; hotreload.Watcher.WatchResources does.
func NewLibrary(fsys fs.FS) *LibraryNewLibrary returns a Library that reads files from fsys, such as os.DirFS(projectRoot) or an embed.FS.
func (l *Library) Animation(path string) (*Animation, error)Animation loads the animation clip at path. It lets a Library serve as an animclip.ClipResolver.
func (l *Library) Load(path string) (Resource, error)Load returns the resource at path, parsing it on first use and returning the shared value after that.
func (l *Library) Loaded(path string) boolLoaded reports whether path has been loaded.
func (l *Library) Material(path string) (*Material, error)Material loads the material at path. It lets a Library serve as a sceneformat.MaterialResolver.
func (l *Library) Paths() []stringPaths returns the loaded paths, sorted.
func (l *Library) PhysicsMaterial(path string) (*PhysicsMaterial, error)PhysicsMaterial loads the physics material at path. It lets a Library serve as a sceneformat.PhysicsMaterialResolver.
func (l *Library) Reload(path string, data []byte) (bool, error)Reload parses data as the new contents of path and, when path is loaded, copies them into the shared value so every holder sees them. It reports whether path was loaded; an unloaded path is ignored. On an error, including a file that changed its type, the loaded value is left as it was.
func (l *Library) ReloadFile(path string) (int64, bool, error)ReloadFile re-reads path from the library's file system and reloads it in place via Reload. It reports the file's byte size, whether path was loaded in the library, and any read or parse error. An unloaded path returns (0, false, nil). On error, the previously loaded resource stays unchanged.
func (l *Library) Revision() uint64Revision counts the successful reloads, so code that derives values from resources, such as a gameui.Theme built with Theme.Apply, can tell when to derive them again.
type LimiterEffect struct {
// CeilingDB is the loudest level a sample may reach.
CeilingDB float64 `yaml:"ceilingDb"`
}LimiterEffect clips every sample to its ceiling.
type Material struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// BaseColor is a CSS color parsed with core.ParseColor; empty is opaque white.
BaseColor string `yaml:"baseColor,omitempty"`
// Texture is an optional slash-separated path to the surface's image, relative to the project root.
Texture string `yaml:"texture,omitempty"`
// Opacity multiplies the alpha of everything drawn with the material, from 0 to 1; nil is 1.
Opacity *float32 `yaml:"opacity,omitempty"`
// Blend is how the surface mixes with what is beneath (see BlendModes); empty is "sourceOver".
Blend string `yaml:"blend,omitempty"`
// Metallic is the PBR metalness from 0 to 1.
Metallic float32 `yaml:"metallic,omitempty"`
// Roughness is the PBR roughness from 0 to 1; nil is 1.
Roughness *float32 `yaml:"roughness,omitempty"`
// Emissive is an optional CSS color the surface gives off; empty is none.
Emissive string `yaml:"emissive,omitempty"`
// DoubleSided draws a 3D surface's back faces too.
DoubleSided bool `yaml:"doubleSided,omitempty"`
// Unlit draws a 3D surface in its base color without lighting.
Unlit bool `yaml:"unlit,omitempty"`
// Shader is an optional slash-separated path, relative to the project root, to a custom .wgsl or .kage shader; a material that sets it may not set the built-in PBR fields (texture, metallic, roughness, emissive, unlit, the maps, shading, toon and vertexColors).
Shader string `yaml:"shader,omitempty"`
// Params contains typed values for Shader uniforms; it requires Shader.
Params ShaderParams `yaml:"params,omitempty"`
// NormalMap is an optional tangent-space normal map.
NormalMap *TextureMap `yaml:"normalMap,omitempty"`
// ORMMap is an optional occlusion-roughness-metallic map.
ORMMap string `yaml:"ormMap,omitempty"`
// MetallicMap is an optional separate metallic map.
MetallicMap string `yaml:"metallicMap,omitempty"`
// RoughnessMap is an optional separate roughness map.
RoughnessMap string `yaml:"roughnessMap,omitempty"`
// EmissiveMap is an optional emission map and strength.
EmissiveMap *TextureMap `yaml:"emissiveMap,omitempty"`
// Alpha selects opaque, cutout, hash or blend alpha handling.
Alpha AlphaSettings `yaml:"alpha,omitempty"`
// Cull selects back, front or no face culling.
Cull string `yaml:"cull,omitempty"`
// Depth controls depth writes and testing.
Depth DepthSettings `yaml:"depth,omitempty"`
// UV controls scale, offset and triplanar projection.
UV UVSettings `yaml:"uv,omitempty"`
// Filter is the texture filter: nearest, linear, nearestMipmap or linearMipmap.
Filter string `yaml:"filter,omitempty"`
// Repeat wraps texture coordinates outside [0, 1] when true and clamps them when false; nil keeps the renderer's default.
Repeat *bool `yaml:"repeat,omitempty"`
// VertexColors multiplies vertex colors into the base color.
VertexColors bool `yaml:"vertexColors,omitempty"`
// Shading selects pbr, unlit or toon shading.
Shading string `yaml:"shading,omitempty"`
// Toon holds the toon shading controls.
Toon ToonSettings `yaml:"toon,omitempty"`
}Material describes how a surface draws: its color and texture, how opaque it is and how it blends with what is beneath. 2D sprites use Opacity and Blend; 3D renderers also read the PBR fields.
func (m *Material) BlendOp() core.CompositeOpBlendOp returns the composite operation Blend names, core.CompositeSourceOver when it is empty or unknown.
func (m *Material) Color() core.ColorColor returns the parsed base color, opaque white when BaseColor is empty or invalid.
func (m *Material) EffectiveOpacity() float32EffectiveOpacity returns Opacity, 1 when it is nil.
func (m *Material) EffectiveRoughness() float32EffectiveRoughness returns Roughness, 1 when it is nil.
func (m *Material) EmissiveColor() (core.Color, bool)EmissiveColor returns the parsed emissive color and whether the material has one.
func (m *Material) Validate() errorValidate checks the header, colors, ranges and blend mode.
type Music struct {
Header `yaml:",inline"`
Name string `yaml:"name,omitempty"`
BPM float32 `yaml:"bpm"`
BeatsPerBar int `yaml:"beatsPerBar"`
Clips []MusicClip `yaml:"clips"`
Transitions []MusicTransition `yaml:"transitions,omitempty"`
Playlist *MusicPlaylist `yaml:"playlist,omitempty"`
}Music is a deterministic adaptive music piece with clips and bar-synced transitions.
func (m *Music) Validate() errorValidate checks the header, that the tempo and bar length are positive, that clips have unique names and either a source or stems with valid paths, that every clip a clip or transition names exists, and that transition points, fades and the playlist are valid, returning a *loaderr.Error naming the field at fault.
type MusicClip struct {
Name string `yaml:"name"`
Source string `yaml:"source,omitempty"`
Stems []string `yaml:"stems,omitempty"`
Loop bool `yaml:"loop,omitempty"`
Next string `yaml:"next,omitempty"`
}MusicClip is one named section of a piece of music: one source file or several stems played together, whether it loops, and the clip that follows it.
type MusicPlaylist struct {
Order string `yaml:"order"`
Crossfade float32 `yaml:"crossfade,omitempty"`
Seed uint64 `yaml:"seed,omitempty"`
}MusicPlaylist plays the clips in an order, cross-fading between them, with Seed fixing a shuffled order.
type MusicTransition struct {
From string `yaml:"from"`
To string `yaml:"to"`
At string `yaml:"at"`
FadeOut float32 `yaml:"fadeOut,omitempty"`
FadeIn float32 `yaml:"fadeIn,omitempty"`
Via string `yaml:"via,omitempty"`
}MusicTransition moves from clip From to clip To at the next point At names, such as a beat or a bar, fading the old clip out and the new one in over the given seconds, optionally through the clip Via.
type PannerEffect struct {
// Pan is -1 for the left channel, 0 for equal power and 1 for the right.
Pan float64 `yaml:"pan"`
}PannerEffect moves a stereo signal between the channels.
type PhaserEffect struct {
// RateHz is the sweep rate; it must be positive.
RateHz float64 `yaml:"rateHz"`
// Mix is the dry/wet mix from 0 to 1.
Mix float64 `yaml:"mix,omitempty"`
// Feedback feeds the wet output back, from 0 to 0.9.
Feedback float64 `yaml:"feedback,omitempty"`
}PhaserEffect sweeps four all-pass stages.
type PhysicsMaterial struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Friction is the Coulomb friction coefficient; it must be finite and non-negative.
Friction *float32 `yaml:"friction,omitempty"`
// Restitution is the bounce from 0, which stops dead, to 1, which bounces back fully.
Restitution *float32 `yaml:"restitution,omitempty"`
// LinearDamping and AngularDamping slow movement and spin each second; they must be finite and non-negative.
LinearDamping *float32 `yaml:"linearDamping,omitempty"`
AngularDamping *float32 `yaml:"angularDamping,omitempty"`
}PhysicsMaterial holds the surface properties of rigid bodies: friction, bounce and damping. A field left out keeps the body's own value when applied.
func (p *PhysicsMaterial) ApplyTo(body *physics.RigidBody)ApplyTo sets the fields the material holds on body, leaving the others as they are.
func (p *PhysicsMaterial) ApplyTo3D(body *physics3d.Body)ApplyTo3D sets the fields the material holds on a 3D physics body, leaving the others as they are.
func (p *PhysicsMaterial) Kind() KindKind returns KindPhysicsMaterial.
func (p *PhysicsMaterial) Validate() errorValidate checks the header and the ranges.
type PitchShiftEffect struct {
// Semitones is the shift from -48 to 48.
Semitones float64 `yaml:"semitones"`
}PitchShiftEffect retunes a signal by Semitones without changing its duration.
type Resource interface {
// Kind returns the resource's type.
Kind() Kind
// Validate checks the header and every field against the schema.
Validate() error
// contains filtered or unexported methods
}Resource is one parsed resource file: a *Material, *Curve, *Gradient, *Animation, *Theme, *BusLayout, *PhysicsMaterial, *AnimGraph, *Sound or *Music.
func New(kind Kind) (Resource, error)New returns an empty resource of kind with its header set, or an error for a kind this package does not know.
func Parse(data []byte) (Resource, error)Parse decodes one YAML resource file and validates it. It reads the header first, refuses an unknown type or unsupported version, then decodes the whole document into the matching type, refusing unknown fields and trailing documents.
type ReverbEffect struct {
// RoomSize, Damping and Wet are each from 0 to 1.
RoomSize float64 `yaml:"roomSize"`
Damping float64 `yaml:"damping,omitempty"`
Wet float64 `yaml:"wet"`
}ReverbEffect is a comb and allpass room reverb.
type ShaderParams struct {
// Scalars holds float uniforms.
Scalars map[string]float32 `yaml:"float,omitempty"`
// Vec2 holds vec2 uniforms.
Vec2 map[string][2]float32 `yaml:"vec2,omitempty"`
// Vec3 holds vec3 uniforms.
Vec3 map[string][3]float32 `yaml:"vec3,omitempty"`
// Vec4 holds vec4 uniforms.
Vec4 map[string][4]float32 `yaml:"vec4,omitempty"`
// Colors holds color uniforms as CSS colors parsed with core.ParseColor.
Colors map[string]string `yaml:"color,omitempty"`
// Textures holds texture uniforms as slash-separated image paths relative to the project root.
Textures map[string]string `yaml:"texture,omitempty"`
}ShaderParams holds typed values passed to a custom material shader. Maps are keyed by the shader uniform name, and a name is used by one map only.
type Sound struct {
Header `yaml:",inline"`
Name string `yaml:"name,omitempty"`
Bus string `yaml:"bus,omitempty"`
Limit int `yaml:"limit,omitempty"`
Mode string `yaml:"mode,omitempty"`
Pitch [2]float32 `yaml:"pitch,omitempty"`
Volume [2]float32 `yaml:"volume,omitempty"`
Variants []SoundVariant `yaml:"variants"`
Spatial *SoundSpatial `yaml:"spatial,omitempty"`
}Sound describes a deterministic randomized sound cue and optional 3D attenuation.
func (s *Sound) Validate() errorValidate checks the header and that the voice limit, pitch, volume and other ranges are valid, returning a *loaderr.Error naming the field at fault.
type SoundCone struct {
Inner float32 `yaml:"inner,omitempty"`
Outer float32 `yaml:"outer,omitempty"`
OuterGain float32 `yaml:"outerGain,omitempty"`
}SoundCone describes the full inner and outer cone angles in radians.
type SoundKey struct {
// Time is where the sound starts, from 0 to the clip's Length.
Time float32 `yaml:"time"`
// Sound is the project-relative path of the sound resource to play.
Sound string `yaml:"sound"`
}SoundKey plays a sound at a time on an Animation's timeline.
type SoundSpatial struct {
Near float32 `yaml:"near,omitempty"`
Far float32 `yaml:"far,omitempty"`
Rolloff string `yaml:"rolloff,omitempty"`
Cone *SoundCone `yaml:"cone,omitempty"`
}SoundSpatial describes optional distance attenuation and a directional cone.
type SoundVariant struct {
Source string `yaml:"source"`
Weight float32 `yaml:"weight,omitempty"`
}SoundVariant is one source clip and its relative selection weight.
type StereoWidthEffect struct {
// Width is 0 for mono, 1 unchanged and wider above 1.
Width float64 `yaml:"width"`
}StereoWidthEffect narrows or widens a stereo signal.
type StyleBorder struct {
// Width is the stroke width in points.
Width float32 `yaml:"width,omitempty"`
// Color is the stroke's CSS color.
Color string `yaml:"color,omitempty"`
}StyleBorder is a StyleBox's border stroke.
type StyleBox struct {
// Kind is flat, image or line.
Kind string `yaml:"kind"`
// Fill is the frame's CSS fill color.
Fill string `yaml:"fill,omitempty"`
// Border is the frame's border stroke.
Border *StyleBorder `yaml:"border,omitempty"`
// Radius is the corner radius in points.
Radius float32 `yaml:"radius,omitempty"`
// Image is the project-relative path of the image an image frame draws; only an image frame sets it, and it must.
Image string `yaml:"image,omitempty"`
}StyleBox describes a named flat, image or line widget frame.
type TextureMap struct {
// Texture is the slash-separated path to the map's image, relative to the project root.
Texture string `yaml:"texture"`
// Scale scales a normal map's effect, 0 or more; nil is 1.
Scale *float32 `yaml:"scale,omitempty"`
// Strength scales an emission map's output, 0 or more; nil is 1.
Strength *float32 `yaml:"strength,omitempty"`
}TextureMap names an optional image map and its scalar control.
type Theme struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Colors holds the theme's CSS colors, each parsed with core.ParseColor.
Colors ThemeColors `yaml:"colors,omitempty"`
// Padding is the default inner padding in points.
Padding *float32 `yaml:"padding,omitempty"`
// CornerRadius is the default corner radius in points.
CornerRadius *float32 `yaml:"cornerRadius,omitempty"`
// BorderWidth is the widget border stroke width in points.
BorderWidth *float32 `yaml:"borderWidth,omitempty"`
// FocusWidth is the focus outline stroke width in points.
FocusWidth *float32 `yaml:"focusWidth,omitempty"`
// Font is the default font of text-bearing widgets.
Font *ThemeFont `yaml:"font,omitempty"`
// StyleBoxes are named widget frames that widget styles refer to by name.
StyleBoxes map[string]StyleBox `yaml:"styleBoxes,omitempty"`
// Types holds the style of each widget type, such as button or label, keyed by the type's name.
Types map[string]WidgetStyle `yaml:"types,omitempty"`
// Variations are named styles derived from a widget type's style, which a widget picks by name.
Variations map[string]ThemeVariation `yaml:"variations,omitempty"`
}Theme is a UI theme for gameui: colors, spacing and font. Every field is optional; Apply overrides only the fields a file sets, so a theme file can restyle a few colors of gameui.DefaultTheme.
func (t *Theme) Apply(base gameui.Theme) gameui.ThemeApply returns base with every field the theme sets replaced. Fields the file leaves out keep base's values, as do gameui.Theme fields a file cannot hold, such as frame drawers.
func (t *Theme) Validate() errorValidate checks the header, every color, the sizes and the fonts, every style box, and that every variation names its base.
type ThemeColors struct {
PanelBackground string `yaml:"panelBackground,omitempty"`
PanelBorder string `yaml:"panelBorder,omitempty"`
Background string `yaml:"background,omitempty"`
Hover string `yaml:"hover,omitempty"`
Active string `yaml:"active,omitempty"`
FocusedBorder string `yaml:"focusedBorder,omitempty"`
Disabled string `yaml:"disabled,omitempty"`
Border string `yaml:"border,omitempty"`
Text string `yaml:"text,omitempty"`
DisabledText string `yaml:"disabledText,omitempty"`
MutedText string `yaml:"mutedText,omitempty"`
Accent string `yaml:"accent,omitempty"`
AccentHover string `yaml:"accentHover,omitempty"`
AccentActive string `yaml:"accentActive,omitempty"`
Track string `yaml:"track,omitempty"`
}ThemeColors holds a Theme's colors, one per gameui.Theme color field; an empty one keeps the base theme's.
type ThemeFont struct {
// Family is a font family name.
Family string `yaml:"family,omitempty"`
// Size is the font size in points; 0 keeps the base theme's.
Size float32 `yaml:"size,omitempty"`
// Weight is "light", "normal", "medium", "semibold" or "bold".
Weight string `yaml:"weight,omitempty"`
// Italic sets the italic style when true; nil keeps the base theme's.
Italic *bool `yaml:"italic,omitempty"`
}ThemeFont is a Theme's default font; an empty or zero field keeps the base theme's.
type ThemeVariation struct {
// Base names the widget type whose style the variation starts from.
Base string `yaml:"base"`
// Normal overrides properties of the base style's normal state.
Normal map[string]any `yaml:"normal,omitempty"`
// Font overrides the base style's font.
Font *ThemeFont `yaml:"font,omitempty"`
}ThemeVariation is a named style derived from the widget style Base, overriding its normal properties and its font.
type ToonSettings struct {
// Bands is the number of lighting bands, 0 or more; 0 is unset.
Bands float32 `yaml:"bands,omitempty"`
// Rim is the rim light amount from 0 to 1.
Rim float32 `yaml:"rim,omitempty"`
}ToonSettings contains the optional toon shading controls.
type Track struct {
// Target names the object the track drives, such as the ID of an object in a scene (animclip binds it that way); empty is the object the clip plays on.
Target string `yaml:"target,omitempty"`
// Property names the property, such as "x", "rotation", "alpha" or "sprite.frame".
Property string `yaml:"property"`
// Keys are the track's numeric keys, with times from 0 to the clip's Length. A track sets either Keys or Frames, not both.
Keys []Key `yaml:"keys,omitempty"`
// Frames are the track's discrete sprite frame keys, with times from 0 to the clip's Length, stepping without interpolation. A track sets either Keys or Frames, not both.
Frames []FrameKey `yaml:"frames,omitempty"`
}Track keys one property of one target over an Animation's length: numeric values in Keys or discrete sprite frames in Frames.
func (tr *Track) Eval(t float32) float32Eval returns the numeric track's value at clip time t, holding the first and last keys' values before and after them.
func (tr *Track) EvalFrame(t float32) stringEvalFrame returns the discrete frame track's frame name at clip time t, holding the first frame before it and stepping at each key's time without interpolation.
func (tr *Track) IsFrameTrack() boolIsFrameTrack reports whether tr holds discrete sprite frame keys rather than numeric keys.
type UVSettings struct {
// Scale multiplies texture coordinates; [0, 0] is unset.
Scale [2]float32 `yaml:"scale,omitempty"`
// Offset is added to texture coordinates after Scale.
Offset [2]float32 `yaml:"offset,omitempty"`
// Triplanar projects textures along the three world axes instead of reading texture coordinates.
Triplanar bool `yaml:"triplanar,omitempty"`
}UVSettings controls texture coordinate scale, offset and triplanar sampling.
func (u UVSettings) IsZero() boolIsZero reports whether u sets nothing, so a material without UV settings writes no uv block. yaml.v3's omitempty never omits arrays such as Scale and Offset by itself.
type WidgetStyle struct {
Normal map[string]any `yaml:"normal,omitempty"`
Hover map[string]any `yaml:"hover,omitempty"`
Pressed map[string]any `yaml:"pressed,omitempty"`
Disabled map[string]any `yaml:"disabled,omitempty"`
Font *ThemeFont `yaml:"font,omitempty"`
}WidgetStyle overrides a widget's style properties in its normal, hovered, pressed and disabled states, and its font.