A referência da API é gerada a partir dos comentários de documentação Go no código-fonte e está escrita em inglês.
package entities
import "github.com/nsgo-dev/game/pkg/entities"Visão geral
Package entities provides a small, zero-reflection entity-component-system (ECS) for NSGo games: generational entities, typed sparse-set components, allocation-free queries, topologically ordered systems, prefabs and JSON world snapshots integrated with game/save.
Architectural Decision (#136)
Three architectures were weighed for representing game objects in github.com/nsgo-dev/game:
- A small, zero-reflection, generational-index ECS with typed sparse-set storage (chosen).
- An object-oriented scene tree of heap-allocated nodes with virtual update methods.
- A reflection-driven archetype ECS with dynamic tables and query planners.
This package chooses (1) for five reasons:
- Predictable, allocation-free hot loops: entities are 64-bit generational handles (32-bit slot index + 32-bit generation) recycled through a free list, and each component type lives in a contiguous typed sparse set. Spawning, destroying, accessing and querying components perform zero heap allocations in steady state and avoid GC pointer chasing.
- Zero reflection: Go generics identify component stores via zero-sized type tags and keep all component access, queries and prefab builders statically typed with no reflect imports.
- Safe handle lifetimes: stale Entity handles are automatically invalidated when a slot is destroyed and recycled, eliminating dangling references without weak pointers or runtime bookkeeping.
- Explicit, deterministic execution: systems declare Before/After ordering constraints resolved once via Kahn's topological sort with registration-order tie-breaking, making frame order inspectable (for debug overlays) and reproducible across runs and platforms.
- Clean serialization boundaries: only component types explicitly registered with RegisterCodec are written into deterministic WorldSnapshot JSON values and persisted through game/save, keeping transient runtime state (such as sprite handles or audio voices) out of save files while preserving entity IDs and cross-entity references.
All methods on World and Scheduler are designed to be called on the engine's goroutine, matching game.Loop and NSGo's core.Scope.
Índice
- Variáveis
- func CodecName[T any](w *World) (string, bool)
- func Each1[A any](w *World, fn func(Entity, *A) bool)
- func Each2[A, B any](w *World, fn func(Entity, *A, *B) bool)
- func Each3[A, B, C any](w *World, fn func(Entity, *A, *B, *C) bool)
- func Get[T any](w *World, e Entity) (*T, bool)
- func Has[T any](w *World, e Entity) bool
- func LoadWorld(store *save.Store, slot string, w *World) error
- func RegisterCodec[T any](w *World, typeName string) error
- func Remove[T any](w *World, e Entity)
- func SaveWorld(store *save.Store, slot string, w *World) error
- func Set[T any](w *World, e Entity, v T)
- type ComponentSnapshot
- type Entity
- type EntitySnapshot
- type Hierarchy2D
- func NewHierarchy2D(w *World) *Hierarchy2D
- func (h *Hierarchy2D) AppendChildren(dst []Entity, e Entity) []Entity
- func (h *Hierarchy2D) ChildCount(e Entity) int
- func (h *Hierarchy2D) Children(e Entity) []Entity
- func (h *Hierarchy2D) DestroyWithPolicy(e Entity, policy RemovePolicy)
- func (h *Hierarchy2D) Detach(child Entity, keepWorld bool)
- func (h *Hierarchy2D) EachChild(e Entity, fn func(Entity) bool)
- func (h *Hierarchy2D) IsDirty(e Entity) bool
- func (h *Hierarchy2D) Local(e Entity) (Transform2D, bool)
- func (h *Hierarchy2D) MarkDirty(e Entity)
- func (h *Hierarchy2D) Parent(e Entity) (Entity, bool)
- func (h *Hierarchy2D) RemovePolicy() RemovePolicy
- func (h *Hierarchy2D) SetLocal(e Entity, t Transform2D)
- func (h *Hierarchy2D) SetParent(child, parent Entity, keepWorld bool) error
- func (h *Hierarchy2D) SetPosition(e Entity, x, y float32)
- func (h *Hierarchy2D) SetRemovePolicy(policy RemovePolicy)
- func (h *Hierarchy2D) SetRotation(e Entity, rotation float32)
- func (h *Hierarchy2D) SetScale(e Entity, sx, sy float32)
- func (h *Hierarchy2D) SetVisible(e Entity, visible bool)
- func (h *Hierarchy2D) Sync() int
- func (h *Hierarchy2D) WorldTransform(e Entity) (WorldTransform2D, bool)
- type Prefab
- type RemovePolicy
- type Scheduler
- type Store
- type SystemOption
- type Transform2D
- type World
- func NewWorld() *World
- func (w *World) Alive(e Entity) bool
- func (w *World) Attach(cx *core.Scope)
- func (w *World) ChildrenOf(e Entity) []Entity
- func (w *World) Clear()
- func (w *World) CodecNames() []string
- func (w *World) Count() int
- func (w *World) DecodeComponent(e Entity, typeName string, raw json.RawMessage) error
- func (w *World) Destroy(e Entity)
- func (w *World) Dispose()
- func (w *World) Disposed() bool
- func (w *World) Each(fn func(Entity) bool)
- func (w *World) EncodeComponent(e Entity, typeName string) (json.RawMessage, bool, error)
- func (w *World) EntityComponents(e Entity) ([]ComponentSnapshot, error)
- func (w *World) HasCodec(e Entity, typeName string) bool
- func (w *World) Hierarchy2D() *Hierarchy2D
- func (w *World) ParentOf(e Entity) (Entity, bool)
- func (w *World) PatchComponent(e Entity, typeName string, raw json.RawMessage) error
- func (w *World) RemoveComponent(e Entity, typeName string) (bool, error)
- func (w *World) Reset()
- func (w *World) Resolve(index, generation uint32) (Entity, bool)
- func (w *World) Restore(snap WorldSnapshot) error
- func (w *World) Snapshot() (WorldSnapshot, error)
- func (w *World) Spawn() Entity
- type WorldSnapshot
- type WorldTransform2D
Variáveis
var (
// ErrCycle reports a SetParent call that would create a cycle in the hierarchy, including parenting an entity to itself.
ErrCycle = errors.New("entities: hierarchy cycle")
// ErrDeadEntity reports a hierarchy operation attempted on Zero or an entity that is not alive in the World.
ErrDeadEntity = errors.New("entities: dead entity")
// ErrNotDecomposable reports a keep-world reparent whose exact relative
// transform contains shear and cannot be stored as a Transform2D.
ErrNotDecomposable = errors.New("entities: relative transform is not decomposable to TRS")
)var (
// ErrEmptySystemName reports a system or ordering constraint with an empty name.
ErrEmptySystemName = errors.New("entities: empty system name")
// ErrDuplicateSystem reports registering a system whose name is already present in the Scheduler.
ErrDuplicateSystem = errors.New("entities: duplicate system name")
// ErrNilSystem reports registering a system with a nil update function.
ErrNilSystem = errors.New("entities: nil system function")
// ErrUnknownSystem reports a Before or After constraint naming a system that was never registered.
ErrUnknownSystem = errors.New("entities: unknown system dependency")
// ErrSystemCycle reports a cycle in the system ordering constraints.
ErrSystemCycle = errors.New("entities: cyclic system dependency")
)var (
// ErrEmptyCodecName reports registering a component codec with an empty type name.
ErrEmptyCodecName = errors.New("entities: empty codec name")
// ErrDuplicateCodec reports registering a codec name or component type that is already registered on the World.
ErrDuplicateCodec = errors.New("entities: duplicate codec registration")
// ErrUnknownCodec reports a snapshot containing a component type that has no registered codec on the target World.
ErrUnknownCodec = errors.New("entities: unknown component codec")
// ErrInvalidSnapshot reports a malformed WorldSnapshot (such as zero generation, duplicate entity index, or out-of-range index).
ErrInvalidSnapshot = errors.New("entities: invalid world snapshot")
)var ErrWorldDisposed = errors.New("entities: world is disposed")ErrWorldDisposed reports an operation attempted on a World that has been disposed.
Funções
func CodecName[T any](w *World) (string, bool)CodecName returns the codec name registered for component type T on w and whether one is registered.
func Each1[A any](w *World, fn func(Entity, *A) bool)Each1 visits every live entity in w carrying component A in deterministic dense order until fn returns false. It performs no reflection and zero heap allocations.
The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or collect entities and add components after Each returns.
func Each2[A, B any](w *World, fn func(Entity, *A, *B) bool)Each2 visits every live entity in w carrying both A and B until fn returns false. It drives iteration from the smaller sparse set and checks membership in the other in O(1) time, with deterministic order, no reflection and zero heap allocations.
A callback may destroy the entity it was handed, but must not add or remove other entities/components of the queried stores.
The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or collect entities and add components after Each returns.
func Each3[A, B, C any](w *World, fn func(Entity, *A, *B, *C) bool)Each3 visits every live entity in w carrying A, B and C until fn returns false. It drives iteration from the smallest of the three sparse sets and checks membership in the other two in O(1) time, with deterministic order, no reflection and zero heap allocations.
The component pointers are valid only during the callback and only until the callback adds a component of a type it is iterating (to any entity): that can grow the store and move its values, so a write through an older pointer would be lost. Read or write through the pointers first, or collect entities and add components after Each returns.
func Get[T any](w *World, e Entity) (*T, bool)Get returns a pointer to entity e's component of type T in w, or (nil, false) if absent or if e is not alive.
func Has[T any](w *World, e Entity) boolHas reports whether live entity e carries component T in w.
func LoadWorld(store *save.Store, slot string, w *World) errorLoadWorld reads slot from store through game/save and atomically restores it into w.
func RegisterCodec[T any](w *World, typeName string) errorRegisterCodec registers a JSON codec for component type T under typeName on w.
Only component types with a registered codec are included in WorldSnapshot output. Registering the same typeName or the same Go type T twice returns ErrDuplicateCodec.
func Remove[T any](w *World, e Entity)Remove detaches component T from entity e in w if present.
func SaveWorld(store *save.Store, slot string, w *World) errorSaveWorld snapshots w and writes it to slot in store through game/save.
func Set[T any](w *World, e Entity, v T)Set attaches or replaces component v on entity e in w. It is a no-op if e is not alive in w. Setting a Transform2D while the World has a Hierarchy2D marks e and its descendants dirty, exactly like Hierarchy2D.SetLocal, so WorldTransform2D never goes stale (#546). Writing through a pointer from Get or a Store still needs Hierarchy2D.MarkDirty.
Tipos
type ComponentSnapshot struct {
Type string `json:"type"`
Data json.RawMessage `json:"data"`
}ComponentSnapshot holds a single JSON-encoded component tagged by its registered codec name.
type Entity uint64Entity is a 64-bit generational handle identifying an entity in a World.
The low 32 bits store the slot index and the high 32 bits store the slot's generation. When an entity is destroyed, its slot is recycled with an incremented generation, so stale handles never alias newly spawned entities.
const Zero Entity = 0Zero is the invalid entity handle. Live entities always have a non-zero generation, so Zero is never alive.
func MakeEntity(index, generation uint32) EntityMakeEntity constructs a generational Entity handle from its 32-bit slot index and generation. It returns Zero when generation is 0.
func (e Entity) Generation() uint32Generation returns the entity's 32-bit generation counter (0 for Zero).
func (e Entity) Index() uint32Index returns the entity's 32-bit slot index.
func (e Entity) IsZero() boolIsZero reports whether e is the invalid Zero handle.
func (e Entity) String() stringString formats e as "Entity(index:generation)" or "Entity(0)" for Zero.
type EntitySnapshot struct {
Index uint32 `json:"index"`
// Parent is the slot index of this entity's hierarchy parent, when the
// snapshot recorded one; it is nil for a root entity.
Parent *uint32 `json:"parent,omitempty"`
Generation uint32 `json:"generation"`
Components []ComponentSnapshot `json:"components,omitempty"`
}EntitySnapshot captures one live entity's generational handle and its serialized components in sorted type-name order.
type Hierarchy2D struct {
// contains filtered or unexported fields
}Hierarchy2D manages parent-child 2D transform relationships, visibility inheritance, and dirty-subtree propagation for a World.
Local transforms are stored in the World's Store[Transform2D] and composed world transforms are cached in Store[WorldTransform2D], allowing ECS queries (Each1/Each2/Each3) to iterate world transforms directly with zero allocations. Parent-child links are maintained in an intrusive, pointer-free slice indexed by Entity.Index(), so steady-state updates, dirty propagation, reparenting, and Sync perform zero heap allocations.
When World.Destroy removes a parent entity directly, Hierarchy2D automatically cleans up its links according to its configured RemovePolicy (default RemoveDetach) so dangling parent/child references never occur.
func NewHierarchy2D(w *World) *Hierarchy2DNewHierarchy2D returns the 2D transform hierarchy bound to w, creating and attaching it on first call. It returns nil if w is nil.
func (h *Hierarchy2D) AppendChildren(dst []Entity, e Entity) []EntityAppendChildren appends e's direct children in deterministic insertion order to dst and returns the extended slice.
func (h *Hierarchy2D) ChildCount(e Entity) intChildCount returns the number of direct children of e (0 if e is dead or has no children).
func (h *Hierarchy2D) Children(e Entity) []EntityChildren returns a newly allocated slice of e's direct children in deterministic insertion order, or nil if e has none. For zero-allocation iteration, use EachChild or AppendChildren.
func (h *Hierarchy2D) DestroyWithPolicy(e Entity, policy RemovePolicy)DestroyWithPolicy destroys e in the World after applying policy to its children:
- RemoveDetach: detaches direct children to root, keeping each child's local Transform2D.
- RemoveDetachKeepWorld: detaches direct children to root while preserving their world transforms.
- RemoveCascade: recursively destroys e and all of its descendants.
In all cases, parent/child links are cleaned up so no dangling handles remain.
func (h *Hierarchy2D) Detach(child Entity, keepWorld bool)Detach removes child from its parent so it becomes a root entity. When keepWorld is true, child's local Transform2D is updated to its composed world transform before detaching. Detaching Zero, a dead entity, or an entity that is already a root is a no-op.
func (h *Hierarchy2D) EachChild(e Entity, fn func(Entity) bool)EachChild calls fn for each direct child of e in deterministic insertion order until fn returns false.
func (h *Hierarchy2D) IsDirty(e Entity) boolIsDirty reports whether e currently needs world-transform recomputation.
func (h *Hierarchy2D) Local(e Entity) (Transform2D, bool)Local returns e's local Transform2D and true, or (zero, false) if e is dead or has no Transform2D.
func (h *Hierarchy2D) MarkDirty(e Entity)MarkDirty marks e and all of its descendants as needing world-transform recomputation. Call MarkDirty after mutating a *Transform2D pointer obtained directly from Store[Transform2D].
func (h *Hierarchy2D) Parent(e Entity) (Entity, bool)Parent returns e's parent entity and true, or (Zero, false) if e is dead, not in the hierarchy, or is a root.
func (h *Hierarchy2D) RemovePolicy() RemovePolicyRemovePolicy returns the default RemovePolicy used when World.Destroy is called directly on a parent entity.
func (h *Hierarchy2D) SetLocal(e Entity, t Transform2D)SetLocal sets e's local Transform2D and marks e and its descendants dirty. It is a no-op if e is not alive.
func (h *Hierarchy2D) SetParent(child, parent Entity, keepWorld bool) errorSetParent attaches child as the last direct child of parent in deterministic insertion order.
If parent is Zero, child is detached to root (equivalent to Detach(child, keepWorld)). SetParent returns ErrWorldDisposed if the World is disposed, ErrDeadEntity if child (or non-Zero parent) is not alive, and ErrCycle if parenting would introduce a cycle (including child == parent). When keepWorld is true, child's local Transform2D is recomputed relative to parent's world transform so child stays at the same world position, rotation, and scale.
func (h *Hierarchy2D) SetPosition(e Entity, x, y float32)SetPosition updates e's local (X, Y) position and marks e and its descendants dirty. If e does not yet have a Transform2D, NewTransform2D(x, y) is attached.
func (h *Hierarchy2D) SetRemovePolicy(policy RemovePolicy)SetRemovePolicy sets the default RemovePolicy used when World.Destroy is called directly on a parent entity.
func (h *Hierarchy2D) SetRotation(e Entity, rotation float32)SetRotation updates e's local rotation in radians and marks e and its descendants dirty. If e does not yet have a Transform2D, IdentityTransform2D with the given rotation is attached.
func (h *Hierarchy2D) SetScale(e Entity, sx, sy float32)SetScale updates e's local (ScaleX, ScaleY) and marks e and its descendants dirty. If e does not yet have a Transform2D, IdentityTransform2D with the given scale is attached.
func (h *Hierarchy2D) SetVisible(e Entity, visible bool)SetVisible updates e's local visibility and marks e and its descendants dirty. If e does not yet have a Transform2D, IdentityTransform2D with the given visibility is attached.
func (h *Hierarchy2D) Sync() intSync updates WorldTransform2D for all dirty subtrees in topological parent-before-child order, skipping clean nodes completely. It returns the number of entities whose WorldTransform2D was recomputed and performs zero heap allocations in steady state.
func (h *Hierarchy2D) WorldTransform(e Entity) (WorldTransform2D, bool)WorldTransform returns e's up-to-date WorldTransform2D and true, resolving e's dirty ancestor chain lazily on demand if needed. It returns (zero, false) if e is dead or has no Transform2D and is not part of the hierarchy.
type Prefab struct {
// contains filtered or unexported fields
}Prefab is a named entity template that attaches a preset list of components to each entity it spawns.
Value components added with With are copied per entity, while reference-containing components (slices, maps, pointers) added with WithFunc invoke their constructor per spawn so entities never share mutable state.
func NewPrefab(name string) *PrefabNewPrefab returns an empty Prefab with the given name.
func With[T any](p *Prefab, v T) *PrefabWith attaches a value component template v of type T to p and returns p. If T is already present on p, its builder is replaced. For components containing slices, maps or pointers, prefer WithFunc so each spawned entity receives an independent copy.
func WithFunc[T any](p *Prefab, make func() T) *PrefabWithFunc attaches a constructor-backed component template of type T to p and returns p. make is invoked once per spawned entity so slices, maps and pointers are never shared across entities. If make is nil, the zero value of T is used.
func (p *Prefab) Clone(name string) *PrefabClone returns a new Prefab named name with a shallow copy of p's component builders, allowing derived prefabs to override or add components without mutating p.
func (p *Prefab) Spawn(w *World) EntitySpawn creates a new entity in w and applies all of p's component builders to it.
func (p *Prefab) SpawnN(w *World, n int) []EntitySpawnN spawns n independent entities from p in w and returns their handles. It returns nil when n <= 0 or w is nil.
type RemovePolicy uint8RemovePolicy controls what happens to direct children when a parent entity is destroyed.
const (
// RemoveDetach detaches direct children to root before destroying the parent, keeping each child's local Transform2D.
// This is the default policy applied when World.Destroy removes a parent directly.
RemoveDetach RemovePolicy = iota
// RemoveDetachKeepWorld detaches direct children to root before destroying the parent, updating each child's local Transform2D to preserve its composed world transform.
RemoveDetachKeepWorld
// RemoveCascade recursively destroys the entity and all of its descendants.
RemoveCascade
)type Scheduler struct {
// contains filtered or unexported fields
}Scheduler runs named systems over a World in a deterministic topological order derived from Before and After constraints.
Ties between unconstrained systems are broken by registration order. The zero value of Scheduler is ready to use.
func (s *Scheduler) AddSystem(name string, fn func(w *World, dt time.Duration), opts ...SystemOption) errorAddSystem registers a named system with optional Before/After constraints.
Constraint targets may be registered later; missing targets and dependency cycles are reported by Build and Step. Immediate errors (empty name, duplicate name, nil function, empty target, or self-dependency) are returned right away without modifying s.
func (s *Scheduler) Build() errorBuild validates all Before/After constraints and resolves the deterministic execution order using Kahn's algorithm with registration-order tie-breaking.
func (s *Scheduler) Order() []stringOrder returns the resolved system names in execution order. It resolves the schedule lazily if needed and returns nil if the schedule is empty or invalid.
func (s *Scheduler) Step(w *World, dt time.Duration) errorStep resolves the schedule if needed and runs every system on w with dt in exact resolved order. Once built, Step performs zero heap allocations of its own.
func (s *Scheduler) String() stringString formats the resolved system order as "a -> b -> c" for debug overlays and logs.
type Store[T any] struct {
// contains filtered or unexported fields
}Store holds all instances of component type T in a World using a typed sparse set.
Dense arrays (dense and values) keep components tightly packed for cache-friendly, zero-allocation iteration, while sparse maps entity slot indices to dense indices in O(1) time.
func Component[T any](w *World) *Store[T]Component returns the typed component Store for T in w, creating it if it does not yet exist.
func (s *Store[T]) Each(fn func(Entity, *T) bool)Each calls fn for every entity carrying T in deterministic dense order until fn returns false. Each visits every entity carrying T in dense (insertion) order until fn returns false.
A callback may destroy the entity it was handed, but not add or remove other entities/components of this store: a removal elsewhere swaps the last entry into the removed slot, which can skip or revisit an entity. When the callback needs to touch other entities of the same store, collect them during Each and act after it returns. The *T is valid only until the callback adds a component to this store, which can grow it and move its values (#546).
func (s *Store[T]) Get(e Entity) (*T, bool)Get returns a pointer to e's component value and true, or (nil, false) if e is not alive or lacks T. The returned pointer remains valid until components are added or removed from this store.
func (s *Store[T]) Has(e Entity) boolHas reports whether live entity e currently carries component T.
func (s *Store[T]) Len() intLen returns the number of entities that currently carry component T.
func (s *Store[T]) Remove(e Entity)Remove detaches component T from e if present. It is a no-op if e is stale or lacks T.
func (s *Store[T]) Set(e Entity, v T)Set attaches or replaces component v on e. It is a no-op if e is not alive in the store's World.
type SystemOption func(*systemEntry)SystemOption declares an ordering constraint on a system added to a Scheduler.
func After(other string) SystemOptionAfter constrains the system to run after the system named other.
func Before(other string) SystemOptionBefore constrains the system to run before the system named other.
type Transform2D struct {
X float32 `json:"x"`
Y float32 `json:"y"`
Rotation float32 `json:"rotation,omitempty"`
ScaleX float32 `json:"scaleX"`
ScaleY float32 `json:"scaleY"`
Hidden bool `json:"hidden,omitempty"`
}Transform2D is an entity's local 2D transform relative to its parent (or to world space when the entity is a root).
The zero value of Transform2D is visible (Hidden == false) with ScaleX == 0 and ScaleY == 0 (collapsed scale), matching game/sprite.Sprite. Use IdentityTransform2D or NewTransform2D to construct a visible transform with unit scale (1, 1).
func IdentityTransform2D() Transform2DIdentityTransform2D returns a visible Transform2D at (0, 0) with zero rotation and unit scale (1, 1).
func NewTransform2D(x, y float32) Transform2DNewTransform2D returns a visible Transform2D at (x, y) with zero rotation and unit scale (1, 1).
func (t Transform2D) Matrix() [6]float32Matrix returns the local 2D affine matrix [a, b, c, d, tx, ty] mapping local points to parent space:
px = a*lx + c*ly + tx py = b*lx + d*ly + ty
The layout matches nsgo/core.Drawing.Transform and game/sprite.
func (t *Transform2D) SetVisible(visible bool)SetVisible sets whether this local transform is visible.
func (t Transform2D) Visible() boolVisible reports whether this local transform is visible (!t.Hidden).
type World struct {
// contains filtered or unexported fields
}World owns entities, their typed component stores, and registered serialization codecs.
The zero value of World is ready to use; NewWorld returns a freshly allocated one.
func NewWorld() *WorldNewWorld returns an empty World ready for spawning entities and attaching components.
func (w *World) Alive(e Entity) boolAlive reports whether e refers to a currently live entity in w.
func (w *World) Attach(cx *core.Scope)Attach binds w's lifetime to cx so w.Dispose runs automatically when cx is disposed.
func (w *World) ChildrenOf(e Entity) []EntityChildrenOf returns e's direct children in w's Hierarchy2D without creating a hierarchy when none is attached.
func (w *World) Clear()Clear removes all live entities and their components while preserving slot generations, allocated capacities and registered codecs for zero-allocation reuse. All entity handles issued before Clear become stale.
func (w *World) CodecNames() []stringCodecNames returns the component codec names registered on w in ascending order.
func (w *World) Count() intCount returns the number of live entities in w.
func (w *World) DecodeComponent(e Entity, typeName string, raw json.RawMessage) errorDecodeComponent strictly decodes raw JSON into the codec-registered component named typeName and attaches or replaces it on live entity e. Unknown JSON fields, trailing data, invalid nulls for non-nullable component types and values the codec cannot encode back, such as a NaN, are rejected without mutating e.
func (w *World) Destroy(e Entity)Destroy removes e and all of its components from w and returns its slot to the free list with an incremented generation. Destroying Zero or an entity that is not alive in w is a no-op.
func (w *World) Dispose()Dispose releases all entities and component storage in w and marks w as disposed. Calling Dispose more than once is a no-op.
func (w *World) Disposed() boolDisposed reports whether w has been disposed.
func (w *World) Each(fn func(Entity) bool)Each calls fn for every live entity in w in ascending slot-index order until fn returns false. Entities spawned during iteration are not visited.
func (w *World) EncodeComponent(e Entity, typeName string) (json.RawMessage, bool, error)EncodeComponent encodes the codec-registered component named typeName on live entity e as JSON. It returns (nil, false, nil) when e is not alive, typeName is not registered, or e does not carry the component.
func (w *World) EntityComponents(e Entity) ([]ComponentSnapshot, error)EntityComponents encodes all codec-registered components carried by live entity e in ascending codec-name order.
func (w *World) HasCodec(e Entity, typeName string) boolHasCodec reports whether live entity e currently carries the codec-registered component named typeName.
func (w *World) Hierarchy2D() *Hierarchy2DHierarchy2D returns the World's 2D transform hierarchy, creating and attaching it on first call.
func (w *World) ParentOf(e Entity) (Entity, bool)ParentOf returns e's parent entity in w's Hierarchy2D without creating a hierarchy when none is attached.
func (w *World) PatchComponent(e Entity, typeName string, raw json.RawMessage) errorPatchComponent strictly decodes raw JSON onto live entity e's existing codec-registered component (or its zero value when absent) and writes the result back atomically. Fields the patch does not change keep their current values, including unexported fields, fields tagged `json:"-"` and the identity of pointers, maps and slices. Unknown JSON fields, trailing data and values the codec cannot encode back, such as a NaN, are rejected without mutating e.
func (w *World) RemoveComponent(e Entity, typeName string) (bool, error)RemoveComponent detaches the codec-registered component named typeName from live entity e and reports whether it was present.
func (w *World) Reset()Reset removes all entities and releases entity and component backing storage while keeping registered codecs intact.
func (w *World) Resolve(index, generation uint32) (Entity, bool)Resolve reconstructs the entity handle for (index, generation) and reports whether it is currently live in w.
func (w *World) Restore(snap WorldSnapshot) errorRestore atomically replaces w's entities and components with snap using w's registered codecs.
Entity indices and generations are preserved verbatim so cross-entity references stored inside components remain valid. If decoding fails (for example due to an unknown codec or invalid JSON), w is left completely unchanged.
An error about the snapshot's contents is a *loaderr.Error that names the field at fault, such as "entities[2].parent", and how to fix it, and matches ErrInvalidSnapshot or ErrUnknownCodec with errors.Is.
func (w *World) Snapshot() (WorldSnapshot, error)Snapshot encodes all live entities and their codec-registered components into a deterministic WorldSnapshot. Entities are emitted in ascending slot-index order and each entity's components in ascending codec-name order.
func (w *World) Spawn() EntitySpawn creates a new live entity, recycling a previously destroyed slot when available. It returns Zero if w has been disposed.
type WorldSnapshot struct {
Entities []EntitySnapshot `json:"entities"`
}WorldSnapshot is a deterministic, JSON-serializable snapshot of a World's live entities and registered components.
type WorldTransform2D struct {
X float32
Y float32
Rotation float32
ScaleX float32
ScaleY float32
Matrix [6]float32
WorldVisible bool
}WorldTransform2D is the cached world-space 2D transform composed from an entity's ancestor chain.
Matrix holds the exact 2D affine transform [a, b, c, d, tx, ty] mapping local coordinates to world space. X, Y, Rotation, ScaleX and ScaleY hold the decomposed world position, orientation (radians), and axis scales. WorldVisible is true only when this entity and every ancestor are visible.
func (wt WorldTransform2D) InverseTransformPoint(wx, wy float32) (lx, ly float32)InverseTransformPoint maps a point (wx, wy) in world space back into this entity's local space. If Matrix is singular (zero determinant), it returns (0, 0).
func (wt WorldTransform2D) TransformPoint(lx, ly float32) (wx, wy float32)TransformPoint maps a point (lx, ly) in this entity's local space into world space.