gohan/component.go

57 lines
1.3 KiB
Go
Raw Normal View History

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