2
0

Game.cpp 7.5 KB

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