59 lines
1.3 KiB
Go
59 lines
1.3 KiB
Go
package gohan
|
|
|
|
import (
|
|
"sync"
|
|
)
|
|
|
|
var componentMutex sync.Mutex
|
|
|
|
// ComponentID is a component identifier. Each Component is assigned a unique ID
|
|
// via NewComponentID, and implements a ComponentID method returning its ID.
|
|
type ComponentID int
|
|
|
|
// Component represents data for an entity, and how it interacts with the world.
|
|
type Component interface {
|
|
ComponentID() ComponentID
|
|
}
|
|
|
|
var maxComponentID ComponentID
|
|
|
|
// NewComponentID returns the next available ComponentID.
|
|
func NewComponentID() ComponentID {
|
|
mutex.Lock()
|
|
defer mutex.Unlock()
|
|
|
|
entityMutex.Lock()
|
|
defer entityMutex.Unlock()
|
|
|
|
componentMutex.Lock()
|
|
defer componentMutex.Unlock()
|
|
|
|
maxComponentID++
|
|
|
|
for i := Entity(1); i < maxEntityID; i++ {
|
|
gameComponents[i] = append(gameComponents[i], nil)
|
|
}
|
|
|
|
return maxComponentID
|
|
}
|
|
|
|
// AddComponent adds a Component to an Entity.
|
|
func (entity Entity) AddComponent(component Component) {
|
|
componentID := component.ComponentID()
|
|
|
|
gameComponents[entity][componentID] = component
|
|
|
|
entityMutex.Lock()
|
|
defer entityMutex.Unlock()
|
|
modifiedEntities = append(modifiedEntities, entity)
|
|
}
|
|
|
|
// Component gets a Component of an Entity.
|
|
func (entity Entity) Component(componentID ComponentID) interface{} {
|
|
components := gameComponents[entity]
|
|
if components == nil {
|
|
return nil
|
|
}
|
|
return components[componentID]
|
|
}
|