-
-
Save Araq/bfcf12baa58ac2ab57641984f0b512c1 to your computer and use it in GitHub Desktop.
This file contains 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
# ECS | |
type | |
EntityID = distinct int | |
ComponentID = distinct int | |
ComponentManger = object | |
create: proc (id: EntityID) # note: does not really work | |
destroy: proc (id: EntityID) | |
var | |
components: BTree[ComponentID, ComponentManager] | |
consistsOf: BTree[EntityID, seq[ComponentID]] | |
eid: EntityID # for unique ID generation | |
template declareComponent(id: ComponentID; t: typeDesc; update) = | |
var data: BTree[EntityID, t] | |
proc updateAll() = | |
for x in data: update(x) | |
proc create(e: EntityID; value: t) = data.insert(e, value) | |
proc destroy(e: EntityID) = data.remove(e) | |
components.insert(id, ComponentManger(create: create, destroy: destroy)) | |
proc createEntity(parts: seq[ComponentID]): EntityID = | |
inc eid.int | |
result = eid | |
consistsOf.insert(result, parts) | |
proc destroyEntity(e: EntityID) = | |
let parts = consistsOf.get(e) | |
for p in parts: | |
components.get(p).destroy() | |
# Position component: | |
type | |
Position = object | |
x, y, z: float32 | |
proc update(p: var Position) = discard | |
declareComponent(ComponentID 1, Position, update) | |
# Physics component: | |
type | |
Physics = object | |
acc, vel: float32 | |
proc update(p: var Physics) = discard | |
declareComponent(ComponentID 2, Physics, update) | |
# declare a Person with 2 legs (positions) and a physics component: | |
let araq = createEntity(@[ComponentID 1, 1, 2]) | |
create(araq, Position(1, 2, 3)) | |
create(araq, Position(2, 3, 4)) | |
create(araq, Physics(1, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment