byke

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2025 License: MIT Imports: 17 Imported by: 0

README

byke

byke is an Entity Component System (ECS) library for Go, inspired by the Bevy API.

Although still under development, it already includes a wide range of features. Documentation and examples will improve in the near feature.

With a background in Bevy, you'll find Byke straightforward. The App type is the main entry point - just add plugins, resources, and systems.

func main() {
   var app App

   app.AddPlugin(GamePlugin)
   app.AddSystems(Startup, spawnCamera, spawnWorld)
   app.AddSystems(Update, Systems(moveObjectsSystem, otherSystem).Chain())
   app.MustRun()
}

Components are defined by embedding the zero-sized Component[T] type. System parameters, such as resources, Local or Query, are automatically injected. Use Query[T] for data retrieval. Byke offers standard query filters such as With, Without, Changed, and more.

type Velocity struct {
   Component[Velocity]
   Linear Vec
}

func moveObjectsSystem(vt VirtualTime, query Query[struct {
   Velocity  Velocity
   Transform *Transform
}]) {
   for item := range query.Items() {
      item.Transform.Translation = item.Transform.Translation.
         Add(item.Velocity.Linear.Mul(vt.DeltaSecs))
   }
}
Core Features
  • Schedules and SystemSets: Organize systems and define execution order.

    • Local[T] local state for systems
    • In[T] to pass a value when invoking a system
  • Resources: Inject shared data into systems.

  • Queries: Supports filters like With, Without, Added, and Changed. Also supports Option[T] and OptionMut[T]. Automatic mapping to struct types.

  • Events: Use EventWriter[E] and EventReader[E] to send and receive events.

  • Observers: Support bevy style (Entity-)Observers

  • States: Manage application state with State[S] and NextState[S].

    • Supports OnEnter(state) and OnExit(state) schedules.
    • Emits StateTransitionEvent[S] during transitions.
    • Allows state-scoped entities via DespawnOnExitState(TitleScreen).
  • Commands: Spawn/despawn entities, trigger observers and add/remove components.

  • Change detection: Components marked as Comparable support automatic change detection.

  • Type Safety: Avoids the need for type assertions like value.(MyType).

  • Entity Hierarchies: Support for parent-child relationships between entities.

  • Fixed Timestep: Execute game logic or physics systems with a fixed timestep interval.

Ebitengine Integration

The bykebiten package provides integration with Ebitengine:

  • Initializes and manages the game loop
  • Configures window settings, screen size, and input
  • Applies transforms through entity hierarchy
  • Manages rendering with z-order, anchors, and sizes
  • Sprites, also supports sprite sheets
  • Text rendering with custom fonts
  • Handles vectors with filled and stroked paths
  • Supports meshes: circles, rectangles, and triangulated polygons
  • Shaders for sprites and meshes with uniforms and image inputs
  • Multi-camera functionality
  • Custom render targets via *ebiten.Image
  • Asset loading:
    • AssetLoader support
    • Tracks asset loads
    • Custom fs.FS: embedded, http, local support
  • Audio playback with looping and despawning
  • Spatial audio (see astroids example)
Example

Check out the examples for a look at how everything comes together.


Note: This README and some documentation was refined using generative AI, but all code in this project is handwritten.

Documentation

Index

Constants

View Source
const NoEntityId = EntityId(0)

Variables

View Source
var (
	// Main is the main schedule that executes all other schedules in the correct order.
	Main             = MakeScheduleId("Main")
	RunFixedMainLoop = MakeScheduleId("RunFixedMainLoop")

	// FixedMain is the fixed time step main schedule that
	// executes the other fixed step schedules in the correct order.
	FixedMain = MakeScheduleId("FixedMain")

	PreStartup      = MakeScheduleId("PreStartup")
	Startup         = MakeScheduleId("Startup")
	PostStartup     = MakeScheduleId("PostStartup")
	First           = MakeScheduleId("First")
	PreUpdate       = MakeScheduleId("PreUpdate")
	StateTransition = MakeScheduleId("StateTransition")
	Update          = MakeScheduleId("Update")
	PostUpdate      = MakeScheduleId("PostUpdate")
	PreRender       = MakeScheduleId("PreRender")
	Render          = MakeScheduleId("Render")
	PostRender      = MakeScheduleId("PostRender")
	Last            = MakeScheduleId("Last")

	FixedFirst      = MakeScheduleId("FixedFirst")
	FixedPreUpdate  = MakeScheduleId("FixedPreUpdate")
	FixedUpdate     = MakeScheduleId("FixedUpdate")
	FixedPostUpdate = MakeScheduleId("FixedPostUpdate")
	FixedLast       = MakeScheduleId("FixedLast")
)
View Source
var ErrSkipSystem = errors.New("skip system")

Functions

func DespawnOnEnterState

func DespawnOnEnterState[S comparable](state S) despawnOnEnterStateComponent[S]

func DespawnOnExitState

func DespawnOnExitState[S comparable](state S) despawnOnExitStateComponent[S]

func EventType

func EventType[E any]() eventType

func ResourceExists

func ResourceExists[T any](res ResOption[T]) bool

ResourceExists is a system predicate that can be passed to Systems.RunIf to only run a system if a given resource does exist in the world. Use it as a reference:

app.AddSystems(Update, System(doSomething).RunIf(ResourceExists[MyResource]))

func ResourceMissing

func ResourceMissing[T any](res ResOption[T]) bool

ResourceMissing is a system predicate thtat can be passed to Systems.RunIf to only run a system if a given resource does not exist in the world. Use it as a reference:

app.AddSystems(Update, System(doSomething).RunIf(ResourceMissing[MyResource]))

func ResourceOf

func ResourceOf[T any](w *World) (*T, bool)

ResourceOf is a typed version of World.Resource.

func ValidateComponent

func ValidateComponent[C IsComponent[C]]() struct{}

ValidateComponent should be called to verify that the IsComponent interface is correctly implemented.

type Position struct {
   Component[Position]
   X, Y float64
}

var _ = ValidateComponent[Position]()

This identifies mistakes in the type passed to Component during compile time.

Types

type Added

type Added[C IsComponent[C]] = query.Added[C]

Added is a query filter that constraints the entities matched to include only entities that have added a component of type C since the last tick that the system owning the Query ran.

type AnyPtr

type AnyPtr = any

type AnySystem

type AnySystem any

AnySystem can be anything that can be coerced into a system.

func InState

func InState[S comparable](expectedState S) AnySystem

InState is a system predicate that can be passed to Systems.RunIf to only run a system if a given state has the expected value.

app.AddSystems(Update, System(doSomething).RunIf(InState(MenuStateTitle)))

func NotInState

func NotInState[S comparable](stateValue S) AnySystem

NotInState is a system predicate that can be passed to Systems.RunIf to only run a system if a given state does not have a specific value.

app.AddSystems(Update, System(doSomething).RunIf(NotInState(MenuStateTitle)))

func TimerJustFinished

func TimerJustFinished(timer Timer) AnySystem

TimerJustFinished is a system predicate that can be passed to Systems.RunIf to only run a system if the provided timer has just finished.

type App

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

App provides an entry point to your application.

func (*App) AddEvent

func (a *App) AddEvent(newEvent eventType)

AddEvent configures a new event in the World. Use EventType to acquire a value implementing eventType.

func (*App) AddPlugin

func (a *App) AddPlugin(plugin Plugin)

AddPlugin adds the given Plugin to this app.

func (*App) AddSystems

func (a *App) AddSystems(scheduleId ScheduleId, system AnySystem, systems ...AnySystem)

AddSystems adds one or more systems to the World.

func (*App) ConfigureSystemSets

func (a *App) ConfigureSystemSets(scheduleId ScheduleId, sets ...*SystemSet)

ConfigureSystemSets configures sets in a schedule.

func (*App) InitState

func (a *App) InitState(newState stateType)

InitState configures a new state in the World. Use StateType to acquire a value implementing stateType.

func (*App) InsertResource

func (a *App) InsertResource(res any)

InsertResource inserts a resource into the World. See World.InsertResource.

func (*App) MustRun

func (a *App) MustRun()

MustRun calls Run and panics if Run returns an error.

func (*App) Run

func (a *App) Run() error

Run will run the Runner configured in Runner.

func (*App) RunWorld

func (a *App) RunWorld(run Runner)

RunWorld configures the function that is executed in Run. This is normally used by plugins to do custom setup like creating a new window and setting up the renderer.

If not called, Run will simply run the Main schedule in a loop.

func (*App) World

func (a *App) World() *World

World returns the world created by the App.

type Changed

Changed is a query filter that constraints the entities matched to include only entities that have a changed Component value of type C since the last tick that the system owning the Query ran.

Change detection currently works by hashing the component value. As such, matching for changed component values is not 100% foolproof in case of hash collisions.

type ChildOf

type ChildOf struct {
	ImmutableComponent[ChildOf]
	Relationship[Children]
	Parent EntityId
}

func (ChildOf) RelationshipEntityId

func (c ChildOf) RelationshipEntityId() EntityId

type Command

type Command interface {
	Apply(world *World)
}

type CommandFn

type CommandFn func(world *World)

func (CommandFn) Apply

func (c CommandFn) Apply(world *World)

type Commands

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

Commands is a SystemParam that allows you to send commands to a world. It allows you to spawn and despawn entities and to add and remove components. It must be injected as a pointer into a system.

func (*Commands) Entity

func (c *Commands) Entity(entityId EntityId) EntityCommands

func (*Commands) InsertResource

func (c *Commands) InsertResource(resource any) *Commands

func (*Commands) Queue

func (c *Commands) Queue(command Command) *Commands

func (*Commands) RunSystem

func (c *Commands) RunSystem(system AnySystem) *Commands

func (*Commands) RunSystemWith

func (c *Commands) RunSystemWith(system AnySystem, inValue any) *Commands

func (*Commands) Spawn

func (c *Commands) Spawn(components ...ErasedComponent) EntityCommands

func (*Commands) Trigger

func (c *Commands) Trigger(eventValue any) *Commands

type ComparableComponent

type ComparableComponent[T IsComparableComponent[T]] = spoke.ComparableComponent[T]

ComparableComponent is a zero sized type that may be embedded into a struct to turn that struct into a comparable component (see IsComponent).

type Component

type Component[T IsComponent[T]] = spoke.Component[T]

Component is a zero sized type that may be embedded into a struct to turn that struct into a component (see IsComponent).

type EntityCommand

type EntityCommand interface {
	Apply(world *World, entityId EntityId)
}

func InsertComponent

func InsertComponent[C IsComponent[C]](optionalValue ...C) EntityCommand

func RemoveComponent

func RemoveComponent[C IsComponent[C]]() EntityCommand

type EntityCommands

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

func (EntityCommands) Despawn

func (e EntityCommands) Despawn()

func (EntityCommands) Id

func (e EntityCommands) Id() EntityId

func (EntityCommands) Insert

func (e EntityCommands) Insert(components ...ErasedComponent) EntityCommands

func (EntityCommands) Observe

func (e EntityCommands) Observe(system AnySystem) EntityCommands

func (EntityCommands) Trigger

func (e EntityCommands) Trigger(eventValue any) EntityCommands

func (EntityCommands) Update

func (e EntityCommands) Update(commands ...EntityCommand) EntityCommands

type EntityId

type EntityId = spoke.EntityId

EntityId uniquely identifies an entity in a World.

type ErasedComponent

type ErasedComponent = spoke.ErasedComponent

ErasedComponent indicates a type erased Component value.

Values given to the consumer of byke of this type are usually pointers, even though the interface is actually implemented directly on the component type.

func BundleOf

func BundleOf(components ...ErasedComponent) ErasedComponent

func SpawnChild

func SpawnChild(components ...ErasedComponent) ErasedComponent

type EventId

type EventId int

type EventReader

type EventReader[E any] struct {
	// contains filtered or unexported fields
}

func (*EventReader[E]) Read

func (r *EventReader[E]) Read() []E

type EventWithId

type EventWithId[E any] struct {
	Id    EventId
	Event E
}

type EventWriter

type EventWriter[E any] struct {
	// contains filtered or unexported fields
}

func (*EventWriter[E]) Write

func (w *EventWriter[E]) Write(event E)

type Events

type Events[E any] struct {
	// contains filtered or unexported fields
}

func (*Events[E]) AppendTo

func (e *Events[E]) AppendTo(target []EventWithId[E]) []EventWithId[E]

func (*Events[E]) Reader

func (e *Events[E]) Reader() *EventReader[E]

func (*Events[E]) Send

func (e *Events[E]) Send(event E)

func (*Events[E]) Update

func (e *Events[E]) Update()

func (*Events[E]) Writer

func (e *Events[E]) Writer() *EventWriter[E]

type FixedTime

type FixedTime struct {
	Elapsed   time.Duration
	Delta     time.Duration
	DeltaSecs float64

	StepInterval time.Duration
	// contains filtered or unexported fields
}

FixedTime should be used in fixed step systems to measure the progression of time.

FixedTime will be updated using the value delta provided by VirtualTime, which might be scaled. In this case, time might accumulate more slowly and FixedTime steps will also be executed less often. To counteract this, you can decrement the StepInterval to executed fixed time step systems more often.

The default value of StepInterval is taken from bevy and is 1/64s.

type Has

type Has[C IsComponent[C]] = query.Has[C]

Has is a query parameter that does not fetch the actual Component value of type T, but rather just indicates if a component of such type exists on the type. Currently it does not provide a performance boost over using an Option.

type ImmutableComponent

type ImmutableComponent[T spoke.IsImmutableComponent[T]] = spoke.ImmutableComponent[T]

ImmutableComponent is a zero sized type that may be embedded into a struct to turn that struct into an immutable component (see IsComponent).

type In

type In[T any] struct {
	Value T
}

In describes an input parameter of a system. A system can only accept exactly one input parameter.

type IsComparableComponent

type IsComparableComponent[T IsComponent[T]] = spoke.IsComparableComponent[T]

IsComparableComponent indicates that a component is comparable. Only comparable components and immutable components can be used with the Changed query filter. At the time of writing, comparable components have a performance overhead when queried by pointer.

To implement the IsComparableComponent interface for a type, you must embed the ComparableComponent type.

type IsComponent

type IsComponent[T any] = spoke.IsComponent[T]

IsComponent can be used in a type parameter to ensure that type T is a Component type.

To implement the IsComponent interface for a type, you must embed the Component type.

type IsImmutableComponent

type IsImmutableComponent[T IsComponent[T]] = spoke.IsImmutableComponent[T]

IsImmutableComponent indicates that a component is immutable and can not be queried using pointer access. Immutable components can be updated by inserting a new copy of the same component into an entity using Command.

To implement the IsImmutableComponent interface for a type, you must embed the ImmutableComponent type.

type IsRelationshipComponent

type IsRelationshipComponent[T IsImmutableComponent[T]] interface {
	IsImmutableComponent[T]
	// contains filtered or unexported methods
}

type IsRelationshipTargetComponent

type IsRelationshipTargetComponent[T IsImmutableComponent[T]] interface {
	IsImmutableComponent[T]
	// contains filtered or unexported methods
}

type Local

type Local[T any] struct {
	Value T
	// contains filtered or unexported fields
}

Local is a SystemParam that provides a value local to a system. It must be injected as a pointer value.

A system can have multiple independent Local parameters even with the same type T.

type Name

type Name struct {
	spoke.ImmutableComponent[Name]
	Name string
}

Name assigns a non unique name to an entity. Adding a name can be helpful for debugging.

func Named

func Named(name string) Name

Named creates a new Name component.

func (Name) String

func (n Name) String() string

type NextState

type NextState[S comparable] struct {
	// contains filtered or unexported fields
}

func (*NextState[S]) Clear

func (n *NextState[S]) Clear()

func (*NextState[S]) Set

func (n *NextState[S]) Set(nextState S)

type Observer

type Observer struct {
	Component[Observer]
	// contains filtered or unexported fields
}

func NewObserver

func NewObserver(fn any) Observer

func (Observer) IsScoped

func (o Observer) IsScoped() bool

func (Observer) Observes

func (o Observer) Observes(id EntityId) bool

func (Observer) ObservesType

func (o Observer) ObservesType(ty reflect.Type) bool

func (Observer) WatchEntity

func (o Observer) WatchEntity(entityId EntityId) Observer

type On

type On[E any] struct {
	Target EntityId
	Event  E
}

type Option

