goecs

package module
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2020 License: Apache-2.0 Imports: 6 Imported by: 36

README

goecs

A simple Go ECS

version godoc Build Status codecov conduct

Info

Entity–component–system (ECS) is an architectural patter that follows the composition over inheritance principle that allows greater flexibility in defining entities where every object in a world.

Every entity consists of one or more components which contains data or state. Therefore, the behavior of an entity can be changed at runtime by systems that add, remove or mutate components.

This eliminates the ambiguity problems of deep and wide inheritance hierarchies that are difficult to understand, maintain and extend.

Common ECS approaches are highly compatible and often combined with data-oriented design techniques.

For a more in deep read on this topic I could recommend this article.

Example

Run it on the Go Playground

package main

import (
	"fmt"
	"github.com/juan-medina/goecs"
)

// Simple Usage
func main() {
	// creates the world
	world := goecs.Default()

	// add our movement system
	world.AddSystem(MovementSystem)

	// add a listener
	world.AddListener(ChangePostListener, PosChangeSignalType)

	// add a first entity
	world.AddEntity(
		Pos{X: 0, Y: 0},
		Vel{X: 2, Y: 2},
	)

	// this entity shouldn't be updated
	world.AddEntity(
		Pos{X: 6, Y: 6},
	)

	// add a third entity
	world.AddEntity(
		Pos{X: 8, Y: 8},
		Vel{X: 4, Y: 4},
	)

	// print the world
	PrintWorld(world)
	fmt.Println()
	fmt.Println("updating world for halve a second:")

	// ask the world to update
	if err := world.Update(0.5); err != nil {
		fmt.Printf("error on update %v\n", err)
	}

	// print the world
	fmt.Println()
	PrintWorld(world)
}

// PrintWorld prints the content of our world
func PrintWorld(world *goecs.World) {
	fmt.Println("World:")
	for it := world.Iterator(); it != nil; it = it.Next() {
		ent := it.Value()
		id := ent.ID()
		pos := ent.Get(PosType).(Pos)
		if ent.Contains(VelType) {
			vel := ent.Get(VelType).(Vel)
			fmt.Printf("Id: %d, Pos: %v, Vel: %v/s\n", id, pos, vel)
		} else {
			fmt.Printf("Id: %d, Pos: %v\n", id, pos)
		}
	}
}

// MovementSystem is a simple movement system
func MovementSystem(world *goecs.World, delta float32) error {
	// get all the entities that we need to update, only if they have Pos & Vel
	for it := world.Iterator(PosType, VelType); it != nil; it = it.Next() {
		// get the values
		ent := it.Value()
		pos := ent.Get(PosType).(Pos)
		vel := ent.Get(VelType).(Vel)

		// calculate new pos
		npos := Pos{
			X: pos.X + vel.X*delta,
			Y: pos.Y + vel.Y*delta,
		}

		// set the new pos
		ent.Set(npos)

		// signal the change
		world.Signal(PosChangeSignal{ID: ent.ID(), From: pos, To: npos})
	}

	return nil
}

// ChangePostListener listen to PosChangeSignal
func ChangePostListener(world *goecs.World, signal goecs.Component, delta float32) error {
	switch s := signal.(type) {
	case PosChangeSignal:
		// print the change
		fmt.Printf("pos change for id: %d, from Pos%v to Pos%v\n", s.ID, s.From, s.To)
	}
	return nil
}

// PosType is the ComponentType of Pos
var PosType = goecs.NewComponentType()

// Pos represent a 2D position
type Pos struct {
	X float32
	Y float32
}

// Type will return Pos goecs.ComponentType
func (p Pos) Type() goecs.ComponentType {
	return PosType
}

// VelType is the ComponentType of Vel
var VelType = goecs.NewComponentType()

// Vel represent a 2D velocity
type Vel struct {
	X float32
	Y float32
}

// Type will return Vel goecs.ComponentType
func (v Vel) Type() goecs.ComponentType {
	return VelType
}

// PosChangeSignalType is the type of the PosChangeSignal
var PosChangeSignalType = goecs.NewComponentType()

// PosChangeSignal is a signal that a Pos has change
type PosChangeSignal struct {
	ID   uint64
	From Pos
	To   Pos
}

// Type will return PosChangeSignal goecs.ComponentType
func (p PosChangeSignal) Type() goecs.ComponentType {
	return PosChangeSignalType
}

This will output:

World:
Id: 1, Pos: {0 0}, Vel: {2 2}/s
Id: 2, Pos: {6 6}
Id: 3, Pos: {8 8}, Vel: {4 4}/s

