Documentation
¶
Overview ¶
Package resource reads, validates and writes shared resource files: reusable data that scenes and code reference by path instead of repeating it, as Godot's .tres files are.
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) and physicsMaterial (PhysicsMaterial). 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.
Index ¶
- Constants
- 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 Animation
- type BitcrushEffect
- type Bus
- type BusEffect
- type BusLayout
- type Curve
- type DelayEffect
- type Event
- type FilterEffect
- type FrameKey
- type GainEffect
- type Gradient
- type GradientStop
- type Header
- type Interp
- type Key
- type Kind
- type 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 Material
- type PhysicsMaterial
- type Resource
- type ReverbEffect
- type Theme
- type ThemeColors
- type ThemeFont
- type Track
Examples ¶
Constants ¶
const CurrentVersion = 1
CurrentVersion is the resource schema version this package reads and writes.
const UIDLength = 13
UIDLength is how many characters a UID has.
Variables ¶
This section is empty.
Functions ¶
func BlendModes ¶
func BlendModes() []string
BlendModes returns the names Material.Blend accepts, sorted: the canvas composite operations in camel case, such as "sourceOver", "multiply" and "lighter".
func Encode ¶
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.
Example ¶
Encode writes a resource with its header and fields in a fixed order, so a file Encode wrote parses and encodes back to the same bytes; Parse refuses unknown fields.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/resource"
)
const stoneMaterial = `type: material
version: 1
name: Stone
baseColor: '#8a8f99'
opacity: 0.75
blend: multiply
`
func main() {
m := &resource.Material{Header: resource.NewHeader(resource.KindMaterial), Name: "Glass", Blend: "screen"}
out, err := resource.Encode(m)
fmt.Print(string(out))
fmt.Println(err)
r, err := resource.Parse(out)
fmt.Println(r.Kind(), err)
_, err = resource.Parse([]byte(stoneMaterial + "shininess: 3\n"))
fmt.Println(err != nil)
}
Output: type: material version: 1 name: Glass blend: screen <nil> material <nil> true
func LoadAs ¶
LoadAs loads the resource at path from l and returns it as T, failing when the file holds another type.
func NewUID ¶
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 ¶
ParseAs parses data and returns it as T, failing when the file holds another type.
Example ¶
ParseAs reads a resource file of an expected type; Eval samples a curve between its keys with each key's interpolation.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/resource"
)
const stoneMaterial = `type: material
version: 1
name: Stone
baseColor: '#8a8f99'
opacity: 0.75
blend: multiply
`
func main() {
curve, err := resource.ParseAs[*resource.Curve]([]byte(`type: curve
version: 1
name: Jump height
keys:
- time: 0
value: 0
interp: smooth
- time: 0.5
value: 1
- time: 1
value: 0
`))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(curve.Name, curve.Eval(0.25), curve.Eval(0.5), curve.Eval(0.75), curve.Eval(2))
_, err = resource.ParseAs[*resource.Curve]([]byte(stoneMaterial))
fmt.Println(err != nil)
}
Output: Jump height 0.5 1 0.5 0 true
Types ¶
type Animation ¶
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"`
}
Animation is a clip of property tracks keyed over its length, played on a scene object or node.
func (*Animation) ClipTime ¶
ClipTime 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 (*Animation) Sample ¶
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 (*Animation) SampleFrames ¶
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.
type BitcrushEffect ¶
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 ¶
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) Chain ¶
func (bus *Bus) Chain() sound.EffectChain
Chain returns the bus's effects as a sound.EffectChain, in order.
type BusEffect ¶
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"`
}
BusEffect is one effect on a bus. Exactly one field must be set.
type BusLayout ¶
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.
type Curve ¶
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.
type DelayEffect ¶
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 Event ¶
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"`
}
Event is one named cue on an Animation's timeline.
type FilterEffect ¶
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 ¶
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 ¶
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 Gradient ¶
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 (*Gradient) At ¶
At returns the gradient's color at t, mixing each channel linearly between the stops around it and holding the end colors beyond them.
func (*Gradient) CoreStops ¶
func (g *Gradient) CoreStops() []core.GradientStop
CoreStops returns the stops as core.GradientStop values for a canvas gradient. A stop whose color does not parse is transparent.
type GradientStop ¶
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 ¶
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.
type Key ¶
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 ¶
type Kind string
Kind 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" )
type Library ¶
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.
Example ¶
A Library shares one value per path, so everything that loads a material holds the same pointer, and Reload changes it in place for all of them.
package main
import (
"fmt"
"testing/fstest"
"github.com/nsgo-dev/game/pkg/resource"
)
const stoneMaterial = `type: material
version: 1
name: Stone
baseColor: '#8a8f99'
opacity: 0.75
blend: multiply
`
func main() {
lib := resource.NewLibrary(fstest.MapFS{
"materials/stone.material.yaml": {Data: []byte(stoneMaterial)},
})
wall, err := lib.Material("materials/stone.material.yaml")
if err != nil {
fmt.Println(err)
return
}
floor, _ := lib.Material("materials/stone.material.yaml")
fmt.Println(wall == floor, wall.Name, wall.EffectiveOpacity(), wall.Blend)
// An edit to the file, as hotreload.Watcher.WatchResources delivers it, reaches every holder.
loaded, err := lib.Reload("materials/stone.material.yaml", []byte("type: material\nversion: 1\nname: Mossy stone\nopacity: 0.5\n"))
fmt.Println(loaded, err, floor.Name, floor.EffectiveOpacity(), lib.Revision())
}
Output: true Stone 0.75 multiply true <nil> Mossy stone 0.5 1
func NewLibrary ¶
NewLibrary returns a Library that reads files from fsys, such as os.DirFS(projectRoot) or an embed.FS.
func (*Library) Animation ¶
Animation loads the animation clip at path. It lets a Library serve as an animclip.ClipResolver.
func (*Library) Load ¶
Load returns the resource at path, parsing it on first use and returning the shared value after that.
func (*Library) Material ¶
Material loads the material at path. It lets a Library serve as a sceneformat.MaterialResolver.
func (*Library) PhysicsMaterial ¶
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 (*Library) Reload ¶
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 (*Library) ReloadFile ¶
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.
type Material ¶
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"`
}
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 (*Material) BlendOp ¶
func (m *Material) BlendOp() core.CompositeOp
BlendOp returns the composite operation Blend names, core.CompositeSourceOver when it is empty or unknown.
func (*Material) Color ¶
Color returns the parsed base color, opaque white when BaseColor is empty or invalid.
func (*Material) EffectiveOpacity ¶
EffectiveOpacity returns Opacity, 1 when it is nil.
func (*Material) EffectiveRoughness ¶
EffectiveRoughness returns Roughness, 1 when it is nil.
func (*Material) EmissiveColor ¶
EmissiveColor returns the parsed emissive color and whether the material has one.
type PhysicsMaterial ¶
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 (*PhysicsMaterial) ApplyTo ¶
func (p *PhysicsMaterial) ApplyTo(body *physics.RigidBody)
ApplyTo sets the fields the material holds on body, leaving the others as they are.
func (*PhysicsMaterial) ApplyTo3D ¶
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 (*PhysicsMaterial) Kind ¶
func (p *PhysicsMaterial) Kind() Kind
Kind returns KindPhysicsMaterial.
func (*PhysicsMaterial) Validate ¶
func (p *PhysicsMaterial) Validate() error
Validate checks the header and the ranges.
type Resource ¶
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 or *PhysicsMaterial.
type ReverbEffect ¶
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 Theme ¶
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"`
}
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.
type ThemeColors ¶
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 ¶
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 Track ¶
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 (*Track) Eval ¶
Eval returns the numeric track's value at clip time t, holding the first and last keys' values before and after them.
func (*Track) EvalFrame ¶
EvalFrame 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 (*Track) IsFrameTrack ¶
IsFrameTrack reports whether tr holds discrete sprite frame keys rather than numeric keys.