Entity Component System framework for Ebiten
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.

58 lines
1.5 KiB

package gohan
import (
"sync"
"time"
)
// Entity is an entity identifier.
type Entity int
var entityMutex sync.Mutex
// NewEntity returns a new (or previously removed and cleared) Entity. Because
// Gohan reuses removed Entity IDs, a previously removed ID may be returned.
func (w *World) NewEntity() Entity {
entityMutex.Lock()
defer entityMutex.Unlock()
if len(w.availableEntityIDs) > 0 {
id := w.availableEntityIDs[0]
w.availableEntityIDs = w.availableEntityIDs[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
}
// RemoveEntity 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 (w *World) RemoveEntity(entity Entity) {
entityMutex.Lock()
defer entityMutex.Unlock()
for i, e := range w.allEntities {
if e == entity {
w.allEntities = append(w.allEntities[:i], w.allEntities[i+1:]...)
w.removedEntities = append(w.removedEntities, e)
return
}
}
}
var numEntities int
var numEntitiesT time.Time
// ActiveEntities returns the number of currently active entities.
func (w *World) ActiveEntities() int {
if time.Since(numEntitiesT) >= w.cacheTime {
numEntities = len(w.allEntities)
numEntitiesT = time.Now()
}
return numEntities
}