assetbuild

package
v0.4.0-rc.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 47 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package assetbuild is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package assetbuild builds a game's assets from the assets section of its game.yaml, which package project defines: it packs sprite atlases, encodes KTX2 textures, converts audio, bakes TrueType and OpenType fonts into AngelCode BMFonts, packs glTF models into single GLB files and generates the Go asset manifest, applying the import settings sidecar beside each image, sound, font or model that package importsettings reads, and keeps a text cache of what each output was built from so a later run rebuilds only the targets whose inputs, sidecars or settings changed.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CollectCharsFile

func CollectCharsFile(fsys fs.FS, rel string) (string, error)

CollectCharsFile reads a UTF-8 plain-text character list at rel in fsys, strips an optional leading UTF-8 BOM and control characters (including line breaks), and returns the sorted, deduplicated characters.

func CollectCharsFromFile

func CollectCharsFromFile(fsys fs.FS, rel string) (string, error)

CollectCharsFromFile reads a supported source file at rel in fsys (a YAML or JSON l10n string table, a YAML data table, or a scene YAML file), strips {placeholders} and rich-text markup from its text values, and returns the sorted, deduplicated non-control characters.

func CollectFontChars

func CollectFontChars(fsys fs.FS, target project.FontTarget, sidecar *importsettings.Font) (string, error)

CollectFontChars collects, merges, sorts and deduplicates the characters a TrueType/OpenType font target bakes from its chars, charsFrom and charsFile settings (after applying sidecar overrides). When all three are empty, it returns project.DefaultFontChars sorted by code point.

func ExtractTextChars

func ExtractTextChars(s string) string

ExtractTextChars strips l10n {placeholders} and rich-text markup from s and returns its non-control characters in their original order.

func FormatMissingRunes

func FormatMissingRunes(runes []rune) string

FormatMissingRunes formats a sorted slice of missing runes for warnings and check diagnostics (such as `"龙" (U+9F99), "凤" (U+51E4)`), truncating after 20 runes with a count of the remainder.

func ModelFiles

func ModelFiles(model string, data []byte) ([]string, error)

ModelFiles returns the slash-separated paths, relative to the project root, of the files the glTF or GLB model at model (slash-separated, relative to the project root) names by relative path in its buffers and images, given the model file's bytes, in the order the model lists them and without repeats: the files a model target embeds and counts as inputs. Data URIs name no file. A URI with a scheme, an absolute path, or one that leaves the project is an error, as is a model whose JSON does not decode.

Types

type Builder

type Builder struct {
	// Root is the directory game.yaml's paths are relative to, normally the one holding game.yaml.
	Root string
	// Audio converts audio targets (a zero Encoder when nil).
	Audio *audioconv.Encoder
	// Version names the tools that build the targets, such as the game layer's module version; a target built by a different Version is rebuilt.
	Version string
	// Force rebuilds every target even when the cache says it is up to date.
	Force bool
	// Check reports which targets are out of date without writing anything under Root: their status is Stale instead of Built. A target whose cache entry does not match is built in a temporary folder and counts as up to date when Root already holds exactly the files it writes, so a check passes on a fresh checkout whose committed outputs are current even without the cache. AAC and MP3 targets are the exception: an external encoder writes them, and another encoder or encoder version writes different bytes for the same input, so with no cache entry for one, as in a fresh checkout, it counts as up to date when its output exists. An atlas also counts as stale when its output folder holds a page file of its name that it no longer writes.
	Check bool
	// ResourcesDir, when non-empty (such as "resources"), redirects every asset target's output path and the manifest's input directory into that directory (replacing a leading "assets" directory prefix when present) and turns off //go:embed on the manifest so outputs ship as app resources loaded by "asset:" URI rather than embedded in the binary.
	ResourcesDir string
	// DataTables binds YAML file patterns to Go row types for Assets.DataTables targets. Required when Assets.DataTables is non-empty.
	DataTables *datatable.Registry
	// Include lists optional slash-separated project-relative glob patterns (supporting ** and path.Match wildcards) restricting which asset targets and manifest entries are built.
	Include []string
	// Exclude lists optional slash-separated project-relative glob patterns (supporting ** and path.Match wildcards) omitted from asset targets and the generated manifest.
	Exclude []string
	// contains filtered or unexported fields
}

Builder builds a project's asset targets against the files in its directory.

func (*Builder) Build

func (b *Builder) Build(ctx context.Context, a *project.Assets) (*Report, error)

Build builds the targets of a, game.yaml's assets section, in order, skipping each whose key (a hash of its settings, its inputs' paths and contents, those of the import settings sidecars beside them, and Version) and outputs match the cache, then saves the cache when it changed. A nil a declares no targets: Build then reads and writes nothing. A setting in a sidecar overrides the target's: a texture target takes an image sidecar's filter, format, mipmaps and sRGB, an atlas cuts each image whose sidecar has a slice into frames, an audio target takes every setting of a sound's sidecar, loop points included, a font target a font sidecar's size, characters and padding, and a model target a model sidecar's scale and whether to keep animations. A model's key also covers the buffers and images it names by relative path. An image that both an atlas and a texture target read may hold both kinds of settings in its sidecar, each target taking its own; otherwise a setting no target of the image reads is refused. Before building, Build refuses a sidecar in a folder a target reads from whose asset no target reads, such as one with a mistyped name, and one whose name differs from its asset's in case, unless it holds only a credit section and its asset is there. A sidecar's credit section changes no output and is left out of the key of the targets that read its asset, so editing a credit rebuilds nothing; the key takes the rest of the sidecar's settings, not its bytes, so a comment or layout change rebuilds nothing either. A second Build with nothing changed writes no file. When a target fails, Build saves what it built so far and returns the report up to that target with the error.

