gohan/entity.go

66 lines
1.6 KiB
Go

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.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
}
// 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) bool {
entityMutex.Lock()
defer entityMutex.Unlock()
for i, e := range w.allEntities {
if e == entity {
w.allEntities = append(w.allEntities[:i], w.allEntities[i+1:]...)
// Remove components.
for i := range w.components[entity] {
w.components[entity][i] = nil
}
w.removedEntities = append(w.removedEntities, entity)
return true
}
}
return false
}
var numEntities int
var numEntitiesT time.Time
// CurrentEntities returns the number of currently active entities.
func (w *World) CurrentEntities() int {
if time.Since(numEntitiesT) >= w.cacheTime {
numEntities = len(w.allEntities)
numEntitiesT = time.Now()
}
return numEntities
}