2
0

Game.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. #include "Game.h"
  9. #include <algorithm>
  10. #include "Renderer.h"
  11. #include "AudioSystem.h"
  12. #include "PhysWorld.h"
  13. #include "Actor.h"
  14. #include "UIScreen.h"
  15. #include "HUD.h"
  16. #include "MeshComponent.h"
  17. #include "FollowActor.h"
  18. #include "PlaneActor.h"
  19. #include "TargetActor.h"
  20. #include "BallActor.h"
  21. #include "PauseMenu.h"
  22. #include <SDL/SDL.h>
  23. #include <SDL/SDL_ttf.h>
  24. #include "Font.h"
  25. #include <fstream>
  26. #include <sstream>
  27. #include <rapidjson/document.h>
  28. #include "Skeleton.h"
  29. #include "Animation.h"
  30. Game::Game()
  31. :mRenderer(nullptr)
  32. ,mAudioSystem(nullptr)
  33. ,mPhysWorld(nullptr)
  34. ,mGameState(EGameplay)
  35. ,mUpdatingActors(false)
  36. {
  37. }
  38. bool Game::Initialize()
  39. {
  40. if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0)
  41. {
  42. SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
  43. return false;
  44. }
  45. // Create the renderer
  46. mRenderer = new Renderer(this);
  47. if (!mRenderer->Initialize(1024.0f, 768.0f))
  48. {
  49. SDL_Log("Failed to initialize renderer");
  50. delete mRenderer;
  51. mRenderer = nullptr;
  52. return false;
  53. }
  54. // Create the audio system
  55. mAudioSystem = new AudioSystem(this);
  56. if (!mAudioSystem->Initialize())
  57. {
  58. SDL_Log("Failed to initialize audio system");
  59. mAudioSystem->Shutdown();
  60. delete mAudioSystem;
  61. mAudioSystem = nullptr;
  62. return false;
  63. }
  64. // Create the physics world
  65. mPhysWorld = new PhysWorld(this);
  66. // Initialize SDL_ttf
  67. if (TTF_Init() != 0)
  68. {
  69. SDL_Log("Failed to initialize SDL_ttf");
  70. return false;
  71. }
  72. LoadData();
  73. mTicksCount = SDL_GetTicks();
  74. return true;
  75. }
  76. void Game::RunLoop()
  77. {
  78. while (mGameState != EQuit)
  79. {
  80. ProcessInput();
  81. UpdateGame();
  82. GenerateOutput();
  83. }
  84. }
  85. void Game::AddPlane(PlaneActor* plane)
  86. {
  87. mPlanes.emplace_back(plane);
  88. }
  89. void Game::RemovePlane(PlaneActor* plane)
  90. {
  91. auto iter = std::find(mPlanes.begin(), mPlanes.end(), plane);
  92. mPlanes.erase(iter);
  93. }
  94. void Game::ProcessInput()
  95. {
  96. SDL_Event event;
  97. while (SDL_PollEvent(&event))
  98. {
  99. switch (event.type)
  100. {
  101. case SDL_QUIT:
  102. mGameState = EQuit;
  103. break;
  104. // This fires when a key's initially pressed
  105. case SDL_KEYDOWN:
  106. if (!event.key.repeat)
  107. {
  108. if (mGameState == EGameplay)
  109. {
  110. HandleKeyPress(event.key.keysym.sym);
  111. }
  112. else if (!mUIStack.empty())
  113. {
  114. mUIStack.back()->
  115. HandleKeyPress(event.key.keysym.sym);
  116. }
  117. }
  118. break;
  119. case SDL_MOUSEBUTTONDOWN:
  120. if (mGameState == EGameplay)
  121. {
  122. HandleKeyPress(event.button.button);
  123. }
  124. else if (!mUIStack.empty())
  125. {
  126. mUIStack.back()->
  127. HandleKeyPress(event.button.button);
  128. }
  129. break;
  130. default:
  131. break;
  132. }
  133. }
  134. const Uint8* state = SDL_GetKeyboardState(NULL);
  135. if (mGameState == EGameplay)
  136. {
  137. for (auto actor : mActors)
  138. {
  139. if (actor->GetState() == Actor::EActive)
  140. {
  141. actor->ProcessInput(state);
  142. }
  143. }
  144. }
  145. else if (!mUIStack.empty())
  146. {
  147. mUIStack.back()->ProcessInput(state);
  148. }
  149. }
  150. void Game::HandleKeyPress(int key)
  151. {
  152. switch (key)
  153. {
  154. case SDLK_ESCAPE:
  155. // Create pause menu
  156. new PauseMenu(this);
  157. break;
  158. case '-':
  159. {
  160. // Reduce master volume
  161. float volume = mAudioSystem->GetBusVolume("bus:/");
  162. volume = Math::Max(0.0f, volume - 0.1f);
  163. mAudioSystem->SetBusVolume("bus:/", volume);
  164. break;
  165. }
  166. case '=':
  167. {
  168. // Increase master volume
  169. float volume = mAudioSystem->GetBusVolume("bus:/");
  170. volume = Math::Min(1.0f, volume + 0.1f);
  171. mAudioSystem->SetBusVolume("bus:/", volume);
  172. break;
  173. }
  174. case '1':
  175. {
  176. // Load English text
  177. LoadText("Assets/English.gptext");
  178. break;
  179. }
  180. case '2':
  181. {
  182. // Load Russian text
  183. LoadText("Assets/Russian.gptext");
  184. break;
  185. }
  186. case SDL_BUTTON_LEFT:
  187. {
  188. break;
  189. }
  190. default:
  191. break;
  192. }
  193. }
  194. void Game::UpdateGame()
  195. {
  196. // Compute delta time
  197. // Wait until 16ms has elapsed since last frame
  198. while (!SDL_TICKS_PASSED(SDL_GetTicks(), mTicksCount + 16))
  199. ;
  200. float deltaTime = (SDL_GetTicks() - mTicksCount) / 1000.0f;
  201. if (deltaTime > 0.05f)
  202. {
  203. deltaTime = 0.05f;
  204. }
  205. mTicksCount = SDL_GetTicks();
  206. if (mGameState == EGameplay)
  207. {
  208. // Update all actors
  209. mUpdatingActors = true;
  210. for (auto actor : mActors)
  211. {
  212. actor->Update(deltaTime);
  213. }
  214. mUpdatingActors = false;
  215. // Move any pending actors to mActors
  216. for (auto pending : mPendingActors)
  217. {
  218. pending->ComputeWorldTransform();
  219. mActors.emplace_back(pending);
  220. }
  221. mPendingActors.clear();
  222. // Add any dead actors to a temp vector
  223. std::vector<Actor*> deadActors;
  224. for (auto actor : mActors)
  225. {
  226. if (actor->GetState() == Actor::EDead)
  227. {
  228. deadActors.emplace_back(actor);
  229. }
  230. }
  231. // Delete dead actors (which removes them from mActors)
  232. for (auto actor : deadActors)
  233. {
  234. delete actor;
  235. }
  236. }
  237. // Update audio system
  238. mAudioSystem->Update(deltaTime);
  239. // Update UI screens
  240. for (auto ui : mUIStack)
  241. {
  242. if (ui->GetState() == UIScreen::EActive)
  243. {
  244. ui->Update(deltaTime);
  245. }
  246. }
  247. // Delete any UIScreens that are closed
  248. auto iter = mUIStack.begin();
  249. while (iter != mUIStack.end())
  250. {
  251. if ((*iter)->GetState() == UIScreen::EClosing)
  252. {
  253. delete *iter;
  254. iter = mUIStack.erase(iter);
  255. }
  256. else
  257. {
  258. ++iter;
  259. }
  260. }
  261. }
  262. void Game::GenerateOutput()
  263. {
  264. mRenderer->Draw();
  265. }
  266. void Game::LoadData()
  267. {
  268. // Load English text
  269. LoadText("Assets/English.gptext");
  270. // Create actors
  271. Actor* a = nullptr;
  272. Quaternion q;
  273. //MeshComponent* mc = nullptr;
  274. // Setup floor
  275. const float start = -1250.0f;
  276. const float size = 250.0f;
  277. for (int i = 0; i < 10; i++)
  278. {
  279. for (int j = 0; j < 10; j++)
  280. {
  281. a = new PlaneActor(this);
  282. a->SetPosition(Vector3(start + i * size, start + j * size, -100.0f));
  283. }
  284. }
  285. // Left/right walls
  286. q = Quaternion(Vector3::UnitX, Math::PiOver2);
  287. for (int i = 0; i < 10; i++)
  288. {
  289. a = new PlaneActor(this);
  290. a->SetPosition(Vector3(start + i * size, start - size, 0.0f));
  291. a->SetRotation(q);
  292. a = new PlaneActor(this);
  293. a->SetPosition(Vector3(start + i * size, -start + size, 0.0f));
  294. a->SetRotation(q);
  295. }
  296. q = Quaternion::Concatenate(q, Quaternion(Vector3::UnitZ, Math::PiOver2));
  297. // Forward/back walls
  298. for (int i = 0; i < 10; i++)
  299. {
  300. a = new PlaneActor(this);
  301. a->SetPosition(Vector3(start - size, start + i * size, 0.0f));
  302. a->SetRotation(q);
  303. a = new PlaneActor(this);
  304. a->SetPosition(Vector3(-start + size, start + i * size, 0.0f));
  305. a->SetRotation(q);
  306. }
  307. // Setup lights
  308. mRenderer->SetAmbientLight(Vector3(0.2f, 0.2f, 0.2f));
  309. DirectionalLight& dir = mRenderer->GetDirectionalLight();
  310. dir.mDirection = Vector3(0.0f, -0.707f, -0.707f);
  311. dir.mDiffuseColor = Vector3(0.78f, 0.88f, 1.0f);
  312. dir.mSpecColor = Vector3(0.8f, 0.8f, 0.8f);
  313. // UI elements
  314. mHUD = new HUD(this);
  315. // Start music
  316. mMusicEvent = mAudioSystem->PlayEvent("event:/Music");
  317. // Enable relative mouse mode for camera look
  318. SDL_SetRelativeMouseMode(SDL_TRUE);
  319. // Make an initial call to get relative to clear out
  320. SDL_GetRelativeMouseState(nullptr, nullptr);
  321. // Different camera actors
  322. mFollowActor = new FollowActor(this);
  323. // Create target actors
  324. a = new TargetActor(this);
  325. a->SetPosition(Vector3(1450.0f, 0.0f, 100.0f));
  326. a = new TargetActor(this);
  327. a->SetPosition(Vector3(1450.0f, 0.0f, 400.0f));
  328. a = new TargetActor(this);
  329. a->SetPosition(Vector3(1450.0f, -500.0f, 200.0f));
  330. a = new TargetActor(this);
  331. a->SetPosition(Vector3(1450.0f, 500.0f, 200.0f));
  332. a = new TargetActor(this);
  333. a->SetPosition(Vector3(0.0f, -1450.0f, 200.0f));
  334. a->SetRotation(Quaternion(Vector3::UnitZ, Math::PiOver2));
  335. a = new TargetActor(this);
  336. a->SetPosition(Vector3(0.0f, 1450.0f, 200.0f));
  337. a->SetRotation(Quaternion(Vector3::UnitZ, -Math::PiOver2));
  338. }
  339. void Game::UnloadData()
  340. {
  341. // Delete actors
  342. // Because ~Actor calls RemoveActor, have to use a different style loop
  343. while (!mActors.empty())
  344. {
  345. delete mActors.back();
  346. }
  347. // Clear the UI stack
  348. while (!mUIStack.empty())
  349. {
  350. delete mUIStack.back();
  351. mUIStack.pop_back();
  352. }
  353. if (mRenderer)
  354. {
  355. mRenderer->UnloadData();
  356. }
  357. // Unload fonts
  358. for (auto f : mFonts)
  359. {
  360. f.second->Unload();
  361. delete f.second;
  362. }
  363. // Unload skeletons
  364. for (auto s : mSkeletons)
  365. {
  366. delete s.second;
  367. }
  368. // Unload animations
  369. for (auto a : mAnims)
  370. {
  371. delete a.second;
  372. }
  373. }
  374. void Game::Shutdown()
  375. {
  376. UnloadData();
  377. TTF_Quit();
  378. delete mPhysWorld;
  379. if (mRenderer)
  380. {
  381. mRenderer->Shutdown();
  382. }
  383. if (mAudioSystem)
  384. {
  385. mAudioSystem->Shutdown();
  386. }
  387. SDL_Quit();
  388. }
  389. void Game::AddActor(Actor* actor)
  390. {
  391. // If we're updating actors, need to add to pending
  392. if (mUpdatingActors)
  393. {
  394. mPendingActors.emplace_back(actor);
  395. }
  396. else
  397. {
  398. mActors.emplace_back(actor);
  399. }
  400. }
  401. void Game::RemoveActor(Actor* actor)
  402. {
  403. // Is it in pending actors?
  404. auto iter = std::find(mPendingActors.begin(), mPendingActors.end(), actor);
  405. if (iter != mPendingActors.end())
  406. {
  407. // Swap to end of vector and pop off (avoid erase copies)
  408. std::iter_swap(iter, mPendingActors.end() - 1);
  409. mPendingActors.pop_back();
  410. }
  411. // Is it in actors?
  412. iter = std::find(mActors.begin(), mActors.end(), actor);
  413. if (iter != mActors.end())
  414. {
  415. // Swap to end of vector and pop off (avoid erase copies)
  416. std::iter_swap(iter, mActors.end() - 1);
  417. mActors.pop_back();
  418. }
  419. }
  420. void Game::PushUI(UIScreen* screen)
  421. {
  422. mUIStack.emplace_back(screen);
  423. }
  424. Font* Game::GetFont(const std::string& fileName)
  425. {
  426. auto iter = mFonts.find(fileName);
  427. if (iter != mFonts.end())
  428. {
  429. return iter->second;
  430. }
  431. else
  432. {
  433. Font* font = new Font(this);
  434. if (font->Load(fileName))
  435. {
  436. mFonts.emplace(fileName, font);
  437. }
  438. else
  439. {
  440. font->Unload();
  441. delete font;
  442. font = nullptr;
  443. }
  444. return font;
  445. }
  446. }
  447. void Game::LoadText(const std::string& fileName)
  448. {
  449. // Clear the existing map, if already loaded
  450. mText.clear();
  451. // Try to open the file
  452. std::ifstream file(fileName);
  453. if (!file.is_open())
  454. {
  455. SDL_Log("Text file %s not found", fileName.c_str());
  456. return;
  457. }
  458. // Read the entire file to a string stream
  459. std::stringstream fileStream;
  460. fileStream << file.rdbuf();
  461. std::string contents = fileStream.str();
  462. // Open this file in rapidJSON
  463. rapidjson::StringStream jsonStr(contents.c_str());
  464. rapidjson::Document doc;
  465. doc.ParseStream(jsonStr);
  466. if (!doc.IsObject())
  467. {
  468. SDL_Log("Text file %s is not valid JSON", fileName.c_str());
  469. return;
  470. }
  471. // Parse the text map
  472. const rapidjson::Value& actions = doc["TextMap"];
  473. for (rapidjson::Value::ConstMemberIterator itr = actions.MemberBegin();
  474. itr != actions.MemberEnd(); ++itr)
  475. {
  476. if (itr->name.IsString() && itr->value.IsString())
  477. {
  478. mText.emplace(itr->name.GetString(),
  479. itr->value.GetString());
  480. }
  481. }
  482. }
  483. const std::string& Game::GetText(const std::string& key)
  484. {
  485. static std::string errorMsg("**KEY NOT FOUND**");
  486. // Find this text in the map, if it exists
  487. auto iter = mText.find(key);
  488. if (iter != mText.end())
  489. {
  490. return iter->second;
  491. }
  492. else
  493. {
  494. return errorMsg;
  495. }
  496. }
  497. Skeleton* Game::GetSkeleton(const std::string& fileName)
  498. {
  499. auto iter = mSkeletons.find(fileName);
  500. if (iter != mSkeletons.end())
  501. {
  502. return iter->second;
  503. }
  504. else
  505. {
  506. Skeleton* sk = new Skeleton();
  507. if (sk->Load(fileName))
  508. {
  509. mSkeletons.emplace(fileName, sk);
  510. }
  511. else
  512. {
  513. delete sk;
  514. sk = nullptr;
  515. }
  516. return sk;
  517. }
  518. }
  519. Animation* Game::GetAnimation(const std::string& fileName)
  520. {
  521. auto iter = mAnims.find(fileName);
  522. if (iter != mAnims.end())
  523. {
  524. return iter->second;
  525. }
  526. else
  527. {
  528. Animation* anim = new Animation();
  529. if (anim->Load(fileName))
  530. {
  531. mAnims.emplace(fileName, anim);
  532. }
  533. else
  534. {
  535. delete anim;
  536. anim = nullptr;
  537. }
  538. return anim;
  539. }
  540. }