ICT290 / src / engine / stateManager.cpp
stateManager.cpp
Raw
#include "stateManager.h"

void StateManager::push(const std::shared_ptr<State>& state) {
    m_states.push(state);
}

void StateManager::pop() {
    m_states.pop();
}

std::shared_ptr<State> StateManager::top() {
    if (!m_states.empty()) {
        // If a new state has been queued
        if (m_states.top()->newState != nullptr) {
            // Store the next state
            auto nextState = m_states.top()->newState;
            // Check if state has set to pop itself on push
            if (m_states.top()->stop) {
                // Destroy & pop current state
                m_states.top()->destroy();
                m_states.pop();
                // unpause the next state
                nextState->pause(false);
                // push the next state
                m_states.push(nextState);
            } else {
                // Pause the current state
                m_states.top()->pause(true);
                // Set the current states next state to nullptr
                m_states.top()->newState = nullptr;
                // unpause the next state
                nextState->pause(false);
                // Push the next state
                m_states.push(nextState);
            }
        }
        // If the current state has set itself too shutdown
        if (m_states.top()->stop) {
            m_states.top()->pause(true);
            m_states.top()->destroy();
            m_states.pop();
            // If there is another state unpause it
            if (!m_states.empty()) {
                m_states.top()->pause(false);
            }
        }
        // Return the top state if there is one
        if (!m_states.empty() && m_states.top() != nullptr) {
            // Reset the new state
            m_states.top()->newState = nullptr;
            return m_states.top();
        }
    }
    // If there are no sates return nullptr
    return nullptr;
}