123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- //
- // RUStateTransition.cpp
- // RoleTool
- //
- // Created by 徐炼新 on 2023/4/19.
- //
- #include "RUStateTransition.h"
- #include "RUState.h"
- #include <stdio.h>
- NS_RU_BEGIN
- StateTransition* StateTransition::create(StateMachine* machine,
- const FsmTransition* transition,
- std::function<void(StateTransition*, std::function<void(void)>, bool)> cf) {
- auto st = new StateTransition();
- st->autorelease();
- st->retain();
- st->_machine = machine;
- st->_transition = transition;
- st->_cf = cf;
- return st;
- }
- void StateTransition::setEvent(const std::string& eventName,
- const std::map<std::string, std::string>& eventParams,
- std::function<void(void)> handleEventCb) {
- _eventName = eventName;
- _eventParams = eventParams;
- _cf4Event = handleEventCb;
- }
- void StateTransition::interrupt() {
- // 打断当前的转移
- _bIsInterrupted = true;
- }
- void StateTransition::execute() {
- // 事件结束的回调处理
- auto execHandleEventCb = [=](void){
- if (_cf) {
- auto cf = _cf;
- _cf = nullptr;
- cf(this, _cf4Event, _bIsInterrupted);
- }
- };
- /***
- 执行顺序
- 1.老状态exit
- 2.老状态before_switch_actions动作
- 3.设置新状态
- 4.新状态after_switch_actions动作
- 5.新状态entry
- 6.事件结束回调
- ***/
- State* fromState = _machine->getState(_transition->fromState);
- State* toState = _machine->getState(_transition->toState);
- const std::vector<StateActInfo>& beforeSwitchActInfos = _transition->beforeSwitchActInfos;
- const std::vector<StateActInfo>& afterSwitchActInfos = _transition->afterSwitchActInfos;
-
- auto execEntry = [=](void){
- if (_bIsInterrupted) {
- execHandleEventCb();
- } else {
- _machine->setRunningStateName(_transition->toState);
- retain();
- toState->entry([=](){
- execHandleEventCb();
- release();
- });
- }
- };
-
- auto execAfterSwitchAct = [=](void) {
- if (_bIsInterrupted) {
- execHandleEventCb();
- } else {
- StateActInfo evt;
- evt.actType = _eventName;
- evt.actParams = _eventParams;
- toState->afterSwitch(afterSwitchActInfos, evt, execEntry);
- }
- };
-
- auto execBeforeSwitchAct = [=](void) {
- if (_bIsInterrupted) {
- execHandleEventCb();
- } else {
- StateActInfo evt;
- evt.actType = _eventName;
- evt.actParams = _eventParams;
- fromState->beforeSwitch(beforeSwitchActInfos, evt, execAfterSwitchAct);
- }
- };
- fromState->exit(execBeforeSwitchAct);
- }
- NS_RU_END
|