type Option[C IsComponent[C]] = query.Option[C]

Option is a query parameter that fetches a given Component of type T if it exists on an entity.

type OptionMut

type OptionMut[C IsComponent[C]] = query.OptionMut[C]

OptionMut is a query parameter that fetches for a pointer to a Component of type T if it exists on an entity.

type Or

type Or[A, B query.Filter] = query.Or[A, B]

Or is a query filter that allows you to combine two query filters with a local 'or'. Simply adding multiple filters to a query requires all filters to match. Using Or you can build a query, where just one of multiple filter need to match

type OrStruct

type OrStruct[S any] = query.OrStruct[S]

OrStruct combines a struct of multiple filters with a logical Or. The type parameter S must be a struct type that contains only fields of type EmbeddableFilter named with an underscore.

type Plugin

type Plugin func(app *App)

Plugin for an App. Call App.AddPlugin to add a Plugin to an App.

type Query

type Query[T any] struct {
	// contains filtered or unexported fields
}

func (*Query[T]) AppendTo

func (q *Query[T]) AppendTo(values []T) []T

func (*Query[T]) Count

func (q *Query[T]) Count() int

func (*Query[T]) Get

func (q *Query[T]) Get(entityId EntityId) (T, bool)

func (*Query[T]) Items

func (q *Query[T]) Items() iter.Seq[T]

func (*Query[T]) MustFirst

func (q *Query[T]) MustFirst() T

func (*Query[T]) Single

func (q *Query[T]) Single() (T, bool)

type Relationship

type Relationship[Parent IsImmutableComponent[Parent]] struct{}

Relationship must be embedded on the client side of a relationship

func (Relationship[Parent]) RelationshipTargetType

func (Relationship[Parent]) RelationshipTargetType() *spoke.ComponentType

type RelationshipTarget

type RelationshipTarget[Child IsImmutableComponent[Child]] struct {
	// contains filtered or unexported fields
}

RelationshipTarget must be embedded on the parent side of a relationship

func (*RelationshipTarget[Child]) Children

func (p *RelationshipTarget[Child]) Children() []EntityId

Children returns the children in this component. You **must not** modify the returned slice.

func (*RelationshipTarget[Child]) RelationshipType

func (*RelationshipTarget[Child]) RelationshipType() *spoke.ComponentType

type RemovedComponents

type RemovedComponents[C IsComponent[C]] struct {
	// contains filtered or unexported fields
}

func (RemovedComponents[C]) Read

func (c RemovedComponents[C]) Read() iter.Seq[EntityId]

type Res

type Res[T any] struct {
	Value T
	// contains filtered or unexported fields
}

Res provides a SystemParam to inject a resource at runtime.

This is currently the same as just declaring the resource type directly as a parameter. In the future, the Res type may offer additional information, such as resource change tracking.

type ResOption

type ResOption[T any] struct {
	Value *T
	// contains filtered or unexported fields
}

ResOption allows to inject a resource as a system param if it exists in the world. If the resource does not exist, the system will still run but a zero ResOption is injected.

type Runner

type Runner func(world *World) error

type ScheduleId

type ScheduleId interface {
	fmt.Stringer
	// contains filtered or unexported methods
}

ScheduleId identifies a schedule. All implementing types must be comparable.

func MakeScheduleId

func MakeScheduleId(name string) ScheduleId

MakeScheduleId creates a new unique ScheduleId. The name passed to the schedule is used for debugging

func OnEnter

func OnEnter[S comparable](stateValue S) ScheduleId

func OnExit

func OnExit[S comparable](stateValue S) ScheduleId

func OnTransition

func OnTransition[S comparable](previousStateValue, currentStateValue S) ScheduleId

type Single

type Single[T any] struct {
	Value T
}

type State

type State[S comparable] struct {
	// contains filtered or unexported fields
}

func (State[S]) Current

func (s State[S]) Current() S

type StateTransitionEvent

type StateTransitionEvent[S comparable] struct {
	PreviousState S
	CurrentState  S
}

func (*StateTransitionEvent[S]) IsIdentity

func (t *StateTransitionEvent[S]) IsIdentity() bool

type StateType

type StateType[S comparable] struct {
	InitialValue S
}

type SystemId

type SystemId unsafe.Pointer

