forked from Argus-Labs/world-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cardinal.go
366 lines (305 loc) · 9.24 KB
/
cardinal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package cardinal
import (
"errors"
"reflect"
"strconv"
"github.com/rotisserie/eris"
"pkg.world.dev/world-engine/cardinal/component"
"pkg.world.dev/world-engine/cardinal/iterators"
"pkg.world.dev/world-engine/cardinal/types"
"pkg.world.dev/world-engine/cardinal/worldstage"
)
var (
ErrEntityMutationOnReadOnly = errors.New("cannot modify state with read only context")
ErrEntitiesCreatedBeforeReady = errors.New("entities should not be created before world is ready")
ErrEntityDoesNotExist = iterators.ErrEntityDoesNotExist
ErrEntityMustHaveAtLeastOneComponent = iterators.ErrEntityMustHaveAtLeastOneComponent
ErrComponentNotOnEntity = iterators.ErrComponentNotOnEntity
ErrComponentAlreadyOnEntity = iterators.ErrComponentAlreadyOnEntity
)
// FilterFunction wrap your component filter function of func(comp T) bool inside FilterFunction to use
// in search.
//
// Usage:
//
// cardinal.NewSearch().Entity(filter.Not(filter.
// Contains(filter.Component[AlphaTest]()))).Where(cardinal.FilterFunction[GammaTest](func(_ GammaTest) bool {
// return true
// }))
func FilterFunction[T types.Component](f func(comp T) bool) func(ctx WorldContext, id types.EntityID) (bool, error) {
return ComponentFilter[T](f)
}
func RegisterSystems(w *World, sys ...System) error {
if w.worldStage.Current() != worldstage.Init {
return eris.Errorf(
"world state is %s, expected %s to register systems",
w.worldStage.Current(),
worldstage.Init,
)
}
return w.SystemManager.registerSystems(false, sys...)
}
func RegisterInitSystems(w *World, sys ...System) error {
if w.worldStage.Current() != worldstage.Init {
return eris.Errorf(
"world state is %s, expected %s to register init systems",
w.worldStage.Current(),
worldstage.Init,
)
}
return w.SystemManager.registerSystems(true, sys...)
}
func RegisterComponent[T types.Component](w *World) error {
if w.worldStage.Current() != worldstage.Init {
return eris.Errorf(
"world state is %s, expected %s to register component",
w.worldStage.Current(),
worldstage.Init,
)
}
compMetadata, err := component.NewComponentMetadata[T]()
if err != nil {
return err
}
err = w.RegisterComponent(compMetadata)
if err != nil {
return err
}
return nil
}
func MustRegisterComponent[T types.Component](w *World) {
err := RegisterComponent[T](w)
if err != nil {
panic(err)
}
}
func EachMessage[In any, Out any](wCtx WorldContext, fn func(TxData[In]) (Out, error)) error {
var msg MessageType[In, Out]
msgType := reflect.TypeOf(msg)
tempRes, ok := wCtx.getMessageByType(msgType)
if !ok {
return eris.Errorf("Could not find %s, Message may not be registered.", msg.Name())
}
var _ types.Message = &msg
res, ok := tempRes.(*MessageType[In, Out])
if !ok {
return eris.New("wrong type")
}
res.Each(wCtx, fn)
return nil
}
// RegisterMessage registers a message to the world. Cardinal will automatically set up HTTP routes that map to each
// registered message. Message URLs are take the form of "group.name". A default group, "game", is used
// unless the WithCustomMessageGroup option is used. Example: game.throw-rock
func RegisterMessage[In any, Out any](world *World, name string, opts ...MessageOption[In, Out]) error {
if world.worldStage.Current() != worldstage.Init {
return eris.Errorf(
"world state is %s, expected %s to register messages",
world.worldStage.Current(),
worldstage.Init,
)
}
// Create the message type
msgType := NewMessageType[In, Out](name, opts...)
// Register the message with the manager
err := world.RegisterMessage(msgType, reflect.TypeOf(*msgType))
if err != nil {
return err
}
return nil
}
func RegisterQuery[Request any, Reply any](
w *World,
name string,
handler func(wCtx WorldContext, req *Request) (*Reply, error),
opts ...QueryOption[Request, Reply],
) (err error) {
if w.worldStage.Current() != worldstage.Init {
return eris.Errorf(
"world state is %s, expected %s to register query",
w.worldStage.Current(),
worldstage.Init,
)
}
q, err := newQueryType[Request, Reply](name, handler, opts...)
if err != nil {
return err
}
res := w.RegisterQuery(q)
return res
}
// Create creates a single entity in the world, and returns the id of the newly created entity.
// At least 1 component must be provided.
func Create(wCtx WorldContext, components ...types.Component) (_ types.EntityID, err error) {
// We don't handle panics here because we let CreateMany handle it for us
entityIDs, err := CreateMany(wCtx, 1, components...)
if err != nil {
return 0, err
}
return entityIDs[0], nil
}
// CreateMany creates multiple entities in the world, and returns the slice of ids for the newly created
// entities. At least 1 component must be provided.
func CreateMany(wCtx WorldContext, num int, components ...types.Component) (entityIDs []types.EntityID, err error) {
defer func() { panicOnFatalError(wCtx, err) }()
// Error if the context is read only
if wCtx.isReadOnly() {
return nil, ErrEntityMutationOnReadOnly
}
if !wCtx.isWorldReady() {
return nil, ErrEntitiesCreatedBeforeReady
}
// Get all component metadata for the given components
acc := make([]types.ComponentMetadata, 0, len(components))
for _, comp := range components {
c, err := wCtx.getComponentByName(comp.Name())
if err != nil {
return nil, eris.Wrap(err, "failed to create entity because component is not registered")
}
acc = append(acc, c)
}
// Create the entities
entityIDs, err = wCtx.storeManager().CreateManyEntities(num, acc...)
if err != nil {
return nil, err
}
// Store the components for the entities
for _, id := range entityIDs {
for _, comp := range components {
var c types.ComponentMetadata
c, err = wCtx.getComponentByName(comp.Name())
if err != nil {
return nil, eris.Wrap(err, "failed to create entity because component is not registered")
}
err = wCtx.storeManager().SetComponentForEntity(c, id, comp)
if err != nil {
return nil, err
}
}
}
return entityIDs, nil
}
// SetComponent sets component data to the entity.
func SetComponent[T types.Component](wCtx WorldContext, id types.EntityID, component *T) (err error) {
defer func() { panicOnFatalError(wCtx, err) }()
// Error if the context is read only
if wCtx.isReadOnly() {
return ErrEntityMutationOnReadOnly
}
// Get the component metadata
var t T
c, err := wCtx.getComponentByName(t.Name())
if err != nil {
return err
}
// Store the component
err = wCtx.storeManager().SetComponentForEntity(c, id, component)
if err != nil {
return err
}
// Log
wCtx.Logger().Debug().
Str("entity_id", strconv.FormatUint(uint64(id), 10)).
Str("component_name", c.Name()).
Int("component_id", int(c.ID())).
Msg("entity updated")
return nil
}
// GetComponent returns component data from the entity.
func GetComponent[T types.Component](wCtx WorldContext, id types.EntityID) (comp *T, err error) {
defer func() { panicOnFatalError(wCtx, err) }()
// Get the component metadata
var t T
c, err := wCtx.getComponentByName(t.Name())
if err != nil {
return nil, err
}
// Get current component value
compValue, err := wCtx.storeReader().GetComponentForEntity(c, id)
if err != nil {
return nil, err
}
// Type assert the component value to the component type
t, ok := compValue.(T)
if !ok {
comp, ok = compValue.(*T)
if !ok {
return nil, err
}
} else {
comp = &t
}
return comp, nil
}
func UpdateComponent[T types.Component](wCtx WorldContext, id types.EntityID, fn func(*T) *T) (err error) {
defer func() { panicOnFatalError(wCtx, err) }()
// Error if the context is read only
if wCtx.isReadOnly() {
return err
}
// Get current component value
val, err := GetComponent[T](wCtx, id)
if err != nil {
return err
}
// Get the new component value
updatedVal := fn(val)
// Store the new component value
err = SetComponent[T](wCtx, id, updatedVal)
if err != nil {
return err
}
return nil
}
func AddComponentTo[T types.Component](wCtx WorldContext, id types.EntityID) (err error) {
defer func() { panicOnFatalError(wCtx, err) }()
// Error if the context is read only
if wCtx.isReadOnly() {
return ErrEntityMutationOnReadOnly
}
// Get the component metadata
var t T
c, err := wCtx.getComponentByName(t.Name())
if err != nil {
return err
}
// Add the component to entity
err = wCtx.storeManager().AddComponentToEntity(c, id)
if err != nil {
return err
}
return nil
}
// RemoveComponentFrom removes a component from an entity.
func RemoveComponentFrom[T types.Component](wCtx WorldContext, id types.EntityID) (err error) {
defer func() { panicOnFatalError(wCtx, err) }()
// Error if the context is read only
if wCtx.isReadOnly() {
return ErrEntityMutationOnReadOnly
}
// Get the component metadata
var t T
c, err := wCtx.getComponentByName(t.Name())
if err != nil {
return err
}
// Remove the component from entity
err = wCtx.storeManager().RemoveComponentFromEntity(c, id)
if err != nil {
return err
}
return nil
}
// Remove removes the given Entity from the world.
func Remove(wCtx WorldContext, id types.EntityID) (err error) {
defer func() { panicOnFatalError(wCtx, err) }()
// Error if the context is read only
if wCtx.isReadOnly() {
return ErrEntityMutationOnReadOnly
}
err = wCtx.storeManager().RemoveEntity(id)
if err != nil {
return err
}
return nil
}