Game.cpp 16 KB

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