2021-11-19 04:13:28 +00:00
|
|
|
package gohan
|
|
|
|
|
2021-11-22 02:48:54 +00:00
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2021-11-22 19:18:28 +00:00
|
|
|
// Entity is an entity identifier.
|
|
|
|
type Entity int
|
2021-11-19 04:13:28 +00:00
|
|
|
|
2021-11-22 19:18:28 +00:00
|
|
|
var maxEntityID Entity
|
2021-11-19 04:13:28 +00:00
|
|
|
|
2021-11-22 02:48:54 +00:00
|
|
|
var entityMutex sync.Mutex
|
|
|
|
|
2021-11-22 19:18:28 +00:00
|
|
|
// 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 {
|
2021-11-22 02:48:54 +00:00
|
|
|
entityMutex.Lock()
|
|
|
|
defer entityMutex.Unlock()
|
|
|
|
|
2021-11-22 19:18:28 +00:00
|
|
|
if len(availableEntityIDs) > 0 {
|
|
|
|
id := availableEntityIDs[0]
|
|
|
|
availableEntityIDs = availableEntityIDs[1:]
|
|
|
|
allEntities = append(allEntities, id)
|
|
|
|
return id
|
|
|
|
}
|
|
|
|
|
|
|
|
maxEntityID++
|
|
|
|
allEntities = append(allEntities, maxEntityID)
|
|
|
|
gameComponents = append(gameComponents, make([]interface{}, maxComponentID+1))
|
|
|
|
return maxEntityID
|
2021-11-22 02:48:54 +00:00
|
|
|
}
|
|
|
|
|
2021-11-22 19:18:28 +00:00
|
|
|
// 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 (entity Entity) Remove() {
|
2021-11-22 02:48:54 +00:00
|
|
|
entityMutex.Lock()
|
|
|
|
defer entityMutex.Unlock()
|
|
|
|
|
|
|
|
for i, e := range allEntities {
|
|
|
|
if e == entity {
|
|
|
|
allEntities = append(allEntities[:i], allEntities[i+1:]...)
|
|
|
|
removedEntities = append(removedEntities, e)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var numEntities int
|
|
|
|
var numEntitiesT time.Time
|
|
|
|
|
|
|
|
// ActiveEntities returns the number of currently active entities.
|
|
|
|
func ActiveEntities() int {
|
|
|
|
if time.Since(numEntitiesT) >= time.Second {
|
|
|
|
numEntities = len(allEntities)
|
|
|
|
numEntitiesT = time.Now()
|
|
|
|
}
|
|
|
|
return numEntities
|
2021-11-19 04:13:28 +00:00
|
|
|
}
|