rts-sim-module/simulation/system/face_system.go

72 lines
1.3 KiB
Go
Raw Normal View History

2023-08-15 16:50:24 +08:00
package system
import (
"sync"
"time"
"joylink.club/ecs"
)
// 外界与world交互请求定义
type FaceRequest func(w ecs.World) any
type faceOutcome struct {
outcome any
ok bool
}
// 外界与world的交互
type FaceSystem struct {
req chan FaceRequest
rsp chan *faceOutcome
world ecs.World
//保证与world的交互串行
locker *sync.Mutex
}
func NewFaceSystem(w ecs.World) *FaceSystem {
return &FaceSystem{req: make(chan FaceRequest), rsp: make(chan *faceOutcome), locker: &sync.Mutex{}, world: w}
}
// world 执行
func (me *FaceSystem) Update(world ecs.World) {
select {
case reqFunc := <-me.req:
{
response := reqFunc(world)
if nil != response {
me.rsp <- &faceOutcome{outcome: response, ok: true}
} else {
me.rsp <- &faceOutcome{outcome: nil, ok: false}
}
}
default:
}
}
// 外界调用此方法与world交互
func (me *FaceSystem) Call(request FaceRequest) (any, bool) {
if !me.world.Running() {
return nil, false
}
//
me.locker.Lock()
defer me.locker.Unlock()
//
me.req <- request
//
result := <-me.rsp
return result.outcome, result.ok
}
// 获取world当前时间
func (me *FaceSystem) WorldTime() *time.Time {
now, ok := me.Call(func(w ecs.World) any {
return GetWorldNow(w)
})
if ok {
return now.(*time.Time)
} else {
return nil
}
}