Created
May 24, 2016 11:29
-
-
Save mzdravkov/e019f5298f83c2c187554268a026e1f5 to your computer and use it in GitHub Desktop.
test ecs idea
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"math" | |
"sync" | |
) | |
type Component interface { | |
Name() string | |
} | |
const ( | |
STARTING_ENTITY_COUNT = 512 | |
STARTING_COMPONENT_COUNT = 64 | |
) | |
var ( | |
EntityComponents [][]string = make([][]string, 0, STARTING_ENTITY_COUNT) | |
entityComponentsLock sync.Mutex | |
Components map[string][]Component = make(map[string][]Component) | |
ComponentSlicesLocks map[string]sync.Mutex = make(map[string]sync.Mutex) | |
ComponentsGlobalLock sync.Mutex | |
) | |
func AddEntity(components map[string]Component) { | |
// take keys(components) | |
componentNames := make([]string, 0, len(components)) | |
for componentName, component := range components { | |
componentNames = append(componentNames, componentName) | |
} | |
entityComponentsLock.Lock() | |
var positionToAdd int | |
if len(EntityComponents) < cap(EntityComponents) { | |
positionToAdd = len(EntityComponents) | |
} else { | |
positionToAdd = len(EntityComponents) + 1 | |
} | |
EntityComponents = append(EntityComponents, componentNames) | |
entityComponentsLock.Unlock() | |
for componentName, component := range components { | |
// if there were no such components until now, we initialize a slice for them in the Components map | |
if componentSlice, ok := Components[componentName]; !ok { | |
ComponentsGlobalLock.Lock() | |
Components[componentName] = make([]Component, 0, STARTING_COMPONENT_COUNT) | |
ComponentSlicesLocks[componentName] = sync.Mutex{} | |
ComponentsGlobalLock.Unlock() | |
} | |
ComponentSlicesLocks[componentName].Lock() | |
if cap(Components[componentName]) <= positionToAdd { | |
// find the power to which we should raise 2 for growing the slice | |
power := math.Ceil(math.Log2(float64(cap(Components[componentName])) / float64(positionToAdd))) | |
// grow the slice | |
newSlice := make([]Component, 0, math.Pow(2, power)*cap(Components[componentName])) | |
copy(newSlice, Components[componentName]) | |
Components[componentName] = newSlice | |
} | |
Components[componentName][positionToAdd] = component | |
ComponentSlicesLocks[componentName].Unlock() | |
} | |
} | |
func RemoveEntity(id uint64) { | |
for _, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment