core

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: Apache-2.0 Imports: 10 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 core provides World-owned entities and resources, Query iteration over components, and the System and Context contracts for updating a game.

Index

Constants

View Source
const PrevTransformSystemName = "engine.prev-transform"

PrevTransformSystemName is the name under which castrum.New registers the previous-transform capture system in the fixed schedule.

Variables

View Source
var ErrResourceNotRegistered = errors.New("resource is not registered")

ErrResourceNotRegistered reports that World.Resource or World.MustResource was called for a type no World.Provide call registered. Distinguish it from resolution failures with errors.Is.

Functions

This section is empty.

Types

type Context

type Context struct {
	// World is the game world.
	World *World
	// Tick counts fixed simulation steps since startup.
	Tick uint64
	// Frame counts display frames since startup.
	Frame uint64
	// DeltaTime is elapsed frame time in [PhaseFrame] or the fixed tick
	// interval in [PhaseFixed].
	DeltaTime time.Duration
	// Alpha is the fixed-loop remainder for interpolation between ticks.
	// A runner sets it when running draw systems.
	Alpha float64
	// LogicalWidth is the render target's internal width in pixels.
	LogicalWidth int
	// LogicalHeight is the render target's internal height in pixels.
	LogicalHeight int
	// Input is the runner's current input snapshot. A nil snapshot reads as
	// no input.
	Input *input.Snapshot
	// Actions is the game's action map when configured with `WithBindings`.
	// It is the same instance as the ActionMap resource; a nil map reads as
	// no actions.
	Actions *input.ActionMap
}

Context gives systems access to the world, simulation clocks, and input published for the current frame. The engine and runner populate it; systems should treat it as read-only.

type Entity

type Entity struct {
	// contains filtered or unexported fields
}

Entity is a handle for addressing a world entity by EntityID. Its liveness flag belongs to the handle and does not reflect whether the ID is present in world storage.

func NewEntity

func NewEntity(id EntityID) *Entity

NewEntity creates a live handle for id. Use World.NewEntity to spawn an entity; use this function to create a handle from an ID obtained elsewhere, such as from a query.

func (*Entity) AddComponent

func (e *Entity) AddComponent[T any](w *World, value T) error

AddComponent attaches a component of type T to the entity. Existing components are preserved. It returns an error if value is a pointer. Adding a Transform also adds an initial PrevTransform if the entity does not already have one.

func (*Entity) Component

func (e *Entity) Component[T any](w *World) (T, bool)

Component returns the entity's component of type T. It reports false if the entity does not exist or has no component of that type.

func (*Entity) HasComponent

func (e *Entity) HasComponent[T any](w *World) bool

HasComponent reports whether the entity has a component of type T. A nonexistent entity reports false.

func (*Entity) ID

func (e *Entity) ID() EntityID

ID returns the entity's identifier.

func (*Entity) IsAlive

func (e *Entity) IsAlive() bool

IsAlive reports whether this handle is alive. It does not check whether the entity still exists in world storage.

func (*Entity) Kill

func (e *Entity) Kill()

Kill marks this handle as dead. It does not remove the entity from the world; use World.DestroyEntity to do both.

func (*Entity) RemoveComponent

func (e *Entity) RemoveComponent[T any](w *World) error

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

func (e *Entity) SetComponent[T any](w *World, value T) error

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 value is a pointer, the entity does not exist, or it has no component of that type.

func (*Entity) Update added in v0.0.4

func (e *Entity) Update[T any](w *World, fn func(*T)) error

Update reads the entity's component of type T, applies fn to the copy, and writes it back. It returns an error if the entity does not exist or has no component of that type; the write validates like SetComponent.

type EntityID

type EntityID = ecs.EntityID

EntityID identifies an entity within a World. IDs are not recycled during a world's lifetime and are safe to retain across query iterations.

type Entry

type Entry struct {
	// contains filtered or unexported fields
}

Entry is a query result for one entity. Its component data is backed by iteration storage and may refer to another row after iteration advances. Retain Entry.ID instead; the ID is safe to keep after the query pass.

func (Entry) Component

func (e Entry) Component[T any]() (T, bool)

Component returns the visited entity's component of type T. It reports false for types not listed in Query.With, even if the entity has them.

func (Entry) ID

func (e Entry) ID() EntityID

ID returns the identifier of the entity associated with this entry.

func (Entry) SetComponent

func (e Entry) SetComponent[T any](value T)

SetComponent overwrites the visited entity's component of type T. Only types listed in Query.With are available; other types cause a panic.

func (Entry) Update added in v0.0.4

func (e Entry) Update[T any](fn func(*T))

Update applies fn to the visited entity's component of type T and writes the result back. Only types listed in Query.With are available; other types cause a panic.

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.
	// Input consumption belongs here.
	PhaseFrame
	// PhaseFixed runs at the fixed simulation rate. Movement,
	// physics, and timers belong here.
	PhaseFixed
)

func (Phase) String

func (s Phase) String() string

String returns the phase's schedule name, or a formatted value for an unknown phase.

type PrevTransform

type PrevTransform struct {
	// Position is the snapshot position.
	Position geom.Vector2
	// Rotation is the snapshot rotation in radians.
	Rotation float64
	// Scale is the snapshot scale, with zero components normalized to 1.
	Scale geom.Vector2
}

