Game.cpp 12 KB

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