Game.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 "FPSActor.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. Game::Game()
  29. :mRenderer(nullptr)
  30. ,mAudioSystem(nullptr)
  31. ,mPhysWorld(nullptr)
  32. ,mGameState(EGameplay)
  33. ,mUpdatingActors(false)
  34. {
  35. }
  36. bool Game::Initialize()
  37. {
  38. if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0)
  39. {
  40. SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
  41. return false;
  42. }
  43. // Create the renderer
  44. mRenderer = new Renderer(this);
  45. if (!mRenderer->Initialize(1024.0f, 768.0f))
  46. {
  47. SDL_Log("Failed to initialize renderer");
  48. delete mRenderer;
  49. mRenderer = nullptr;
  50. return false;
  51. }
  52. // Create the audio system
  53. mAudioSystem = new AudioSystem(this);
  54. if (!mAudioSystem->Initialize())
  55. {
  56. SDL_Log("Failed to initialize audio system");
  57. mAudioSystem->Shutdown();
  58. delete mAudioSystem;
  59. mAudioSystem = nullptr;
  60. return false;
  61. }
  62. // Create the physics world
  63. mPhysWorld = new PhysWorld(this);
  64. // Initialize SDL_ttf
  65. if (TTF_Init() != 0)
  66. {
  67. SDL_Log("Failed to initialize SDL_ttf");
  68. return false;
  69. }
  70. LoadData();
  71. mTicksCount = SDL_GetTicks();
  72. return true;
  73. }
  74. void Game::RunLoop()
  75. {
  76. while (mGameState != EQuit)
  77. {
  78. ProcessInput();
  79. UpdateGame();
  80. GenerateOutput();
  81. }
  82. }
  83. void Game::AddPlane(PlaneActor* plane)
  84. {
  85. mPlanes.emplace_back(plane);
  86. }
  87. void Game::RemovePlane(PlaneActor* plane)
  88. {
  89. auto iter = std::find(mPlanes.begin(), mPlanes.end(), plane);
  90. mPlanes.erase(iter);
  91. }
  92. void Game::ProcessInput()
  93. {
  94. SDL_Event event;
  95. while (SDL_PollEvent(&event))
  96. {
  97. switch (event.type)
  98. {
  99. case SDL_QUIT:
  100. mGameState = EQuit;
  101. break;
  102. // This fires when a key's initially pressed
  103. case SDL_KEYDOWN:
  104. if (!event.key.repeat)
  105. {
  106. if (mGameState == EGameplay)
  107. {
  108. HandleKeyPress(event.key.keysym.sym);
  109. }
  110. else if (!mUIStack.empty())
  111. {
  112. mUIStack.back()->
  113. HandleKeyPress(event.key.keysym.sym);
  114. }
  115. }
  116. break;
  117. case SDL_MOUSEBUTTONDOWN:
  118. if (mGameState == EGameplay)
  119. {
  120. HandleKeyPress(event.button.button);
  121. }
  122. else if (!mUIStack.empty())
  123. {
  124. mUIStack.back()->
  125. HandleKeyPress(event.button.button);
  126. }
  127. break;
  128. default:
  129. break;
  130. }
  131. }
  132. const Uint8* state = SDL_GetKeyboardState(NULL);
  133. if (mGameState == EGameplay)
  134. {
  135. for (auto actor : mActors)
  136. {
  137. if (actor->GetState() == Actor::EActive)
  138. {
  139. actor->ProcessInput(state);
  140. }
  141. }
  142. }
  143. else if (!mUIStack.empty())
  144. {
  145. mUIStack.back()->ProcessInput(state);
  146. }
  147. }
  148. void Game::HandleKeyPress(int key)
  149. {
  150. switch (key)
  151. {
  152. case SDLK_ESCAPE:
  153. // Create pause menu
  154. new PauseMenu(this);
  155. break;
  156. case '-':
  157. {
  158. // Reduce master volume
  159. float volume = mAudioSystem->GetBusVolume("bus:/");
  160. volume = Math::Max(0.0f, volume - 0.1f);
  161. mAudioSystem->SetBusVolume("bus:/", volume);
  162. break;
  163. }
  164. case '=':
  165. {
  166. // Increase master volume
  167. float volume = mAudioSystem->GetBusVolume("bus:/");
  168. volume = Math::Min(1.0f, volume + 0.1f);
  169. mAudioSystem->SetBusVolume("bus:/", volume);
  170. break;
  171. }
  172. case '1':
  173. {
  174. // Load English text
  175. LoadText("Assets/English.gptext");
  176. break;
  177. }
  178. case '2':
  179. {
  180. // Load Russian text
  181. LoadText("Assets/Russian.gptext");
  182. break;
  183. }
  184. case SDL_BUTTON_LEFT:
  185. {
  186. // Fire weapon
  187. mFPSActor->Shoot();
  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. LoadFont("Assets/Carlito-Regular.ttf");
  269. // Load English text
  270. LoadText("Assets/English.gptext");
  271. // Create actors
  272. Actor* a = nullptr;
  273. Quaternion q;
  274. //MeshComponent* mc = nullptr;
  275. // Setup floor
  276. const float start = -1250.0f;
  277. const float size = 250.0f;
  278. for (int i = 0; i < 10; i++)
  279. {
  280. for (int j = 0; j < 10; j++)
  281. {
  282. a = new PlaneActor(this);
  283. a->SetPosition(Vector3(start + i * size, start + j * size, -100.0f));
  284. }
  285. }
  286. // Left/right walls
  287. q = Quaternion(Vector3::UnitX, Math::PiOver2);
  288. for (int i = 0; i < 10; i++)
  289. {
  290. a = new PlaneActor(this);
  291. a->SetPosition(Vector3(start + i * size, start - size, 0.0f));
  292. a->SetRotation(q);
  293. a = new PlaneActor(this);
  294. a->SetPosition(Vector3(start + i * size, -start + size, 0.0f));
  295. a->SetRotation(q);
  296. }
  297. q = Quaternion::Concatenate(q, Quaternion(Vector3::UnitZ, Math::PiOver2));
  298. // Forward/back walls
  299. for (int i = 0; i < 10; i++)
  300. {
  301. a = new PlaneActor(this);
  302. a->SetPosition(Vector3(start - size, start + i * size, 0.0f));
  303. a->SetRotation(q);
  304. a = new PlaneActor(this);
  305. a->SetPosition(Vector3(-start + size, start + i * size, 0.0f));
  306. a->SetRotation(q);
  307. }
  308. // Setup lights
  309. mRenderer->SetAmbientLight(Vector3(0.2f, 0.2f, 0.2f));
  310. DirectionalLight& dir = mRenderer->GetDirectionalLight();
  311. dir.mDirection = Vector3(0.0f, -0.707f, -0.707f);
  312. dir.mDiffuseColor = Vector3(0.78f, 0.88f, 1.0f);
  313. dir.mSpecColor = Vector3(0.8f, 0.8f, 0.8f);
  314. // UI elements
  315. mHUD = new HUD(this);
  316. // Start music
  317. mMusicEvent = mAudioSystem->PlayEvent("event:/Music");
  318. // Enable relative mouse mode for camera look
  319. SDL_SetRelativeMouseMode(SDL_TRUE);
  320. // Make an initial call to get relative to clear out
  321. SDL_GetRelativeMouseState(nullptr, nullptr);
  322. // Different camera actors
  323. mFPSActor = new FPSActor(this);
  324. // Create target actors
  325. a = new TargetActor(this);
  326. a->SetPosition(Vector3(1450.0f, 0.0f, 100.0f));
  327. a = new TargetActor(this);
  328. a->SetPosition(Vector3(1450.0f, 0.0f, 400.0f));
  329. a = new TargetActor(this);
  330. a->SetPosition(Vector3(1450.0f, -500.0f, 200.0f));
  331. a = new TargetActor(this);
  332. a->SetPosition(Vector3(1450.0f, 500.0f, 200.0f));
  333. a = new TargetActor(this);
  334. a->SetPosition(Vector3(0.0f, -1450.0f, 200.0f));
  335. a->SetRotation(Quaternion(Vector3::UnitZ, Math::PiOver2));
  336. a = new TargetActor(this);
  337. a->SetPosition(Vector3(0.0f, 1450.0f, 200.0f));
  338. a->SetRotation(Quaternion(Vector3::UnitZ, -Math::PiOver2));
  339. }
  340. void Game::UnloadData()
  341. {
  342. // Delete actors
  343. // Because ~Actor calls RemoveActor, have to use a different style loop
  344. while (!mActors.empty())
  345. {
  346. delete mActors.back();
  347. }
  348. // Clear the UI stack
  349. while (!mUIStack.empty())
  350. {
  351. delete mUIStack.back();
  352. mUIStack.pop_back();
  353. }
  354. if (mRenderer)
  355. {
  356. mRenderer->UnloadData();
  357. }
  358. }
  359. void Game::Shutdown()
  360. {
  361. UnloadData();
  362. TTF_Quit();
  363. delete mPhysWorld;
  364. if (mRenderer)
  365. {
  366. mRenderer->Shutdown();
  367. }
  368. if (mAudioSystem)
  369. {
  370. mAudioSystem->Shutdown();
  371. }
  372. SDL_Quit();
  373. }
  374. void Game::AddActor(Actor* actor)
  375. {
  376. // If we're updating actors, need to add to pending
  377. if (mUpdatingActors)
  378. {
  379. mPendingActors.emplace_back(actor);
  380. }
  381. else
  382. {
  383. mActors.emplace_back(actor);
  384. }
  385. }
  386. void Game::RemoveActor(Actor* actor)
  387. {
  388. // Is it in pending actors?
  389. auto iter = std::find(mPendingActors.begin(), mPendingActors.end(), actor);
  390. if (iter != mPendingActors.end())
  391. {
  392. // Swap to end of vector and pop off (avoid erase copies)
  393. std::iter_swap(iter, mPendingActors.end() - 1);
  394. mPendingActors.pop_back();
  395. }
  396. // Is it in actors?
  397. iter = std::find(mActors.begin(), mActors.end(), actor);
  398. if (iter != mActors.end())
  399. {
  400. // Swap to end of vector and pop off (avoid erase copies)
  401. std::iter_swap(iter, mActors.end() - 1);
  402. mActors.pop_back();
  403. }
  404. }
  405. void Game::PushUI(UIScreen* screen)
  406. {
  407. mUIStack.emplace_back(screen);
  408. }
  409. void Game::LoadFont(const std::string& fileName)
  410. {
  411. Font* font = new Font(this);
  412. if (font->Load(fileName))
  413. {
  414. mFonts.emplace(fileName, font);
  415. }
  416. else
  417. {
  418. font->Unload();
  419. delete font;
  420. }
  421. }
  422. Font* Game::GetFont(const std::string& fileName)
  423. {
  424. auto iter = mFonts.find(fileName);
  425. if (iter != mFonts.end())
  426. {
  427. return iter->second;
  428. }
  429. else
  430. {
  431. return nullptr;
  432. }
  433. }
  434. void Game::LoadText(const std::string& fileName)
  435. {
  436. // Clear the existing map, if already loaded
  437. mText.clear();
  438. // Try to open the file
  439. std::ifstream file(fileName);
  440. if (!file.is_open())
  441. {
  442. SDL_Log("Text file %s not found", fileName.c_str());
  443. return;
  444. }
  445. // Read the entire file to a string stream
  446. std::stringstream fileStream;
  447. fileStream << file.rdbuf();
  448. std::string contents = fileStream.str();
  449. // Open this file in rapidJSON
  450. rapidjson::StringStream jsonStr(contents.c_str());
  451. rapidjson::Document doc;
  452. doc.ParseStream(jsonStr);
  453. if (!doc.IsObject())
  454. {
  455. SDL_Log("Text file %s is not valid JSON", fileName.c_str());
  456. return;
  457. }
  458. // Parse the text map
  459. const rapidjson::Value& actions = doc["TextMap"];
  460. for (rapidjson::Value::ConstMemberIterator itr = actions.MemberBegin();
  461. itr != actions.MemberEnd(); ++itr)
  462. {
  463. if (itr->name.IsString() && itr->value.IsString())
  464. {
  465. mText.emplace(itr->name.GetString(),
  466. itr->value.GetString());
  467. }
  468. }
  469. }
  470. const std::string& Game::GetText(const std::string& key)
  471. {
  472. static std::string errorMsg("**KEY NOT FOUND**");
  473. // Find this text in the map, if it exists
  474. auto iter = mText.find(key);
  475. if (iter != mText.end())
  476. {
  477. return iter->second;
  478. }
  479. else
  480. {
  481. return errorMsg;
  482. }
  483. }