PrevTransform stores an entity's transform at the start of a fixed tick. Renderers interpolate between it and Transform to smooth motion between ticks.

Rotation is interpolated as a numeric value, not along the shortest arc.

The capture system updates this component; game code should treat it as read-only. A Transform without a PrevTransform is not rendered.

type Query

type Query struct {
	// contains filtered or unexported fields
}

Query selects entities by component presence and an optional predicate. Configure it with Query.With, Query.Without, and Query.Where, then iterate its results with Query.Execute.

func NewQuery

func NewQuery(world *World) *Query

NewQuery creates a query over world.

func (*Query) Execute

func (q *Query) Execute() iter.Seq[Entry]

Execute yields entries for matching entities in stable order while the world's structure is unchanged. Breaking the range stops the pass, and the query can be executed again immediately.

A query cannot be executed recursively; use a separate query for nested iteration. Do not spawn or destroy entities, or add or remove components, during a pass. Such changes invalidate the iteration. Updating component values through an Entry is allowed.

func (*Query) First

func (q *Query) First() (Entry, bool)

First returns the first entry yielded by the query and whether a match exists.

func (*Query) Where

func (q *Query) Where(predicate func(e Entry) bool) *Query

Where adds a predicate that an entity must satisfy to match. The predicate runs for each candidate on every pass and can access only components listed in Query.With, through Entry.Component. Use Query.With or Query.Without for component-presence filters.

func (*Query) With

func (q *Query) With(components ...any) *Query

With adds component types that an entity must have to match. Pass zero values as type markers; nil and pointer values cause a panic. These are the only types available through Entry.Component, Entry.SetComponent, and Entry.Update during iteration.

func (*Query) Without

func (q *Query) Without(components ...any) *Query

Without adds component types that an entity must not have to match. Pass zero values as type markers; nil and pointer values cause a panic.

type System

type System interface {
	Update(ctx *Context) error
}

System is a unit of game logic that updates state during a schedule phase.

func NewPrevTransformCapture

func NewPrevTransformCapture() System

NewPrevTransformCapture returns the system that updates each existing PrevTransform from its entity's Transform for rendering interpolation.

Run it before systems that change transforms so the snapshot represents the start of the tick. castrum.New registers it first in the fixed phase under PrevTransformSystemName.

type SystemFunc

type SystemFunc func(ctx *Context) error

SystemFunc adapts a function to the System interface.

func (SystemFunc) Update

func (f SystemFunc) Update(ctx *Context) error

Update calls f with ctx.

type Transform

type Transform struct {
	// Position is the entity's position in 2D space.
	Position geom.Vector2
	// Rotation is the entity's rotation in radians.
	Rotation float64
	// Scale is the entity's 2D scale. A zero component is treated as 1.
	Scale geom.Vector2
	// Offset is the transform's position offset.
	Offset geom.Vector2
}

Transform stores an entity's position, rotation, scale, and offset in 2D space.

When World.NewEntity or Entity.AddComponent adds a Transform, the world also adds a PrevTransform if one is not already present.

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 {
	// contains filtered or unexported fields
}

World owns a game's entities, components, and registered resources.

A World is not safe for concurrent use. In a running game, access it from the engine goroutine, including from systems. To do work on another goroutine, copy the needed data and return results to the engine goroutine. The asset loader's loading API is safe to call from other goroutines.

func NewWorld

func NewWorld() *World

NewWorld creates an empty world.

func (*World) DestroyEntities

func (w *World) DestroyEntities(entities []*Entity) error

DestroyEntities removes the given entities and kills their handles, stopping at the first error. Entities removed before an error remain destroyed.

func (*World) DestroyEntity

func (w *World) DestroyEntity(entity *Entity) error

DestroyEntity removes the entity from the world and kills entity's handle.

func (*World) MustResource added in v0.1.0

func (w *World) MustResource[T any]() T

MustResource returns the resource of type T, panicking if it is not registered or cannot be resolved. Use it only for resources guaranteed by engine-owned wiring; use World.Resource when the resource may be absent.

func (*World) NewEntities

func (w *World) NewEntities(count int, components ...any) ([]*Entity, error)

NewEntities creates count entities with the same components and returns their handles. Count must be non-negative. If creation fails, it returns the error and no handles; entities created before the failure remain in the world. Components must be non-nil, non-pointer values.

func (*World) NewEntity

func (w *World) NewEntity(components ...any) (*Entity, error)

NewEntity creates an entity with the given components and returns its handle. It returns an error if a component is nil, a pointer, or fails validation. Adding a Transform also adds its initial PrevTransform unless one is provided.

func (*World) Provide

func (w *World) Provide[T any](ctor func(*World) (T, error)) error

Provide registers a resource constructor. The resource is created on its first World.Resource request.

func (*World) ProvideEager

func (w *World) ProvideEager[T any](ctor func(*World) (T, error)) error

ProvideEager registers a resource constructor for resolution by World.ResolveEager.

func (*World) ResolveEager

func (w *World) ResolveEager() error

ResolveEager resolves resources registered with World.ProvideEager, in registration order. It stops at and returns the first resolution error.

func (*World) Resource

func (w *World) Resource[T any]() (T, error)

Resource returns the registered resource of type T, resolving it on first access. It returns ErrResourceNotRegistered if T is not registered, and the resolution error if the resource's constructor fails.

Jump to

Keyboard shortcuts

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