Documentation
¶
Overview ¶
Package game is the high-level entry point of the engine: an Engine implements ebiten.Game and owns the plumbing that every game otherwise wires by hand (World, asset server and loaders, renderer, camera, the extract schedule, audio, GOD resolver, level loading).
e := game.New(game.Config{Width: 320, Height: 180, FS: assets})
e.AddSystem(game.StageSimulate, move)
e.Start(func(e *game.Engine) { /* spawn entities, load a level */ })
ebiten.SetWindowSize(640, 360)
ebiten.SetWindowTitle("demo")
err := ebiten.RunGame(e) // the window is yours to configure
e.Close()
The low-level packages (asset, render, extract, anim, sound, resolver) remain the escape hatch: the Engine exposes the objects it created.
Index ¶
- Constants
- func DevScreenshotKey() input.Key
- type Config
- type Context
- type DrawGate
- type EditRunner
- type Engine
- func (e *Engine) AddAudioRunner(runners ...system.Runner)
- func (e *Engine) AddExtract(runners ...system.Runner)
- func (e *Engine) AddRunner(st Stage, runners ...Runner)
- func (e *Engine) AddSystem(st Stage, sys ...System)
- func (e *Engine) Assets() *asset.Server
- func (e *Engine) Audio() *sound.AudioSystem
- func (e *Engine) Background() color.Color
- func (e *Engine) Boot() *library.Load
- func (e *Engine) Camera() *render.Camera
- func (e *Engine) CameraRig() *camera.Rig
- func (e *Engine) Canvases() *render.Canvases
- func (e *Engine) Close()
- func (e *Engine) Debug() bool
- func (e *Engine) Draw(screen *ebiten.Image)
- func (e *Engine) DrawFinalScreen(screen ebiten.FinalScreen, offscreen *ebiten.Image, geoM ebiten.GeoM)
- func (e *Engine) FrameChanged() bool
- func (e *Engine) Groups() *render.GroupConfig
- func (e *Engine) Held() bool
- func (e *Engine) Hold() (release func())
- func (e *Engine) Input() *input.Router
- func (e *Engine) Layers() *render.LayerConfig
- func (e *Engine) Layout(outW, outH int) (int, int)
- func (e *Engine) Levels() []*Level
- func (e *Engine) Library() *library.Library
- func (e *Engine) Listener() *sound.Listener
- func (e *Engine) LoadLevel(path string) (*Level, error)
- func (e *Engine) LoadLevelBase(base string, opts tilemap.SpawnOptions) (*Level, error)
- func (e *Engine) LoadLevelData(path string, data []byte) (*Level, error)
- func (e *Engine) LoadMap(path string, opts tilemap.SpawnOptions) (*Level, error)
- func (e *Engine) LoadPackage(sc *asset.Scope, name string) *library.Load
- func (e *Engine) LogicalToWindow(p gfx.Vec2) gfx.Vec2
- func (e *Engine) Mixer() *sound.Mixer
- func (e *Engine) Pop()
- func (e *Engine) Post() *render.PostChain
- func (e *Engine) Push(s *Scene)
- func (e *Engine) Quit()
- func (e *Engine) Renderer() *render.Renderer
- func (e *Engine) Replace(s *Scene)
- func (e *Engine) ReportAssetError(err error)
- func (e *Engine) Root() *Scene
- func (e *Engine) SampleRate() int
- func (e *Engine) SceneOf(en ecs.Entity) *Scene
- func (e *Engine) Scenes() []*Scene
- func (e *Engine) Screenshot(req ShotRequest)
- func (e *Engine) SetBackground(c color.Color)
- func (e *Engine) SetDebug(on bool)
- func (e *Engine) SetScreenshotSink(sink func(ShotResult) error)
- func (e *Engine) SetStatsOverlay(on bool)
- func (e *Engine) SetTimeScale(s float32)
- func (e *Engine) Sound() *sound.Queue
- func (e *Engine) Start(fn func(*Engine))
- func (e *Engine) StartupActive() bool
- func (e *Engine) StatsOverlay() bool
- func (e *Engine) Stores() Stores
- func (e *Engine) Time() *gfx.Time
- func (e *Engine) TimeScale() float32
- func (e *Engine) ToolPaused() bool
- func (e *Engine) ToolTime() *ToolTime
- func (e *Engine) Top() *Scene
- func (e *Engine) TouchControls() *inputsys.TouchControlsExtract
- func (e *Engine) Tweens() *tween.Tweens
- func (e *Engine) UnloadLevel(l *Level)
- func (e *Engine) Update() error
- func (e *Engine) WindowToLogical(p image.Point) gfx.Vec2
- func (e *Engine) World() *ecs.World
- type Initializer
- type InputConfig
- type Level
- func (l *Level) Bounds() gfx.Rect
- func (l *Level) Done() bool
- func (l *Level) Err() error
- func (l *Level) Maps() []LoadedMap
- func (l *Level) Name() string
- func (l *Level) Objects() []god.Object
- func (l *Level) Path() string
- func (l *Level) Progress() (ready, total int)
- func (l *Level) Scope() *asset.Scope
- func (l *Level) SetObjects(objs []god.Object)
- func (l *Level) Spawned() bool
- type LoadedMap
- type Runner
- type Scene
- func (s *Scene) AddRunner(st Stage, runners ...Runner)
- func (s *Scene) AddSystem(st Stage, sys ...System)
- func (s *Scene) LoadLevel(path string) (*Level, error)
- func (s *Scene) LoadLevelBase(base string, opts tilemap.SpawnOptions) (*Level, error)
- func (s *Scene) LoadMap(path string, opts tilemap.SpawnOptions) (*Level, error)
- func (s *Scene) Name() string
- func (s *Scene) OnCover(fn func(*Engine, *Scene))
- func (s *Scene) OnEnter(fn func(*Engine, *Scene))
- func (s *Scene) OnExit(fn func(*Engine, *Scene))
- func (s *Scene) OnUncover(fn func(*Engine, *Scene))
- func (s *Scene) Options() SceneOptions
- func (s *Scene) Own(entities ...ecs.Entity)
- func (s *Scene) Scope() *asset.Scope
- type SceneOptions
- type ScreenshotConfig
- type ShotRequest
- type ShotResult
- type ShotTarget
- type Stage
- type StartupConfig
- type StartupScreen
- type StartupState
- type Stores
- func (s Stores) Atlases() render.AtlasStore
- func (s Stores) Bindings() inputsys.BindingsStore
- func (s Stores) ClipSets() anim.ClipSetStore
- func (s Stores) Clips() anim.ClipStore
- func (s Stores) Fonts() render.FontStore
- func (s Stores) Maps() tilemap.MapStore
- func (s Stores) Music() sound.MusicStore
- func (s Stores) Prefabs() prefab.Store
- func (s Stores) Shaders() render.ShaderStore
- func (s Stores) Sounds() sound.SoundStore
- func (s Stores) Sprites() render.SpriteStore
- func (s Stores) Tilesets() tilemap.TilesetStore
- func (s Stores) Worlds() tilemap.WorldStore
- type System
- type TickMode
- type Time
- type Tool
- type ToolTime
Constants ¶
const MaxShotScale = 8
MaxShotScale is the largest ShotRequest.Scale.
Variables ¶
This section is empty.
Functions ¶
func DevScreenshotKey ¶
DevScreenshotKey is the hotkey development builds turn on with ScreenshotConfig.Key: F12, or F9 in js/wasm, because a browser keeps F12 for its developer tools and the game never sees it.
Types ¶
type Config ¶
type Config struct {
// Width and Height are the logical resolution the game renders at.
// Default 640x360. The window may be larger; see IntegerScale.
Width, Height int
// IntegerScale restricts the output scale to whole multiples
// (see [render.Layout]).
IntegerScale bool
// TPS is the update rate. 0 keeps Ebiten's current rate (60 by default),
// otherwise New calls ebiten.SetTPS.
TPS int
// FS is the asset root. nil means no assets: loads then fail and report
// through OnAssetError. Leave it nil when Library is set.
FS fs.FS
// Library is an asset library of packages
// (doc/guide/engine/asset-library.md), opened with library.Open. When
// set, the engine reads assets through Library.FS (FS must be nil),
// mounts boot/ (if any) and loads the "global" package into the global
// scope (see [Engine.Boot]), mounts a key's package before LoadLevel,
// LoadMap and LoadLevelBase read it, and can preload packages
// ([Engine.LoadPackage]). nil, the default, uses FS directly.
Library *library.Library
// Workers is the number of asset decode workers. 0 means GOMAXPROCS-1,
// at least 1. Ignored with InlineAssets.
Workers int
// CommitBudget bounds the time per tick spent finishing loaded assets
// on the game goroutine. 0 means 2ms. Ignored with InlineAssets.
CommitBudget time.Duration
// InlineAssets decodes and finishes every asset inside Update, on the
// game goroutine: no decode workers and no CommitBudget. A load then
// takes the same number of ticks on every machine, so a headless test
// that steps the engine tick by tick is reproducible (see package
// game/gametest). Meant for tests, tools and replays; a tick blocks
// while it decodes, so never set it in a browser build or a game that
// streams large assets.
InlineAssets bool
// KeepAlive is the byte budget of released assets that stay loaded
// (asset.Options.KeepAlive): returning to a level whose scope was just
// released reuses its art instead of decoding it again. 0, the default,
// unloads released assets at the next tick.
KeepAlive int64
// WatchInterval turns on asset hot reload (asset.Options.WatchInterval):
// changed files under FS are reloaded in place while the game runs.
// Use it in development builds with an os.DirFS; 0 (the default) is off.
WatchInterval time.Duration
// AssetChanges feeds changed asset keys (slash-separated, relative to
// FS) into hot reload, for hosts that know about changes without FS
// polling: a dev server pushing to a browser build (see
// httpfs.WatchChanges), a test, a custom file watcher. At the start of
// its assets stage the engine receives every pending batch without
// blocking and passes it to Assets().Changed. The engine only receives;
// the sender owns and closes the channel. nil, the default, is off.
AssetChanges <-chan []string
// OnAssetError is called for assets that fail to load, and for hot
// reloads that fail. nil logs the error with the standard logger.
OnAssetError func(error)
// TransparentPlaceholders draws nothing, instead of the magenta
// checker, for assets that are not ready yet.
TransparentPlaceholders bool
// SampleRate is the audio sample rate. 0 means sound.DefaultSampleRate
// (48000). Ebiten allows one audio context per process: if one exists
// already, its rate is used instead.
SampleRate int
// NoAudio plays nothing and never opens the audio device: sounds and
// music still load and the audio system still runs, on a
// sound.NullBackend. Use it for servers, tools and tests.
NoAudio bool
// Background clears the screen before each frame. nil means opaque
// black.
Background color.Color
// Camera is the initial camera. A zero Zoom means 1.
Camera render.Camera
// CameraRig is the initial follow-camera configuration (see
// [Engine.CameraRig]). The zero value is a hard follow of the
// camera.Target entity without bounds; with no Target entity the
// camera stays where your systems put it. New panics with
// `camera: unknown follow mode` for an unknown Mode.
CameraRig camera.Rig
// World is an optional pre-built World. nil means [ecs.NewWorld].
World *ecs.World
// Debug enables the debug-shape extract at startup;
// see [Engine.SetDebug].
Debug bool
// StatsOverlay draws the renderer statistics, FPS and TPS in the
// top-left corner at startup (render.StatsOverlay);
// see [Engine.SetStatsOverlay].
StatsOverlay bool
// FrameLog is the path of a CSV file that receives one row per Draw
// (tick count, gaps, alpha, camera positions, GC count) to analyse
// stutter. Empty means off, unless the WPIX_FRAMELOG environment
// variable names a path. See the engine guide.
FrameLog string
// Screenshots configures [Engine.Screenshot]: the folder of native
// captures and an optional sink that replaces file and download.
Screenshots ScreenshotConfig
// Startup turns on the startup screen shown while the initial assets
// load: &StartupConfig{} shows [WeakpixelScreen] for at least 5
// seconds. nil, the default, shows none. Ignored when Tool is set. See
// [StartupConfig].
Startup *StartupConfig
// Input configures the input system; see [InputConfig].
Input InputConfig
// Tool attaches a development tool (an editor, a debugger): it can
// pause and step the game, filter input and draw at window resolution.
// nil, the default, attaches nothing. See [Tool].
Tool Tool
}
Config configures an Engine. The zero value is valid: every field has a default noted below.
type Context ¶
type Context struct {
// World is the Engine's World.
World *ecs.World
// Commands is the World's deferred-change buffer (system.CommandsOf).
// The Engine applies it at the end of every stage.
Commands *system.Commands
// Time describes the current tick, as this system sees it.
Time Time
// Engine is the Engine that runs the system.
Engine *Engine
// Scene is the scene the system belongs to: [Engine.Root] for the
// systems added to the Engine, the pushed scene for a scene's own.
Scene *Scene
// contains filtered or unexported fields
}
Context is what the Engine hands to every game system: the systems added with Engine.AddSystem, Engine.AddRunner, Scene.AddSystem and Scene.AddRunner. It carries the World, the stage's deferred commands, the tick's time, the Engine and the scene the system belongs to, so a system needs no constructor argument and no field to reach them.
Rule for new fields: only what the Engine owns and refreshes for every call. State owned by the game (settings, score) lives in World resources.
Lifetime: the Engine reuses one Context per game stage, which is what keeps a tick free of allocations. The pointer is valid only for the duration of the call it is passed to. Systems must not keep it, or its Commands or Time, after returning; keep ctx.Engine, ctx.Scene or ctx.World if they are needed later.
The Engine's own systems, the extract and audio runners (Engine.AddExtract, Engine.AddAudioRunner) and runners added through Wrap get the ECS's system.Context instead; EngineOf reaches the Engine from there.
func (*Context) Spawn ¶
Spawn queues ctx.World.NewEntity(values...) like ctx.Commands.Spawn, and makes ctx.Scene own the new entity: popping the scene deletes it if it is still alive. Owning has no effect for the root scene, which is never popped. The values are not copied, so the caller must not change the slice's contents before the stage ends. The call allocates (the variadic slice and the queued command).
type DrawGate ¶
type DrawGate interface {
// DrawFrame reports whether this frame is drawn. It is called from
// Draw, on the game goroutine, and must not change the World.
DrawFrame(e *Engine) bool
}
DrawGate is an optional interface of a Tool that decides which frames are drawn. Engine.Draw calls DrawFrame once per frame; when it returns false, Draw leaves the screen as it is, so Ebitengine keeps showing the last drawn frame and, after a few such frames, stops presenting and skips DrawFinalScreen too. A tool uses it to draw only when something changed, for example once per tick of a slow-ticking editor.
The engine draws regardless of DrawFrame while the startup screen is up and while a capture (Engine.Screenshot) waits for a frame, and does not call it then.
Skipping a frame only keeps the last image when the screen is not cleared between frames: whoever runs the game must call ebiten.SetScreenClearedEveryFrame(false). A drawn frame always fills the whole screen first, so that setting changes nothing else.
type EditRunner ¶
type EditRunner interface {
RunsWhilePaused() bool
}
EditRunner is an optional interface for a system.Runner. A runner whose RunsWhilePaused returns true keeps running while a Tool pauses the game (TickPause), so an edited scene gets the setup and presentation work it needs (placing the hero once a world has spawned, merging layers). Use it for that, never for simulation. It is asked when the schedule is built and whenever the scene stack changes, and has no effect without a Tool. A held StageSimulate (Engine.Hold) skips EditRunners too. See doc/guide/engine/engine.md#what-runs-when.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine implements ebiten.Game and owns the engine plumbing. Create it with New, add systems, then run it with ebiten.RunGame (the window is yours to configure) and call Engine.Close afterwards. An Engine, like its World, is single-goroutine.
func EngineOf ¶
EngineOf returns the Engine that runs ctx's World. Game systems have it as ctx.Engine (Context); EngineOf is for the runners that get the ECS's system.Context: extract and audio runners and those added through Wrap.
func New ¶
New creates an Engine: the World, the asset server with the render, animation, tilemap and sound loaders, the GOD asset resolver, the render resources (queue, camera, layers, groups, post chain), the audio resources (sound queue, mixer, listener) and the layout. It calls ebiten.SetTPS when cfg.TPS is set; it opens no window and needs no display. Unless cfg.NoAudio is set it creates Ebiten's audio context (or reuses the existing one), which opens the audio device only once the game loop runs.
Panics with "game: ..." if the pieces cannot be wired, for example when cfg.World already has an incompatible resource.
func (*Engine) AddAudioRunner ¶
AddAudioRunner adds runners to the audio stage, before the audio system. They run every tick, whatever the scene stack, a Tool's pause or Hold do to the game's stages, so an audio source can tell that the game froze and silence what it holds (package speech releases its notes when its own StagePost system did not run). A runner that implements system.Initializer is initialized before its first Run. Use it for that, never for game logic.
Panics with "game: AddSystem after the first Update" once the schedule is built, and with "game: nil system".
func (*Engine) AddExtract ¶
AddExtract adds runners to the extract stage, after the engine's own extract systems (tiles, sprites, nine-slices, particles, screen items, labels, touch controls) and before the debug shapes and the sort. They fill the render.Queue (a world resource) with items of their own, such as shapes, text or sprites drawn through a shader, and the engine sorts them with the rest. Like the other extract systems they run every tick, whatever the scene stack, a Tool's pause or Hold do, so what they queue also shows in the editor. A runner that implements system.Initializer is initialized before its first Run. Use it for drawing only, never for game logic. See doc/guide/engine/rendering.md#writing-your-own.
Panics with "game: AddSystem after the first Update" once the schedule is built, and with "game: nil system".
func (*Engine) AddRunner ¶
AddRunner is like Engine.AddSystem for Runner values. A runner that implements Initializer is initialized before its first Run. Add a system.Runner (an engine package's system, a Lua system from github.com/weakpixel/contrib/lua) with Wrap:
e.AddRunner(game.StageSimulate, game.Wrap(phys), &HeroSystem{})
Panics like Engine.AddSystem.
func (*Engine) AddSystem ¶
AddSystem appends systems to a stage slot; they run in the order added. Plain functions get no Init call: use Engine.AddRunner for systems that implement Initializer.
They are the systems of the root scene (Engine.Root).
Panics with "game: AddSystem after the first Update" once the engine has started, and with "game: invalid stage" for an unknown stage.
func (*Engine) Assets ¶
Assets returns the asset server. Load with render.LoadSprite, render.LoadFont, anim.LoadClip or tilemap.LoadMap (asset.Load for other types) on its Global scope or a scope of your own.
func (*Engine) Audio ¶
func (e *Engine) Audio() *sound.AudioSystem
Audio returns the audio system, for its Stats.
func (*Engine) Background ¶
Background returns the colour the screen is cleared with (Config.Background, or what SetBackground set last).
func (*Engine) Boot ¶
Boot returns the load of the library's global package, which New starts in the global scope: use its Progress and Done for a boot screen. It is nil without Config.Library or without a global/ folder. With a boot/ package, New mounts boot/ first and global/ loads in the background, so a startup screen drawn with boot/'s assets can show this progress.
func (*Engine) Camera ¶
Camera returns the camera. Mutate it from StageCamera systems; the engine records its view in Camera.Prev at the start of every tick.
func (*Engine) CameraRig ¶
CameraRig returns the follow-camera configuration, initially Config.CameraRig. It is also the World resource *camera.Rig. The engine's camera.System runs first in StageCamera and moves the camera after the camera.Target entity as the Rig says; change its fields at any time, and call Snap after a teleport or level load. Without a Target entity it does nothing. See doc/guide/engine/camera.md.
func (*Engine) Canvases ¶
Canvases returns the pre-rendered images the renderer draws for render.KindCanvas items: the chunks of tilemap layers with TileLayer.Chunked. It is also a World resource.
func (*Engine) Close ¶
func (e *Engine) Close()
Close stops every sound and the asset workers. Call it after ebiten.RunGame returns. It is idempotent.
func (*Engine) Draw ¶
Draw implements ebiten.Game: it clears the screen and draws the queue the last Update extracted. It never reads the World. Entities are drawn interpolated between their last two ticks, and the shader Time uniform is the simulation time interpolated the same way (see [shaderTime]). A Tool that is a DrawGate can skip frames; Draw then leaves screen as it is.
func (*Engine) DrawFinalScreen ¶
func (e *Engine) DrawFinalScreen(screen ebiten.FinalScreen, offscreen *ebiten.Image, geoM ebiten.GeoM)
DrawFinalScreen implements ebiten.FinalScreenDrawer: it draws the frame onto the window through the post chain's final pass, or with Ebiten's default scaling when there is none (see render.Renderer.DrawFinal), then lets the Tool, if any, draw over it. Pending ShotWindow captures are taken first, from the frame copy without the stats overlay. While the startup screen is up it draws that instead, at window resolution.
func (*Engine) FrameChanged ¶
FrameChanged reports whether a Draw now would show something else than the last drawn frame: the render queue the last Update extracted differs item by item, the camera, background, fade or window size changed, an asset finished loading or reloaded since, or the frame depends on time (an item with a shader, a post-processing pass or a final pass, whose Time uniform moves every tick). While the clock stands still (the last tick's scaled delta was 0, see Engine.Time) Time stands still too, so such items and passes count as changed only when they differ from the last drawn frame. Before the first drawn frame it is true.
A DrawGate uses it to skip the frames of a scene that stands still. It compares every queue item, which costs about as much as copying the queue; call it at most once per tick. It allocates nothing once the copy's capacity has grown to the queue's.
func (*Engine) Groups ¶
func (e *Engine) Groups() *render.GroupConfig
Groups returns the layer groups the renderer draws offscreen and composites, for example to run layers 2..3 through a water shader:
water := e.Groups().Add(render.GroupOptions{From: 2, To: 3, Shader: wave})
It is also a World resource (ecs.GetResource[render.GroupConfig]), so systems can animate a group with Set.
func (*Engine) Held ¶
Held reports whether a Engine.Hold is active, so StageSimulate is skipped. The startup screen holds the game on its own and does not count.
func (*Engine) Hold ¶
func (e *Engine) Hold() (release func())
Hold holds the game's StageSimulate until the returned release is called: its systems are skipped while at least one hold is active. The input, camera and post stages keep running (tweens advance, the follow camera moves, input is read), and so do the engine's own stages, so a screen transition can animate while gameplay stands still. Holds nest: each Hold needs its own release, and calling a release twice is a no-op. Simulation time keeps advancing. Hold may be called before the first Update and from any system; a Hold taken in an earlier stage holds StageSimulate of the same tick. It holds every scene, and wins over a Tool's TickPause (held EditRunners do not run either). See doc/guide/engine/engine.md#what-runs-when.
func (*Engine) Input ¶
Input returns the input router: player states, mapping stacks, devices, rebinding. It is also the World resource *input.Router, and the router's events are the resource *input.Events. The engine updates it first in StageInput, so every game system of a tick reads the same state.
func (*Engine) Layers ¶
func (e *Engine) Layers() *render.LayerConfig
Layers returns the layer configuration, for example to Y-sort a layer:
e.Layers().Set(1, render.LayerOptions{YSort: true})
func (*Engine) Layout ¶
Layout implements ebiten.Game: it returns the logical size for the window size and keeps extract.Screen in sync, so culling and screen-space sprites follow resizes.
func (*Engine) Levels ¶
Levels returns the levels loaded with Engine.LoadLevel, Engine.LoadLevelData or Engine.LoadMap and not unloaded yet, in load order. The slice is a copy.
func (*Engine) Listener ¶
Listener returns the audio listener. The engine moves it to the camera every tick (Pos, and HalfWidth from the screen width and zoom); set Range to make distant positional sounds quieter.
func (*Engine) LoadLevel ¶
LoadLevel reads the GOD file at path from Config.FS and spawns its objects into the World. The entities exist immediately; assets load in the background and sprites draw the placeholder until Level.Done.
Asset references resolve in a scope owned by the level, so Engine.UnloadLevel can free them. To switch levels without a gap, load the new level, wait for Done, then unload the old one.
A document whose objects are prefab instances ("prefab": "<key>", see doc/guide/engine/game-objects.md#prefabs) loads those prefabs into the level's scope first and spawns in the assets stage of the tick in which they are all Ready, before any game system runs; until then Level.Spawned is false. Errors found then (a prefab that failed, an invalid override) go to Level.Err and Config.OnAssetError, and nothing spawns.
It returns an error for a missing file, invalid JSON or an invalid object; nothing is spawned then. Call it from a Start hook or a system.
func (*Engine) LoadLevelBase ¶
LoadLevelBase loads the level named base, a key without suffix ("forest/cave"), into a new scope owned by the returned Level and returns at once. Once the packs of base's package and of the packages it uses are mounted (at once for loose files), it spawns the level's parts into the same Level:
- <base>.level.json, a GOD document, like LoadLevel;
- <base>.tmj or <base>.world, like LoadMap with opts, which also spawns the documents paired with the map (<base>.level.json is the pair of <base>.tmj and spawns once; a world's children bring their own <map>.level.json).
Every part is optional, but one must exist. opts.NoDocuments and opts.SkipDocuments leave documents out. Everything lives in the Level's one scope; the package's other files load only when something references them (preload with Engine.LoadPackage). With loose files the GOD objects exist when it returns; from a pack they spawn in the assets stage of the tick in which the pack is mounted. Level.Spawned reports true once every part has spawned. Unload it with Engine.UnloadLevel, which also unmounts the packs it holds.
It works without a library too (the parts are looked up in Config.FS). It returns an error for an unknown package, for a base with none of the three files (loose files only) and, loose files only, for a GOD document that does not spawn; from a pack those errors go to Level.Err and OnAssetError. A paired document that does not spawn goes to Level.Err and OnAssetError and never blocks the map. Call it from a Start hook or a system.
func (*Engine) LoadLevelData ¶
LoadLevelData is Engine.LoadLevel for a document held in memory, for example the unsaved text of an editor: it spawns the objects of the GOD document data. path only names the level (its asset scope and Level.Path); nothing is read from it. Assets still load from Config.FS. A document with prefab instances spawns later, like LoadLevel's.
It returns an error for invalid JSON or an invalid object; nothing is spawned then. Call it from a Start hook or a system.
func (*Engine) LoadMap ¶
LoadMap starts loading a Tiled map (*.tmj) or world (*.world) into a scope owned by the level and returns immediately. The engine spawns the layers (see tilemap.Spawn and tilemap.SpawnWorld; opts applies to each map, and a world's maps are placed at opts.Pos plus their world position) in the assets stage of the tick in which the map, or every map of the world, becomes Ready, before any game system runs. Until then Level.Spawned is false and Level.Maps is empty. A map that fails to load spawns nothing and sets Level.Err.
A map inside a library package that is packed and not mounted loads once the packs of its package (and of the packages it uses) are mounted, which the level's scope then holds.
It returns an error for a path with another suffix or when Config.FS is nil. Call it from a Start hook or a system.
func (*Engine) LoadPackage ¶
LoadPackage loads every entry of the library package name into sc and returns at once (see library.Library.LoadPackage): the explicit preload of a package, for prefabs, effects or sounds that code spawns or plays by key. Loading a level never preloads its package. Load into a level's scope (Level.Scope) to release the assets with the level.
It panics with "game: LoadPackage: Config.Library is nil" and like the library for an unknown package.
func (*Engine) LogicalToWindow ¶
LogicalToWindow is the inverse of Engine.WindowToLogical: it converts logical screen pixels (what render.Camera.WorldToScreen returns) to window pixels, where a Tool's DrawFinal draws.
func (*Engine) Mixer ¶
Mixer returns the mixer, for bus and master volumes and voice limits. It is also the world resource *sound.Mixer.
func (*Engine) Pop ¶
func (e *Engine) Pop()
Pop removes the topmost scene: OnExit, then its levels are unloaded, its owned entities deleted and its scope released, then OnUncover goes to the scene below. The scene may be pushed again; its levels and scope start empty and its Init does not run again.
Applying it panics with "game: Pop with only the root scene" when only the root is left.
func (*Engine) Post ¶
Post returns the post-processing chain: full-screen shader passes over the finished frame and an optional final pass at window resolution, for example
e.Post().Passes = []render.Pass{{Shader: vignette, Params: [4]float32{0.6}}}
e.Post().Final = &render.Pass{Shader: crt}
It is also a World resource (ecs.GetResource[render.PostChain]), so systems can change a pass's Params or Off between frames.
func (*Engine) Push ¶
Push puts s on top of the stack. Push, Pop and Replace only queue the change: Engine.Update applies the queue in call order at its start, before any system runs, so systems never see a half-switched stack. Called before the first Update or from a Start hook, they apply before the first tick.
Applying a push sends OnCover to the old top, initializes the runners of s the first time it is pushed (before the root's own Init on the very first tick), then sends OnEnter to s.
Panics with "game: nil scene" for a nil s. Applying it panics with "game: scene already on the stack" if s is on the stack.
func (*Engine) Quit ¶
func (e *Engine) Quit()
Quit makes the next Update return ebiten.Termination, which ends ebiten.RunGame without an error.
func (*Engine) Renderer ¶
Renderer returns the renderer. It is created on first use because render.NewRenderer allocates Ebiten images, which must happen on the game goroutine; call this from Update, Draw or a Start hook.
func (*Engine) Replace ¶
Replace pops the topmost scene and pushes s in its place, without OnUncover and OnCover in between. Replacing with the scene itself reenters it.
Panics like Engine.Push; applying it panics like Engine.Pop when only the root is left.
func (*Engine) ReportAssetError ¶
ReportAssetError sends err to Config.OnAssetError, or logs it when that is nil. Packages that check asset data after it loaded (a script's parameters, an entity's overrides) report through it, so a game sees every bad asset in one place.
func (*Engine) Root ¶
Root returns the root scene: the systems added with Engine.AddSystem and Engine.AddRunner. It is always the bottom of the stack and cannot be popped or replaced. A game that never pushes a scene only has the root.
func (*Engine) SampleRate ¶
SampleRate returns the audio sample rate in Hz: the audio context's, or Config.SampleRate (sound.DefaultSampleRate by default) under NoAudio. A stream source (sound.AudioSystem.AddStream) must produce PCM at this rate.
func (*Engine) SceneOf ¶
SceneOf returns the scene that owns e: the scene that spawned it (Context.Spawn, Scene.Own) or loaded the level it belongs to (Scene.LoadLevel, Scene.LoadMap, Scene.LoadLevelBase), else the root. A dead entity, or one that no scene owns, returns the root. Map layer entities count; other entities a map spawns do not.
Systems that run per scene use it to pick their entities: a behavior runner on a pause scene runs that scene's buttons, the root's runner the rest. It is a map lookup when scenes own entities and allocates nothing.
func (*Engine) Scenes ¶
Scenes returns the scene stack, bottom to top, root first. The slice is a copy.
func (*Engine) Screenshot ¶
func (e *Engine) Screenshot(req ShotRequest)
Screenshot queues a capture of the next drawn frame; see ShotRequest for the options and doc/guide/engine/dev-tools.md#screenshots for what a capture contains. The next Draw serves every queued request (while the startup screen is up, they wait); the PNG is encoded off the game goroutine and the result is delivered at the start of a later Update. It never panics: invalid requests are answered with ShotResult.Err. Call it on the game goroutine.
func (*Engine) SetBackground ¶
SetBackground sets the colour the screen is cleared with before each frame (see Config.Background); nil is opaque black. An editor uses it to change the look of a stage while the game runs.
func (*Engine) SetScreenshotSink ¶
func (e *Engine) SetScreenshotSink(sink func(ShotResult) error)
SetScreenshotSink replaces Config.Screenshots.Sink; see there. Editor hosts call it to send captures to their host instead of writing files. nil restores the default sink. Call it on the game goroutine; captures already encoding use the sink set when they are delivered.
func (*Engine) SetStatsOverlay ¶
SetStatsOverlay turns the stats overlay on or off: at the end of every Draw, a render.StatsOverlay shows Renderer.Stats, FPS and TPS in the top-left corner.
func (*Engine) SetTimeScale ¶
SetTimeScale sets the game's time scale: 1 is normal speed, 0.5 slow motion, 0 stops time (hit-stop: set 0 for a few ticks, then 1 again). Every stage's ctx.Time.Delta is the tick times the effective scale, so game systems, physics, animations, particles, tweens and the follow camera all slow down and stop with it. What keeps real time reads gfx.Time.Unscaled (see Engine.Time). The scale applies from the next Update. A scene with SceneOptions.PauseTime and the tool clock (Engine.ToolTime) multiply it without changing it, so the game never has to restore it.
Panics with "game: negative time scale" if s < 0.
func (*Engine) Sound ¶
Sound returns the sound queue: systems play effects with Play and switch music with PlayMusic. It is also the world resource *sound.Queue.
func (*Engine) Start ¶
Start registers fn to run once, at the first Update, after the schedule is built and before the first tick runs. Use it to spawn entities and load levels. Hooks run in registration order. A hook may call Quit.
func (*Engine) StartupActive ¶
StartupActive reports whether the startup screen is up. While it is, the game's systems (StageInput to StagePost) do not run, and nothing of the game is drawn. It is false once the last screen has faded out, and always without Config.Startup or with a Tool.
func (*Engine) StatsOverlay ¶
StatsOverlay reports whether the stats overlay is drawn.
func (*Engine) Time ¶
Time returns the game clock of the last tick, also published as the gfx.Time World resource. Read it; only the Engine writes it.
func (*Engine) TimeScale ¶
TimeScale returns the game's own time scale (see Engine.SetTimeScale); it is 1 unless the game changed it.
func (*Engine) ToolPaused ¶
ToolPaused reports whether the current (or, outside Update, the last) tick ran in TickPause mode, which only a Tool sets. A pause menu is a Scene, not this. See doc/guide/engine/engine.md#what-runs-when.
func (*Engine) ToolTime ¶
ToolTime returns the tool clock; a tool writes it, typically from Tool.Tick, and it applies from that tick on.
func (*Engine) TouchControls ¶
func (e *Engine) TouchControls() *inputsys.TouchControlsExtract
TouchControls returns the system that draws the touch regions, to set its colors or AlwaysShow.
func (*Engine) Tweens ¶
Tweens returns the running tweens. It is also the World resource *tween.Tweens, which systems use to start them:
tween.To(ecs.GetResource[tween.Tweens](ctx.World), e, tween.Pos, to, 0.4)
The engine's tween.System advances them first in StageCamera, so they stop while a Tool pauses the game. See doc/guide/engine/tweens.md.
func (*Engine) UnloadLevel ¶
UnloadLevel deletes the level's entities that are still alive (Game Objects or map layers) and releases its assets (and the packs it holds, which are unmounted unless another scope holds them). A map level that has not spawned yet never will. The level must not be used afterwards, except Path. Unloading twice is a no-op.
func (*Engine) Update ¶
Update implements ebiten.Game: it runs one tick of the schedule. The first call builds the schedule and runs the Start hooks. The tick length is 1s/TPS, constant; the stages see it times the time scale (see Engine.SetTimeScale and gfx.Time).
func (*Engine) WindowToLogical ¶
WindowToLogical converts a position in window pixels (what ebiten.CursorPosition reports to a Tool, and what DrawFinal draws in) to logical screen pixels, the space render.Camera.ScreenToWorld takes. It inverts the scale and offset of the most recent Engine.DrawFinalScreen; before the first one, it is the identity.
type Initializer ¶
type Initializer interface {
Init(ctx *Context)
}
Initializer is an optional interface for a Runner that needs one-time setup: building views, loading assets, setting resources, queueing initial spawns. The Engine calls Init once per runner value: for the root's runners before the first tick, for a scene's when the scene is first pushed. ctx.Scene is the scene being set up.
type InputConfig ¶
type InputConfig struct {
// Actions is the game's action table. It is frozen by New if it is not
// already. nil means an empty table: the router runs, but no action
// exists.
Actions *input.Actions
// Bindings is the asset key of the default bindings file, for example
// "input/bindings.json". It is loaded on the Global scope and applied
// when ready (and again whenever the asset is committed). Empty means
// nothing is bound until the game calls Router.SetBindings.
Bindings string
// Players is the number of player slots, 1..input.MaxPlayers. 0 means 1.
Players int
// Assign is the device assignment policy. The zero value,
// input.AssignSingle, gives every device to player 0.
Assign input.AssignPolicy
// JoinAction is the Button action that claims a player slot with
// input.AssignJoin.
JoinAction input.Action
// Source replaces the Ebiten source, for tests and replays
// (input.ManualSource, input.ReplaySource). nil means
// ebiteninput.New, reading Ebiten.
Source input.Source
// OnError receives profile problems and bindings files that fail to
// load. nil logs them.
OnError func(error)
// HideTouchControls turns off the drawing of the touch regions
// (inputsys.TouchControlsExtract).
HideTouchControls bool
}
InputConfig configures the input system: the input.Router the engine creates and updates first in StageInput. See doc/guide/engine/input.md.
type Level ¶
type Level struct {
// contains filtered or unexported fields
}
Level is a loaded level: a GOD file (Engine.LoadLevel), a Tiled map or world (Engine.LoadMap) with its optional <map>.level.json documents, or the parts of a base key (Engine.LoadLevelBase). It owns the entities it spawned and the one asset scope holding the assets of the map and of all its documents.
func (*Level) Bounds ¶
Bounds returns the world rectangle covered by the maps of a map level: the union of each map's tilemap.Map.Bounds placed at its Pos. It is the zero Rect until Level.Spawned, and for a GOD level. Use it for the camera bounds, after the level spawned:
e.CameraRig().Bounds = level.Bounds()
func (*Level) Done ¶
Done reports whether every asset of the level is ready (or failed). A level is also done when the packs of its package failed.
func (*Level) Err ¶
Err returns the asset errors of the level joined, or nil. It includes each GOD document that did not spawn (unreadable, invalid, a failed prefab) and failed packs. A missing paired document is never an error.
func (*Level) Maps ¶
Maps returns the maps of a map level with their layer entities: one map for a .tmj, every map of a .world in file order. It is empty until Level.Spawned, and for a GOD level.
func (*Level) Name ¶
Name returns the optional top-level "name" of the level's first document (the base's document, else the first paired one), a label for editors, or "" when it has none, there is no document and after UnloadLevel. Names are not unique and nothing looks levels up by them.
func (*Level) Objects ¶
Objects returns the spawned Game Objects of all the level's documents, in spawn order. A map level without a document has none: the map's objects are data in its Maps.
func (*Level) Path ¶
Path returns the file the level was loaded from, or the base key ("forest/cave") for a level loaded with LoadLevelBase.
func (*Level) Progress ¶
Progress returns how many of the level's assets are ready and how many it references; use it for a loading bar. A level whose package is packed counts the packs first (see library.Load.Progress).
func (*Level) Scope ¶
Scope returns the asset scope that holds the level's assets; nil after Engine.UnloadLevel. Tools that decode more components for the level resolve their asset keys into it (resolver.Resolver.SetScope).
func (*Level) SetObjects ¶
SetObjects replaces the level's object list, for tools that create and delete a level's objects in place (an editor applying a changed document): Engine.UnloadLevel deletes the entities listed here. The level keeps objs; the caller must not change it afterwards.
func (*Level) Spawned ¶
Spawned reports whether the level's entities exist. A GOD level spawns in LoadLevel, or, when its document places prefab instances, in the tick in which those prefabs are Ready; a map level in the tick in which its maps become Ready. It is true when every map and every document has spawned or failed. A level that failed never spawns: check Level.Err.
type LoadedMap ¶
type LoadedMap struct {
// Map is the map's handle; read it with tilemap.MapStoreOf.
Map tilemap.MapHandle
// Pos is the world position of the map's top-left corner.
Pos gfx.Vec2
// Layers are the map's layer entities, in draw order.
Layers []ecs.Entity
}
LoadedMap is one spawned map of a map level.
type Runner ¶
type Runner interface {
Run(ctx *Context)
}
Runner is a game system that keeps state (prebuilt views, loaded handles) in a struct:
type Movement struct{ view ecs.View2[gfx.Transform, Velocity] }
func (m *Movement) Run(ctx *game.Context) { ... }
A System is itself a Runner, so plain functions and structs mix freely. Runners of the ECS's own type (system.Runner) go through Wrap.
func Wrap ¶
Wrap makes a system.Runner from package ecs/system a Runner, so it can be added to a stage with Engine.AddRunner or Scene.AddRunner. Use it for the systems of engine packages below game (physics, collision, animbody, hierarchy, particles, ...) and for Lua systems (github.com/weakpixel/contrib/lua). The wrapped runner gets the ECS's system.Context of the same call, with the same Time.Delta, and keeps its system.Initializer and EditRunner.
Panics with "game: nil system" for a nil r.
type Scene ¶
type Scene struct {
// contains filtered or unexported fields
}
Scene is one top-level screen of the game (title, gameplay, pause): its own systems, levels, entities and asset scope, run while it is on the engine's scene stack. Create it with NewScene, add systems, then Engine.Push it. A Scene belongs to one Engine. Like the Engine, it is single-goroutine.
func NewScene ¶
func NewScene(name string, opts SceneOptions) *Scene
NewScene returns a scene named name (for debugging and its asset scope) with the given options. Nothing runs until it is pushed.
func (*Scene) AddRunner ¶
AddRunner is like Scene.AddSystem for Runner values. A runner that implements Initializer is initialized when the scene is first pushed, once per Scene value. Add a system.Runner (an engine package's system, a Lua system) with Wrap.
Panics like Scene.AddSystem.
func (*Scene) AddSystem ¶
AddSystem appends systems to a stage slot of the scene; within a slot they run in the order added, after the systems of the scenes below. Like Engine.AddSystem, plain functions get no Init call.
Panics with "game: AddSystem after the scene was pushed" once the scene has been pushed, with "game: invalid stage" for an unknown stage and with "game: nil system".
func (*Scene) LoadLevel ¶
LoadLevel is Engine.LoadLevel for a level the scene owns: popping the scene unloads it. It returns an error if the scene was never pushed.
func (*Scene) LoadLevelBase ¶
LoadLevelBase is Engine.LoadLevelBase for a level the scene owns.
func (*Scene) LoadMap ¶
LoadMap is Engine.LoadMap for a level the scene owns.
func (*Scene) Name ¶
Name returns the name given to NewScene ("root" for Engine.Root).
func (*Scene) OnCover ¶
OnCover registers fn to run when another scene is pushed on top of this one (not for a Engine.Replace of the scene above it).
func (*Scene) OnEnter ¶
OnEnter registers fn to run each time the scene is pushed, after its Init (the first time) and with the scene already on the stack. Spawn the scene's entities and load its levels here.
func (*Scene) OnExit ¶
OnExit registers fn to run when the scene is popped or replaced, before its levels, owned entities and scope are cleaned up.
func (*Scene) OnUncover ¶
OnUncover registers fn to run when the scene above this one is popped (not for a Engine.Replace).
func (*Scene) Own ¶
Own records entities spawned by the scene's systems; popping the scene deletes those still alive. Entities of the scene's levels need no Own.
The entities are recorded for Engine.SceneOf while the scene is on the stack (from its push on, for entities owned before it).
type SceneOptions ¶
type SceneOptions struct {
// UpdateBelow keeps the scenes below updating (their systems run) while
// this scene is on the stack.
UpdateBelow bool
// InputBelow lets the scenes below run their [StageInput] systems. When
// false, only the scenes above them read input, even if UpdateBelow
// keeps them simulating.
InputBelow bool
// DrawBelow keeps the scenes below drawing. When false, items on layers
// below Layer are not drawn (see render.Queue.SetMinLayer), so give
// stacked scenes increasing layer bands (game 0 to 999, pause 1000 up).
DrawBelow bool
// Layer is the lowest layer this scene draws on when DrawBelow is false.
Layer int16
// PauseTime stops the game clock while this scene is on the stack: the
// effective time scale is 0, so sprite clips, animated tiles,
// particles, tweens, the follow camera, the shader Time and the scenes
// below that keep updating (UpdateBelow) stand still. This scene and
// the scenes above it run on real time: their systems see the unscaled
// tick as ctx.Time.Delta. Entities with the gfx.Unscaled marker and
// tweens started with tween.Builder.Unscaled keep moving. Popping the
// scene restores the game's own scale ([Engine.SetTimeScale]). Off by
// default, so a gameplay scene pushed over a title screen does not
// stop time.
PauseTime bool
}
SceneOptions say how a Scene affects the scenes below it on the stack. The zero value is the pause/menu default: scenes below are frozen, get no input and are not drawn. Time keeps running unless PauseTime is set. How the options combine with Engine.Hold, a Tool's pause and the startup screen: doc/guide/engine/engine.md#what-runs-when.
type ScreenshotConfig ¶
type ScreenshotConfig struct {
// Dir is the folder native captures without a ShotRequest.Path go to,
// relative to the working directory and created on first use. Empty
// means "screenshots".
Dir string
// Sink, if set, replaces the default sink (the file natively, the
// download in a browser): it receives every successful capture, with
// PNG set and Path empty, on the game goroutine at the start of a later
// Update, before the request's Done. A returned error becomes the
// result's Err. Editors use it to send captures to their host.
Sink func(ShotResult) error
// Key is a development hotkey: each press (an edge from up to down of
// the raw key state) takes one capture of KeyTarget. The zero Key is
// none, unless the WPIX_SCREENSHOT_KEY environment variable names
// a key; a Key set here wins over it. It reads the router's raw keys,
// so it needs no input action, works in any game and also while a Tool
// pauses the game (keys the tool's UI used never reach it).
Key input.Key
// KeyTarget is what the hotkey captures; the default is ShotGame.
KeyTarget ShotTarget
}
ScreenshotConfig configures Engine.Screenshot. The zero value writes native captures into ./screenshots and downloads them in a browser.
type ShotRequest ¶
type ShotRequest struct {
// Target is what to capture; the default is ShotGame.
Target ShotTarget
// Scale enlarges a ShotGame capture by a whole multiple with
// nearest-neighbour filtering, 1..MaxShotScale; 0 means 1. Ignored for
// ShotWindow.
Scale int
// KeepAlpha keeps the frame's alpha channel. By default the PNG is
// opaque: the frame as the window shows it over black.
KeepAlpha bool
// Path is the file the default native sink writes (relative to the
// working directory, its folder created, an existing file
// overwritten). Empty means a new name in Config.Screenshots.Dir.
// Ignored in a browser and when Config.Screenshots.Sink is set.
Path string
// ID is an opaque tag the engine echoes in ShotResult.ID, for hosts
// that match answers to requests (the editor protocols use it).
ID string
// Done, if set, receives the result on the game goroutine, at the
// start of a later Update (or in Close). Without Done the engine logs
// the file written, or the error.
Done func(ShotResult)
}
ShotRequest asks for one screenshot. The zero value captures the logical frame, opaque, into a new file in Config.Screenshots.Dir.
type ShotResult ¶
type ShotResult struct {
// Path is the file the default native sink wrote; "" when no file was
// written (an error, a browser download, a custom sink).
Path string
// PNG is the encoded image; nil on error.
PNG []byte
// ID is the request's ID; "" for captures the engine took itself
// (hotkey, environment variables).
ID string
// Width and Height are the image's size in pixels.
Width, Height int
// Tick is the Engine tick (the number of Updates) the frame belongs to.
Tick uint64
// Err is set when the capture, the encode or the sink failed.
Err error
}
ShotResult is the outcome of a ShotRequest.
type ShotTarget ¶
type ShotTarget int
ShotTarget selects what a screenshot captures. See Engine.Screenshot.
const ( // ShotGame captures the logical frame at the game's resolution // (Config.Width x Config.Height): layer groups, post passes and // PostChain.Fade included, the final pass and the window scaling not. ShotGame ShotTarget = iota // ShotWindow captures the frame as the window shows it: window // resolution, with the post chain's final pass (or Ebiten's default // scaling) and the letterbox bars of IntegerScale. ShotWindow )
func (ShotTarget) String ¶
func (t ShotTarget) String() string
String returns "game" or "window", the names the editor protocols use.
type Stage ¶
type Stage int
Stage is a slot in the Engine's fixed per-tick order where game systems can be added. The engine's own systems run around them:
assets, snapshot | input, simulate, camera, post | hierarchy, anim, extract, sort, audio
The input stage starts with the engine's inputsys.InputSystem, which updates the input router (see Engine.Input) before any game system. The camera stage starts with the engine's tween.System, which advances the tweens (see Engine.Tweens), then the engine's camera.System, which follows the camera.Target entity (see Engine.CameraRig), so the camera sees the tweened position.
The hierarchy stage writes the world Transform and the draw layers of the entities with a hierarchy.Parent, and deletes the children of dead parents; it is not gated by a Tool pause. The assets stage runs it once right after a document spawned objects, so their children are placed in that tick.
The anim stage runs the animations, then the particle simulation, so both keep playing while a Tool pauses the game. The extract stage queues the particles right after the sprites.
The assets stage also spawns the layers of maps loaded with Engine.LoadMap once they are Ready, before the snapshot, so new layers have their previous pose from the first tick. The extract stage queues tiles (tilemap) before sprites, so in a layer without Y-sorting tiles draw under sprites. The audio stage runs last, so every sound requested during the tick starts in the same tick, with the listener at the camera's final position.
const ( // StageInput runs first: read devices, set intent. StageInput Stage = iota // StageSimulate is the main game logic. StageSimulate // StageCamera moves the camera. The engine has already recorded the // camera's view for this tick (Camera.Snapshot), so systems here just // assign Camera.Pos, Zoom and Rotation. The engine's tween.System runs first, then its // follow camera (camera.System). StageCamera // StagePost runs after the camera and before animation and extraction: // last-minute changes to Transform, Sprite, Label. StagePost )
type StartupConfig ¶
type StartupConfig struct {
// NoSkip ignores input: by default a key, mouse button, touch or pad
// button ends the current screen early (never before the initial load
// on the last screen).
NoSkip bool
// Screens are shown in order. Empty means one [WeakpixelScreen].
Screens []StartupScreen
// MinDuration is the minimum time on screen of every screen without its
// own Duration. 0 means 5 seconds.
MinDuration time.Duration
// Ready is an extra condition for the end of the last screen, checked
// once per tick after the initial load is done. nil means the initial
// load alone decides.
Ready func(*Engine) bool
}
StartupConfig configures the startup screen: one or more screens the engine shows from the first frame until the initial assets have loaded, each for at least a minimum time. Set Config.Startup to turn it on; the zero value shows WeakpixelScreen for at least 5 seconds. A Tool turns it off. See doc/guide/engine/dev-tools.md#startup-screen.
type StartupScreen ¶
type StartupScreen struct {
// Image is the picture, scaled to fit the window (aspect kept, centred).
Image image.Image
// Path is a PNG or JPEG that New reads from Config.FS (the library's
// files included) and shows like Image. A file that fails to read or
// decode is reported through OnAssetError and the screen is skipped.
Path string
// Draw draws the screen itself into dst, which is window-sized, for
// example a loading bar from s.Ready and s.Total. dst is cleared to
// Background first; the engine applies the fade.
Draw func(dst *ebiten.Image, s StartupState)
// Duration is the minimum time on screen, fades included. 0 means
// StartupConfig.MinDuration.
Duration time.Duration
// Background fills the window around the image. nil means black.
Background color.Color
// Fade is the length of the fade in and of the fade out, from and to
// black, inside Duration. 0 means 250ms; negative means no fade.
Fade time.Duration
}
StartupScreen is one screen of the startup sequence. Exactly one of Image, Path and Draw must be set; New panics with "game: startup screen <i>: set one of Image, Path or Draw" otherwise.
func WeakpixelScreen ¶
func WeakpixelScreen() StartupScreen
WeakpixelScreen returns the default startup screen: the Weakpixel Engine image on its own dark background. Use it to keep the default when adding screens:
Startup: &game.StartupConfig{Screens: []game.StartupScreen{{Image: studio}, game.WeakpixelScreen()}}
type StartupState ¶
type StartupState struct {
// Screen is the index of the current screen in Screens, Screens their
// number.
Screen, Screens int
// Elapsed is the time the current screen has been up; Duration is its
// minimum time.
Elapsed, Duration time.Duration
// Ready and Total count the assets of the initial load (the global
// scope and every level loaded so far): how many are ready and how
// many there are.
Ready, Total int
// Alpha is the fade, 0 (black) to 1 (fully shown).
Alpha float32
}
StartupState is what a StartupScreen.Draw function draws from.
type Stores ¶
type Stores struct {
// contains filtered or unexported fields
}
Stores gives typed access to the asset stores of an Engine: e.Stores().ClipSets().Get(h) instead of anim.ClipSetStoreOf(e.Assets()). It is a small value; copy it freely.
Every method resolves its store when called (one map lookup, like the XStoreOf function it wraps) and panics like asset.StoreOf if that kind's loaders are not registered, so an unregistered kind fails only when asked for. Hot paths cache the store in a local or a system field. A kind the engine does not know uses asset.StoreOf with e.Assets().
func StoresOf ¶
StoresOf returns the stores of srv, for code that has a server but no Engine. It panics only when a store is asked for, not here.
func (Stores) Atlases ¶
func (s Stores) Atlases() render.AtlasStore
Atlases returns the atlas store; see render.AtlasStoreOf.
func (Stores) Bindings ¶
func (s Stores) Bindings() inputsys.BindingsStore
Bindings returns the input bindings store; see inputsys.BindingsStoreOf.
func (Stores) ClipSets ¶
func (s Stores) ClipSets() anim.ClipSetStore
ClipSets returns the clip set store; see anim.ClipSetStoreOf.
func (Stores) Clips ¶
Clips returns the clip store; see anim.ClipStoreOf.
func (Stores) Fonts ¶
Fonts returns the font store; see render.FontStoreOf.
func (Stores) Maps ¶
Maps returns the map store; see tilemap.MapStoreOf.
func (Stores) Music ¶
func (s Stores) Music() sound.MusicStore
Music returns the music store; see sound.MusicStoreOf.
func (Stores) Prefabs ¶
Prefabs returns the prefab store; see prefab.StoreOf.
func (Stores) Shaders ¶
func (s Stores) Shaders() render.ShaderStore
Shaders returns the shader store; see render.ShaderStoreOf.
func (Stores) Sounds ¶
func (s Stores) Sounds() sound.SoundStore
Sounds returns the sound store; see sound.SoundStoreOf.
func (Stores) Sprites ¶
func (s Stores) Sprites() render.SpriteStore
Sprites returns the sprite store; see render.SpriteStoreOf.
func (Stores) Tilesets ¶
func (s Stores) Tilesets() tilemap.TilesetStore
Tilesets returns the tileset store; see tilemap.TilesetStoreOf.
func (Stores) Worlds ¶
func (s Stores) Worlds() tilemap.WorldStore
Worlds returns the world store; see tilemap.WorldStoreOf.
type System ¶
type System func(ctx *Context)
System is one unit of game logic: a plain function. It runs on the Engine's goroutine. Structural changes made while a view is iterating panic in package ecs, so queue them with ctx.Commands or Context.Spawn. See Context for the lifetime of ctx.
type TickMode ¶
type TickMode int
TickMode is how one Update runs; a Tool returns it from Tick.
const ( // TickRun runs the whole schedule (the default). TickRun TickMode = iota // TickPause skips the game: the input stage (including the engine's // input system) and every system in StageSimulate, StageCamera and // StagePost. The engine's own stages still run: assets load and // hot-reload, transforms are snapshotted, animations play, the frame is // extracted and audio is updated, so the paused scene keeps drawing and // stays live. Simulation time (the shader Time uniform) keeps advancing. // Runners that are [EditRunner]s keep running. See // doc/guide/engine/engine.md#what-runs-when. TickPause // TickStep runs one full tick, like TickRun. A tool returns it once // while paused to advance the game by one tick, then TickPause again. TickStep )
type Time ¶
type Time struct {
// Delta is the length of the tick in game time: the fixed tick times
// the time scale. The systems of a scene with SceneOptions.PauseTime,
// and of the scenes above it, see the unscaled tick instead, so a pause
// menu keeps animating while the game stands still.
Delta time.Duration
// Dt is Delta in seconds, the factor most systems multiply speeds by.
Dt float32
// Unscaled is the fixed length of a tick, 1s/TPS, whatever the scale.
Unscaled time.Duration
// Tick is the index of the current tick: 0 for the first, then 1, 2,
// and so on.
Tick uint64
}
Time is the timing of one tick as a game system sees it.
type Tool ¶
type Tool interface {
// Init is called once, at the end of [New], when every engine part
// exists. The schedule is not built yet.
Init(e *Engine)
// Input is called once, in [New] before Init, with the device source
// (Ebiten's, or InputConfig.Source). The router reads the source it returns, so a
// tool can hide the clicks its own UI used from the game. Returning src
// leaves input unchanged.
Input(src input.Source) input.Source
// Tick is called at the start of every Update, after the Start hooks of
// the first one, and decides how this tick runs.
Tick(e *Engine) TickMode
// DrawFinal is called at the end of [Engine.DrawFinalScreen], after the
// final pass, to draw in window pixels (use [Engine.WindowToLogical] to
// map the mouse into the game).
DrawFinal(e *Engine, screen ebiten.FinalScreen)
}
Tool is a development tool attached to an Engine with Config.Tool, for example a level editor. It can pause and step the game, filter the input the game sees and draw over the finished frame at window resolution. The engine never implements one: a game that sets no Tool links no tool code and pays one nil check per Update and Draw.
type ToolTime ¶
type ToolTime struct {
// Scale multiplies the tick's delta; 0 means 1.
Scale float32
// Paused stops the clock. Each count of Step runs one tick while paused.
Paused bool
// Step is the number of ticks to run, at Scale, while Paused; the Engine
// counts it down. It is ignored while not Paused.
Step int
}
ToolTime is the tool's input to the game clock: editors and tools pause, single-step and speed up or slow down everything that moves on its own (sprite clips, animated tiles, particles, tweens, the follow camera, the shader Time) without touching the game's own scale. Only tools write it; get it with Engine.ToolTime. The zero ToolTime changes nothing.
It multiplies the game's scale (Engine.SetTimeScale) and the pause of a SceneOptions.PauseTime scene, so a tool pause never loses the scale a game set. It is not TickPause: that skips the game stages, ToolTime stops the clock that every stage and engine system reads.