Example

Build packs the atlas game.yaml's assets section declares, then finds it up to date on the next run and writes nothing.

package main

import (
	"bytes"
	"context"
	"fmt"
	"image"
	"image/color"
	"image/png"
	"os"
	"path/filepath"

	"github.com/nsgo-dev/game/pkg/project"
	"github.com/nsgo-dev/game/pkg/tooling/assetbuild"
)

func main() {
	root, err := os.MkdirTemp("", "assetbuild-example")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(root)
	img := image.NewNRGBA(image.Rect(0, 0, 4, 4))
	img.SetNRGBA(1, 1, color.NRGBA{R: 255, A: 255})
	var buf bytes.Buffer
	if err := png.Encode(&buf, img); err != nil {
		fmt.Println(err)
		return
	}
	if err := os.MkdirAll(filepath.Join(root, "art", "ui"), 0o755); err != nil {
		fmt.Println(err)
		return
	}
	if err := os.WriteFile(filepath.Join(root, "art", "ui", "dot.png"), buf.Bytes(), 0o644); err != nil {
		fmt.Println(err)
		return
	}
	f := project.MustParse([]byte(`version: 2
name: Example
id: dev.example.assets
appVersion: '1'
window: {width: 320, height: 240}
assets:
  atlases:
    - name: ui
      in: art/ui
      out: assets
`))
	b := &assetbuild.Builder{Root: root}
	for range 2 {
		r, err := b.Build(context.Background(), f.Assets)
		if err != nil {
			fmt.Println(err)
			return
		}
		for _, t := range r.Targets {
			fmt.Println(t.Status, t.ID, t.Outputs)
		}
	}
}
Output:
built atlas assets/ui [assets/ui.json assets/ui.png]
up to date atlas assets/ui [assets/ui.json assets/ui.png]

type Kind

type Kind string

Kind is the sort of work a target does.

const (
	// KindAtlas packs a folder of PNG images into atlas pages.
	KindAtlas Kind = "atlas"
	// KindTexture encodes an image into a KTX2 container.
	KindTexture Kind = "texture"
	// KindAudio converts a WAV file.
	KindAudio Kind = "audio"
	// KindFont bakes a TrueType or OpenType font, or a folder of PNG glyph images, into a bitmap font.
	KindFont Kind = "font"
	// KindModel packs a glTF model into one GLB file.
	KindModel Kind = "model"
	// KindDataTable filters canonical YAML data tables to the columns read by a target side.
	KindDataTable Kind = "datatable"
	// KindManifest generates the Go asset manifest.
	KindManifest Kind = "manifest"
	// KindRemote copies loose assets to content-hashed files and writes remote.yaml.
	KindRemote Kind = "remote"
)

type PluginSource

type PluginSource struct {
	// Path is the slash-separated path of the source asset relative to Builder.Root.
	Path string
	// Sidecar is the slash-separated path of the asset's *.import.yaml sidecar relative to Builder.Root.
	Sidecar string
	// Importer is the plugin importer identifier named by the sidecar ("<plugin>.<id>").
	Importer string
}

PluginSource describes a source asset whose *.import.yaml sidecar delegates importing to an editor plugin. Builder does not link project plugins, so it leaves these sources untouched and lists them in Report.PluginSources.

type Report

type Report struct {
	Targets       []Target
	PluginSources []PluginSource
}

Report lists every target of a build in the order it ran: atlases, textures, audio, fonts and models in their game.yaml order, the manifest last, together with any plugin-owned source assets left untouched.

func (*Report) Count

func (r *Report) Count(s Status) int

Count returns how many targets in r have status s.

type Status

type Status string

Status is what a build did with a target.

const (
	// Built means the target's outputs were written.
	Built Status = "built"
	// UpToDate means the target's inputs, settings and outputs matched the cache, so nothing was written.
	UpToDate Status = "up to date"
	// Stale means a check found the target out of date; nothing was written.
	Stale Status = "stale"
)

type Target

type Target struct {
	// ID names the target: its kind and its output, such as "atlas assets/atlases/ui" or "texture assets/albedo.ktx2".
	ID string
	// Kind is the sort of work the target does.
	Kind Kind
	// Status is what the build did with it.
	Status Status
	// Outputs are the slash-separated paths, relative to the project directory, of the files the target wrote or would write, sorted; when Status is Stale they are the outputs of the previous build, if any.
	Outputs []string
	// Warnings are non-fatal diagnostics produced while building or checking the target, such as characters requested for a font target that the source font file has no glyph for.
	Warnings []string
}

Target is one target's outcome in a Report.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL