Game.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. unsigned int gamepadCount = Gamepad::getGamepadCount();
  155. for (unsigned int i = 0; i < gamepadCount; i++)
  156. {
  157. Gamepad* gamepad = Gamepad::getGamepad(i, false);
  158. SAFE_DELETE(gamepad);
  159. }
  160. _animationController->finalize();
  161. SAFE_DELETE(_animationController);
  162. _audioController->finalize();
  163. SAFE_DELETE(_audioController);
  164. _physicsController->finalize();
  165. SAFE_DELETE(_physicsController);
  166. _aiController->finalize();
  167. SAFE_DELETE(_aiController);
  168. // Note: we do not clean up the script controller here
  169. // because users can call Game::exit() from a script.
  170. SAFE_DELETE(_audioListener);
  171. FrameBuffer::finalize();
  172. RenderState::finalize();
  173. SAFE_DELETE(_properties);
  174. _state = UNINITIALIZED;
  175. }
  176. }
  177. void Game::pause()
  178. {
  179. if (_state == RUNNING)
  180. {
  181. GP_ASSERT(_animationController);
  182. GP_ASSERT(_audioController);
  183. GP_ASSERT(_physicsController);
  184. GP_ASSERT(_aiController);
  185. _state = PAUSED;
  186. _pausedTimeLast = Platform::getAbsoluteTime();
  187. _animationController->pause();
  188. _audioController->pause();
  189. _physicsController->pause();
  190. _aiController->pause();
  191. }
  192. ++_pausedCount;
  193. }
  194. void Game::resume()
  195. {
  196. if (_state == PAUSED)
  197. {
  198. --_pausedCount;
  199. if (_pausedCount == 0)
  200. {
  201. GP_ASSERT(_animationController);
  202. GP_ASSERT(_audioController);
  203. GP_ASSERT(_physicsController);
  204. GP_ASSERT(_aiController);
  205. _state = RUNNING;
  206. _pausedTimeTotal += Platform::getAbsoluteTime() - _pausedTimeLast;
  207. _animationController->resume();
  208. _audioController->resume();
  209. _physicsController->resume();
  210. _aiController->resume();
  211. }
  212. }
  213. }
  214. void Game::exit()
  215. {
  216. // Only perform a full/clean shutdown if FORCE_CLEAN_SHUTDOWN or
  217. // GAMEPLAY_MEM_LEAK_DETECTION is defined. Every modern OS is able to
  218. // handle reclaiming process memory hundreds of times faster than it
  219. // would take us to go through every pointer in the engine and release
  220. // them nicely. For large games, shutdown can end up taking long time,
  221. // so we'll just call ::exit(0) to force an instant shutdown.
  222. #if defined FORCE_CLEAN_SHUTDOWN || defined GAMEPLAY_MEM_LEAK_DETECTION
  223. // Schedule a call to shutdown rather than calling it right away.
  224. // This handles the case of shutting down the script system from
  225. // within a script function (which can cause errors).
  226. static ShutdownListener listener;
  227. schedule(0, &listener);
  228. #else
  229. // End the process immediately without a full shutdown
  230. ::exit(0);
  231. #endif
  232. }
  233. void Game::frame()
  234. {
  235. if (!_initialized)
  236. {
  237. initialize();
  238. _scriptController->initializeGame();
  239. _initialized = true;
  240. }
  241. static double lastFrameTime = Game::getGameTime();
  242. double frameTime = getGameTime();
  243. // Fire time events to scheduled TimeListeners
  244. fireTimeEvents(frameTime);
  245. if (_state == Game::RUNNING)
  246. {
  247. GP_ASSERT(_animationController);
  248. GP_ASSERT(_audioController);
  249. GP_ASSERT(_physicsController);
  250. GP_ASSERT(_aiController);
  251. // Update Time.
  252. float elapsedTime = (frameTime - lastFrameTime);
  253. lastFrameTime = frameTime;
  254. // Update the scheduled and running animations.
  255. _animationController->update(elapsedTime);
  256. // Update the physics.
  257. _physicsController->update(elapsedTime);
  258. // Update AI.
  259. _aiController->update(elapsedTime);
  260. // Application Update.
  261. update(elapsedTime);
  262. // Run script update.
  263. _scriptController->update(elapsedTime);
  264. // Audio Rendering.
  265. _audioController->update(elapsedTime);
  266. // Graphics Rendering.
  267. render(elapsedTime);
  268. // Run script render.
  269. _scriptController->render(elapsedTime);
  270. // Update FPS.
  271. ++_frameCount;
  272. if ((Game::getGameTime() - _frameLastFPS) >= 1000)
  273. {
  274. _frameRate = _frameCount;
  275. _frameCount = 0;
  276. _frameLastFPS = getGameTime();
  277. }
  278. }
  279. else if (_state == Game::PAUSED)
  280. {
  281. // Application Update.
  282. update(0);
  283. // Script update.
  284. _scriptController->update(0);
  285. // Graphics Rendering.
  286. render(0);
  287. // Script render.
  288. _scriptController->render(0);
  289. }
  290. }
  291. void Game::renderOnce(const char* function)
  292. {
  293. _scriptController->executeFunction<void>(function, NULL);
  294. Platform::swapBuffers();
  295. }
  296. void Game::updateOnce()
  297. {
  298. GP_ASSERT(_animationController);
  299. GP_ASSERT(_audioController);
  300. GP_ASSERT(_physicsController);
  301. GP_ASSERT(_aiController);
  302. // Update Time.
  303. static double lastFrameTime = getGameTime();
  304. double frameTime = getGameTime();
  305. float elapsedTime = (frameTime - lastFrameTime);
  306. lastFrameTime = frameTime;
  307. // Update the internal controllers.
  308. _animationController->update(elapsedTime);
  309. _physicsController->update(elapsedTime);
  310. _aiController->update(elapsedTime);
  311. _audioController->update(elapsedTime);
  312. _scriptController->update(elapsedTime);
  313. }
  314. void Game::setViewport(const Rectangle& viewport)
  315. {
  316. _viewport = viewport;
  317. glViewport((GLuint)viewport.x, (GLuint)viewport.y, (GLuint)viewport.width, (GLuint)viewport.height);
  318. }
  319. void Game::clear(ClearFlags flags, const Vector4& clearColor, float clearDepth, int clearStencil)
  320. {
  321. GLbitfield bits = 0;
  322. if (flags & CLEAR_COLOR)
  323. {
  324. if (clearColor.x != _clearColor.x ||
  325. clearColor.y != _clearColor.y ||
  326. clearColor.z != _clearColor.z ||
  327. clearColor.w != _clearColor.w )
  328. {
  329. glClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
  330. _clearColor.set(clearColor);
  331. }
  332. bits |= GL_COLOR_BUFFER_BIT;
  333. }
  334. if (flags & CLEAR_DEPTH)
  335. {
  336. if (clearDepth != _clearDepth)
  337. {
  338. glClearDepth(clearDepth);
  339. _clearDepth = clearDepth;
  340. }
  341. bits |= GL_DEPTH_BUFFER_BIT;
  342. // We need to explicitly call the static enableDepthWrite() method on StateBlock
  343. // to ensure depth writing is enabled before clearing the depth buffer (and to
  344. // update the global StateBlock render state to reflect this).
  345. RenderState::StateBlock::enableDepthWrite();
  346. }
  347. if (flags & CLEAR_STENCIL)
  348. {
  349. if (clearStencil != _clearStencil)
  350. {
  351. glClearStencil(clearStencil);
  352. _clearStencil = clearStencil;
  353. }
  354. bits |= GL_STENCIL_BUFFER_BIT;
  355. }
  356. glClear(bits);
  357. }
  358. void Game::clear(ClearFlags flags, float red, float green, float blue, float alpha, float clearDepth, int clearStencil)
  359. {
  360. clear(flags, Vector4(red, green, blue, alpha), clearDepth, clearStencil);
  361. }
  362. AudioListener* Game::getAudioListener()
  363. {
  364. if (_audioListener == NULL)
  365. {
  366. _audioListener = new AudioListener();
  367. }
  368. return _audioListener;
  369. }
  370. void Game::menuEvent()
  371. {
  372. }
  373. void Game::keyEvent(Keyboard::KeyEvent evt, int key)
  374. {
  375. }
  376. void Game::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
  377. {
  378. }
  379. bool Game::mouseEvent(Mouse::MouseEvent evt, int x, int y, int wheelDelta)
  380. {
  381. return false;
  382. }
  383. bool Game::isGestureSupported(Gesture::GestureEvent evt)
  384. {
  385. return Platform::isGestureSupported(evt);
  386. }
  387. void Game::registerGesture(Gesture::GestureEvent evt)
  388. {
  389. Platform::registerGesture(evt);
  390. }
  391. void Game::unregisterGesture(Gesture::GestureEvent evt)
  392. {
  393. Platform::unregisterGesture(evt);
  394. }
  395. bool Game::isGestureRegistered(Gesture::GestureEvent evt)
  396. {
  397. return Platform::isGestureRegistered(evt);
  398. }
  399. void Game::gestureSwipeEvent(int x, int y, int direction)
  400. {
  401. }
  402. void Game::gesturePinchEvent(int x, int y, float scale)
  403. {
  404. }
  405. void Game::gestureTapEvent(int x, int y)
  406. {
  407. }
  408. void Game::gamepadEvent(Gamepad::GamepadEvent evt, Gamepad* gamepad)
  409. {
  410. }
  411. void Game::schedule(float timeOffset, TimeListener* timeListener, void* cookie)
  412. {
  413. GP_ASSERT(_timeEvents);
  414. TimeEvent timeEvent(getGameTime() + timeOffset, timeListener, cookie);
  415. _timeEvents->push(timeEvent);
  416. }
  417. void Game::schedule(float timeOffset, const char* function)
  418. {
  419. if (!_scriptListeners)
  420. _scriptListeners = new std::vector<ScriptListener*>();
  421. ScriptListener* listener = new ScriptListener(function);
  422. _scriptListeners->push_back(listener);
  423. schedule(timeOffset, listener, NULL);
  424. }
  425. void Game::fireTimeEvents(double frameTime)
  426. {
  427. while (_timeEvents->size() > 0)
  428. {
  429. const TimeEvent* timeEvent = &_timeEvents->top();
  430. if (timeEvent->time > frameTime)
  431. {
  432. break;
  433. }
  434. if (timeEvent->listener)
  435. {
  436. timeEvent->listener->timeEvent(frameTime - timeEvent->time, timeEvent->cookie);
  437. }
  438. _timeEvents->pop();
  439. }
  440. }
  441. Game::ScriptListener::ScriptListener(const char* url)
  442. {
  443. function = Game::getInstance()->getScriptController()->loadUrl(url);
  444. }
  445. void Game::ScriptListener::timeEvent(long timeDiff, void* cookie)
  446. {
  447. Game::getInstance()->getScriptController()->executeFunction<void>(function.c_str(), "l", timeDiff);
  448. }
  449. Game::TimeEvent::TimeEvent(double time, TimeListener* timeListener, void* cookie)
  450. : time(time), listener(timeListener), cookie(cookie)
  451. {
  452. }
  453. bool Game::TimeEvent::operator<(const TimeEvent& v) const
  454. {
  455. // The first element of std::priority_queue is the greatest.
  456. return time > v.time;
  457. }
  458. Properties* Game::getConfig() const
  459. {
  460. if (_properties == NULL)
  461. const_cast<Game*>(this)->loadConfig();
  462. return _properties;
  463. }
  464. void Game::loadConfig()
  465. {
  466. if (_properties == NULL)
  467. {
  468. // Try to load custom config from file.
  469. if (FileSystem::fileExists("game.config"))
  470. {
  471. _properties = Properties::create("game.config");
  472. // Load filesystem aliases.
  473. Properties* aliases = _properties->getNamespace("aliases", true);
  474. if (aliases)
  475. {
  476. FileSystem::loadResourceAliases(aliases);
  477. }
  478. }
  479. else
  480. {
  481. // Create an empty config
  482. _properties = new Properties();
  483. }
  484. }
  485. }
  486. void Game::loadGamepads()
  487. {
  488. // Load virtual gamepads.
  489. if (_properties)
  490. {
  491. // Check if there are any virtual gamepads included in the .config file.
  492. // If there are, create and initialize them.
  493. _properties->rewind();
  494. Properties* inner = _properties->getNextNamespace();
  495. while (inner != NULL)
  496. {
  497. std::string spaceName(inner->getNamespace());
  498. // This namespace was accidentally named "gamepads" originally but we'll keep this check
  499. // for backwards compatibility.
  500. if (spaceName == "gamepads" || spaceName == "gamepad")
  501. {
  502. if (inner->exists("form"))
  503. {
  504. const char* gamepadFormPath = inner->getString("form");
  505. GP_ASSERT(gamepadFormPath);
  506. Gamepad* gamepad = Gamepad::add(gamepadFormPath);
  507. GP_ASSERT(gamepad);
  508. }
  509. }
  510. inner = _properties->getNextNamespace();
  511. }
  512. }
  513. }
  514. void Game::ShutdownListener::timeEvent(long timeDiff, void* cookie)
  515. {
  516. Game::getInstance()->shutdown();
  517. }
  518. }