Entity Component System framework for Ebitengine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
1.9 KiB

package gohan
import (
"time"
)
// Entity is an entity identifier.
type Entity int
// NewEntity returns a new (or previously removed and cleared) Entity. Because
// Gohan reuses removed Entity IDs, a previously removed ID may be returned.
func NewEntity() Entity {
w.entityMutex.Lock()
defer w.entityMutex.Unlock()
if len(w.availableEntities) > 0 {
id := w.availableEntities[0]
w.availableEntities = w.availableEntities[1:]
w.allEntities = append(w.allEntities, id)
return id
}
w.maxEntityID++
w.allEntities = append(w.allEntities, w.maxEntityID)
w.components = append(w.components, make([]interface{}, w.maxComponentID+1))
return w.maxEntityID
}
// Remove removes the provided Entity's components, causing it to no
// longer be handled by any system. Because Gohan reuses removed EntityIDs,
// applications must also remove any internal references to the removed Entity.
func (e Entity) Remove() bool {
w.entityMutex.Lock()
defer w.entityMutex.Unlock()
for i, ent := range w.allEntities {
if ent == e {
w.allEntities = _removeAt(w.allEntities, i)
// Remove components.
for i := range w.components[e] {
w.components[e][i] = nil
}
w.removedEntities = append(w.removedEntities, e)
return true
}
}
return false
}
// AllEntities returns a slice of all active entities. To retrieve only the
// number of currently active entities, use CurrentEntities.
func AllEntities() []Entity {
w.entityMutex.Lock()
defer w.entityMutex.Unlock()
allEntities := make([]Entity, len(w.allEntities))
copy(allEntities, w.allEntities)
return allEntities
}
var numEntities int
var numEntitiesT time.Time
// CurrentEntities returns the number of currently active entities.
func CurrentEntities() int {
if time.Since(numEntitiesT) >= w.cacheTime {
numEntities = len(w.allEntities)
numEntitiesT = time.Now()
}
return numEntities
}
func _removeAt(v []Entity, i int) []Entity {
v[i] = v[len(v)-1]
return v[:len(v)-1]
}