Documentation
¶
Overview ¶
Package resource is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package resource 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), music (Music) and labelStyle (LabelStyle). 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 Clone[T Resource](r T) T
- func Encode(r Resource) ([]byte, error)
- func EvalBezierSegment(dt, v0, v1 float64, out, in *[2]float32, u float64) float64
- func LerpColor(a, b core.Color, u float64) core.Color
- 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 RegisterKind(spec KindSpec) error
- func Schema(opts jsonschema.Options) (*jsonschema.Schema, error)
- func ValidUID(s string) bool
- func ValidateKindSpec(spec KindSpec) error
- type AlphaSettings
- type AnimGraph
- type AnimGraphAdd
- type AnimGraphBlend
- type AnimGraphBlend1D
- type AnimGraphBlend2D
- type AnimGraphBoneWeight
- type AnimGraphChainIK
- type AnimGraphFoot
- type AnimGraphFootPlacement
- type AnimGraphJointLimit
- type AnimGraphLayer
- type AnimGraphLookAt
- type AnimGraphMachine
- type AnimGraphMask
- type AnimGraphModifier
- type AnimGraphOneShot
- type AnimGraphParam
- type AnimGraphRoot
- type AnimGraphSample
- type AnimGraphSample2D
- type AnimGraphSpringBones
- type AnimGraphSpringCapsule
- type AnimGraphSpringChain
- type AnimGraphSpringCollider
- type AnimGraphSpringJoint
- type AnimGraphSpringPlane
- type AnimGraphSpringSphere
- type AnimGraphState
- type AnimGraphTimeScale
- type AnimGraphTimeSeek
- type AnimGraphTransition
- type AnimGraphTwoBoneIK
- type Animation
- func (a *Animation) ClipTime(t float32) float32
- func (a *Animation) Kind() Kind
- func (a *Animation) Sample(t float32, set func(target, property string, value float32))
- func (a *Animation) SampleColors(t float32, set func(target, property string, color core.Color))
- func (a *Animation) SampleFrames(t float32, set func(target, property, frame string))
- func (a *Animation) Validate() error
- type BandFilterEffect
- type BitcrushEffect
- type Bus
- type BusEffect
- type BusLayout
- type ChorusEffect
- type ClipKey
- type ColorKey
- type CompressorEffect
- type Curve
- type CustomEffect
- 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 KindSpec
- type LabelStyle
- type Library
- func (l *Library) AnimGraph(path string) (*AnimGraph, error)
- func (l *Library) Animation(path string) (*Animation, error)
- func (l *Library) LabelStyle(path string) (*LabelStyle, 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) Music(path string) (*Music, error)
- func (l *Library) Paths() []string
- func (l *Library) PhysicsMaterial(path string) (*PhysicsMaterial, error)
- func (l *Library) Release(path string) bool
- func (l *Library) Reload(path string, data []byte) (bool, error)
- func (l *Library) ReloadFile(path string) (int64, bool, error)
- func (l *Library) Retain(path string)
- func (l *Library) Revision() uint64
- func (l *Library) Source(path string) ([]byte, bool)
- 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 SoundCaption
- type SoundCone
- type SoundKey
- type SoundSpatial
- type SoundVariant
- type StereoWidthEffect
- type StyleBorder
- type StyleBox
- type StyleCorners
- type StyleShadow
- type StyleSides
- type TextOffset
- type TextureMap
- type Theme
- type ThemeColors
- type ThemeFont
- type ThemeStateStyle
- type ThemeVariation
- type ToonSettings
- type Track
- type UVSettings
- type WidgetStyle
Examples ¶
Constants ¶
const CurrentVersion = 1
CurrentVersion is the resource schema version this package reads and writes.
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURL
SchemaComment is the first line Encode writes: a YAML comment that points a YAML language server at SchemaURL. Parse ignores it like any other comment.
const SchemaURL = "https://nsgo.games/schemas/resource.v1.json"
SchemaURL is where the JSON Schema of version 1 resource files is published. Encode names it in a yaml-language-server comment on a file's first line, so editors and AI tools validate and complete resource files as they are written.
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 Clone ¶
func Clone[T Resource](r T) T
Clone returns a deep copy of r with no shared slices, maps or nested pointers. The copy keeps Header.UID so tools still identify the source file. Passing a nil Resource or a typed nil pointer returns the zero value of T.
func Encode ¶
Encode validates r and writes it as deterministic 2-space YAML, SchemaComment on its first line: the header first, then the type's fields in declaration order, omitting fields left at their defaults. A plugin kind registered with RegisterKind has no arm in the published schema, so its file gets no schema comment.
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: # yaml-language-server: $schema=https://nsgo.games/schemas/resource.v1.json type: material version: 1 name: Glass blend: screen <nil> material <nil> true
func EvalBezierSegment ¶
EvalBezierSegment evaluates a cubic Bezier segment of duration dt between values v0 and v1 at normalized time progress u in [0, 1], shaped by outgoing handle out (offset [dt, dv] from (0, v0)) and incoming handle in (offset [dt, dv] from (dt, v1)). Non-finite or out-of-range handle offsets are clamped so time stays monotonic, and degenerate zero-slope tangents fall back to bisection.
func LerpColor ¶
LerpColor mixes each 8-bit RGBA channel of a and b at progress u, clamping each channel to [0, 255] so overshooting eases stay valid.
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
func RegisterKind ¶
RegisterKind registers a plugin-provided resource kind for New, Parse, ParseAs and Library. Built-in kinds cannot be overridden, spec.Kind must be namespaced as "<plugin>.<name>" (such as "dialoguekit.graph"), and registering the same kind twice fails.
func Schema ¶
func Schema(opts jsonschema.Options) (*jsonschema.Schema, error)
Schema returns the draft-07 JSON Schema of version 1 resource files, for an editor or AI tool to validate and complete them while they are written.
A resource file is one of the built-in kinds, so the schema is a oneOf over one schema per kind: each names its `type` and `version` as the only allowed values, and refuses keys its kind does not define, as Parse does. A plugin kind registered with RegisterKind has fields this schema cannot know, so no arm covers it.
func ValidUID ¶
ValidUID 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.
func ValidateKindSpec ¶
ValidateKindSpec checks that spec declares a valid namespaced plugin resource kind and constructor without registering it.
Types ¶
type AlphaSettings ¶
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 ¶
type AnimGraph struct {
Header `yaml:",inline"`
Name string `yaml:"name,omitempty"`
Model string `yaml:"model"`
Params []AnimGraphParam `yaml:"params,omitempty"`
Root AnimGraphRoot `yaml:"root"`
Modifiers []AnimGraphModifier `yaml:"modifiers,omitempty"`
}
AnimGraph is a text-authored 3D animation graph with layers, state machines, blend spaces, one-shots, blend/additive nodes, time modifiers, named bone masks, and optional post-animation skeleton modifiers.
func (*AnimGraph) Validate ¶
Validate 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 pose source whose states, transitions, blends, parameters, time modifiers, masks, weights and modes are consistent, returning a *loaderr.Error naming the field at fault.
type AnimGraphAdd ¶
type AnimGraphAdd struct {
Clip string `yaml:"clip"`
Ref string `yaml:"ref,omitempty"`
Param string `yaml:"param,omitempty"`
Amount *float32 `yaml:"amount,omitempty"`
Loop *bool `yaml:"loop,omitempty"`
}
AnimGraphAdd applies an additive clip (optionally computed relative to the reference clip Ref at time 0) at Amount (in [0, 1]) or a float parameter Param.
type AnimGraphBlend ¶
type AnimGraphBlend struct {
A string `yaml:"a"`
B string `yaml:"b"`
Param string `yaml:"param,omitempty"`
Weight *float32 `yaml:"weight,omitempty"`
Loop *bool `yaml:"loop,omitempty"`
}
AnimGraphBlend blends between two clips A and B by Weight (in [0, 1]) or a float parameter Param.
type AnimGraphBlend1D ¶
type AnimGraphBlend1D struct {
Param string `yaml:"param"`
Samples []AnimGraphSample `yaml:"samples"`
}
AnimGraphBlend1D blends the clips of Samples by the value of the float parameter Param.
type AnimGraphBlend2D ¶
type AnimGraphBlend2D struct {
ParamX string `yaml:"paramX"`
ParamY string `yaml:"paramY"`
Samples []AnimGraphSample2D `yaml:"samples"`
}
AnimGraphBlend2D blends the clips of Samples by two float parameters ParamX and ParamY.
type AnimGraphBoneWeight ¶
AnimGraphBoneWeight sets the blend weight (in [0, 1]) of one named bone in an AnimGraphMask.
type AnimGraphChainIK ¶
type AnimGraphChainIK struct {
Root string `yaml:"root"`
Tip string `yaml:"tip"`
Solver string `yaml:"solver,omitempty"`
Iterations int `yaml:"iterations,omitempty"`
Tolerance float32 `yaml:"tolerance,omitempty"`
Limits []AnimGraphJointLimit `yaml:"limits,omitempty"`
}
AnimGraphChainIK configures an arbitrary bone chain (Root .. Tip) solved by "fabrik" (default) or "ccd", with optional per-joint Limits.
type AnimGraphFoot ¶
type AnimGraphFoot struct {
Foot string `yaml:"foot"`
UpperLeg string `yaml:"upperLeg,omitempty"`
LowerLeg string `yaml:"lowerLeg,omitempty"`
PoleBone string `yaml:"poleBone,omitempty"`
FootHeight float32 `yaml:"footHeight,omitempty"`
}
AnimGraphFoot configures one leg/foot chain inside AnimGraphFootPlacement.Feet.
type AnimGraphFootPlacement ¶
type AnimGraphFootPlacement struct {
Foot string `yaml:"foot,omitempty"`
Feet []AnimGraphFoot `yaml:"feet,omitempty"`
Pelvis string `yaml:"pelvis,omitempty"`
UpperLeg string `yaml:"upperLeg,omitempty"`
LowerLeg string `yaml:"lowerLeg,omitempty"`
PoleBone string `yaml:"poleBone,omitempty"`
RayUp float32 `yaml:"rayUp,omitempty"`
RayDown float32 `yaml:"rayDown,omitempty"`
FootHeight float32 `yaml:"footHeight,omitempty"`
MaxPelvisOffset float32 `yaml:"maxPelvisOffset,omitempty"`
MaxFootTilt float32 `yaml:"maxFootTilt,omitempty"`
Up []float32 `yaml:"up,omitempty"`
}
AnimGraphFootPlacement configures ground ray-cast foot placement and pelvis height adjustment by bone name; the Ray callback is attached at runtime.
type AnimGraphJointLimit ¶
type AnimGraphJointLimit struct {
Bone string `yaml:"bone"`
Axis []float32 `yaml:"axis,omitempty"`
MinAngle float32 `yaml:"minAngle,omitempty"`
MaxAngle float32 `yaml:"maxAngle,omitempty"`
}
AnimGraphJointLimit constrains one bone's rotation relative to its rest pose inside a ChainIK modifier.
type AnimGraphLayer ¶
type AnimGraphLayer struct {
Name string `yaml:"name"`
Machine *AnimGraphMachine `yaml:"machine,omitempty"`
OneShot *AnimGraphOneShot `yaml:"oneShot,omitempty"`
Clip string `yaml:"clip,omitempty"`
Blend1D *AnimGraphBlend1D `yaml:"blend1d,omitempty"`
Blend2D *AnimGraphBlend2D `yaml:"blend2d,omitempty"`
Blend *AnimGraphBlend `yaml:"blend,omitempty"`
Add *AnimGraphAdd `yaml:"add,omitempty"`
Loop *bool `yaml:"loop,omitempty"`
TimeScale *AnimGraphTimeScale `yaml:"timeScale,omitempty"`
TimeSeek *AnimGraphTimeSeek `yaml:"timeSeek,omitempty"`
Mask *AnimGraphMask `yaml:"mask,omitempty"`
Mode string `yaml:"mode,omitempty"`
Weight *float32 `yaml:"weight,omitempty"`
WeightParam string `yaml:"weightParam,omitempty"`
}
AnimGraphLayer is one layer of the graph: exactly one pose source (machine, oneShot, clip, blend1d, blend2d, blend or add), optionally modified by timeScale/timeSeek, masked to a branch or set of bones by name, weighted, and combined with the layers below it by Mode.
type AnimGraphLookAt ¶
type AnimGraphLookAt struct {
Bone string `yaml:"bone"`
Forward []float32 `yaml:"forward,omitempty"`
Up []float32 `yaml:"up,omitempty"`
MaxYaw float32 `yaml:"maxYaw,omitempty"`
MaxPitch float32 `yaml:"maxPitch,omitempty"`
Smooth float32 `yaml:"smooth,omitempty"`
}
AnimGraphLookAt aims Bone's local Forward axis toward its runtime world-space target within MaxYaw and MaxPitch radians, optionally smoothed at Smooth (1/s).
type AnimGraphMachine ¶
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 ¶
type AnimGraphMask struct {
Branch string `yaml:"branch,omitempty"`
Weight float32 `yaml:"weight,omitempty"`
Bones []AnimGraphBoneWeight `yaml:"bones,omitempty"`
}
AnimGraphMask limits a layer to the skeleton branch rooted at Branch (at Weight) and/or explicit per-bone weights in Bones, all addressed by bone name.
type AnimGraphModifier ¶
type AnimGraphModifier struct {
Name string `yaml:"name,omitempty"`
Influence *float32 `yaml:"influence,omitempty"`
InfluenceParam string `yaml:"influenceParam,omitempty"`
LookAt *AnimGraphLookAt `yaml:"lookAt,omitempty"`
TwoBoneIK *AnimGraphTwoBoneIK `yaml:"twoBoneIK,omitempty"`
ChainIK *AnimGraphChainIK `yaml:"chainIK,omitempty"`
FootPlacement *AnimGraphFootPlacement `yaml:"footPlacement,omitempty"`
SpringBones *AnimGraphSpringBones `yaml:"springBones,omitempty"`
}
AnimGraphModifier defines one post-animation skeleton modifier applied in declaration order after the graph's layers. Exactly one of LookAt, TwoBoneIK, ChainIK, FootPlacement, or SpringBones must be set.
type AnimGraphOneShot ¶
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 trigger parameter is set, fading in and out over the given seconds and returning automatically when done.
type AnimGraphParam ¶
AnimGraphParam declares one parameter the game sets to drive the graph, by name and type ("float", "bool" or "trigger").
type AnimGraphRoot ¶
type AnimGraphRoot struct {
Layers []AnimGraphLayer `yaml:"layers"`
}
AnimGraphRoot is the graph's layers, blended in order.
type AnimGraphSample ¶
type AnimGraphSample struct {
At float32 `yaml:"at"`
Clip string `yaml:"clip"`
FootPhaseOffset float32 `yaml:"footPhaseOffset,omitempty"`
}
AnimGraphSample places a clip at the value At of a 1D blend's parameter, with an optional normalized foot-phase offset.
type AnimGraphSample2D ¶
type AnimGraphSample2D struct {
X float32 `yaml:"x"`
Y float32 `yaml:"y"`
Clip string `yaml:"clip"`
FootPhaseOffset float32 `yaml:"footPhaseOffset,omitempty"`
}
AnimGraphSample2D places a clip at the 2D coordinate (X, Y) of a 2D blend space, with an optional normalized foot-phase offset.
type AnimGraphSpringBones ¶
type AnimGraphSpringBones struct {
FromGLTF bool `yaml:"fromGLTF,omitempty"`
Wind []float32 `yaml:"wind,omitempty"`
Chains []AnimGraphSpringChain `yaml:"chains,omitempty"`
Colliders []AnimGraphSpringCollider `yaml:"colliders,omitempty"`
}
AnimGraphSpringBones configures a post-animation spring-bone secondary-motion modifier in an AnimGraph. Chains can be authored explicitly in Chains and/or imported from the model's VRMC_springBone extension via FromGLTF.
type AnimGraphSpringCapsule ¶
type AnimGraphSpringCapsule struct {
Offset []float32 `yaml:"offset,omitempty"`
Tail []float32 `yaml:"tail,omitempty"`
Radius float32 `yaml:"radius"`
Inside bool `yaml:"inside,omitempty"`
}
AnimGraphSpringCapsule configures a capsule collider from Offset to Tail in bone local space.
type AnimGraphSpringChain ¶
type AnimGraphSpringChain struct {
Name string `yaml:"name,omitempty"`
Root string `yaml:"root,omitempty"`
Tip string `yaml:"tip,omitempty"`
Center string `yaml:"center,omitempty"`
Stiffness float32 `yaml:"stiffness,omitempty"`
Drag float32 `yaml:"drag,omitempty"`
Gravity []float32 `yaml:"gravity,omitempty"`
Radius float32 `yaml:"radius,omitempty"`
RotationAxis []float32 `yaml:"rotationAxis,omitempty"`
Joints []AnimGraphSpringJoint `yaml:"joints,omitempty"`
ColliderGroups []string `yaml:"colliderGroups,omitempty"`
}
AnimGraphSpringChain describes one secondary-motion bone chain in an AnimGraph. Specify either Root and Tip (with optional per-joint overrides in Joints) or an explicit list of at least two Joints.
type AnimGraphSpringCollider ¶
type AnimGraphSpringCollider struct {
Bone string `yaml:"bone,omitempty"`
Group string `yaml:"group,omitempty"`
Sphere *AnimGraphSpringSphere `yaml:"sphere,omitempty"`
Capsule *AnimGraphSpringCapsule `yaml:"capsule,omitempty"`
Plane *AnimGraphSpringPlane `yaml:"plane,omitempty"`
}
AnimGraphSpringCollider attaches a sphere, capsule, or plane collider to Bone (or the model root when Bone is empty) inside AnimGraphSpringBones.
type AnimGraphSpringJoint ¶
type AnimGraphSpringJoint struct {
Bone string `yaml:"bone"`
Stiffness *float32 `yaml:"stiffness,omitempty"`
Drag *float32 `yaml:"drag,omitempty"`
Gravity []float32 `yaml:"gravity,omitempty"`
Radius *float32 `yaml:"radius,omitempty"`
RotationAxis []float32 `yaml:"rotationAxis,omitempty"`
}
AnimGraphSpringJoint configures one joint inside AnimGraphSpringChain.Joints.
type AnimGraphSpringPlane ¶
type AnimGraphSpringPlane struct {
Offset []float32 `yaml:"offset,omitempty"`
Normal []float32 `yaml:"normal,omitempty"`
}
AnimGraphSpringPlane configures a plane collider through Offset with outward Normal in bone local space.
type AnimGraphSpringSphere ¶
type AnimGraphSpringSphere struct {
Offset []float32 `yaml:"offset,omitempty"`
Radius float32 `yaml:"radius"`
Inside bool `yaml:"inside,omitempty"`
}
AnimGraphSpringSphere configures a sphere collider in bone local space.
type AnimGraphState ¶
type AnimGraphState struct {
Name string `yaml:"name"`
Clip string `yaml:"clip,omitempty"`
Blend1D *AnimGraphBlend1D `yaml:"blend1d,omitempty"`
Blend2D *AnimGraphBlend2D `yaml:"blend2d,omitempty"`
Loop *bool `yaml:"loop,omitempty"`
Speed float32 `yaml:"speed,omitempty"`
TimeScale *AnimGraphTimeScale `yaml:"timeScale,omitempty"`
TimeSeek *AnimGraphTimeSeek `yaml:"timeSeek,omitempty"`
}
AnimGraphState is one state of a machine, playing a clip, a 1D blend space, or a 2D blend space, with optional loop override, speed, timeScale and timeSeek modifiers.
type AnimGraphTimeScale ¶
type AnimGraphTimeScale struct {
Scale *float32 `yaml:"scale,omitempty"`
Param string `yaml:"param,omitempty"`
}
AnimGraphTimeScale scales playback speed by a fixed non-negative Scale, a float parameter Param, or both multiplied together.
type AnimGraphTimeSeek ¶
type AnimGraphTimeSeek struct {
Time *float32 `yaml:"time,omitempty"`
Param string `yaml:"param,omitempty"`
}
AnimGraphTimeSeek seeks playback to a fixed non-negative Time (in seconds) or a float parameter Param.
type AnimGraphTransition ¶
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 From (a state name or "*" for any state) to To when its condition holds, cross-fading over XFade seconds.
type AnimGraphTwoBoneIK ¶
type AnimGraphTwoBoneIK struct {
Root string `yaml:"root"`
Mid string `yaml:"mid"`
Tip string `yaml:"tip"`
PoleBone string `yaml:"poleBone,omitempty"`
}
AnimGraphTwoBoneIK configures a two-bone inverse kinematics chain (Root -> Mid -> Tip) with an optional PoleBone to steer the hinge bend plane.
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"`
// 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 (*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) SampleColors ¶
SampleColors evaluates every color track at play time t (mapped through ClipTime) and calls set with each track's target, property and color, in track order.
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 BandFilterEffect ¶
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 ¶
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"`
// 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"`
// Custom is a plugin-registered bus effect built through sound.RegisterEffect.
Custom *CustomEffect `yaml:"custom,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.
func (*BusLayout) Apply ¶
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 (*BusLayout) ApplySoftware ¶
func (b *BusLayout) ApplySoftware(m *sound.SoftwareMixer)
ApplySoftware sets each bus's stateful effect chain (including sidechain compressors and lookahead limiters) on m with sound.SoftwareMixer.SetBusEffects.
type ChorusEffect ¶
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 ¶
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 ColorKey ¶
type ColorKey struct {
// Time is where the color sits, from 0 to the clip's Length; color keys must be in strictly increasing Time order.
Time float32 `yaml:"time"`
// Color is a CSS color parsed with core.ParseColor, such as "#ff4040" or "rgba(255, 64, 64, 0.5)".
Color string `yaml:"color"`
// Interp is how the color moves from this key to the next; empty is InterpLinear. InterpBezier is not allowed on color keys.
Interp Interp `yaml:"interp,omitempty"`
}
ColorKey is one keyed color on a color animation Track, moving to the next key's color according to Interp (empty is InterpLinear).
type CompressorEffect ¶
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"`
// Sidechain optionally names another bus in this layout whose level keys the compressor.
Sidechain string `yaml:"sidechain,omitempty"`
}
CompressorEffect is a feed-forward peak compressor.
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 CustomEffect ¶
type CustomEffect struct {
// Type is the namespaced effect name registered with sound.RegisterEffect, such as "dynakit.compressor".
Type string `yaml:"type"`
// Params holds effect-specific parameters passed to the registered sound.EffectFactory.
Params map[string]any `yaml:"params,omitempty"`
}
CustomEffect configures a plugin-registered sound.BusEffect by its namespaced type and parameters.
func (CustomEffect) MarshalYAML ¶
func (c CustomEffect) MarshalYAML() (any, error)
MarshalYAML writes type first and params (when non-empty) with keys sorted in strict byte order for deterministic YAML output.
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 DepthSettings ¶
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 ¶
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 ¶
type EQBandEffect struct {
// Hz is the band center or shelf corner 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"`
// Kind selects the band shape: peaking (default when empty), lowShelf or highShelf.
Kind string `yaml:"kind,omitempty"`
}
EQBandEffect is one band of EQ.
type EQEffect ¶
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 ¶
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 ¶
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 GainFilterEffect ¶
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 ¶
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" schema:"required"`
// Version is the schema version; it must equal CurrentVersion (1).
Version int `yaml:"version" schema:"required"`
// 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 Interp ¶
type Interp string
Interp 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" // InterpBezier moves along a cubic Bezier segment shaped by this key's Out handle and the next key's In handle. InterpBezier Interp = "bezier" // InterpSineIn starts slowly and accelerates along a quarter sine wave. InterpSineIn Interp = "sine_in" // InterpSineOut decelerates smoothly along a quarter sine wave. InterpSineOut Interp = "sine_out" // InterpSineInOut eases in and out along a half sine wave. InterpSineInOut Interp = "sine_in_out" // InterpQuadIn accelerates quadratically from zero velocity. InterpQuadIn Interp = "quad_in" // InterpQuadOut decelerates quadratically to zero velocity. InterpQuadOut Interp = "quad_out" // InterpQuadInOut accelerates quadratically for the first half and decelerates for the second. InterpQuadInOut Interp = "quad_in_out" // InterpCubicIn accelerates cubically from zero velocity. InterpCubicIn Interp = "cubic_in" // InterpCubicOut decelerates cubically to zero velocity. InterpCubicOut Interp = "cubic_out" // InterpCubicInOut accelerates cubically for the first half and decelerates for the second. InterpCubicInOut Interp = "cubic_in_out" // InterpExpoIn stays near the start and accelerates sharply near the end. InterpExpoIn Interp = "expo_in" // InterpExpoOut shoots out quickly and settles exponentially at the target. InterpExpoOut Interp = "expo_out" // InterpExpoInOut accelerates and decelerates exponentially around the midpoint. InterpExpoInOut Interp = "expo_in_out" // InterpBackIn pulls slightly past the start before accelerating toward the target. InterpBackIn Interp = "back_in" // InterpBackOut overshoots the target slightly and settles back onto it. InterpBackOut Interp = "back_out" // InterpBackInOut pulls back at the start and overshoots at the end. InterpBackInOut Interp = "back_in_out" // InterpBounceIn bounces away from the start before accelerating into the target. InterpBounceIn Interp = "bounce_in" // InterpBounceOut bounces off the target until settling onto it. InterpBounceOut Interp = "bounce_out" // InterpBounceInOut bounces at both the start and the end. InterpBounceInOut Interp = "bounce_in_out" // InterpElasticIn oscillates with growing amplitude before snapping toward the target. InterpElasticIn Interp = "elastic_in" // InterpElasticOut overshoots the target and oscillates with decaying amplitude onto it. InterpElasticOut Interp = "elastic_out" // InterpElasticInOut oscillates elastically at both the start and the end. InterpElasticInOut Interp = "elastic_in_out" )
func Interps ¶
func Interps() []Interp
Interps returns every supported key interpolation mode in canonical display order.
func (Interp) Eases ¶
Eases reports whether interp is a recognized mode that Eval evaluates on its own: every Valid mode but InterpBezier, whose shape comes from a key pair's handles. A curve named without keys, such as a camera blend's, takes only these.
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"`
// In is the optional incoming cubic Bezier handle offset [dt, dv] relative to (Time, Value), used when the preceding key has InterpBezier. dt must be finite and <= 0 and not reach before the preceding key.
In *[2]float32 `yaml:"in,omitempty"`
// Out is the optional outgoing cubic Bezier handle offset [dt, dv] relative to (Time, Value), used when this key has InterpBezier. dt must be finite and >= 0 and not reach past the next key.
Out *[2]float32 `yaml:"out,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" // 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" // KindLabelStyle is a LabelStyle: reusable font, size, color and text effects shared across labels. KindLabelStyle Kind = "labelStyle" )
func Kinds ¶
func Kinds() []Kind
Kinds returns every resource type this package reads: the built-in kinds in a fixed order, followed by any plugin kinds registered with RegisterKind in sorted order.
type KindSpec ¶
type KindSpec struct {
// Kind is the namespaced resource type written in the header's type field, in "<plugin>.<name>" form such as "dialoguekit.graph".
Kind Kind
// New returns a non-nil pointer to a struct embedding [Header] with `yaml:",inline"`, initialized with h.
New func(h Header) Resource
}
KindSpec describes a plugin-registered resource kind that New, Parse and Library can load alongside the built-in kinds.
type LabelStyle ¶
type LabelStyle struct {
Header `yaml:",inline"`
// Name is an optional human-readable name.
Name string `yaml:"name,omitempty"`
// Font is a font family name or project-relative font asset path.
Font string `yaml:"font,omitempty"`
// Size is the font size in points; 0 keeps the caller's default size.
Size float32 `yaml:"size,omitempty"`
// Weight is "light", "normal", "medium", "semibold" or "bold".
Weight string `yaml:"weight,omitempty"`
// Italic enables italic rendering when true.
Italic bool `yaml:"italic,omitempty"`
// Color is the text fill CSS color, parsed with core.ParseColor.
Color string `yaml:"color,omitempty"`
// Outline is the text outline width in points; 0 draws no outline.
Outline float32 `yaml:"outline,omitempty"`
// OutlineColor is the text outline CSS color, parsed with core.ParseColor.
OutlineColor string `yaml:"outlineColor,omitempty"`
// Shadow is the drop shadow offset in points.
Shadow *TextOffset `yaml:"shadow,omitempty"`
// ShadowColor is the drop shadow CSS color, parsed with core.ParseColor.
ShadowColor string `yaml:"shadowColor,omitempty"`
// ShadowBlur is the drop shadow blur radius in points (platform text only).
ShadowBlur float32 `yaml:"shadowBlur,omitempty"`
// Underline draws a line under the text when true.
Underline bool `yaml:"underline,omitempty"`
// Strike draws a line through the text when true.
Strike bool `yaml:"strike,omitempty"`
}
LabelStyle is a reusable text appearance for labels and HUD text: font, size, color, and text effects (outline, drop shadow, underline, and strikethrough). Many labels can share one LabelStyle so edits apply everywhere at once.
func (*LabelStyle) ApplyLabel ¶
func (s *LabelStyle) ApplyLabel(l *gameui.Label)
ApplyLabel applies s's font, size, color, and text effects onto l. Fields left unset in s preserve l's existing values.
func (*LabelStyle) Effects ¶
func (s *LabelStyle) Effects() text.TextEffects
Effects converts s's outline, shadow, underline, and strikethrough fields into a text.TextEffects value.
func (*LabelStyle) PlatformStyle ¶
func (s *LabelStyle) PlatformStyle(base text.PlatformStyle) text.PlatformStyle
PlatformStyle returns base with every field s sets applied.
func (*LabelStyle) Validate ¶
func (s *LabelStyle) Validate() error
Validate checks the header, font size and weight, colors, and effect parameters.
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".
Values loaded directly with Load stay cached until Release is called for their path. Asset groups (assets.Group.AddResource) retain each resource they load and release it when the group is released; a path is dropped from the cache once no group retains it and no direct Load holds it.
Load, Retain, Release 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) LabelStyle ¶
func (l *Library) LabelStyle(path string) (*LabelStyle, error)
LabelStyle loads the label style at path.
func (*Library) Load ¶
Load returns the resource at path, parsing it on first use and returning the shared value after that. Reading and parsing run outside the library lock so concurrent loads of different paths proceed in parallel, while concurrent loads of the same path parse once and share the resulting pointer.
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) Release ¶
Release drops one reference to path and evicts its cached value once no Retain calls remain and no direct Load holds it. It reports whether the cached value was evicted; the next Load of an evicted path reads and parses the file again. Calling Release on a path loaded directly with Load (with no outstanding Retain calls) evicts it immediately and returns true.
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 or released 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.
func (*Library) Retain ¶
Retain increments the reference count for path when it is loaded in l. Asset groups use Retain and Release to keep shared resources cached while any group references them. Calling Retain on an unloaded path or nil Library is a no-op.
func (*Library) Revision ¶
Revision 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 ¶
type LimiterEffect struct {
// CeilingDB is the loudest level a sample may reach.
CeilingDB float64 `yaml:"ceilingDb"`
// ReleaseMs is the lookahead limiter's release time in milliseconds; 0 uses a sample clipper.
ReleaseMs float64 `yaml:"releaseMs,omitempty"`
}
LimiterEffect limits every sample to its ceiling; when ReleaseMs is positive it runs as a lookahead true-peak limiter.
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"`
// 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 (*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 Music ¶
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 (*Music) MusicPiece ¶
func (m *Music) MusicPiece() sound.MusicPiece
MusicPiece converts m into a runtime sound.MusicPiece so *resource.Music satisfies sound.MusicPieceSource and can be passed directly to sound.Mixer.Interactive.
func (*Music) Validate ¶
Validate 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 PitchShiftEffect ¶
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 ¶
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, *Music or *LabelStyle.
func New ¶
New returns an empty resource of kind with its header set, checking both built-in kinds and plugin kinds registered with RegisterKind. For an unregistered namespaced kind ("<plugin>.<name>"), the error names both the kind and its plugin prefix.
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 ShaderParams ¶
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 ¶
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"`
Doppler bool `yaml:"doppler,omitempty"`
Variants []SoundVariant `yaml:"variants"`
Spatial *SoundSpatial `yaml:"spatial,omitempty"`
Caption *SoundCaption `yaml:"caption,omitempty"`
}
Sound describes a deterministic randomized sound cue and optional 3D attenuation.
type SoundCaption ¶
type SoundCaption struct {
Key string `yaml:"key"`
Kind string `yaml:"kind,omitempty"`
MinInterval time.Duration `yaml:"minInterval,omitempty"`
}
SoundCaption describes an optional accessibility caption attached to a sound resource. Key is an l10n string table key (or literal fallback label), Kind classifies the cue ("sfx", "important", "music", or "chatter"; empty defaults to "sfx"), and MinInterval debounces rapid repeats (such as "250ms").
func (*SoundCaption) SoundCaption ¶
func (c *SoundCaption) SoundCaption() sound.Caption
SoundCaption returns c converted into a runtime sound.Caption (zero value when c is nil).
type SoundCone ¶
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 ¶
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 ¶
type SoundSpatial struct {
Near float32 `yaml:"near,omitempty"`
Far float32 `yaml:"far,omitempty"`
Rolloff string `yaml:"rolloff,omitempty"`
FarCutoffHz float32 `yaml:"farCutoffHz,omitempty"`
Cone *SoundCone `yaml:"cone,omitempty"`
}
SoundSpatial describes optional distance attenuation, distance low-pass cutoff, and a directional cone.
type SoundVariant ¶
SoundVariant is one source clip and its relative selection weight.
type StereoWidthEffect ¶
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 ¶
type StyleBorder struct {
// Width is the width of every side in points.
Width float32 `yaml:"width,omitempty" schema:"minimum=0"`
// Color is the border's CSS color.
Color string `yaml:"color,omitempty"`
// Top, Right, Bottom and Left override Width for one side.
Top *float32 `yaml:"top,omitempty" schema:"minimum=0"`
Right *float32 `yaml:"right,omitempty" schema:"minimum=0"`
Bottom *float32 `yaml:"bottom,omitempty" schema:"minimum=0"`
Left *float32 `yaml:"left,omitempty" schema:"minimum=0"`
}
StyleBorder is a flat StyleBox's border, drawn inside the box.
type StyleBox ¶
type StyleBox struct {
// Kind is flat, image or line.
Kind string `yaml:"kind" schema:"required,enum=flat|image|line"`
// Fill is a flat box's CSS fill color.
Fill string `yaml:"fill,omitempty"`
// Border is a flat box's border.
Border *StyleBorder `yaml:"border,omitempty"`
// Radius is a flat box's corner radius in points.
Radius float32 `yaml:"radius,omitempty" schema:"minimum=0"`
// Corners overrides Radius for single corners of a flat box.
Corners *StyleCorners `yaml:"corners,omitempty"`
// Shadow is a flat box's drop shadow.
Shadow *StyleShadow `yaml:"shadow,omitempty"`
// Expand grows the drawn area past the widget's bounds on each side, in points, without changing layout.
Expand *StyleSides `yaml:"expand,omitempty"`
// Image is an image box's project-relative image path; the image's import sidecar gives its nine-slice insets.
Image string `yaml:"image,omitempty"`
// Color is a line box's CSS color.
Color string `yaml:"color,omitempty"`
// Thickness is a line box's width in points; 0 draws 1 point.
Thickness float32 `yaml:"thickness,omitempty" schema:"minimum=0"`
// Vertical runs a line box from top to bottom instead of left to right.
Vertical bool `yaml:"vertical,omitempty"`
}
StyleBox is a named widget frame: a flat rectangle (kind flat), a nine-slice image (kind image) or a line (kind line). Each kind takes only its own fields.
type StyleCorners ¶
type StyleCorners struct {
TopLeft *float32 `yaml:"topLeft,omitempty" schema:"minimum=0"`
TopRight *float32 `yaml:"topRight,omitempty" schema:"minimum=0"`
BottomRight *float32 `yaml:"bottomRight,omitempty" schema:"minimum=0"`
BottomLeft *float32 `yaml:"bottomLeft,omitempty" schema:"minimum=0"`
}
StyleCorners overrides a flat StyleBox's radius for single corners, in points.
type StyleShadow ¶
type StyleShadow struct {
// Color is the shadow's CSS color.
Color string `yaml:"color"`
// Size grows the shadow past the box on every side, in points.
Size float32 `yaml:"size,omitempty" schema:"minimum=0"`
// Offset moves the shadow, in points.
Offset *TextOffset `yaml:"offset,omitempty"`
}
StyleShadow is a flat StyleBox's drop shadow: the box's shape grown by Size, moved by Offset and filled with Color under the box.
type StyleSides ¶
type StyleSides struct {
Top float32 `yaml:"top,omitempty" schema:"minimum=0"`
Right float32 `yaml:"right,omitempty" schema:"minimum=0"`
Bottom float32 `yaml:"bottom,omitempty" schema:"minimum=0"`
Left float32 `yaml:"left,omitempty" schema:"minimum=0"`
}
StyleSides holds a length in points for each side of a box.
type TextOffset ¶
TextOffset is a 2D offset in points, such as a text drop shadow offset.
type TextureMap ¶
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 ¶
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"`
// Outline is the default text outline width in points.
Outline *float32 `yaml:"outline,omitempty"`
// OutlineColor is the default text outline CSS color.
OutlineColor string `yaml:"outlineColor,omitempty"`
// Shadow is the default text drop shadow offset in points.
Shadow *TextOffset `yaml:"shadow,omitempty"`
// ShadowColor is the default text drop shadow CSS color.
ShadowColor string `yaml:"shadowColor,omitempty"`
// ShadowBlur is the default text drop shadow blur radius in points (platform text only).
ShadowBlur *float32 `yaml:"shadowBlur,omitempty"`
// Underline draws an underline under theme text by default when true.
Underline *bool `yaml:"underline,omitempty"`
// Strike draws a strikethrough through theme text by default when true.
Strike *bool `yaml:"strike,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, keyed by button, label or panel.
Types map[string]WidgetStyle `yaml:"types,omitempty"`
// Variations are named styles that extend a widget type's style or another variation, 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 (*Theme) Apply ¶
Apply returns base with every field the theme sets replaced, as ApplyWithImages does without an image loader, so image style boxes are left out.
func (*Theme) ApplyWithImages ¶
func (t *Theme) ApplyWithImages(base gameui.Theme, images func(path string) (gameui.NineSlice, bool)) gameui.Theme
ApplyWithImages 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. Each entry of types and variations replaces base's Styles entry of the same name. images loads an image style box's nine-slice frame from its project-relative path, with the insets of the image's import sidecar; a box it cannot load, or every image box when images is nil, is left out, so states that name it fall back as if it were unset.
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 ThemeStateStyle ¶
type ThemeStateStyle struct {
// Box names one of the theme's styleBoxes.
Box string `yaml:"box,omitempty"`
// TextColor is the text's CSS color.
TextColor string `yaml:"textColor,omitempty"`
// Offset moves the text, in points.
Offset *TextOffset `yaml:"offset,omitempty"`
}
ThemeStateStyle is a widget style's look in one state.
type ThemeVariation ¶
type ThemeVariation struct {
// Base names the widget type (button, label or panel) or the variation this one extends.
Base string `yaml:"base" schema:"required"`
WidgetStyle `yaml:",inline"`
}
ThemeVariation is a named style that extends Base, a widget type or another variation: every state and font field it sets overrides Base's.
type ToonSettings ¶
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 ¶
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", "tint" 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 one of Keys, Frames or Colors.
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 one of Keys, Frames or Colors.
Frames []FrameKey `yaml:"frames,omitempty"`
// Colors are the track's color keys, with times from 0 to the clip's Length. A track sets one of Keys, Frames or Colors.
Colors []ColorKey `yaml:"colors,omitempty"`
}
Track keys one property of one target over an Animation's length: numeric values in Keys, discrete sprite frames in Frames, or RGBA colors in Colors.
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) EvalColor ¶
EvalColor returns the color track's interpolated color at clip time t, holding the first and last colors 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) IsColorTrack ¶
IsColorTrack reports whether tr holds color keys rather than numeric or sprite frame keys.
func (*Track) IsFrameTrack ¶
IsFrameTrack reports whether tr holds discrete sprite frame keys rather than numeric or color keys.
type UVSettings ¶
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 (UVSettings) IsZero ¶
func (u UVSettings) IsZero() bool
IsZero 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 ¶
type WidgetStyle struct {
Normal *ThemeStateStyle `yaml:"normal,omitempty"`
Hover *ThemeStateStyle `yaml:"hover,omitempty"`
Pressed *ThemeStateStyle `yaml:"pressed,omitempty"`
Disabled *ThemeStateStyle `yaml:"disabled,omitempty"`
// Focus takes only box, drawn over the focused widget in place of the focus ring.
Focus *ThemeStateStyle `yaml:"focus,omitempty"`
// Font overrides the theme's font field by field.
Font *ThemeFont `yaml:"font,omitempty"`
}
WidgetStyle is the look of a widget type in its normal, hover, pressed, disabled and focus states, and its font. A field a state leaves out resolves as gameui.WidgetStyle describes.