1 #include "Application.h"
4 #include "../sdl/InitScreen.h"
10 Application::Application(sdl::InitScreen &screen, State *initialState)
13 , last(SDL_GetTicks())
14 , inStateChage(false) {
15 assert(initialState && "cannot create application without initial state");
16 RealPushState(initialState);
19 Application::~Application() {
24 State *Application::CurrentState() {
25 return states.empty() ? 0 : states.top();
28 void Application::UpdateState() {
30 while (!stateChanges.empty()) {
31 switch (stateChanges.front().type) {
32 case StateCommand::PUSH:
33 RealPushState(stateChanges.front().state);
35 case StateCommand::POP:
38 case StateCommand::CHANGE:
39 RealChangeState(stateChanges.front().state);
47 void Application::ChangeState(State *s) {
52 cmd.type = StateCommand::CHANGE;
54 stateChanges.push(cmd);
58 void Application::PushState(State *s) {
63 cmd.type = StateCommand::PUSH;
65 stateChanges.push(cmd);
69 void Application::PopState() {
74 cmd.type = StateCommand::POP;
76 stateChanges.push(cmd);
80 void Application::RealChangeState(State *s) {
81 if (!states.empty()) {
82 states.top()->PauseState(screen.Screen());
83 states.top()->ExitState(*this, screen.Screen());
87 s->EnterState(*this, screen.Screen());
88 s->ResumeState(screen.Screen());
91 void Application::RealPushState(State *s) {
92 if (!states.empty()) {
93 states.top()->PauseState(screen.Screen());
96 s->EnterState(*this, screen.Screen());
97 s->ResumeState(screen.Screen());
100 void Application::RealPopState() {
101 if (states.empty()) return;
102 states.top()->PauseState(screen.Screen());
103 states.top()->ExitState(*this, screen.Screen());
106 if (!states.empty()) {
107 states.top()->ResumeState(screen.Screen());
111 void Application::Quit() {
115 void Application::PopAllStates() {
116 while (!states.empty()) {
117 states.top()->PauseState(screen.Screen());
118 states.top()->ExitState(*this, screen.Screen());
125 void Application::Run() {
126 while (CurrentState()) {
131 void Application::Loop() {
132 Uint32 now(SDL_GetTicks());
133 Uint32 deltaT(now - last);
134 GlobalTimers().Update(deltaT);
135 if (deltaT > 30) deltaT = 30;
137 if (CurrentState()) {
138 CurrentState()->GraphicsTimers().Update(deltaT);
141 if (!StateChangePending()) {
151 void Application::HandleEvents() {
152 if (!CurrentState()) return;
153 input.ResetInteractiveState();
155 while (SDL_PollEvent(&event)) {
156 switch (event.type) {
160 case SDL_VIDEORESIZE:
161 screen.Resize(event.resize.w, event.resize.h);
162 CurrentState()->Resize(event.resize.w, event.resize.h);
166 input.HandleKeyboardEvent(event.key);
173 if (CurrentState()) CurrentState()->HandleEvents(input);
176 void Application::UpdateWorld(Uint32 deltaT) {
177 if (!CurrentState()) return;
178 for (Uint32 i(0); i < deltaT && !StateChangePending(); ++i) {
179 CurrentState()->PhysicsTimers().Update(1);
180 CurrentState()->UpdateWorld(1);
184 void Application::Render(void) {
185 if (!CurrentState()) return;
186 CurrentState()->Render(screen.Screen());