Skip to content

Commit

Permalink
Added ability to store arbitrary resources in the world outside
Browse files Browse the repository at this point in the history
  • Loading branch information
unitoftime committed Aug 2, 2023
1 parent 8544739 commit 7329175
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
30 changes: 30 additions & 0 deletions world.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package ecs

import (
"math"

"reflect" // For resourceName
)

const (
Expand All @@ -16,6 +18,7 @@ type World struct {
minId, maxId Id // This is the range of Ids returned by NewId
arch map[Id]archetypeId
engine *archEngine
resources map[reflect.Type]any
}

// Creates a new world
Expand All @@ -26,6 +29,8 @@ func NewWorld() *World {
maxId: MaxEntity,
arch: make(map[Id]archetypeId),
engine: newArchEngine(),

resources: make(map[reflect.Type]any),
}
}

Expand Down Expand Up @@ -180,3 +185,28 @@ func (world *World) Exists(id Id) bool {
_, ok := world.arch[id]
return ok
}


// --------------------------------------------------------------------------------
// - Resources
// --------------------------------------------------------------------------------
func resourceName(t any) reflect.Type {
return reflect.TypeOf(t)
}

// TODO: Should I force people to do pointers?
func PutResource[T any](world *World, resource *T) {
name := resourceName(resource)
world.resources[name] = resource
}

func GetResource[T any](world *World) *T {
var t T
name := resourceName(&t)
anyVal, ok := world.resources[name]
if !ok {
return nil
}

return anyVal.(*T)
}
14 changes: 14 additions & 0 deletions world_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,3 +182,17 @@ func TestWorldWriteDelete(t *testing.T) {
}
}
}

func TestResources(t *testing.T) {
world := NewWorld()
p := position{1, 2, 3}

p0 := GetResource[position](world)
compare(t, p0, nil) // should be nil b/c it isnt added yet

PutResource(world, &p)

p1 := GetResource[position](world)
compare(t, p1, &p) // Should match the original pointer
compare(t, *p1, p)
}

0 comments on commit 7329175

Please sign in to comment.