StateMachine.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. #include <utility>
  11. ls_std::StateMachine::StateMachine(std::string _name) :
  12. Class("StateMachine"),
  13. name(std::move(_name))
  14. {}
  15. bool ls_std::StateMachine::addState(const std::shared_ptr<State>& _state) {
  16. bool condition = !this->_hasState(_state->getId());
  17. if(condition) {
  18. this->states.insert({_state->getId(), _state});
  19. condition = this->_hasState(_state->getId());
  20. }
  21. return condition;
  22. }
  23. std::shared_ptr<ls_std::State> ls_std::StateMachine::getCurrentState() {
  24. return this->currentState;
  25. }
  26. std::vector<ls_std::StateId> ls_std::StateMachine::getMemory() {
  27. return this->memory;
  28. }
  29. std::string ls_std::StateMachine::getName() {
  30. return this->name;
  31. }
  32. std::unordered_map<ls_std::StateId, std::shared_ptr<ls_std::State>> ls_std::StateMachine::getStates()
  33. {
  34. return this->states;
  35. }
  36. bool ls_std::StateMachine::hasState(const StateId &_id)
  37. {
  38. return this->_hasState(_id);
  39. }
  40. bool ls_std::StateMachine::proceed() {
  41. std::vector<ls_std::StateId> nextValidStates = this->_getNextValidStates();
  42. bool condition = nextValidStates.size() == 1;
  43. if(condition) {
  44. this->currentState = this->states[nextValidStates.at(0)];
  45. this->_remember(nextValidStates.at(0));
  46. }
  47. return condition;
  48. }
  49. void ls_std::StateMachine::setMemory(std::vector<ls_std::StateId> _memory)
  50. {
  51. this->memory = std::move(_memory);
  52. }
  53. void ls_std::StateMachine::setName(std::string _name)
  54. {
  55. this->name = std::move(_name);
  56. }
  57. bool ls_std::StateMachine::setStartState(const ls_std::StateId&_id) {
  58. bool exists = this->_hasState(_id);
  59. if(exists) {
  60. this->currentState = this->states[_id];
  61. this->_remember(_id);
  62. }
  63. return exists;
  64. }
  65. std::vector<ls_std::StateId> ls_std::StateMachine::_getNextValidStates() {
  66. std::vector<ls_std::StateId> validStates {};
  67. for(const auto& state : this->currentState->getConnectedStates()) {
  68. if(state.second->isPassable()) {
  69. validStates.push_back(state.second->getStateId());
  70. }
  71. }
  72. return validStates;
  73. }
  74. void ls_std::StateMachine::_remember(const ls_std::StateId &_id) {
  75. this->memory.push_back(_id);
  76. }
  77. bool ls_std::StateMachine::_hasState(const ls_std::StateId &_id) {
  78. return this->states.find(_id) != this->states.end();
  79. }