-
Notifications
You must be signed in to change notification settings - Fork 452
/
Entity.go
1377 lines (1166 loc) · 38 KB
/
Entity.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package entity
import (
"fmt"
"reflect"
"time"
"github.com/xiaonanln/goTimer"
"unsafe"
"github.com/pkg/errors"
"github.com/xiaonanln/go-aoi"
"github.com/xiaonanln/goworld/engine/common"
"github.com/xiaonanln/goworld/engine/config"
"github.com/xiaonanln/goworld/engine/consts"
"github.com/xiaonanln/goworld/engine/dispatchercluster"
"github.com/xiaonanln/goworld/engine/gwlog"
"github.com/xiaonanln/goworld/engine/netutil"
"github.com/xiaonanln/goworld/engine/post"
"github.com/xiaonanln/goworld/engine/proto"
"github.com/xiaonanln/goworld/engine/storage"
"github.com/xiaonanln/typeconv"
)
var (
saveInterval time.Duration
)
// Yaw is the type of entity Yaw
type Yaw float32
type entityTimerInfo struct {
FireTime time.Time
RepeatInterval time.Duration
Method string
Args []interface{}
Repeat bool
rawTimer *timer.Timer
}
// Entity is the basic execution unit in GoWorld server. Entities can be used to
// represent players, NPCs, monsters. Entities can migrate among spaces.
type Entity struct {
ID common.EntityID
TypeName string
I IEntity
V reflect.Value
destroyed bool
typeDesc *EntityTypeDesc
Space *Space
Position Vector3
Neighbors EntitySet
aoi aoi.AOI
yaw Yaw
rawTimers map[*timer.Timer]struct{}
timers map[EntityTimerID]*entityTimerInfo
lastTimerId EntityTimerID
client *GameClient
syncingFromClient bool
Attrs *MapAttr
syncInfoFlag syncInfoFlag
enteringSpaceRequest struct {
SpaceID common.EntityID
EnterPos Vector3
RequestTime int64
migrateRequestIsSent bool
}
}
type clientData struct {
ClientID common.ClientID
GateID uint16
}
// entity info that should be migrated
type entityMigrateData struct {
Type string `msgpack:"T"`
Attrs map[string]interface{} `msgpack:"A"`
Client *clientData `msgpack:"C,omitempty"`
Pos Vector3 `msgpack:"Pos"`
Yaw Yaw `msgpack:"Yaw"`
SpaceID common.EntityID `msgpack:"SP"`
TimerData []byte `msgpack:"TD,omitempty"`
FilterProps map[string]string `msgpack:"FP"`
SyncingFromClient bool `msgpack""SFC`
SyncInfoFlag syncInfoFlag `msgpack:"SIF"`
}
type syncInfoFlag int
const (
sifSyncOwnClient syncInfoFlag = 1 << iota
sifSyncNeighborClients
)
// IEntity declares functions that is defined in Entity
// These functions are mostly component functions
type IEntity interface {
// Entity Lifetime
OnInit() // Called when initializing entity struct, override to initialize entity custom fields
OnAttrsReady() // Called when entity attributes are ready.
OnCreated() // Called when entity is just created
OnDestroy() // Called when entity is destroying (just before destroy)
// Migration
OnMigrateOut() // Called just before entity is migrating out
OnMigrateIn() // Called just after entity is migrating in
// Freeze && Restore
OnFreeze() // Called when entity is freezing
OnRestored() // Called when entity is restored
// Space Operations
OnEnterSpace() // Called when entity leaves space
OnLeaveSpace(space *Space) // Called when entity enters space
// Client Notifications
OnClientConnected() // Called when Client is connected to entity (become player)
OnClientDisconnected() // Called when Client disconnected
DescribeEntityType(desc *EntityTypeDesc) // Define entity attributes in this function
}
func (e *Entity) String() string {
return fmt.Sprintf("%s<%s>", e.TypeName, e.ID)
}
// Destroy destroys the entity
func (e *Entity) Destroy() {
if e.destroyed {
return
}
gwlog.Debugf("%s.Destroy ...", e)
e.destroyEntity(false)
dispatchercluster.SendNotifyDestroyEntity(e.ID)
}
func (e *Entity) destroyEntity(isMigrate bool) {
e.Space.leave(e)
if !isMigrate {
//e.callCompositiveMethod("OnDestroy")
e.I.OnDestroy()
} else {
//e.callCompositiveMethod("OnMigrateOut")
e.I.OnMigrateOut()
}
e.clearRawTimers()
e.rawTimers = nil // prohibit further use
if !isMigrate {
e.SetClient(nil) // always set Client to nil before destroy
e.Save()
} else {
if e.client != nil {
entityManager.onEntityLoseClient(e.client.clientid)
e.client = nil
}
}
e.destroyed = true
entityManager.del(e)
}
// IsDestroyed returns if the entity is destroyed
func (e *Entity) IsDestroyed() bool {
return e.destroyed
}
// Save the entity
func (e *Entity) Save() {
if !e.IsPersistent() {
return
}
if consts.DEBUG_SAVE_LOAD {
gwlog.Debugf("SAVING %s ...", e)
}
data := e.getPersistentData()
storage.Save(e.TypeName, e.ID, data, nil)
}
// IsSpaceEntity returns if the entity is actually a space
func (e *Entity) IsSpaceEntity() bool {
return e.TypeName == _SPACE_ENTITY_TYPE
}
// AsSpace converts entity to space (only works for space entity)
func (e *Entity) AsSpace() *Space {
if !e.IsSpaceEntity() {
gwlog.Panicf("%s is not a space", e)
}
return (*Space)(unsafe.Pointer(e))
}
func (e *Entity) init(typeName string, entityid common.EntityID, entityInstance reflect.Value) {
e.ID = entityid
e.V = entityInstance
e.I = entityInstance.Interface().(IEntity)
e.TypeName = typeName
e.typeDesc = registeredEntityTypes[typeName]
//if !e.typeDesc.definedAttrs {
// // first time entity of this type is created, define Attrs now
// e.callCompositiveMethod("DescribeEntityType", e.typeDesc)
//}
e.rawTimers = map[*timer.Timer]struct{}{}
e.timers = map[EntityTimerID]*entityTimerInfo{}
attrs := NewMapAttr()
attrs.owner = e
e.Attrs = attrs
e.Neighbors = EntitySet{}
aoi.InitAOI(&e.aoi, _DEFAULT_AOI_DISTANCE, e, e)
//e.initComponents()
//e.callCompositiveMethod("OnInit")
e.I.OnInit()
}
//func (e *Entity) initComponents() {
// entityVal := reflect.Indirect(e.V)
// for fi := 0; fi < entityVal.NumField(); fi++ {
// field := entityVal.Field(fi)
// //fieldStruct := entityVal.Type().Field(fi)
// if isComponentType(field.Type()) {
// //gwlog.Infof("%s: Field %s %d %T is a component, initializing ...", e, fieldStruct.Name, fi, field.Interface())
// comp := field.FieldByName("Component").Addr().Interface().(*Component)
// e.initComponent(comp)
// }
// }
//}
//func (e *Entity) initComponent(comp *Component) {
// comp.Entity = e
//}
//func (e *Entity) callCompositiveMethod(methodName string, args ...interface{}) {
// entityPtr := e.V
// entityVal := reflect.Indirect(entityPtr)
// var methodIn []reflect.Value
// if len(args) > 0 {
// methodIn = make([]reflect.Value, len(args), len(args))
// for i := 0; i < len(args); i++ {
// methodIn[i] = reflect.ValueOf(args[i])
// }
// }
//
// method := entityPtr.MethodByName(methodName)
// if method.IsValid() {
// gwutils.RunPanicless(func() {
// method.Call(methodIn)
// })
// }
//
// compIndices, ok := e.typeDesc.compositiveMethodComponentIndices[methodName]
// if !ok {
// // collect compositiveMethodComponentIndices for the first time
// entityType := entityVal.Type()
// for fi := 0; fi < entityType.NumField(); fi++ {
// field := entityType.Field(fi)
// if isComponentType(field.Type) {
// //gwlog.Infof("Field %v is a component", field.Name)
// _, ok := reflect.PtrTo(field.Type).MethodByName(methodName)
// if ok {
// compIndices = append(compIndices, fi)
// }
// }
// }
//
// e.typeDesc.compositiveMethodComponentIndices[methodName] = compIndices
// }
//
// for _, ci := range compIndices {
// field := entityVal.Field(ci)
// //gwlog.Infof("Calling method %s on field %d=>%s", methodName, ci, field)
// gwutils.RunPanicless(func() {
// field.Addr().MethodByName(methodName).Call(methodIn)
// })
// }
//}
func (e *Entity) setupSaveTimer() {
e.addRawTimer(saveInterval, e.Save)
}
// SetSaveInterval sets the save interval for entity system
func SetSaveInterval(duration time.Duration) {
saveInterval = duration
gwlog.Infof("Save interval set to %s", saveInterval)
}
// Space Operations related to aoi
func (e *Entity) OnEnterAOI(otherAoi *aoi.AOI) {
e.interest(otherAoi.Data.(*Entity))
}
func (e *Entity) OnLeaveAOI(otherAoi *aoi.AOI) {
e.uninterest(otherAoi.Data.(*Entity))
}
// Interests and Uninterest among entities
func (e *Entity) interest(other *Entity) {
if e == other || e.Neighbors.Contains(other) {
gwlog.Panicf("interest multiple times: %s & %s", e, other)
}
e.Neighbors.Add(other)
e.client.sendCreateEntity(other, false)
}
func (e *Entity) uninterest(other *Entity) {
if e == other || !e.Neighbors.Contains(other) {
gwlog.Panicf("not interested yet: %s & %s", e, other)
}
e.Neighbors.Del(other)
e.client.sendDestroyEntity(other)
}
// IsNeighbor checks if other entity is a neighbor
func (e *Entity) IsNeighbor(other *Entity) bool {
return e.Neighbors.Contains(other)
}
// DistanceTo calculates the distance between two entities
func (e *Entity) DistanceTo(other *Entity) Coord {
return e.Position.DistanceTo(other.Position)
}
// Timer & Callback Management
// EntityTimerID is the type of entity timer ID
type EntityTimerID int
// IsValid returns if the EntityTimerID is still valid (not fired and not cancelled)
func (tid EntityTimerID) IsValid() bool {
return tid > 0
}
// AddCallback adds a one-time callback for the entity
//
// The callback will be cancelled if entity is destroyed
func (e *Entity) AddCallback(d time.Duration, method string, args ...interface{}) EntityTimerID {
tid := e.genTimerId()
now := time.Now()
info := &entityTimerInfo{
FireTime: now.Add(d),
Method: method,
Args: args,
Repeat: false,
}
e.timers[tid] = info
info.rawTimer = e.addRawCallback(d, func() {
e.triggerTimer(tid, false)
})
gwlog.Debugf("%s.AddCallback %s: %d", e, method, tid)
return tid
}
// AddTimer adds a repeat timer for the entity
//
// The callback will be cancelled if entity is destroyed
func (e *Entity) AddTimer(d time.Duration, method string, args ...interface{}) EntityTimerID {
if d < time.Millisecond*10 { // minimal interval for repeat timer
d = time.Millisecond * 10
}
tid := e.genTimerId()
now := time.Now()
info := &entityTimerInfo{
FireTime: now.Add(d),
RepeatInterval: d,
Method: method,
Args: args,
Repeat: true,
}
e.timers[tid] = info
info.rawTimer = e.addRawTimer(d, func() {
e.triggerTimer(tid, true)
})
gwlog.Debugf("%s.AddTimer %s: %d", e, method, tid)
return tid
}
// CancelTimer cancels the Callback / Timer
func (e *Entity) CancelTimer(tid EntityTimerID) {
timerInfo := e.timers[tid]
if timerInfo == nil {
return // timer already fired or cancelled
}
delete(e.timers, tid)
e.cancelRawTimer(timerInfo.rawTimer)
}
func (e *Entity) triggerTimer(tid EntityTimerID, isRepeat bool) {
timerInfo := e.timers[tid] // should never be nil
if !timerInfo.Repeat {
delete(e.timers, tid)
} else {
if !isRepeat {
timerInfo.rawTimer = e.addRawTimer(timerInfo.RepeatInterval, func() {
e.triggerTimer(tid, true)
})
}
now := time.Now()
timerInfo.FireTime = now.Add(timerInfo.RepeatInterval)
}
e.onCallFromLocal(timerInfo.Method, timerInfo.Args)
}
func (e *Entity) genTimerId() EntityTimerID {
e.lastTimerId += 1
tid := e.lastTimerId
return tid
}
var timersPacker = netutil.MessagePackMsgPacker{}
func (e *Entity) dumpTimers() []byte {
if len(e.timers) == 0 {
return nil
}
timers := make([]*entityTimerInfo, 0, len(e.timers))
for _, t := range e.timers {
timers = append(timers, t)
}
e.timers = nil // no more AddCallback or AddTimer
data, err := timersPacker.PackMsg(timers, nil)
if err != nil {
gwlog.TraceError("%s dump timers failed: %s", e, err)
}
//gwlog.Infof("%s dump %d timers: %v", e, len(timers), data)
return data
}
func (e *Entity) restoreTimers(data []byte) error {
if len(data) == 0 {
return nil
}
var timers []*entityTimerInfo
if err := timersPacker.UnpackMsg(data, &timers); err != nil {
return err
}
gwlog.Debugf("%s: %d timers restored: %v", e, len(timers), timers)
now := time.Now()
for _, timer := range timers {
//if timer.rawTimer != nil {
// gwlog.Panicf("raw timer should be nil")
//}
tid := e.genTimerId()
e.timers[tid] = timer
timer.rawTimer = e.addRawCallback(timer.FireTime.Sub(now), func() {
e.triggerTimer(tid, false)
})
}
return nil
}
func (e *Entity) addRawCallback(d time.Duration, cb timer.CallbackFunc) *timer.Timer {
var t *timer.Timer
t = timer.AddCallback(d, func() {
delete(e.rawTimers, t)
cb()
})
e.rawTimers[t] = struct{}{}
return t
}
func (e *Entity) addRawTimer(d time.Duration, cb timer.CallbackFunc) *timer.Timer {
t := timer.AddTimer(d, cb)
e.rawTimers[t] = struct{}{}
return t
}
func (e *Entity) cancelRawTimer(t *timer.Timer) {
delete(e.rawTimers, t)
t.Cancel()
}
func (e *Entity) clearRawTimers() {
for t := range e.rawTimers {
t.Cancel()
}
e.rawTimers = map[*timer.Timer]struct{}{}
}
// Post a function which will be executed immediately but not in the current stack frames
func (e *Entity) Post(cb func()) {
post.Post(cb)
}
// Call other entities
func (e *Entity) Call(id common.EntityID, method string, args ...interface{}) {
Call(id, method, args)
}
func (e *Entity) syncPositionYawFromClient(x, y, z Coord, yaw Yaw) {
//gwlog.Infof("%s.syncPositionYawFromClient: %v,%v,%v, Yaw %v, syncing %v", e, x, y, z, Yaw, e.SyncingFromClient)
if e.syncingFromClient {
e.setPositionYaw(Vector3{x, y, z}, yaw, true)
}
}
// SetClientSyncing set if entity infos (position, Yaw) is syncing with Client
func (e *Entity) SetClientSyncing(syncing bool) {
e.syncingFromClient = syncing
}
func (e *Entity) onCallFromLocal(methodName string, args []interface{}) {
defer func() {
err := recover() // recover from any error during RPC call
if err != nil {
gwlog.TraceError("%s.%s paniced: %s", e, methodName, err)
}
}()
rpcDesc := e.typeDesc.rpcDescs[methodName]
if rpcDesc == nil {
// rpc not found
gwlog.Panicf("%s.onCallFromLocal: Method %s is not a valid RPC, args=%v", e, methodName, args)
}
// rpc call from server
if rpcDesc.Flags&rfServer == 0 {
// can not call from server
gwlog.Panicf("%s.onCallFromLocal: Method %s can not be called from Server: flags=%v", e, methodName, rpcDesc.Flags)
}
if rpcDesc.NumArgs < len(args) {
gwlog.Panicf("%s.onCallFromLocal: Method %s receives %d arguments, but given %d", e, methodName, rpcDesc.NumArgs, len(args))
}
methodType := rpcDesc.MethodType
in := make([]reflect.Value, rpcDesc.NumArgs+1)
in[0] = e.V // first argument is the bind instance (self)
for i, arg := range args {
argType := methodType.In(i + 1)
in[i+1] = typeconv.Convert(arg, argType)
}
for i := len(args); i < rpcDesc.NumArgs; i++ { // use zero value for missing arguments
argType := methodType.In(i + 1)
in[i+1] = reflect.Zero(argType)
}
rpcDesc.Func.Call(in)
}
func (e *Entity) onCallFromRemote(methodName string, args [][]byte, clientid common.ClientID) {
defer func() {
err := recover() // recover from any error during RPC call
if err != nil {
gwlog.TraceError("%s.%s paniced: %s", e, methodName, err)
}
}()
rpcDesc := e.typeDesc.rpcDescs[methodName]
if rpcDesc == nil {
// rpc not found
gwlog.Errorf("%s.onCallFromRemote: Method %s is not a valid RPC, args=%v", e, methodName, args)
return
}
methodType := rpcDesc.MethodType
if clientid == "" {
// rpc call from server
if rpcDesc.Flags&rfServer == 0 {
// can not call from server
gwlog.Panicf("%s.onCallFromRemote: Method %s can not be called from Server: flags=%v", e, methodName, rpcDesc.Flags)
}
} else {
isFromOwnClient := clientid == e.getClientID()
if rpcDesc.Flags&rfOwnClient == 0 && isFromOwnClient {
gwlog.Panicf("%s.onCallFromRemote: Method %s can not be called from OwnClient: flags=%v", e, methodName, rpcDesc.Flags)
} else if rpcDesc.Flags&rfOtherClient == 0 && !isFromOwnClient {
gwlog.Panicf("%s.onCallFromRemote: Method %s can not be called from OtherClient: flags=%v, OwnClient=%s, OtherClient=%s", e, methodName, rpcDesc.Flags, e.getClientID(), clientid)
}
}
if rpcDesc.NumArgs < len(args) {
gwlog.Errorf("%s.onCallFromRemote: Method %s receives %d arguments, but given %d", e, methodName, rpcDesc.NumArgs, len(args))
return
}
in := make([]reflect.Value, rpcDesc.NumArgs+1)
in[0] = e.V // first argument is the bind instance (self)
for i, arg := range args {
argType := methodType.In(i + 1)
argValPtr := reflect.New(argType)
err := netutil.MSG_PACKER.UnpackMsg(arg, argValPtr.Interface())
if err != nil {
gwlog.Panicf("Convert argument %d failed: type=%s", i+1, argType.Name())
}
in[i+1] = reflect.Indirect(argValPtr)
}
for i := len(args); i < rpcDesc.NumArgs; i++ { // use zero value for missing arguments
argType := methodType.In(i + 1)
in[i+1] = reflect.Zero(argType)
}
rpcDesc.Func.Call(in)
}
// OnInit is called when entity is initializing
//
// Can override this function in custom entity type
func (e *Entity) OnInit() {
//gwlog.Warnf("%s.OnInit not implemented", e)
}
// OnAttrsReady is called when entity's attribute is ready
//
// Can override this function in custom entity type
func (e *Entity) OnAttrsReady() {
}
// OnCreated is called when entity is created
//
// Can override this function in custom entity type
func (e *Entity) OnCreated() {
//gwlog.Debugf("%s.OnCreated", e)
}
// OnFreeze is called when entity is freezed
//
// Can override this function in custom entity type
func (e *Entity) OnFreeze() {
}
// OnRestored is called when entity is restored
//
// Can override this function in custom entity type
func (e *Entity) OnRestored() {
}
// OnEnterSpace is called when entity enters space
//
// Can override this function in custom entity type
func (e *Entity) OnEnterSpace() {
if consts.DEBUG_SPACES {
gwlog.Debugf("%s.OnEnterSpace >>> %s", e, e.Space)
}
}
// OnLeaveSpace is called when entity leaves space
//
// Can override this function in custom entity type
func (e *Entity) OnLeaveSpace(space *Space) {
if consts.DEBUG_SPACES {
gwlog.Debugf("%s.OnLeaveSpace <<< %s", e, space)
}
}
// OnDestroy is called when entity is destroying
//
// Can override this function in custom entity type
func (e *Entity) OnDestroy() {
}
// Default handlers for persistence
// IsPersistent returns if the entity is persistent
//
// Default implementation check entity for persistent attributes
func (e *Entity) IsPersistent() bool {
return e.typeDesc.IsPersistent
}
// getPersistentData gets the persistent data
//
// Returns persistent attributes by default
func (e *Entity) getPersistentData() map[string]interface{} {
return e.Attrs.ToMapWithFilter(e.typeDesc.persistentAttrs.Contains)
}
// loadPersistentData loads persistent data
//
// Load persistent data to attributes
func (e *Entity) loadPersistentData(data map[string]interface{}) {
e.Attrs.AssignMap(data)
}
func (e *Entity) getClientData() map[string]interface{} {
return e.Attrs.ToMapWithFilter(e.typeDesc.clientAttrs.Contains)
}
func (e *Entity) getAllClientData() map[string]interface{} {
return e.Attrs.ToMapWithFilter(e.typeDesc.allClientAttrs.Contains)
}
// GetMigrateData gets the migration data
func (e *Entity) GetMigrateData(spaceid common.EntityID) *entityMigrateData {
md := &entityMigrateData{
Type: e.TypeName,
Attrs: e.Attrs.ToMap(), // all Attrs are migrated, without filter
Pos: e.Position,
Yaw: e.yaw,
TimerData: e.dumpTimers(),
SpaceID: spaceid,
SyncingFromClient: e.syncingFromClient,
SyncInfoFlag: e.syncInfoFlag,
}
if e.client != nil {
md.Client = &clientData{
ClientID: e.client.clientid,
GateID: e.client.gateid,
}
}
return md
}
// loadMigrateData loads migrate data
func (e *Entity) loadMigrateData(data map[string]interface{}) {
e.Attrs.AssignMap(data)
}
// getFreezeData gets freezed data
func (e *Entity) getFreezeData() *entityMigrateData {
return e.GetMigrateData(e.Space.ID)
}
// Client related utilities
// GetClient returns the Client of entity
func (e *Entity) GetClient() *GameClient {
return e.client
}
func (e *Entity) getClientID() common.ClientID {
if e.client != nil {
return e.client.clientid
}
return ""
}
// SetClient sets the Client of entity
func (e *Entity) SetClient(client *GameClient) {
oldClient := e.client
if oldClient == client {
return
}
e.client = client
if oldClient != nil {
// send destroy entity to Client
entityManager.onEntityLoseClient(oldClient.clientid)
dispatchercluster.SendClearClientFilterProp(oldClient.gateid, oldClient.clientid)
for neighbor := range e.Neighbors {
oldClient.sendDestroyEntity(neighbor)
}
oldClient.sendDestroyEntity(e)
}
if client != nil {
// send create entity to new Client
entityManager.onEntityGetClient(e.ID, client.clientid)
client.sendCreateEntity(e, true)
for neighbor := range e.Neighbors {
client.sendCreateEntity(neighbor, false)
}
}
if oldClient == nil && client != nil {
// got net Client
e.I.OnClientConnected()
//e.callCompositiveMethod("OnClientConnected")
} else if oldClient != nil && client == nil {
//e.callCompositiveMethod("OnClientDisconnected")
e.I.OnClientDisconnected()
}
}
// CallClient calls the Client entity
func (e *Entity) CallClient(method string, args ...interface{}) {
e.client.call(e.ID, method, args)
}
// CallAllClients calls the entity method on all clients
func (e *Entity) CallAllClients(method string, args ...interface{}) {
e.client.call(e.ID, method, args)
for neighbor := range e.Neighbors {
neighbor.client.call(e.ID, method, args)
}
}
// GiveClientTo gives Client to other entity
func (e *Entity) GiveClientTo(other *Entity) {
if e.client == nil {
gwlog.Warnf("%s.GiveClientTo(%s): Client is nil", e, other)
return
}
if consts.DEBUG_CLIENTS {
gwlog.Debugf("%s.GiveClientTo(%s): Client=%s", e, other, e.client)
}
client := e.client
e.SetClient(nil)
other.SetClient(client)
}
// ForAllClients visits all clients (own Client and clients of neighbors)
func (e *Entity) ForAllClients(f func(client *GameClient)) {
if e.client != nil {
f(e.client)
}
for neighbor := range e.Neighbors {
if neighbor.client != nil {
f(neighbor.client)
}
}
}
func (e *Entity) notifyClientDisconnected() {
// called when Client disconnected
if e.client == nil {
gwlog.Panic(e.client)
}
e.client = nil
e.I.OnClientDisconnected()
//e.callCompositiveMethod("OnClientDisconnected")
}
// OnClientConnected is called when Client is connected
//
// Can override this function in custom entity type
func (e *Entity) OnClientConnected() {
if consts.DEBUG_CLIENTS {
gwlog.Debugf("%s.OnClientConnected: %s, %d Neighbors", e, e.client, len(e.Neighbors))
}
}
// OnClientDisconnected is called when Client is disconnected
//
// Can override this function in custom entity type
func (e *Entity) OnClientDisconnected() {
if consts.DEBUG_CLIENTS {
gwlog.Debugf("%s.OnClientDisconnected: %s", e, e.client)
}
}
func (e *Entity) getAttrFlag(attrName string) (flag attrFlag) {
if e.typeDesc.allClientAttrs.Contains(attrName) {
flag = afAllClient
} else if e.typeDesc.clientAttrs.Contains(attrName) {
flag = afClient
}
return
}
func (e *Entity) sendMapAttrChangeToClients(ma *MapAttr, key string, val interface{}) {
var flag attrFlag
if ma == e.Attrs {
// this is the root attr
flag = e.getAttrFlag(key)
} else {
flag = ma.flag
}
if flag&afAllClient != 0 {
path := ma.getPathFromOwner()
e.client.sendNotifyMapAttrChange(e.ID, path, key, val)
for neighbor := range e.Neighbors {
neighbor.client.sendNotifyMapAttrChange(e.ID, path, key, val)
}
} else if flag&afClient != 0 {
path := ma.getPathFromOwner()
e.client.sendNotifyMapAttrChange(e.ID, path, key, val)
}
}
func (e *Entity) sendMapAttrDelToClients(ma *MapAttr, key string) {
var flag attrFlag
if ma == e.Attrs {
// this is the root attr
flag = e.getAttrFlag(key)
} else {
flag = ma.flag
}
if flag&afAllClient != 0 {
path := ma.getPathFromOwner()
e.client.sendNotifyMapAttrDel(e.ID, path, key)
for neighbor := range e.Neighbors {
neighbor.client.sendNotifyMapAttrDel(e.ID, path, key)
}
} else if flag&afClient != 0 {
path := ma.getPathFromOwner()
e.client.sendNotifyMapAttrDel(e.ID, path, key)
}
}
func (e *Entity) sendMapAttrClearToClients(ma *MapAttr) {
if ma == e.Attrs {
// this is the root attr
gwlog.Panicf("outmost e.Attrs can not be cleared")
}
flag := ma.flag
if flag&afAllClient != 0 {
path := ma.getPathFromOwner()
e.client.sendNotifyMapAttrClear(e.ID, path)
for neighbor := range e.Neighbors {
neighbor.client.sendNotifyMapAttrClear(e.ID, path)
}
} else if flag&afClient != 0 {
path := ma.getPathFromOwner()
e.client.sendNotifyMapAttrClear(e.ID, path)
}
}
func (e *Entity) sendListAttrChangeToClients(la *ListAttr, index int, val interface{}) {
flag := la.flag
if flag&afAllClient != 0 {
// TODO: only pack 1 packet, do not marshal multiple times
path := la.getPathFromOwner()
e.client.sendNotifyListAttrChange(e.ID, path, uint32(index), val)
for neighbor := range e.Neighbors {
neighbor.client.sendNotifyListAttrChange(e.ID, path, uint32(index), val)
}
} else if flag&afClient != 0 {
path := la.getPathFromOwner()
e.client.sendNotifyListAttrChange(e.ID, path, uint32(index), val)
}
}
func (e *Entity) sendListAttrPopToClients(la *ListAttr) {
flag := la.flag
if flag&afAllClient != 0 {
path := la.getPathFromOwner()
e.client.sendNotifyListAttrPop(e.ID, path)
for neighbor := range e.Neighbors {
neighbor.client.sendNotifyListAttrPop(e.ID, path)
}
} else if flag&afClient != 0 {
path := la.getPathFromOwner()
e.client.sendNotifyListAttrPop(e.ID, path)
}
}
func (e *Entity) sendListAttrAppendToClients(la *ListAttr, val interface{}) {
flag := la.flag
if flag&afAllClient != 0 {
path := la.getPathFromOwner()
e.client.sendNotifyListAttrAppend(e.ID, path, val)
for neighbor := range e.Neighbors {
neighbor.client.sendNotifyListAttrAppend(e.ID, path, val)
}
} else if flag&afClient != 0 {
path := la.getPathFromOwner()
e.client.sendNotifyListAttrAppend(e.ID, path, val)
}
}
// Define Attributes Properties
// Fast access to Attrs
// GetInt gets an outtermost attribute as int
func (e *Entity) GetInt(key string) int64 {
return e.Attrs.GetInt(key)
}
// GetBool gets an outtermost attribute as int
func (e *Entity) GetBool(key string) bool {
return e.Attrs.GetBool(key)
}
// GetStr gets an outtermost attribute as string
func (e *Entity) GetStr(key string) string {
return e.Attrs.GetStr(key)
}