Documentation
¶
Overview ¶
Package core provides the foundational structures and mechanisms for managing the game world, including entities and resources, and their lifecycle within the world.
Index ¶
- type AtlasSource
- type Camera
- type CameraView
- type CircleShape
- type Collector
- type Context
- type DrawItem
- type DrawList
- type Drawable
- type Entity
- func (e *Entity) AddComponent[T any](w *World, value T) error
- func (e *Entity) Component[T any](w *World) (T, bool)
- func (e *Entity) HasComponent[T any](w *World) bool
- func (e *Entity) ID() EntityID
- func (e *Entity) IsAlive() bool
- func (e *Entity) Kill()
- func (e *Entity) RemoveComponent[T any](w *World) error
- func (e *Entity) SetComponent[T any](w *World, value T) error
- type EntityID
- type Entry
- type LineShape
- type Phase
- type PrevTransform
- type Query
- type RectShape
- type Resources
- type Shape
- type Sprite
- type System
- type SystemFunc
- type TextureSource
- type Transform
- type Validatable
- type World
- func (w *World) DestroyEntities(entities []*Entity) error
- func (w *World) DestroyEntity(entity *Entity) error
- func (w *World) NewEntities(count int, components ...any) ([]*Entity, error)
- func (w *World) NewEntity(components ...any) (*Entity, error)
- func (w *World) Provide[T any](ctor func(*World) (T, error)) error
- func (w *World) ProvideEager[T any](ctor func(*World) (T, error)) error
- func (w *World) ResolveEager() error
- func (w *World) Resource[T any]() (T, error)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AtlasSource ¶ added in v0.0.2
AtlasSource draws one named region of a registered atlas.
type Camera ¶
type Camera struct {
// Zoom is a multiplier on the world-to-screen scale; 1.0 means none.
Zoom float64
// Primary marks this camera as the one the renderer uses.
Primary bool
}
Camera is the framing half of a camera entity: pair it with a Transform, which owns the position. An entity with a Camera and Primary set is the camera the renderer uses; cameras move by moving their Transform, and interpolated rendering covers them the same as any other entity.
Game.New spawns a default primary camera and hands it out through Game.MainCamera; a user-spawned primary takes precedence over it.
The render target's dimensions are not part of the Camera: the runner owns the logical resolution. Keeping a camera inside level bounds is a game-system concern, not component data.
type CameraView ¶
CameraView is the resolved view of a camera for rendering, containing its interpolated position and zoom.
It is used to convert between world and screen coordinates during rendering and input picking.
func (CameraView) ScreenToWorld ¶ added in v0.0.3
ScreenToWorld converts a screen-space point back to world coordinates.
This is the inverse of WorldToScreen, without the rounding: a screen point maps back to fractional world coordinates.
func (CameraView) WorldToScreen ¶ added in v0.0.3
WorldToScreen projects a world-space point onto the render target and snaps it to whole pixels.
Pixel snapping is applied to keep the texel grid stable during rendering.
type CircleShape ¶ added in v0.0.2
CircleShape draws a filled or outlined circle — an ellipse whenever the radii differ — of Radii world units, centered on the position and scaled by the scale. The transform's scale still applies on top, so non-uniform scale widens any radii just as it stretches a rect.
type Collector ¶
type Collector struct {
// SortedItems is the sorted output the returned DrawList views.
// It is reused across frames; do not modify or retain it.
SortedItems []DrawItem
// contains filtered or unexported fields
}
Collector assembles each frame's draw list: it owns the camera and sprite queries, resolves texture sources through the asset server, culls against the camera viewport, and sorts by layer, sort order, then world Y. Reused across frames - construct once per game; the runner's engine draw calls Collect every frame.
func NewCollector ¶
NewCollector builds a Collector over world: two camera queries (user-spawned primaries first, the engine camera as fallback) and one sprite query — every Drawable kind flows through the same query, because Sprite carries its Drawable as data rather than as component variants. Each is predicate-filtered (Primary; sprites not Hidden). The first primary camera in deterministic query order frames the world; sprites pair with a Transform and a PrevTransform to match.
func (*Collector) Collect ¶
Collect resolves the primary camera, collects every sprite — the Drawable sum picks the path: texture sources resolve through the asset server, shapes carry geometry alone, nil is style without a picture and skips — interpolates positions from PrevTransform by ctx.Alpha, culls against the camera viewport, and sorts by layer → SortOrder → world Y. It returns a DrawList viewing the collector's buffers; do not retain it across frames.
No primary camera: an empty DrawList, no error - overlays still run. An unresolvable texture source - an unregistered atlas or region, or a texture that will not load - fails the collect, naming the handles: registration problems surface at the first rendered frame. Shapes cannot fail: there is nothing to resolve.
type Context ¶
type Context struct {
// World represents the current world instance.
World *World
// Tick counts fixed simulation steps since startup.
Tick uint64
// Frame counts display frames since startup.
Frame uint64
// DeltaTime is the current schedule's step: elapsed frame time in
// PhaseFrame, the fixed tick interval in PhaseFixed.
DeltaTime time.Duration
// Alpha is the fixed-loop remainder over the tick interval, for
// interpolating between the last two ticks. Only a runner sets it,
// when running its draw systems.
Alpha float64
// LogicalWidth is the render target's internal width in pixels.
// Read along with LogicalHeight to determine the render target's
// internal resolution.
LogicalWidth int
// LogicalHeight is the render target's internal height in pixels.
// Read along with LogicalWidth to determine the render target's
// internal resolution.
LogicalHeight int
// Input is the current snapshot of all input devices, published
// by the runner each frame. nil means no runner published input -
// the headless case - and every read on a nil snapshot returns
// zero.
Input *input.Snapshot
// Actions is the game's action map, published by the engine when
// WithBindings configures one. It is the same instance the
// ActionMap resource resolves: mutating through either handle
// affects the one map. Queries on a nil Actions read zero, so
// headless games and systems running without bindings need no
// guards.
Actions *input.ActionMap
}
Context is the state systems run with: the world, the clocks, and the input the engine published this frame. The engine and the runner write these fields; game systems read them. Treat the context as read-only inside systems.
type DrawItem ¶
type DrawItem struct {
// Texture is the texture the sprite's pixels come from: a
// standalone texture's path, or the atlas's texture path. Applies
// when Shape is nil.
Texture asset.ID
// Rect is the region of Texture to draw, in pixels. Empty means
// the whole texture - dimension knowledge lives in the blit.
// Applies when Shape is nil.
Rect image.Rectangle
// Shape is the primitive to draw instead of a texture. nil means
// this item is a texture sprite and Texture and Rect apply. When
// non-nil, Color is the shape's color and is never nil: the
// collector defaults a nil Sprite.Color to black.
Shape Shape
// Position is the interpolated position of the drawable in world
// space.
Position geom.Vector2
// Rotation is the rotation of the drawable in world space, in
// radians.
Rotation float64
// Scale is the scale of the drawable in world space.
Scale geom.Vector2
// FlipH and FlipV mirror the sprite horizontally and vertically.
// Applies when Shape is nil; shapes have no flip.
FlipH, FlipV bool
// Color is the color to multiply the sprite's pixels by, or the
// shape's fill and stroke color; its alpha channel is the
// drawable's opacity. nil means no color on a sprite; shape
// items always carry a concrete color.
Color color.Color
// Outline strokes the shape's border instead of filling it.
// Applies when Shape is non-nil.
Outline bool
// StrokeWidth is the outline's width in world units; the blit
// scales it by zoom. Applies when Shape is non-nil and Outline
// is set.
StrokeWidth float64
}
DrawItem is one resolved drawable, ready to blit: a texture sprite or a shape primitive. The render source is fully resolved at collection - an atlas region became (Texture, Rect) here, and a geometry variant became Shape - so the runner never deals in atlas IDs or component variants. World-space, interpolated; the blit projects to screen.
type DrawList ¶
type DrawList struct {
Camera CameraView
Items []DrawItem
}
DrawList is one collected frame: the resolved camera and the sorted draw items. Items views the collector's reused buffer; do not modify it or retain the list beyond the frame it was collected for.
type Drawable ¶ added in v0.0.2
type Drawable interface {
// contains filtered or unexported methods
}
Drawable is what a Sprite draws: one of the two texture sources or one of the three shapes. It is a sealed sum — the only implementations are in this file — so exactly-one-drawable is a construction guarantee: a sprite cannot declare two pictures, and the collector type-switches one field instead of querying per variant.
type Entity ¶
type Entity struct {
// contains filtered or unexported fields
}
Entity is a lightweight handle to an entity's ID. It exists for spawn-time ergonomics - creation code keeps the handle for a few follow-up calls before dropping down to the ID-keyed world methods. The handle carries no engine state beyond its liveness flag, and liveness here reflects the handle, not the storage: it reports false only after World.DestroyEntity killed this handle. The ID is the source of truth.
func NewEntity ¶
NewEntity creates a handle for the entity with the given ID. Use World.NewEntity to spawn an entity and receive its handle; for an ID already in a world - collected from a query, for example - minting a handle with NewEntity is the way to turn the ID back into a working Entity whose methods perform component operations.
func SpawnEngineCamera ¶ added in v0.0.3
SpawnEngineCamera creates the engine's default primary camera: zoom 1 at the world origin, marked as the engine's. The collector prefers any user-spawned primary camera over it. Game.New spawns it and hands it out through MainCamera; games never spawn it themselves.
func (*Entity) AddComponent ¶
AddComponent attaches a component of type T to the entity, migrating it to the archetype for its new component set. Existing components are preserved.
func (*Entity) Component ¶
Component returns the entity's component of type T. It reports false if the entity does not exist in the world or has no component of that type. The world is passed explicitly: a handle holds no storage, so every component operation goes through the world.
func (*Entity) HasComponent ¶
HasComponent reports whether the entity has a component of type T. A nonexistent entity reports false.
func (*Entity) IsAlive ¶
IsAlive reports whether this handle's entity has not been destroyed through World.DestroyEntity. Storage membership is the authoritative liveness: queries only yield entities that exist.
func (*Entity) Kill ¶
func (e *Entity) Kill()
Kill marks the handle's entity as destroyed. It does not remove the entity from the world; World.DestroyEntity does both.
func (*Entity) RemoveComponent ¶
RemoveComponent detaches the component of type T from the entity, migrating it to the archetype for its remaining components. Removing a component the entity does not have succeeds without effect.
func (*Entity) SetComponent ¶
SetComponent overwrites the entity's component of type T. The entity must already have the component; use AddComponent to attach one. It returns an error if the entity does not exist or has no component of that type.
type EntityID ¶
EntityID identifies an entity. IDs are the durable reference to an entity: query results carry IDs, every world operation accepts one, and an ID remains valid to hold across iterations.
type Entry ¶
type Entry struct {
// contains filtered or unexported fields
}
Entry represents a single entity and its associated component data within a query result. It provides methods to access the entity ID and retrieve component values by type.
By design Entries are not meant to be retained. The component columns a Get reads are the query's shared prefetch scratch, reused for every archetype the iteration visits: a retained entry keeps a stale row index into whichever archetype the iteration is on now, so a later Get reads the wrong data. Keep the ID instead - Entry.ID is a copy, safe to hold and resolve through the world's ID-keyed methods after iteration.
func (Entry) Component ¶
Component retrieves the component value of type T for the entity associated with this entry. It returns the value and a boolean indicating whether the component was found. Only the component types listed in Query.With are available: the prefetch carries those types alone, so any other type reports false even if the entity has the component.
func (Entry) ID ¶
ID returns the unique identifier of the entity associated with this entry. Unlike the entry itself, the ID is safe to retain.
func (Entry) SetComponent ¶
SetComponent overwrites the visited entity's component of type T in place, through the prefetched column. Only the types listed in Query.With are available - the same contract as Entry.Component. Value writes are safe during iteration: they mutate the entity's slot without moving rows. Structural changes (spawning, destroying, adding or removing components) remain invalid during a pass.
type LineShape ¶ added in v0.0.2
LineShape draws a segment between From and To, both relative to the position, scaled by the scale. A zero From anchors the segment at the position itself; either way the whole segment moves rigidly and interpolates for free.
type Phase ¶
type Phase int8
Phase identifies when a system runs.
const ( // PhaseStartup runs once, before the first frame. PhaseStartup Phase = iota // PhaseFrame runs once per display frame, before fixed ticks. // Timers and input consumption belong here. PhaseFrame // PhaseFixed runs at the fixed simulation rate. Movement and // physics belong here. PhaseFixed )
type PrevTransform ¶
PrevTransform is the engine-managed snapshot of an entity's position as it stood at the start of the current fixed tick — the end of the previous tick. Renderers interpolate between PrevTransform and Transform by alpha to display smooth motion between fixed ticks.
The engine's capture system writes it; game code may read it but must never write it.
type Query ¶
type Query struct {
// contains filtered or unexported fields
}
Query selects entities by component types and, optionally, a per-entity predicate. Construct it with NewQuery, configure it with With, Without, and Where, then range over Execute. A Query is reusable across passes: it caches the matching archetypes and re-matches only when the world's structure changes. One Query supports one active iteration at a time.
func NewQuery ¶
NewQuery creates a reusable query against world. Configure it with With, Without, and Where; each Execute reuses the query's cached archetype matches until the world's structure changes.
func (*Query) Execute ¶
Execute runs the query and yields matching entries to the provided iterator function. It reuses the query's cached archetype matches and component columns for efficiency. Only one active iteration is allowed per query at a time; nested iterations require separate queries.
Iteration order is deterministic: matches are sorted by archetype ID, and entities are visited in storage order within an archetype, so two passes over an unchanged world yield the same sequence. Breaking out of the range stops iteration cleanly, and the query can be executed again immediately.
Structural mutation - spawning, destroying, or adding and removing components - during iteration is not supported: it moves rows under the iterator and corrupts the pass. Perform structural changes before iterating or between passes.
func (*Query) Where ¶
Where adds a predicate function that must return true for an entity to match the query. The predicate is evaluated once per entity during iteration and is never cached; it can only Get the types listed in With, like the loop body itself. Prefer a component over a predicate when the condition is stable: structural filters are archetype-granular and free, while predicates pay per entity on every pass.
func (*Query) With ¶
With adds component types that must be present for an entity to match the query. Pass zero values of the component types - the values are markers, only their types are used. A nil or a pointer value panics: both are build-time mistakes, and a pointer would otherwise silently match no component at all.
The listed types are also the only ones Entry.Component can retrieve during iteration: they are prefetched per archetype, which is what makes Get a bare column lookup.
type RectShape ¶ added in v0.0.2
RectShape draws a filled or outlined rectangle of Size world units, centered on the position and scaled by the scale.
type Resources ¶
type Resources struct {
// contains filtered or unexported fields
}
Resources manages the collection of all resources within the world. It keeps track of their registration, resolution state, and the order in which eager resources should be resolved.
type Shape ¶ added in v0.0.2
type Shape interface {
Drawable
// contains filtered or unexported methods
}
Shape is a Drawable that is geometry instead of an image — the sum a DrawItem carries when it resolved from a shape sprite. Sealed: RectShape, CircleShape, and LineShape.
type Sprite ¶
type Sprite struct {
// Layer orders the sprite against every other drawable, 0-31,
// back to front.
Layer uint8
// SortOrder orders within the layer: higher draws on top, with
// the world-Y fallback below that.
SortOrder int8
// Hidden skips collection entirely. false — the zero value —
// means shown.
Hidden bool
// FlipH and FlipV mirror the sprite horizontally and vertically.
// Applies when Drawable is a texture source; shapes have no flip.
FlipH, FlipV bool
// Drawable is what to draw. nil means style without a picture:
// the sprite is legal but not drawn.
Drawable Drawable
// Outline strokes the shape's border instead of filling it.
// Applies when Drawable is a shape; false — the zero value —
// fills, the prototyping default. Outline requires a positive
// StrokeWidth, enforced by Validate.
Outline bool
// StrokeWidth is the outline's width in world units. Applies when
// Drawable is a shape and Outline is set.
StrokeWidth float64
// Color is the color to multiply a texture's pixels by, or a
// shape's fill and stroke color. Its alpha channel is the
// drawable's opacity: a half-alpha color draws half-faded, so
// fading is expressing a color, not a separate field —
// color.NRGBA{R: 255, G: 255, B: 255, A: 128} fades an uncolored
// sprite to half.
//
// nil means no color on a texture source (fully
// opaque); shapes default a nil color to black at collection.
Color color.Color
}
Sprite is the single drawable component: the shared style plus what to draw. The Drawable sum carries the picture — an atlas region or a standalone texture — or a shape: rect, circle, or line. Pair it with a Transform and a PrevTransform and the collector renders it, interpolated, culled, and sorted.
The zero value is the shown, opaque sprite. With a nil Drawable it declares style but no picture and simply does not draw until a Drawable is set. Hide it with Hidden; see through it with Color's alpha; outline shapes with Outline.
type System ¶
System is a unit of game logic. It runs during a specific phase and updates the game state.
func NewPrevTransformCapture ¶
func NewPrevTransformCapture() System
NewPrevTransformCapture returns the engine system that snapshots every entity's Transform position into PrevTransform.
It must run FIRST in the fixed phase — before gameplay systems move anything. The snapshot at tick start is the previous tick's end state; gameplay then advances Transform. The render pair is therefore (previous tick, current tick), which alpha interpolates between. Registering the capture last would snapshot the already-advanced Transform, making prev and curr identical and silently disabling interpolation.
Entities spawned during a tick have no snapshot; the capture materializes their spawn position at the next tick start, so they first render at the beginning of the next tick. Game.New registers this system; games never register it themselves.
type SystemFunc ¶
SystemFunc is an adapter to allow the use of ordinary functions as systems.
func (SystemFunc) Update ¶
func (f SystemFunc) Update(ctx *Context) error
Update calls the system function with the given context.
type TextureSource ¶ added in v0.0.2
TextureSource draws a standalone texture, whole.
type Transform ¶
type Transform struct {
// Position represents the position of the transform in 2D space.
Position geom.Vector2
// Rotation represents the rotation of the transform in radians.
Rotation float64
// Scale represents the scale of the transform in 2D space. A zero
// axis - the zero value - reads as unscaled: collection treats it
// as 1.
Scale geom.Vector2
// Offset represents the offset of the transform relative to its position.
Offset geom.Vector2
}
Transform represents the 2d spatial state of an entity.
type Validatable ¶
type Validatable interface {
// Validate checks that the component's values satisfy its
// constraints.
Validate() error
}
Validatable is the opt-in contract for spawn-time component validation. Implement it on components with value constraints; the engine calls Validate whenever the component enters storage.
type World ¶
type World struct {
*Resources
// contains filtered or unexported fields
}
World represents the game world, containing all entities and resources.
func NewWorld ¶
func NewWorld() *World
NewWorld creates and initializes a new game world with empty resources. It returns a pointer to the newly created World instance.
func (*World) DestroyEntities ¶
DestroyEntities removes all the given entities from the world and kills their handles, stopping at the first error.
func (*World) DestroyEntity ¶
DestroyEntity removes the entity from the world and kills its handle.
func (*World) NewEntities ¶
NewEntities spawns count entities with the same components and returns their handles. It returns an error under the same conditions as NewEntity, without partial results.
func (*World) NewEntity ¶
NewEntity spawns an entity with the given components and returns its handle. The handle is convenience for immediate follow-up calls; the ID is the durable reference, and every component operation accepts it directly. It returns an error if any component is nil or fails its Validate; a failed spawn consumes no ID and leaves no state behind.
func (*World) Provide ¶
Provide registers a new resource with the world using the given constructor function. The resource will be lazily resolved when first requested.
func (*World) ProvideEager ¶
ProvideEager registers a new resource with the world using the given constructor function. The resource will be resolved immediately when ResolveEager is called.
func (*World) ResolveEager ¶
ResolveEager resolves all eager resources registered with the world. It returns an error if any resource fails to resolve.