github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/ecs/entity.go (about) 1 package ecs 2 3 import ( 4 "github.com/15mga/kiwi/ds" 5 "github.com/15mga/kiwi/util" 6 ) 7 8 func NewEntity(id string) *Entity { 9 e := &Entity{ 10 id: id, 11 comps: ds.NewKSet[TComponent, IComponent](1, func(component IComponent) TComponent { 12 return component.Type() 13 }), 14 } 15 return e 16 } 17 18 type Entity struct { 19 scene *Scene 20 id string 21 comps *ds.KSet[TComponent, IComponent] 22 } 23 24 func (e *Entity) Scene() *Scene { 25 return e.scene 26 } 27 28 func (e *Entity) setScene(scene *Scene) { 29 e.scene = scene 30 } 31 32 func (e *Entity) Id() string { 33 return e.id 34 } 35 36 func (e *Entity) AddComponent(c IComponent) *util.Err { 37 err := e.comps.Add(c) 38 if err != nil { 39 return err 40 } 41 c.setEntity(e) 42 c.Init() 43 return nil 44 } 45 46 func (e *Entity) AddComponents(components ...IComponent) { 47 for _, c := range components { 48 ok := e.comps.AddNX(c) 49 if !ok { 50 continue 51 } 52 c.setEntity(e) 53 c.Init() 54 } 55 } 56 57 func (e *Entity) DelComponent(t TComponent) bool { 58 c, ok := e.comps.Del(t) 59 if !ok { 60 return false 61 } 62 c.Dispose() 63 return true 64 } 65 66 func (e *Entity) GetComponent(t TComponent) (IComponent, bool) { 67 c, ok := e.comps.Get(t) 68 if !ok { 69 return nil, false 70 } 71 return c, true 72 } 73 74 func (e *Entity) MGetComponent(t TComponent) IComponent { 75 c, _ := e.comps.Get(t) 76 return c 77 } 78 79 func (e *Entity) Components() []IComponent { 80 return e.comps.Values() 81 } 82 83 func (e *Entity) IterComponent(fn func(IComponent)) { 84 e.comps.Iter(fn) 85 } 86 87 func (e *Entity) start() { 88 for _, c := range e.comps.Values() { 89 c.Start() 90 } 91 } 92 93 func (e *Entity) Dispose() { 94 for _, c := range e.comps.Values() { 95 c.Dispose() 96 } 97 e.comps.Reset() 98 }