2 // Copyright (C) 2008 Albert Brown
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>
17 // engine_core: operates subsystems when registered. Controls timing
29 void engine_subsystem::tick(state
&s
)
31 // To be overloaded by derived subsystems
35 engine_core
*engine_core::_instance
= NULL
;
37 engine_core::engine_core(int argc
, char *argv
[])
39 // This is cleaner then waiting for the libraries to throw a fit
41 throw std::logic_error("Only one engine_core instance "
42 "at a time, please.");
44 // Init SDL (nothing window/video/audio related
45 if(SDL_Init(SDL_INIT_EVERYTHING
))
47 // Something went wrong
48 std::string msg
= std::string("SDL failed to initialize: ")
50 throw std::runtime_error(msg
.c_str());
53 std::cout
<< "engine_core initialized." << std::endl
;
57 engine_core::~engine_core()
63 std::cout
<< "engine_core shut down." << std::endl
;
66 static bool subsystem_order_sort(std::pair
<int, engine_subsystem
*> a
,
67 std::pair
<int, engine_subsystem
*> b
)
69 return (a
.first
< b
.first
);
72 void engine_core::register_subsystem(engine_subsystem
*sys
, int order
)
74 _subsystems
.push_back(std::pair
<int, engine_subsystem
*>(order
, sys
));
75 _subsystems
.sort(subsystem_order_sort
);
78 void engine_core::release_subsystem(engine_subsystem
*sys
)
80 std::list
<std::pair
<int, engine_subsystem
*> >::iterator it
;
82 for(it
= _subsystems
.begin(); it
!= _subsystems
.end(); ++it
)
84 if(sys
== (*it
).second
)
86 _subsystems
.erase(it
);
91 if(it
== _subsystems
.end())
92 throw std::runtime_error("Can't release subsystem not registered "
97 void engine_core::run()
101 // TODO: when we have a conf system, we can un-hardcode these values
102 _state
.running
= true;
103 _state
.time
= SDL_GetTicks();
104 _state
.tickrate
= 15;
107 while(_state
.running
)
109 //std::cout << _subsystems.size() << std::endl;
110 // we'll never get a signal to stop if there are no active subsystems
111 if(_subsystems
.empty())
113 std::cerr
<< "Run engine with no subsystems??" << std::endl
;
117 // Run each subsystem's 'tick' function
118 std::list
<std::pair
<int, engine_subsystem
*> >::iterator it
;
119 for(it
= _subsystems
.begin(); it
!= _subsystems
.end(); ++it
)
120 (*it
).second
->tick(_state
);
122 time2
= SDL_GetTicks();
123 if(time2
< (_state
.time
+= (1000 / _state
.tickrate
)))
124 SDL_Delay(_state
.time
- time2
);