StateMachine.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Company: Lynar Studios
  4. * E-Mail: webmaster@lynarstudios.com
  5. * Created: 2020-09-05
  6. * Changed: 2020-11-06
  7. *
  8. * */
  9. #include "../../../include/ls_std/logic/StateMachine.hpp"
  10. ls_std::StateMachine::StateMachine(std::string _name) :
  11. Class("StateMachine"),
  12. name(std::move(_name))
  13. {}
  14. bool ls_std::StateMachine::addState(const std::shared_ptr<State>& _state) {
  15. bool condition = !this->_hasState(_state->getId());
  16. if(condition) {
  17. this->states.insert({_state->getId(), _state});
  18. condition = this->_hasState(_state->getId());
  19. }
  20. return condition;
  21. }
  22. std::shared_ptr<ls_std::State> ls_std::StateMachine::getCurrentState() {
  23. return this->currentState;
  24. }
  25. std::vector<ls_std::StateId> ls_std::StateMachine::getMemory() {
  26. return this->memory;
  27. }
  28. std::string ls_std::StateMachine::getName() {
  29. return this->name;
  30. }
  31. std::unordered_map<ls_std::StateId, std::shared_ptr<ls_std::State>> ls_std::StateMachine::getStates()
  32. {
  33. return this->states;
  34. }
  35. bool ls_std::StateMachine::hasState(const StateId &_id)
  36. {
  37. return this->_hasState(_id);
  38. }
  39. bool ls_std::StateMachine::proceed() {
  40. std::vector<ls_std::StateId> nextValidStates = this->_getNextValidStates();
  41. bool condition = nextValidStates.size() == 1;
  42. if(condition) {
  43. this->currentState = this->states[nextValidStates.at(0)];
  44. this->_remember(nextValidStates.at(0));
  45. }
  46. return condition;
  47. }
  48. void ls_std::StateMachine::setMemory(std::vector<ls_std::StateId> _memory)
  49. {
  50. this->memory = std::move(_memory);
  51. }
  52. void ls_std::StateMachine::setName(std::string _name)
  53. {
  54. this->name = std::move(_name);
  55. }
  56. bool ls_std::StateMachine::setStartState(const ls_std::StateId&_id) {
  57. bool exists = this->_hasState(_id);
  58. if(exists) {
  59. this->currentState = this->states[_id];
  60. this->_remember(_id);
  61. }
  62. return exists;
  63. }
  64. std::vector<ls_std::StateId> ls_std::StateMachine::_getNextValidStates() {
  65. std::vector<ls_std::StateId> validStates {};
  66. for(const auto& state : this->currentState->getConnectedStates()) {
  67. if(state.second->isPassable()) {
  68. validStates.push_back(state.second->getStateId());
  69. }
  70. }
  71. return validStates;
  72. }
  73. void ls_std::StateMachine::_remember(const ls_std::StateId &_id) {
  74. this->memory.push_back(_id);
  75. }
  76. bool ls_std::StateMachine::_hasState(const ls_std::StateId &_id) {
  77. return this->states.find(_id) != this->states.end();
  78. }