Game.cpp 16 KB

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