updating world for halve a second:
pos change for id: 1, from Pos{0 0} to Pos{1 1}
pos change for id: 3, from Pos{8 8} to Pos{10 10}

World:
Id: 1, Pos: {1 1}, Vel: {2 2}/s
Id: 2, Pos: {6 6}
Id: 3, Pos: {10 10}, Vel: {4 4}/s

Installation

go get -v -u github.com/juan-medina/goecs

License

    Copyright (C) 2020 Juan Medina

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

Documentation

Overview

Package goecs provides a Go implementation of an Entity–component–system (ECS)

Entity–component–system (ECS) is an architectural patter that follows the composition over inheritance principle that allows greater flexibility in defining entities where every object in a world.

Every entity consists of one or more components which contains data or state. Therefore, the behavior of an entity can be changed at runtime by systems that add, remove or mutate components.

This eliminates the ambiguity problems of deep and wide inheritance hierarchies that are difficult to understand, maintain and extend.

Common ECS approaches are highly compatible and often combined with data-oriented design techniques.

See: World, Entity

Example

Simple Usage

/*
 * Copyright (c) 2020 Juan Medina.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */

package main

import (
	"fmt"
	"github.com/juan-medina/goecs"
)

// Simple Usage
func main() {
	// creates the world
	world := goecs.Default()

	// add our movement system
	world.AddSystem(MovementSystem)

	// add a listener
	world.AddListener(ChangePostListener, PosChangeSignalType)

	// add a first entity
	world.AddEntity(
		Pos{X: 0, Y: 0},
		Vel{X: 2, Y: 2},
	)

	// this entity shouldn't be updated
	world.AddEntity(
		Pos{X: 6, Y: 6},
	)

	// add a third entity
	world.AddEntity(
		Pos{X: 8, Y: 8},
		Vel{X: 4, Y: 4},
	)

	// print the world
	PrintWorld(world)
	fmt.Println()
	fmt.Println("updating world for halve a second:")

	// ask the world to update
	if err := world.Update(0.5); err != nil {
		fmt.Printf("error on update %v\n", err)
	}

	// print the world
	fmt.Println()
	PrintWorld(world)

}

// PrintWorld prints the content of our world
func PrintWorld(world *goecs.World) {
	fmt.Println("World:")
	for it := world.Iterator(); it != nil; it = it.Next() {
		ent := it.Value()
		id := ent.ID()
		pos := ent.Get(PosType).(Pos)
		if ent.Contains(VelType) {
			vel := ent.Get(VelType).(Vel)
			fmt.Printf("Id: %d, Pos: %v, Vel: %v/s\n", id, pos, vel)
		} else {
			fmt.Printf("Id: %d, Pos: %v\n", id, pos)
		}
	}
}

// MovementSystem is a simple movement system
func MovementSystem(world *goecs.World, delta float32) error {
	// get all the entities that we need to update, only if they have Pos & Vel
	for it := world.Iterator(PosType, VelType); it != nil; it = it.Next() {
		// get the values
		ent := it.Value()
		pos := ent.Get(PosType).(Pos)
		vel := ent.Get(VelType).(Vel)

		// calculate new pos
		npos := Pos{
			X: pos.X + vel.X*delta,
			Y: pos.Y + vel.Y*delta,
		}

		// set the new pos
		ent.Set(npos)

		// signal the change
		world.Signal(PosChangeSignal{ID: ent.ID(), From: pos, To: npos})
	}

	return nil
}

// ChangePostListener listen to PosChangeSignal
func ChangePostListener(world *goecs.World, signal goecs.Component, delta float32) error {
	switch s := signal.(type) {
	case PosChangeSignal:
		// print the change
		fmt.Printf("pos change for id: %d, from Pos%v to Pos%v\n", s.ID, s.From, s.To)
	}
	return nil
}

// PosType is the ComponentType of Pos
var PosType = goecs.NewComponentType()

// Pos represent a 2D position
type Pos struct {
	X float32
	Y float32
}

// Type will return Pos goecs.ComponentType
func (p Pos) Type() goecs.ComponentType {
	return PosType
}

// VelType is the ComponentType of Vel
var VelType = goecs.NewComponentType()

// Vel represent a 2D velocity
type Vel struct {
	X float32
	Y float32
}

// Type will return Vel goecs.ComponentType
func (v Vel) Type() goecs.ComponentType {
	return VelType
}

// PosChangeSignalType is the type of the PosChangeSignal
var PosChangeSignalType = goecs.NewComponentType()

// PosChangeSignal is a signal that a Pos has change
type PosChangeSignal struct {
	ID   goecs.EntityID
	From Pos
	To   Pos
}

// Type will return PosChangeSignal goecs.ComponentType
func (p PosChangeSignal) Type() goecs.ComponentType {
	return PosChangeSignalType
}
Output:

World:
Id: 1, Pos: {0 0}, Vel: {2 2}/s
Id: 2, Pos: {6 6}
Id: 3, Pos: {8 8}, Vel: {4 4}/s

updating world for halve a second:
pos change for id: 1, from Pos{0 0} to Pos{1 1}
pos change for id: 3, from Pos{8 8} to Pos{10 10}

World:
Id: 1, Pos: {1 1}, Vel: {2 2}/s
Id: 2, Pos: {6 6}
Id: 3, Pos: {10 10}, Vel: {4 4}/s

Index

Examples

Constants

View Source
const (
	DefaultSignalsInitialCapacity   = 20   // Default Signals initial capacity
	DefaultSystemsInitialCapacity   = 50   // Default System initial capacity
	DefaultListenersInitialCapacity = 50   // Default Listener initial capacity
	DefaultEntitiesInitialCapacity  = 2000 // Default Entity initial capacity
	DefaultResourcesInitialCapacity = 20   // Default Resources initial capacity
)

Default values for Default()

Variables

View Source
var (
	// ErrEntityNotFound is the error when we could not find an viewItem
	ErrEntityNotFound = errors.New("entity not found")
)

Functions

This section is empty.

Types

type Component added in v1.5.0

type Component interface {
	Type() ComponentType
}

Component represent a Entity component

type ComponentType added in v1.5.0

type ComponentType uint64

ComponentType represents the type of a Component

func NewComponentType added in v1.5.0

func NewComponentType() ComponentType

NewComponentType return a new component type

type Entity

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

Entity represents a instance of an object in a ECS

func NewEntity

func NewEntity(ID EntityID, components ...Component) *Entity

NewEntity creates a new Entity giving a set of varg components

func (*Entity) Add

func (ent *Entity) Add(component Component) *Entity

Add a new component into an Entity

func (*Entity) Clear added in v1.5.0

func (ent *Entity) Clear()

Clear the Entity

func (Entity) Contains

func (ent Entity) Contains(types ...ComponentType) bool

Contains check that the Entity has the given varg ComponentType

func (Entity) Get

func (ent Entity) Get(ctype ComponentType) Component

Get the component of the given ComponentType

func (Entity) ID

func (ent Entity) ID() EntityID

ID : get the unique id for this Entity

func (Entity) IsEmpty added in v1.5.0

func (ent Entity) IsEmpty() bool

IsEmpty check if the Entity has not Component

func (Entity) NotContains

func (ent Entity) NotContains(types ...ComponentType) bool

NotContains check that the Entity has not the given varg ComponentType

func (*Entity) Remove

func (ent *Entity) Remove(ctype ComponentType)

Remove the component of the given ComponentType

func (*Entity) Reuse added in v1.5.0

func (ent *Entity) Reuse(id EntityID, components ...Component)

Reuse this Entity with new data

func (*Entity) Set

func (ent *Entity) Set(component Component) *Entity

Set a new component into an Entity

func (Entity) String

func (ent Entity) String() string

String : get a string representation of an Entity

type EntityID added in v1.5.0

type EntityID uint64

EntityID is the ID for an Entity

type Iterator

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

Iterator allow to iterate trough the View

func (*Iterator) Next

func (ei *Iterator) Next() *Iterator

Next return a Iterator to the next Entity

func (*Iterator) Value

func (ei *Iterator) Value() *Entity

Value returns the value of the current Iterator

type Listener

type Listener func(world *World, signal Component, delta float32) error

Listener that get notified that a new signal has been received by World.Signal

type Subscriptions added in v1.4.0

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

Subscriptions manage subscriptions of Listeners to signals

func NewSubscriptions added in v1.4.0

func NewSubscriptions(listeners, signals int) *Subscriptions

NewSubscriptions creates a new Subscriptions

func (*Subscriptions) Clear added in v1.4.0

func (subs *Subscriptions) Clear()

Clear the subscriptions & signals

func (*Subscriptions) Signal added in v1.4.0

func (subs *Subscriptions) Signal(signal interface{})

Signal adds a signal to to be sent

func (Subscriptions) String added in v1.4.0

func (subs Subscriptions) String() string

String returns the string representation of the subscriptions

func (*Subscriptions) Subscribe added in v1.4.0

func (subs *Subscriptions) Subscribe(listener Listener, priority int32, signals ...ComponentType)

Subscribe adds a new subscription given a priority and set of signals types

func (*Subscriptions) Update added in v1.4.0

func (subs *Subscriptions) Update(world *World, delta float32) error

Update send the pending signals to the listeners on the world

type System

type System func(world *World, delta float32) error

System get invoke with Update() from a World

type Systems added in v1.4.0

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

Systems manage registration of systems

func NewSystems added in v1.4.0

func NewSystems(systems int) *Systems

NewSystems creates a new Systems

func (*Systems) Clear added in v1.4.0

func (sys *Systems) Clear()

Clear the systems

func (*Systems) Register added in v1.4.0

func (sys *Systems) Register(system System, priority int32)

Register adds a new registration with a given priority

func (Systems) String added in v1.4.0

func (sys Systems) String() string

String returns the string representation of the systems

func (*Systems) Update added in v1.4.0

func (sys *Systems) Update(world *World, delta float32) error

Update the systems

type View

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

View represent a set of Entity objects

func NewView

func NewView(capacity int) *View

NewView creates a new empty View with a given capacity

func (*View) AddEntity

func (v *View) AddEntity(data ...Component) EntityID

AddEntity a Entity instance to a View given it components

func (*View) Clear

func (v *View) Clear()

Clear removes all Entity from the View

func (*View) First added in v1.5.1

func (v *View) First(components ...ComponentType) (EntityID, error)

First return the first EntityID that match the given ComponentType

func (*View) Get added in v1.5.0

func (v *View) Get(id EntityID) *Entity

Get a Entity from a View giving it EntityID

func (*View) Iterator

func (v *View) Iterator(types ...ComponentType) *Iterator

Iterator return an view.Iterator for the given varg ComponentType

func (*View) Remove

func (v *View) Remove(id EntityID) error

Remove a Entity from a View

func (View) Size

func (v View) Size() int

Size is the number of Entity in this View

func (*View) Sort

func (v *View) Sort(less func(a, b *Entity) bool)

Sort the entities in place with a less function

func (View) String

func (v View) String() string

String get a string representation of a View

type World

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

World is a view.View that contains the Entity and System of our ECS

func Default added in v1.3.1

func Default() *World

Default creates a default World with a initial capacity

const (
	DefaultSignalsInitialCapacity   = 20   // Default Signals initial capacity
	DefaultSystemsInitialCapacity   = 50   // Default System initial capacity
	DefaultListenersInitialCapacity = 50   // Default Listener initial capacity
	DefaultEntitiesInitialCapacity  = 2000 // Default Entity initial capacity
)

func New

func New(entities, systems, listeners, signals, resources int) *World

New creates World with a giving initial capacity of entities, systems, listeners and signals

Since those elements are sparse.Slice the will grow dynamically

func (*World) AddListener

func (world *World) AddListener(lis Listener, signals ...ComponentType)

AddListener adds the given Listener to the world

func (*World) AddListenerWithPriority

func (world *World) AddListenerWithPriority(lis Listener, priority int32, signals ...ComponentType)

AddListenerWithPriority adds the given Listener to the world with a priority

func (*World) AddResource added in v1.5.1

func (world *World) AddResource(components ...Component) EntityID

AddResource create a new resource and add it to the world resources a global entities with a single instance that are no return by the Iterator for example things like a game score

func (*World) AddSystem

func (world *World) AddSystem(sys System)

AddSystem adds the given System to the world

func (*World) AddSystemWithPriority

func (world *World) AddSystemWithPriority(sys System, priority int32)

AddSystemWithPriority adds the given System to the world with a priority

func (*World) Clear

func (world *World) Clear()

Clear removes all System, Listener, Subscriptions, Entity and Resources from the World

func (World) FindResource added in v1.5.1

func (world World) FindResource(components ...ComponentType) EntityID

FindResource find a resource in the world that match the given ComponentType

func (World) GetResource added in v1.5.1

func (world World) GetResource(id EntityID) *Entity

GetResource gets a resource from the world

func (World) RemoveResource added in v1.5.2

func (world World) RemoveResource(id EntityID) error

RemoveResource removes a resource from the world

func (*World) Signal

func (world *World) Signal(signal interface{})

Signal to be sent

func (World) String

func (world World) String() string

String get a string representation of our World

func (*World) Update

func (world *World) Update(delta float32) error

Update ask to update the System and send the signals

Directories

Path Synopsis
Package sparse provides the creation of sparse.Slice via sparse.NewSlice Sparse items are design to automatically grow and reuse memory so they try to minimize the GC pauses
Package sparse provides the creation of sparse.Slice via sparse.NewSlice Sparse items are design to automatically grow and reuse memory so they try to minimize the GC pauses

Jump to

Keyboard shortcuts

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