SystemId uniquely identifies a system.

Implementation note: this currently uses the function pointer. A function pointer in go has two layers of indirection to be able to handle closures correctly. The function pointer points to a small memory region holding a pointer to the actual function, as well as all data closed over by a closure. The SystemId currently points to this outer region of memory, not to the function code itself.

type SystemParam

type SystemParam interface {
	// contains filtered or unexported methods
}

SystemParam is an interface to give a type special behaviour when it is used as a parameter to a system.

While a system is being prepared, byke will check each parameter if it fulfills the SystemParam interface. If a parameter type does, a new instance will be allocate and the init method will be called.

See Local, ResOption or Query for some implementations of SystemParam.

type SystemParamState

type SystemParamState interface {
	// contains filtered or unexported methods
}

SystemParamState is the state produced by SystemParam. TODO i need to check this interface & the assumptions,

maybe it makes sense to merge it into SystemParam.

type SystemSet

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

SystemSet groups multiple systems together within one ScheduleId. SystemSet instances can be ordered between each other

func (*SystemSet) After

func (s *SystemSet) After(other *SystemSet) *SystemSet

func (*SystemSet) Before

func (s *SystemSet) Before(other *SystemSet) *SystemSet

func (*SystemSet) RunIf

func (s *SystemSet) RunIf(predicate AnySystem) *SystemSet

type Systems

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

Systems wrap one or more systems. See System for more details.

func System

func System(systems ...AnySystem) Systems

System wraps one or multiple systems (raw functions, other Systems) as a Systems instance. The Systems instance can then be used to configure inter system ordering or run predicates.

func (Systems) After

func (s Systems) After(other AnySystem) Systems

After adds an ordering constraint to require all systems to run after the provided systems.

func (Systems) Before

func (s Systems) Before(other AnySystem) Systems

Before adds an ordering constraint to require all systems to run before the provided systems.

func (Systems) Chain

func (s Systems) Chain() Systems

Chain chains the systems to run one after another.

func (Systems) InSet

func (s Systems) InSet(systemSet *SystemSet) Systems

InSet marks the systems to be part of the given SystemSet.

func (Systems) RunIf

func (s Systems) RunIf(predicate AnySystem) Systems

RunIf appends a run predicate to all systems. The predicate will be executed for each system in turn to determine if the system it should be executed or not.

type Timer

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

Timer is either a one of or a repeating timer with a specific duration.

func NewTimer

func NewTimer(duration time.Duration, mode TimerMode) Timer

NewTimer creates a new timer

func NewTimerWithFrequency

func NewTimerWithFrequency(hz float64) Timer

NewTimerWithFrequency creates a new repeating timer with the given frequency

func (*Timer) Duration

func (t *Timer) Duration() time.Duration

Duration returns the configured duration of the Timer.

func (*Timer) Elapsed

func (t *Timer) Elapsed() time.Duration

Elapsed returns the already elapsed time of the Timer.

func (*Timer) Finished

func (t *Timer) Finished() bool

Finished returns true if the timer has finished. In case this is a timer with mode TimerModeRepeating, this method will never return true.

func (*Timer) Fraction

func (t *Timer) Fraction() float64

Fraction returns the fraction to that this timer has finished. A freshly started timer will have a Fraction value of 0.

func (*Timer) FractionRemaining

func (t *Timer) FractionRemaining() float64

FractionRemaining is the inverse of Fraction.

func (*Timer) JustFinished

func (t *Timer) JustFinished() bool

JustFinished returns true if the timer has reached its duration at the previous call to Tick.

func (*Timer) Remaining

func (t *Timer) Remaining() time.Duration

Remaining returns the remaining time of the Timer.

func (*Timer) Reset

func (t *Timer) Reset()

Reset resets the timer back to its starting point.

func (*Timer) Tick

func (t *Timer) Tick(delta time.Duration) *Timer

Tick adds the given amount of time to the Timer.

func (*Timer) TimesFinishedThisTick

func (t *Timer) TimesFinishedThisTick() int

TimesFinishedThisTick returns the number of times this timer has finished at the previous call to Tick. E.g. if you tick a 1 second timer with a 3.5 second delta, the timer will have finished three times in this tick.

type TimerMode

