Game.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. #include "Base.h"
  2. #include "Game.h"
  3. #include "Platform.h"
  4. #include "RenderState.h"
  5. #include "FileSystem.h"
  6. #include "FrameBuffer.h"
  7. #include "SceneLoader.h"
  8. /** @script{ignore} */
  9. GLenum __gl_error_code = GL_NO_ERROR;
  10. /** @script{ignore} */
  11. ALenum __al_error_code = AL_NO_ERROR;
  12. namespace gameplay
  13. {
  14. static Game* __gameInstance = NULL;
  15. double Game::_pausedTimeLast = 0.0;
  16. double Game::_pausedTimeTotal = 0.0;
  17. Game::Game()
  18. : _initialized(false), _state(UNINITIALIZED), _pausedCount(0),
  19. _frameLastFPS(0), _frameCount(0), _frameRate(0),
  20. _clearDepth(1.0f), _clearStencil(0), _properties(NULL),
  21. _animationController(NULL), _audioController(NULL),
  22. _physicsController(NULL), _aiController(NULL), _audioListener(NULL),
  23. _timeEvents(NULL), _scriptController(NULL), _scriptListeners(NULL)
  24. {
  25. GP_ASSERT(__gameInstance == NULL);
  26. __gameInstance = this;
  27. _timeEvents = new std::priority_queue<TimeEvent, std::vector<TimeEvent>, std::less<TimeEvent> >();
  28. }
  29. Game::~Game()
  30. {
  31. SAFE_DELETE(_scriptController);
  32. // Do not call any virtual functions from the destructor.
  33. // Finalization is done from outside this class.
  34. SAFE_DELETE(_timeEvents);
  35. #ifdef GAMEPLAY_MEM_LEAK_DETECTION
  36. Ref::printLeaks();
  37. printMemoryLeaks();
  38. #endif
  39. }
  40. Game* Game::getInstance()
  41. {
  42. GP_ASSERT(__gameInstance);
  43. return __gameInstance;
  44. }
  45. double Game::getAbsoluteTime()
  46. {
  47. return Platform::getAbsoluteTime();
  48. }
  49. double Game::getGameTime()
  50. {
  51. return Platform::getAbsoluteTime() - _pausedTimeTotal;
  52. }
  53. void Game::setVsync(bool enable)
  54. {
  55. Platform::setVsync(enable);
  56. }
  57. bool Game::isVsync()
  58. {
  59. return Platform::isVsync();
  60. }
  61. int Game::run()
  62. {
  63. if (_state != UNINITIALIZED)
  64. return -1;
  65. loadConfig();
  66. _width = Platform::getDisplayWidth();
  67. _height = Platform::getDisplayHeight();
  68. // Start up game systems.
  69. if (!startup())
  70. {
  71. shutdown();
  72. return -2;
  73. }
  74. return 0;
  75. }
  76. bool Game::startup()
  77. {
  78. if (_state != UNINITIALIZED)
  79. return false;
  80. setViewport(Rectangle(0.0f, 0.0f, (float)_width, (float)_height));
  81. RenderState::initialize();
  82. FrameBuffer::initialize();
  83. _animationController = new AnimationController();
  84. _animationController->initialize();
  85. _audioController = new AudioController();
  86. _audioController->initialize();
  87. _physicsController = new PhysicsController();
  88. _physicsController->initialize();
  89. _aiController = new AIController();
  90. _aiController->initialize();
  91. _scriptController = new ScriptController();
  92. _scriptController->initialize();
  93. // Load any gamepads, ui or physical.
  94. loadGamepads();
  95. // Set the script callback functions.
  96. if (_properties)
  97. {
  98. Properties* scripts = _properties->getNamespace("scripts", true);
  99. if (scripts)
  100. {
  101. const char* name;
  102. while ((name = scripts->getNextProperty()) != NULL)
  103. {
  104. ScriptController::ScriptCallback callback = ScriptController::toCallback(name);
  105. if (callback != ScriptController::INVALID_CALLBACK)
  106. {
  107. std::string url = scripts->getString();
  108. std::string file;
  109. std::string id;
  110. splitURL(url, &file, &id);
  111. if (file.size() <= 0 || id.size() <= 0)
  112. {
  113. GP_ERROR("Invalid %s script callback function '%s'.", name, url.c_str());
  114. }
  115. else
  116. {
  117. _scriptController->loadScript(file.c_str());
  118. _scriptController->registerCallback(callback, id);
  119. }
  120. }
  121. else
  122. {
  123. // Ignore everything else.
  124. }
  125. }
  126. }
  127. }
  128. _state = RUNNING;
  129. return true;
  130. }
  131. void Game::shutdown()
  132. {
  133. // Call user finalization.
  134. if (_state != UNINITIALIZED)
  135. {
  136. GP_ASSERT(_animationController);
  137. GP_ASSERT(_audioController);
  138. GP_ASSERT(_physicsController);
  139. GP_ASSERT(_aiController);
  140. Platform::signalShutdown();
  141. // Call user finalize
  142. finalize();
  143. // Shutdown scripting system first so that any objects allocated in script are released before our subsystems are released
  144. _scriptController->finalizeGame();
  145. if (_scriptListeners)
  146. {
  147. for (size_t i = 0; i < _scriptListeners->size(); i++)
  148. {
  149. SAFE_DELETE((*_scriptListeners)[i]);
  150. }
  151. SAFE_DELETE(_scriptListeners);
  152. }
  153. _scriptController->finalize();
  154. std::vector<Gamepad*>* gamepads = Gamepad::getGamepads();
  155. if (gamepads)
  156. {
  157. for (size_t i = 0, count = gamepads->size(); i < count; ++i)
  158. {
  159. SAFE_DELETE((*gamepads)[i]);
  160. }
  161. gamepads->clear();
  162. }
  163. _animationController->finalize();
  164. SAFE_DELETE(_animationController);
  165. _audioController->finalize();
  166. SAFE_DELETE(_audioController);
  167. _physicsController->finalize();
  168. SAFE_DELETE(_physicsController);
  169. _aiController->finalize();
  170. SAFE_DELETE(_aiController);
  171. // Note: we do not clean up the script controller here
  172. // because users can call Game::exit() from a script.
  173. SAFE_DELETE(_audioListener);
  174. RenderState::finalize();
  175. SAFE_DELETE(_properties);
  176. _state = UNINITIALIZED;
  177. }
  178. }
  179. void Game::pause()
  180. {
  181. if (_state == RUNNING)
  182. {
  183. GP_ASSERT(_animationController);
  184. GP_ASSERT(_audioController);
  185. GP_ASSERT(_physicsController);
  186. GP_ASSERT(_aiController);
  187. _state = PAUSED;
  188. _pausedTimeLast = Platform::getAbsoluteTime();
  189. _animationController->pause();
  190. _audioController->pause();
  191. _physicsController->pause();
  192. _aiController->pause();
  193. }
  194. ++_pausedCount;
  195. }
  196. void Game::resume()
  197. {
  198. if (_state == PAUSED)
  199. {
  200. --_pausedCount;
  201. if (_pausedCount == 0)
  202. {
  203. GP_ASSERT(_animationController);
  204. GP_ASSERT(_audioController);
  205. GP_ASSERT(_physicsController);
  206. GP_ASSERT(_aiController);
  207. _state = RUNNING;
  208. _pausedTimeTotal += Platform::getAbsoluteTime() - _pausedTimeLast;
  209. _animationController->resume();
  210. _audioController->resume();
  211. _physicsController->resume();
  212. _aiController->resume();
  213. }
  214. }
  215. }
  216. void Game::exit()
  217. {
  218. // Schedule a call to shutdown rather than calling it right away.
  219. // This handles the case of shutting down the script system from
  220. // within a script function (which can cause errors).
  221. static ShutdownListener listener;
  222. schedule(0, &listener);
  223. }
  224. void Game::frame()
  225. {
  226. if (!_initialized)
  227. {
  228. initialize();
  229. _scriptController->initializeGame();
  230. _initialized = true;
  231. }
  232. static double lastFrameTime = Game::getGameTime();
  233. double frameTime = getGameTime();
  234. // Fire time events to scheduled TimeListeners
  235. fireTimeEvents(frameTime);
  236. if (_state == Game::RUNNING)
  237. {
  238. GP_ASSERT(_animationController);
  239. GP_ASSERT(_audioController);
  240. GP_ASSERT(_physicsController);
  241. GP_ASSERT(_aiController);
  242. // Update Time.
  243. float elapsedTime = (frameTime - lastFrameTime);
  244. lastFrameTime = frameTime;
  245. // Update the scheduled and running animations.
  246. _animationController->update(elapsedTime);
  247. // Update the physics.
  248. _physicsController->update(elapsedTime);
  249. // Update AI.
  250. _aiController->update(elapsedTime);
  251. // Application Update.
  252. update(elapsedTime);
  253. // Run script update.
  254. _scriptController->update(elapsedTime);
  255. // Audio Rendering.
  256. _audioController->update(elapsedTime);
  257. // Graphics Rendering.
  258. render(elapsedTime);
  259. // Run script render.
  260. _scriptController->render(elapsedTime);
  261. // Update FPS.
  262. ++_frameCount;
  263. if ((Game::getGameTime() - _frameLastFPS) >= 1000)
  264. {
  265. _frameRate = _frameCount;
  266. _frameCount = 0;
  267. _frameLastFPS = getGameTime();
  268. }
  269. }
  270. else if (_state == Game::PAUSED)
  271. {
  272. // Application Update.
  273. update(0);
  274. // Script update.
  275. _scriptController->update(0);
  276. // Graphics Rendering.
  277. render(0);
  278. // Script render.
  279. _scriptController->render(0);
  280. }
  281. }
  282. void Game::renderOnce(const char* function)
  283. {
  284. _scriptController->executeFunction<void>(function, NULL);
  285. Platform::swapBuffers();
  286. }
  287. void Game::updateOnce()
  288. {
  289. GP_ASSERT(_animationController);
  290. GP_ASSERT(_audioController);
  291. GP_ASSERT(_physicsController);
  292. GP_ASSERT(_aiController);
  293. // Update Time.
  294. static double lastFrameTime = getGameTime();
  295. double frameTime = getGameTime();
  296. float elapsedTime = (frameTime - lastFrameTime);
  297. lastFrameTime = frameTime;
  298. // Update the internal controllers.
  299. _animationController->update(elapsedTime);
  300. _physicsController->update(elapsedTime);
  301. _aiController->update(elapsedTime);
  302. _audioController->update(elapsedTime);
  303. _scriptController->update(elapsedTime);
  304. }
  305. void Game::setViewport(const Rectangle& viewport)
  306. {
  307. _viewport = viewport;
  308. glViewport((GLuint)viewport.x, (GLuint)viewport.y, (GLuint)viewport.width, (GLuint)viewport.height);
  309. }
  310. void Game::clear(ClearFlags flags, const Vector4& clearColor, float clearDepth, int clearStencil)
  311. {
  312. GLbitfield bits = 0;
  313. if (flags & CLEAR_COLOR)
  314. {
  315. if (clearColor.x != _clearColor.x ||
  316. clearColor.y != _clearColor.y ||
  317. clearColor.z != _clearColor.z ||
  318. clearColor.w != _clearColor.w )
  319. {
  320. glClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
  321. _clearColor.set(clearColor);
  322. }
  323. bits |= GL_COLOR_BUFFER_BIT;
  324. }
  325. if (flags & CLEAR_DEPTH)
  326. {
  327. if (clearDepth != _clearDepth)
  328. {
  329. glClearDepth(clearDepth);
  330. _clearDepth = clearDepth;
  331. }
  332. bits |= GL_DEPTH_BUFFER_BIT;
  333. // We need to explicitly call the static enableDepthWrite() method on StateBlock
  334. // to ensure depth writing is enabled before clearing the depth buffer (and to
  335. // update the global StateBlock render state to reflect this).
  336. RenderState::StateBlock::enableDepthWrite();
  337. }
  338. if (flags & CLEAR_STENCIL)
  339. {
  340. if (clearStencil != _clearStencil)
  341. {
  342. glClearStencil(clearStencil);
  343. _clearStencil = clearStencil;
  344. }
  345. bits |= GL_STENCIL_BUFFER_BIT;
  346. }
  347. glClear(bits);
  348. }
  349. void Game::clear(ClearFlags flags, float red, float green, float blue, float alpha, float clearDepth, int clearStencil)
  350. {
  351. clear(flags, Vector4(red, green, blue, alpha), clearDepth, clearStencil);
  352. }
  353. AudioListener* Game::getAudioListener()
  354. {
  355. if (_audioListener == NULL)
  356. {
  357. _audioListener = new AudioListener();
  358. }
  359. return _audioListener;
  360. }
  361. void Game::menuEvent()
  362. {
  363. }
  364. void Game::keyEvent(Keyboard::KeyEvent evt, int key)
  365. {
  366. }
  367. void Game::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
  368. {
  369. }
  370. bool Game::mouseEvent(Mouse::MouseEvent evt, int x, int y, int wheelDelta)
  371. {
  372. return false;
  373. }
  374. bool Game::isGestureSupported(Gesture::GestureEvent evt)
  375. {
  376. return Platform::isGestureSupported(evt);
  377. }
  378. void Game::registerGesture(Gesture::GestureEvent evt)
  379. {
  380. Platform::registerGesture(evt);
  381. }
  382. void Game::unregisterGesture(Gesture::GestureEvent evt)
  383. {
  384. Platform::unregisterGesture(evt);
  385. }
  386. bool Game::isGestureRegistered(Gesture::GestureEvent evt)
  387. {
  388. return Platform::isGestureRegistered(evt);
  389. }
  390. void Game::gestureSwipeEvent(int x, int y, int direction)
  391. {
  392. }
  393. void Game::gesturePinchEvent(int x, int y, float scale)
  394. {
  395. }
  396. void Game::gestureTapEvent(int x, int y)
  397. {
  398. }
  399. void Game::gamepadEvent(Gamepad::GamepadEvent evt, Gamepad* gamepad)
  400. {
  401. }
  402. void Game::schedule(float timeOffset, TimeListener* timeListener, void* cookie)
  403. {
  404. GP_ASSERT(_timeEvents);
  405. TimeEvent timeEvent(getGameTime() + timeOffset, timeListener, cookie);
  406. _timeEvents->push(timeEvent);
  407. }
  408. void Game::schedule(float timeOffset, const char* function)
  409. {
  410. if (!_scriptListeners)
  411. _scriptListeners = new std::vector<ScriptListener*>();
  412. ScriptListener* listener = new ScriptListener(function);
  413. _scriptListeners->push_back(listener);
  414. schedule(timeOffset, listener, NULL);
  415. }
  416. void Game::fireTimeEvents(double frameTime)
  417. {
  418. while (_timeEvents->size() > 0)
  419. {
  420. const TimeEvent* timeEvent = &_timeEvents->top();
  421. if (timeEvent->time > frameTime)
  422. {
  423. break;
  424. }
  425. if (timeEvent->listener)
  426. {
  427. timeEvent->listener->timeEvent(frameTime - timeEvent->time, timeEvent->cookie);
  428. }
  429. _timeEvents->pop();
  430. }
  431. }
  432. Game::ScriptListener::ScriptListener(const char* url)
  433. {
  434. function = Game::getInstance()->getScriptController()->loadUrl(url);
  435. }
  436. void Game::ScriptListener::timeEvent(long timeDiff, void* cookie)
  437. {
  438. Game::getInstance()->getScriptController()->executeFunction<void>(function.c_str(), "l", timeDiff);
  439. }
  440. Game::TimeEvent::TimeEvent(double time, TimeListener* timeListener, void* cookie)
  441. : time(time), listener(timeListener), cookie(cookie)
  442. {
  443. }
  444. bool Game::TimeEvent::operator<(const TimeEvent& v) const
  445. {
  446. // The first element of std::priority_queue is the greatest.
  447. return time > v.time;
  448. }
  449. Properties* Game::getConfig() const
  450. {
  451. if (_properties == NULL)
  452. const_cast<Game*>(this)->loadConfig();
  453. return _properties;
  454. }
  455. void Game::loadConfig()
  456. {
  457. if (_properties == NULL)
  458. {
  459. // Try to load custom config from file.
  460. if (FileSystem::fileExists("game.config"))
  461. {
  462. _properties = Properties::create("game.config");
  463. // Load filesystem aliases.
  464. Properties* aliases = _properties->getNamespace("aliases", true);
  465. if (aliases)
  466. {
  467. FileSystem::loadResourceAliases(aliases);
  468. }
  469. }
  470. else
  471. {
  472. // Create an empty config
  473. _properties = new Properties();
  474. }
  475. }
  476. }
  477. void Game::loadGamepads()
  478. {
  479. // Load virtual gamepads.
  480. if (_properties)
  481. {
  482. // Check if there are any virtual gamepads included in the .config file.
  483. // If there are, create and initialize them.
  484. Properties* gamepadProperties = _properties->getNamespace("gamepads", true);
  485. if (gamepadProperties && gamepadProperties->exists("form"))
  486. {
  487. const char* gamepadFormPath = gamepadProperties->getString("form");
  488. GP_ASSERT(gamepadFormPath);
  489. Gamepad* gamepad = Gamepad::add(gamepadFormPath);
  490. GP_ASSERT(gamepad);
  491. }
  492. }
  493. }
  494. void Game::ShutdownListener::timeEvent(long timeDiff, void* cookie)
  495. {
  496. Game::getInstance()->shutdown();
  497. }
  498. }