Documentation
¶
Overview ¶
Package asset loads and saves typed data using format-specific codecs. Loader caches decoded values from an fs.FS; Saver encodes documents through a SaveStore or caller-owned writer. Directory provides rooted host-file reads and staged document replacement. Codecs supplies reusable registration configuration without sharing caches or runtime state. Paths are relative and slash-separated. Media values stay backend-free; runners own conversion to backend textures, fonts, and audio.
Index ¶
- func WithCachePolicy(policy CachePolicy) loadOption
- func WithFormat(format Format) formatOption
- type AssetError
- type AudioData
- type CachePolicy
- type Codecs
- func (c *Codecs) Decode[T any](reader io.Reader, format Format) (T, error)
- func (c *Codecs) Encode[T any](writer io.Writer, value T, format Format) error
- func (c *Codecs) HasDecoder[T any](format Format) bool
- func (c *Codecs) SetDecoder[T any](format Format, d Decoder[T]) error
- func (c *Codecs) SetEncoder[T any](format Format, e Encoder[T]) error
- func (c *Codecs) SetJSON[T any]() error
- type Decoder
- type Directory
- type Encoder
- type FontData
- type Format
- type ID
- type Loader
- type LoaderOptions
- type SaveStore
- type Saver
- type SaverOptions
- type Sheet
- type SheetRef
- type SheetRegion
- type TextureData
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func WithCachePolicy ¶ added in v0.4.0
func WithCachePolicy(policy CachePolicy) loadOption
WithCachePolicy overrides the loader's default cache policy for one Loader.Load. CacheBypass does not refresh or invalidate an existing cached value.
func WithFormat ¶
func WithFormat(format Format) formatOption
WithFormat overrides the format inferred from the extension for a path load or save.
Types ¶
type AssetError ¶
type AssetError struct {
// Op is the failing operation: "Load", "Open", "Decode", "Close", "Save", or "Encode".
Op string
// ID is the normalized path of the asset, if known.
ID ID
// Err is the underlying cause; Unwrap preserves it for errors.Is.
Err error
}
AssetError identifies a failed asset operation and its path, if known.
func (AssetError) Error ¶
func (e AssetError) Error() string
Error returns the operation, asset path, and underlying error.
type AudioData ¶ added in v0.0.4
type AudioData struct {
// PCM is 16-bit signed little-endian interleaved stereo audio at SampleRate.
PCM []byte
// SampleRate is the decoded audio sample rate.
SampleRate int
// Length is the decoded PCM length in bytes.
Length int64
}
AudioData holds decoded PCM and its sample rate and length.
type CachePolicy ¶ added in v0.4.0
type CachePolicy int
CachePolicy controls decoded-value caching and in-flight load sharing.
const ( // CacheReuse reuses successful loads and shares in-flight reads. CacheReuse CachePolicy = iota // CacheBypass reads independently without consuming or populating the cache. CacheBypass )
type Codecs ¶ added in v0.4.0
type Codecs struct {
// contains filtered or unexported fields
}
Codecs configures typed encoders and decoders. Its zero value is empty. Loaders and savers read it on every call, so registrations and replacements made after construction take effect for them. Registered closures must support concurrent calls if used concurrently.
Registration is safe for concurrent use. Codecs must not be copied.
func NewCodecs ¶ added in v0.4.0
func NewCodecs() *Codecs
NewCodecs returns codecs with backend-free texture and font decoders and paired JSON codecs for Sheet, whose decoder validates metadata. Other JSON types require registration. Audio decoders are runner-owned.
func (*Codecs) Decode ¶ added in v0.4.0
Decode reads one value of type T in format from reader using the registered decoder. It returns an error naming the type and format when none is registered.
func (*Codecs) Encode ¶ added in v0.4.0
Encode writes value in format using the registered encoder. It returns an error naming the type and format when none is registered.
func (*Codecs) HasDecoder ¶ added in v0.4.0
HasDecoder reports whether a decoder for T and format is registered.
func (*Codecs) SetDecoder ¶ added in v0.4.0
SetDecoder installs or replaces d for T and format. Nil decoders and empty formats are errors. Existing loaders use the new decoder on their next call.
func (*Codecs) SetEncoder ¶ added in v0.4.0
SetEncoder installs or replaces e for T and format. Nil encoders and empty formats are errors. Existing savers use the new encoder on their next call.
func (*Codecs) SetJSON ¶ added in v0.4.0
SetJSON installs or replaces JSON encoding and decoding for T atomically. Existing loaders and savers are unaffected.
Decoding reads one complete JSON value, allowing trailing whitespace but rejecting additional content. Standard encoding/json field and custom marshaling rules apply; missing fields retain their zero values. Domain validation, defaults, and migration remain the caller's responsibility.
type Decoder ¶
Decoder decodes a value of type T from a reader without closing it. The returned value must not retain the reader.
type Directory ¶ added in v0.4.0
type Directory struct {
// contains filtered or unexported fields
}
Directory reads files and publishes encoded documents beneath an open root. It implements fs.FS and SaveStore. The caller must close it after all loaders, savers, and open files have finished using it.
func NewDirectory ¶ added in v0.4.0
NewDirectory opens an existing directory at path. It does not create the directory or select an application-data location.
func (*Directory) Open ¶ added in v0.4.0
Open opens a slash-separated name relative to the directory. The caller owns the returned file and must close it.
func (*Directory) Write ¶ added in v0.4.0
Write encodes a document to a private staging file and replaces name after encoding and closing succeed. Missing parent directories are created. Name must satisfy fs.ValidPath, must not be ".", and must not contain backslashes.
Encoding or close failures leave the destination untouched. Failed writes attempt staging cleanup and preserve cleanup errors alongside the cause. Replacement uses the platform's rename operation; atomicity and crash durability are not guaranteed. Callers must order writes to the same name.
type FontData ¶ added in v0.1.0
type FontData struct {
// Raw contains the original font-file bytes for creating renderer-specific faces.
Raw []byte
// contains filtered or unexported fields
}
FontData is a decoded font asset. It provides text measurements through FontData.Measure and retains the original bytes for renderers.
func (FontData) Measure ¶ added in v0.1.0
Measure returns the shaped width and horizontal line height of text at size, in pixels. The width includes shaping effects such as kerning. Empty text has zero width and the same height as non-empty text.
Measure is not safe for concurrent use on the same FontData value.
type Format ¶
type Format string
Format identifies an asset's encoding and selects its decoder or encoder. Path loads and saves infer it from the lowercased file extension by default.
const ( // FormatJSON is the JSON format. FormatJSON Format = "json" // FormatYAML is the YAML format. FormatYAML Format = "yaml" // FormatYML is the YML format. FormatYML Format = "yml" // FormatPNG is the PNG format. FormatPNG Format = "png" // FormatJPG is the JPG format. FormatJPG Format = "jpg" // FormatJPEG is the JPEG format. FormatJPEG Format = "jpeg" // FormatWAV is the WAV format. FormatWAV Format = "wav" // FormatMP3 is the MP3 format. FormatMP3 Format = "mp3" // FormatOGG is the OGG format. FormatOGG Format = "ogg" // FormatTTF is the TTF format. FormatTTF Format = "ttf" // FormatOTF is the OTF format. FormatOTF Format = "otf" )
Format constants identify common asset encodings, not installed codecs. Register typed encoders and decoders with Codecs.
type Loader ¶ added in v0.2.0
type Loader struct {
// contains filtered or unexported fields
}
Loader loads assets from a filesystem and decodes them with registered decoders.
func NewLoader ¶ added in v0.2.0
func NewLoader(filesystem fs.FS, opts LoaderOptions) (*Loader, error)
NewLoader creates a Loader backed by filesystem. If filesystem is nil, assets are read from the current working directory. Loading is lazy and begins on the first call to Loader.Load. A filesystem containing a nil pointer returns an error, as does an invalid cache policy.
func (*Loader) Load ¶ added in v0.2.0
Load reads and decodes the asset at fpath as T. Fpath is a slash-separated path relative to the loader's filesystem. The format is inferred from its extension unless overridden by WithFormat.
The loader's CachePolicy applies unless overridden by WithCachePolicy. Cached values are shared by cleaned path, exact Go type, and format.
Load closes the file it opens and returns the zero value of T on failure. A value is cached only after decoding and closing both succeed.
func (*Loader) LoadReader ¶ added in v0.2.0
LoadReader decodes a value of type T from reader using the decoder registered for format. The format must be supplied explicitly.
Unlike Loader.Load, LoadReader does not cache and does not deduplicate concurrent decodes. It does not close reader; the caller owns it.
func (*Loader) Open ¶ added in v0.2.0
Open opens the asset at fpath as a raw file and returns its inferred format. Unlike Loader.Load, it does not decode or cache the asset. The caller owns the file and must close it.
Consumers that need seeking for looping or position resets must verify that the returned file supports it.
type LoaderOptions ¶ added in v0.4.0
type LoaderOptions struct {
// Codecs supplies shared registrations for decoding. Nil selects the defaults.
Codecs *Codecs
// CachePolicy is the default for path loads. Zero selects [CacheReuse].
CachePolicy CachePolicy
}
LoaderOptions configures a loader at construction.
type SaveStore ¶ added in v0.4.0
type SaveStore interface {
// Write publishes the output of encode at name and returns any encoding,
// write, close, or publication error.
//
// Write owns the writer and calls encode synchronously at most once.
// It must call encode before reporting success and must not retain it or
// publish incomplete output on an encoding failure. Publication guarantees
// depend on the store.
Write(name string, encode func(io.Writer) error) error
}
SaveStore publishes encoded documents.
type Saver ¶ added in v0.4.0
type Saver struct {
// contains filtered or unexported fields
}
Saver encodes values with shared codecs. Path saves delegate publication to a borrowed SaveStore; Saver never closes the store. Concurrent calls require concurrency-safe encoders and storage. Callers must order saves to the same destination when the newest value must win.
func NewSaver ¶ added in v0.4.0
func NewSaver(store SaveStore, opts SaverOptions) (*Saver, error)
NewSaver creates a saver that reads the configured codecs on each call. A nil store permits Saver.SaveWriter only. A store containing a nil pointer returns an error.
func (*Saver) Save ¶ added in v0.4.0
Save encodes value and publishes it at name through the store. The format defaults to the lowercased extension; WithFormat overrides it. Names are cleaned slash-separated paths relative to the store. Missing encoders and invalid names fail before the store is called. Save does not invalidate loader caches.
type SaverOptions ¶ added in v0.4.0
type SaverOptions struct {
// Codecs supplies shared registrations, read on each call. Nil selects the defaults.
Codecs *Codecs
}
SaverOptions configures a saver at construction.
type Sheet ¶ added in v0.4.0
type Sheet struct {
// Texture is the slash-separated, root-relative texture asset path.
Texture ID `json:"texture"`
// Regions maps region names to pixel rectangles within Texture.
Regions map[string]SheetRegion `json:"regions"`
}
Sheet describes named regions of one texture. Texture paths are relative to the loader's root, not to the document. Its zero value is invalid.
Sheet uses ordinary JSON fields. Its default decoder validates metadata before caching, without loading the texture. Use ValidateBounds during setup to check every region against the image. Treat cached sheets and sheets retained by MemorySheet as read-only, including their region maps.
func NewSheet ¶ added in v0.4.0
func NewSheet(texture ID, regions map[string]SheetRegion) (*Sheet, error)
NewSheet creates a validated sheet, cleaning texture and copying regions. It does not load the image; use Sheet.ValidateBounds to check its extent.
func (Sheet) Region ¶ added in v0.4.0
Region returns a named region's pixel bounds. It rejects missing names and invalid geometry without scanning other regions or loading the texture.
func (*Sheet) Save ¶ added in v0.4.0
Save validates s and writes it as JSON through saver, regardless of name's extension. It does not save the texture, choose storage, or invalidate caches. It uses the value-type Sheet encoder supplied by NewCodecs.
type SheetRef ¶ added in v0.4.0
type SheetRef struct {
// contains filtered or unexported fields
}
SheetRef identifies a JSON sheet file or retains a sheet in memory. It is comparable and may be shared by sprites and animation clips. Its zero value is invalid; use FileSheet or MemorySheet.
func FileSheet ¶ added in v0.4.0
FileSheet refers to a JSON document at name, relative to the loader's root. It cleans the slash-separated path without loading anything. Invalid paths are reported by SheetRef.Validate or SheetRef.Resolve.
func MemorySheet ¶ added in v0.4.0
MemorySheet retains sheet without copying it. The sheet and its region map must remain read-only while references are in use. Nil and zero sheets are invalid; use Sheet.Validate to check all regions before sharing.
func (SheetRef) Resolve ¶ added in v0.4.0
Resolve returns the referenced sheet with a cleaned texture path. File references load JSON through loader and follow its cache policy; memory references need no loader. Returned values share read-only region maps.
Resolve checks the texture path and a non-empty region map without loading pixels or scanning all regions. Use Sheet.Region for a selected rectangle or Sheet.ValidateBounds to check the complete sheet during setup.
type SheetRegion ¶ added in v0.4.0
type SheetRegion struct {
// X is the left coordinate in pixels.
X int `json:"x"`
// Y is the top coordinate in pixels.
Y int `json:"y"`
// W is the width in pixels.
W int `json:"w"`
// H is the height in pixels.
H int `json:"h"`
}
SheetRegion describes a rectangle in texture pixel coordinates.
type TextureData ¶
type TextureData struct {
// Image is the decoded image.
Image image.Image
// Width is the image width in pixels.
Width int
// Height is the image height in pixels.
Height int
}
TextureData holds a decoded image and its dimensions. Collectors use its bounds to validate sheet regions; runners convert it to a backend texture.