Game.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 <GL/glew.h>
  10. #include "Texture.h"
  11. #include "VertexArray.h"
  12. #include "Shader.h"
  13. #include <algorithm>
  14. #include "Actor.h"
  15. #include "SpriteComponent.h"
  16. #include "Actor.h"
  17. #include "Ship.h"
  18. #include "Asteroid.h"
  19. #include "Random.h"
  20. #include "InputSystem.h"
  21. Game::Game()
  22. :mWindow(nullptr)
  23. ,mSpriteShader(nullptr)
  24. ,mIsRunning(true)
  25. ,mUpdatingActors(false)
  26. {
  27. }
  28. bool Game::Initialize()
  29. {
  30. if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0)
  31. {
  32. SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
  33. return false;
  34. }
  35. // Set OpenGL attributes
  36. // Use the core OpenGL profile
  37. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  38. // Specify version 3.3
  39. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  40. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
  41. // Request a color buffer with 8-bits per RGBA channel
  42. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
  43. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
  44. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
  45. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
  46. // Enable double buffering
  47. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  48. // Force OpenGL to use hardware acceleration
  49. SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
  50. mWindow = SDL_CreateWindow("Game Programming in C++ (Chapter 5)", 100, 100,
  51. 1024, 768, SDL_WINDOW_OPENGL);
  52. if (!mWindow)
  53. {
  54. SDL_Log("Failed to create window: %s", SDL_GetError());
  55. return false;
  56. }
  57. // Initialize input system
  58. mInputSystem = new InputSystem();
  59. if (!mInputSystem->Initialize())
  60. {
  61. SDL_Log("Failed to initialize input system");
  62. return false;
  63. }
  64. // Create an OpenGL context
  65. mContext = SDL_GL_CreateContext(mWindow);
  66. // Initialize GLEW
  67. glewExperimental = GL_TRUE;
  68. if (glewInit() != GLEW_OK)
  69. {
  70. SDL_Log("Failed to initialize GLEW.");
  71. return false;
  72. }
  73. // On some platforms, GLEW will emit a benign error code,
  74. // so clear it
  75. glGetError();
  76. // Make sure we can create/compile shaders
  77. if (!LoadShaders())
  78. {
  79. SDL_Log("Failed to load shaders.");
  80. return false;
  81. }
  82. // Create quad for drawing sprites
  83. CreateSpriteVerts();
  84. LoadData();
  85. mTicksCount = SDL_GetTicks();
  86. return true;
  87. }
  88. void Game::RunLoop()
  89. {
  90. while (mIsRunning)
  91. {
  92. ProcessInput();
  93. UpdateGame();
  94. GenerateOutput();
  95. }
  96. }
  97. void Game::ProcessInput()
  98. {
  99. mInputSystem->PrepareForUpdate();
  100. SDL_Event event;
  101. while (SDL_PollEvent(&event))
  102. {
  103. switch (event.type)
  104. {
  105. case SDL_QUIT:
  106. mIsRunning = false;
  107. break;
  108. }
  109. }
  110. mInputSystem->Update();
  111. const InputState& state = mInputSystem->GetState();
  112. if (state.Keyboard.GetKeyState(SDL_SCANCODE_ESCAPE)
  113. == EReleased)
  114. {
  115. mIsRunning = false;
  116. }
  117. mUpdatingActors = true;
  118. for (auto actor : mActors)
  119. {
  120. actor->ProcessInput(state);
  121. }
  122. mUpdatingActors = false;
  123. }
  124. void Game::UpdateGame()
  125. {
  126. // Compute delta time
  127. // Wait until 16ms has elapsed since last frame
  128. while (!SDL_TICKS_PASSED(SDL_GetTicks(), mTicksCount + 16))
  129. ;
  130. float deltaTime = (SDL_GetTicks() - mTicksCount) / 1000.0f;
  131. if (deltaTime > 0.05f)
  132. {
  133. deltaTime = 0.05f;
  134. }
  135. mTicksCount = SDL_GetTicks();
  136. // Update all actors
  137. mUpdatingActors = true;
  138. for (auto actor : mActors)
  139. {
  140. actor->Update(deltaTime);
  141. }
  142. mUpdatingActors = false;
  143. // Move any pending actors to mActors
  144. for (auto pending : mPendingActors)
  145. {
  146. pending->ComputeWorldTransform();
  147. mActors.emplace_back(pending);
  148. }
  149. mPendingActors.clear();
  150. // Add any dead actors to a temp vector
  151. std::vector<Actor*> deadActors;
  152. for (auto actor : mActors)
  153. {
  154. if (actor->GetState() == Actor::EDead)
  155. {
  156. deadActors.emplace_back(actor);
  157. }
  158. }
  159. // Delete dead actors (which removes them from mActors)
  160. for (auto actor : deadActors)
  161. {
  162. delete actor;
  163. }
  164. }
  165. void Game::GenerateOutput()
  166. {
  167. // Set the clear color to grey
  168. glClearColor(0.86f, 0.86f, 0.86f, 1.0f);
  169. // Clear the color buffer
  170. glClear(GL_COLOR_BUFFER_BIT);
  171. // Draw all sprite components
  172. // Enable alpha blending on the color buffer
  173. glEnable(GL_BLEND);
  174. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  175. // Set shader/vao as active
  176. mSpriteShader->SetActive();
  177. mSpriteVerts->SetActive();
  178. for (auto sprite : mSprites)
  179. {
  180. sprite->Draw(mSpriteShader);
  181. }
  182. // Swap the buffers
  183. SDL_GL_SwapWindow(mWindow);
  184. }
  185. bool Game::LoadShaders()
  186. {
  187. mSpriteShader = new Shader();
  188. if (!mSpriteShader->Load("Shaders/Sprite.vert", "Shaders/Sprite.frag"))
  189. {
  190. return false;
  191. }
  192. mSpriteShader->SetActive();
  193. // Set the view-projection matrix
  194. Matrix4 viewProj = Matrix4::CreateSimpleViewProj(1024.f, 768.f);
  195. mSpriteShader->SetMatrixUniform("uViewProj", viewProj);
  196. return true;
  197. }
  198. void Game::CreateSpriteVerts()
  199. {
  200. float vertices[] = {
  201. -0.5f, 0.5f, 0.f, 0.f, 0.f, // top left
  202. 0.5f, 0.5f, 0.f, 1.f, 0.f, // top right
  203. 0.5f, -0.5f, 0.f, 1.f, 1.f, // bottom right
  204. -0.5f, -0.5f, 0.f, 0.f, 1.f // bottom left
  205. };
  206. unsigned int indices[] = {
  207. 0, 1, 2,
  208. 2, 3, 0
  209. };
  210. mSpriteVerts = new VertexArray(vertices, 4, indices, 6);
  211. }
  212. void Game::LoadData()
  213. {
  214. // Create player's ship
  215. mShip = new Ship(this);
  216. mShip->SetRotation(Math::PiOver2);
  217. // Create asteroids
  218. const int numAsteroids = 20;
  219. for (int i = 0; i < numAsteroids; i++)
  220. {
  221. new Asteroid(this);
  222. }
  223. }
  224. void Game::UnloadData()
  225. {
  226. // Delete actors
  227. // Because ~Actor calls RemoveActor, have to use a different style loop
  228. while (!mActors.empty())
  229. {
  230. delete mActors.back();
  231. }
  232. // Destroy textures
  233. for (auto i : mTextures)
  234. {
  235. i.second->Unload();
  236. delete i.second;
  237. }
  238. mTextures.clear();
  239. }
  240. Texture* Game::GetTexture(const std::string& fileName)
  241. {
  242. Texture* tex = nullptr;
  243. auto iter = mTextures.find(fileName);
  244. if (iter != mTextures.end())
  245. {
  246. tex = iter->second;
  247. }
  248. else
  249. {
  250. tex = new Texture();
  251. if (tex->Load(fileName))
  252. {
  253. mTextures.emplace(fileName, tex);
  254. }
  255. else
  256. {
  257. delete tex;
  258. tex = nullptr;
  259. }
  260. }
  261. return tex;
  262. }
  263. void Game::AddAsteroid(Asteroid* ast)
  264. {
  265. mAsteroids.emplace_back(ast);
  266. }
  267. void Game::RemoveAsteroid(Asteroid* ast)
  268. {
  269. auto iter = std::find(mAsteroids.begin(),
  270. mAsteroids.end(), ast);
  271. if (iter != mAsteroids.end())
  272. {
  273. mAsteroids.erase(iter);
  274. }
  275. }
  276. void Game::Shutdown()
  277. {
  278. UnloadData();
  279. mInputSystem->Shutdown();
  280. delete mInputSystem;
  281. delete mSpriteVerts;
  282. mSpriteShader->Unload();
  283. delete mSpriteShader;
  284. SDL_GL_DeleteContext(mContext);
  285. SDL_DestroyWindow(mWindow);
  286. SDL_Quit();
  287. }
  288. void Game::AddActor(Actor* actor)
  289. {
  290. // If we're updating actors, need to add to pending
  291. if (mUpdatingActors)
  292. {
  293. mPendingActors.emplace_back(actor);
  294. }
  295. else
  296. {
  297. mActors.emplace_back(actor);
  298. }
  299. }
  300. void Game::RemoveActor(Actor* actor)
  301. {
  302. // Is it in pending actors?
  303. auto iter = std::find(mPendingActors.begin(), mPendingActors.end(), actor);
  304. if (iter != mPendingActors.end())
  305. {
  306. // Swap to end of vector and pop off (avoid erase copies)
  307. std::iter_swap(iter, mPendingActors.end() - 1);
  308. mPendingActors.pop_back();
  309. }
  310. // Is it in actors?
  311. iter = std::find(mActors.begin(), mActors.end(), actor);
  312. if (iter != mActors.end())
  313. {
  314. // Swap to end of vector and pop off (avoid erase copies)
  315. std::iter_swap(iter, mActors.end() - 1);
  316. mActors.pop_back();
  317. }
  318. }
  319. void Game::AddSprite(SpriteComponent* sprite)
  320. {
  321. // Find the insertion point in the sorted vector
  322. // (The first element with a higher draw order than me)
  323. int myDrawOrder = sprite->GetDrawOrder();
  324. auto iter = mSprites.begin();
  325. for (;
  326. iter != mSprites.end();
  327. ++iter)
  328. {
  329. if (myDrawOrder < (*iter)->GetDrawOrder())
  330. {
  331. break;
  332. }
  333. }
  334. // Inserts element before position of iterator
  335. mSprites.insert(iter, sprite);
  336. }
  337. void Game::RemoveSprite(SpriteComponent* sprite)
  338. {
  339. auto iter = std::find(mSprites.begin(), mSprites.end(), sprite);
  340. mSprites.erase(iter);
  341. }