type TimerMode uint8
const TimerModeOnce TimerMode = 0
const TimerModeRepeating TimerMode = 1

type TimingStats

type TimingStats struct {
	Visible bool

	BySchedule    map[ScheduleId]Timings
	ScheduleOrder []ScheduleId

	BySystem map[*preparedSystem]Timings
}

func NewTimingStats

func NewTimingStats() TimingStats

func (*TimingStats) MeasureSchedule

func (t *TimingStats) MeasureSchedule(scheduleId ScheduleId) TimingStopwatch

func (*TimingStats) MeasureSystem

func (t *TimingStats) MeasureSystem(system *preparedSystem) TimingStopwatch

type TimingStopwatch

type TimingStopwatch struct {
	Stop func()
}

type Timings

type Timings struct {
	Count         int
	Latest        time.Duration
	MovingAverage time.Duration
	Min, Max      time.Duration
}

func (Timings) Add

func (t Timings) Add(d time.Duration) Timings

type VirtualTime

type VirtualTime struct {
	Elapsed   time.Duration
	Delta     time.Duration
	DeltaSecs float64

	Scale float64
}

VirtualTime tracks time.

The progression of time can be scaled by setting the Scale field. This will scale the Delta and DeltaSecs values starting at the next frame.

type With

type With[C IsComponent[C]] = query.With[C]

With is a query filter that constraints the entities queried to include only entities that have a Component of type T.

type Without

type Without[C IsComponent[C]] = query.Without[C]

Without is a query filter that constraints the entities queried to include only entities that do not have a Component of type T.

type World

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

World holds all entities and resources, schedules, systems, etc. While an empty World can be created using NewWorld, it is normally created and configured by using the App api.

func NewWorld

func NewWorld() *World

NewWorld creates a new empty world. You probably want to use the App api instead.

func (*World) AddObserver

func (w *World) AddObserver(observer Observer) EntityId

AddObserver adds a new observer. Observers are entities containing the Observer component.

func (*World) AddSystems

func (w *World) AddSystems(scheduleId ScheduleId, firstSystem AnySystem, systems ...AnySystem)

AddSystems adds systems to a schedule within the world.

func (*World) ConfigureSystemSets

func (w *World) ConfigureSystemSets(scheduleId ScheduleId, systemSets ...*SystemSet)

func (*World) Despawn

func (w *World) Despawn(entityId EntityId)

Despawn recursively despawns the given entity following Children relations.

func (*World) InsertResource

func (w *World) InsertResource(resource any)

InsertResource inserts a new resource into the world. The resource should be provided as a non-pointer type.

If the resource does not yet exist, a new value of the resources type will be allocated on the heap and the value provided will be copied into that memory location.

If the world already contains a resource of the same type, this value will just be updated with the newly provided one.

func (*World) RemoveResource

func (w *World) RemoveResource(resourceType reflect.Type)

RemoveResource removes a resource previously added with InsertResource.

func (*World) Resource

func (w *World) Resource(ty reflect.Type) (AnyPtr, bool)

Resource returns a pointer to the resource of the given reflect type. The type must be the non-pointer type of the resource, i.e. the type of the resource as it was passed to InsertResource.

func (*World) RunSchedule

func (w *World) RunSchedule(scheduleId ScheduleId)

RunSchedule runs the schedule identified by the given ScheduleId. If no schedule with this id exists, no action is performed.

func (*World) RunSystem

func (w *World) RunSystem(system AnySystem)

RunSystem runs a system within the world.

func (*World) RunSystemWithInValue

func (w *World) RunSystemWithInValue(system AnySystem, inValue any)

func (*World) Spawn

func (w *World) Spawn(components []ErasedComponent) EntityId

Spawn spawns a new entity with the given components.

func (*World) TriggerObserver

func (w *World) TriggerObserver(targetId EntityId, eventValue any)

TriggerObserver triggers all observers listening on the given target (or all targets) for the given event value.

TODO observer event propagation is not yet implemented.

Directories

Path Synopsis
examples/camera command
examples/shader command
Package gm (stands for geometry math) provides some geometry primitives.
Package gm (stands for geometry math) provides some geometry primitives.
internal
set

Jump to

Keyboard shortcuts

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