GameEngine.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. #include "GameEngine.h"
  2. #include "MouseManager.h"
  3. #include <cmath>
  4. GameEngine* GameEngine::instance = nullptr;
  5. void GameEngine::start(int width, int height, const char* name, InitFunction init, TickFunction tick, RenderTickFunction renderTick)
  6. {
  7. if(!glfwInit())
  8. {
  9. cout << "could not initialize GLFW" << endl;
  10. return;
  11. }
  12. glfwDefaultWindowHints();
  13. glfwWindowHint(GLFW_VISIBLE, 0);
  14. glfwWindowHint(GLFW_RESIZABLE, 1);
  15. GLFWwindow* window = glfwCreateWindow(width, height, name, nullptr, nullptr);
  16. if(!window)
  17. {
  18. cout << "could not create window" << endl;
  19. glfwTerminate();
  20. return;
  21. }
  22. glfwMakeContextCurrent(window);
  23. glfwSwapInterval(1);
  24. glfwShowWindow(window);
  25. GLenum err = glewInit();
  26. if(GLEW_OK != err)
  27. {
  28. cout << "could not initialize GLEW: " << glewGetErrorString(err) << endl;
  29. return;
  30. }
  31. cout << "Status: Using GLEW " << glewGetString(GLEW_VERSION) << endl;
  32. GLuint vShader = 0;
  33. GLuint fShader = 0;
  34. GLuint program = createProgram(vShader, program);
  35. if(program == 0)
  36. {
  37. if(vShader != 0)
  38. {
  39. glDeleteShader(vShader);
  40. }
  41. if(fShader != 0)
  42. {
  43. glDeleteShader(fShader);
  44. }
  45. glfwDestroyWindow(window);
  46. glfwTerminate();
  47. return;
  48. }
  49. GameEngine::instance = new GameEngine(program, vShader, fShader, window, width, height, tick, renderTick);
  50. glfwSetKeyCallback(window, [](GLFWwindow* w, int key, int scancode, int action, int mods)
  51. {
  52. GameEngine::instance->onKeyEvent(w, key, scancode, action, mods);
  53. });
  54. glfwSetMouseButtonCallback(window, [](GLFWwindow* w, int button, int action, int mods)
  55. {
  56. GameEngine::instance->onMouseClick(w, button, action, mods);
  57. });
  58. glfwSetFramebufferSizeCallback(window, [](GLFWwindow* w, int width, int height)
  59. {
  60. GameEngine::instance->onWindowResize(w, width, height);
  61. });
  62. //glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  63. //glfwSetCursorPosCallback(window, onMouseMove);
  64. init();
  65. instance->run();
  66. delete instance;
  67. }
  68. void GameEngine::stop()
  69. {
  70. if(GameEngine::instance != nullptr)
  71. {
  72. glfwSetWindowShouldClose(GameEngine::instance->window, 1);
  73. }
  74. }
  75. void GameEngine::run()
  76. {
  77. glEnable(GL_CULL_FACE);
  78. glEnable(GL_DEPTH_TEST);
  79. glDepthFunc(GL_LEQUAL);
  80. uint64_t newTime = glfwGetTimerValue();
  81. uint64_t oldTime = newTime;
  82. uint64_t lag = 0;
  83. while(!glfwWindowShouldClose(window))
  84. {
  85. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  86. oldTime = newTime;
  87. newTime = glfwGetTimerValue();
  88. lag += newTime - oldTime;
  89. int ticksPerFrame = 0;
  90. while(lag >= NANOS_PER_TICK)
  91. {
  92. lag -= NANOS_PER_TICK;
  93. tps.update();
  94. tick();
  95. keyManager.tick();
  96. mouseManager.tick();
  97. ticksPerFrame++;
  98. if(ticksPerFrame >= MAX_TICKS_PER_FRAME)
  99. {
  100. long skip = lag / NANOS_PER_TICK;
  101. lag -= skip * NANOS_PER_TICK;
  102. if(skip > 0)
  103. {
  104. cout << "skipped " << skip << " game ticks " << lag << endl;
  105. }
  106. break;
  107. }
  108. }
  109. fps.update();
  110. renderTick((float) lag / NANOS_PER_TICK);
  111. glfwSwapBuffers(window);
  112. glfwPollEvents();
  113. }
  114. glDeleteShader(vShader);
  115. glDeleteShader(fShader);
  116. glDeleteProgram(program);
  117. glfwDestroyWindow(window);
  118. glfwTerminate();
  119. }
  120. GLuint GameEngine::setInstance(GLuint program, GameEngine* en)
  121. {
  122. GameEngine::instance = en;
  123. return program;
  124. }
  125. GameEngine::GameEngine(GLuint program, GLuint vShader, GLuint fShader, GLFWwindow* window,
  126. int width, int height, TickFunction tick, RenderTickFunction renderTick) :
  127. program(setInstance(program, this)), vShader(vShader), fShader(fShader), window(window), width(width), height(height), tick(tick), renderTick(renderTick)
  128. {
  129. updateScale();
  130. }
  131. GameEngine::~GameEngine()
  132. {
  133. }
  134. void GameEngine::onKeyEvent(GLFWwindow* w, int key, int scancode, int action, int mods)
  135. {
  136. if(action == GLFW_RELEASE)
  137. {
  138. if(key == GLFW_KEY_ESCAPE)
  139. {
  140. //activeFocus = 0;
  141. glfwSetInputMode(w, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
  142. }
  143. keyManager.release(key);
  144. }
  145. else if(action == GLFW_PRESS)
  146. {
  147. keyManager.press(key);
  148. }
  149. }
  150. void GameEngine::onMouseClick(GLFWwindow* w, int button, int action, int mods)
  151. {
  152. if(action == GLFW_PRESS)
  153. {
  154. /*if(!activeFocus)
  155. {
  156. glfwSetInputMode(w, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  157. oldMouseX = 0;
  158. oldMouseY = 0;
  159. activeFocus = 1;
  160. }
  161. else
  162. {*/
  163. mouseManager.press(button);
  164. //}
  165. }
  166. else if(action == GLFW_RELEASE)
  167. {
  168. mouseManager.release(button);
  169. }
  170. }
  171. /*void GameEngine::onMouseMove(GLFWwindow* w, double x, double y)
  172. {
  173. if(activeFocus)
  174. {
  175. if(oldMouseX == 0 && oldMouseY == 0)
  176. {
  177. oldMouseX = x;
  178. oldMouseY = y;
  179. }
  180. else
  181. {
  182. mouseMove(x - oldMouseX, y - oldMouseY);
  183. oldMouseX = x;
  184. oldMouseY = y;
  185. }
  186. }
  187. }*/
  188. void GameEngine::onWindowResize(GLFWwindow* w, int width, int height)
  189. {
  190. glViewport(0, 0, width, height);
  191. GameEngine::width = width;
  192. GameEngine::height = height;
  193. updateScale();
  194. }
  195. GLchar* GameEngine::readFile(const char* name)
  196. {
  197. ifstream in;
  198. in.open(name);
  199. if(!in.fail())
  200. {
  201. int size = 128;
  202. int index = 0;
  203. GLchar* content = new GLchar[size];
  204. while(true)
  205. {
  206. GLchar c = in.get();
  207. if(in.eof())
  208. {
  209. break;
  210. }
  211. if(index >= size - 1)
  212. {
  213. GLchar* newContent = new GLchar[size * 2];
  214. memcpy(newContent, content, size);
  215. size *= 2;
  216. delete[] content;
  217. content = newContent;
  218. }
  219. content[index] = c;
  220. index++;
  221. }
  222. content[index] = '\0';
  223. index++;
  224. in.close();
  225. return content;
  226. }
  227. return nullptr;
  228. }
  229. bool GameEngine::checkShaderErrors(const char* name, GLuint shader)
  230. {
  231. bool returnValue = false;
  232. cout << "compiling " << name << " shader ..." << endl;
  233. GLenum error = glGetError();
  234. if(error)
  235. {
  236. cout << "error: " << glGetError() << endl;
  237. returnValue = true;
  238. }
  239. else
  240. {
  241. cout << "no error occured ..." << endl;
  242. }
  243. GLint compiled[1];
  244. glGetShaderiv(shader, GL_COMPILE_STATUS, compiled);
  245. if(compiled[0])
  246. {
  247. cout << name << " shader successfully compiled" << endl;
  248. }
  249. else
  250. {
  251. cout << name << "compiling of " << name << " failed:" << endl;
  252. GLchar buffer[512];
  253. GLsizei bufferSize = 512;
  254. GLsizei charsUsed = 0;
  255. glGetShaderInfoLog(shader, bufferSize, &charsUsed, buffer);
  256. // glGetProgramInfoLog should be null terminated ...
  257. buffer[bufferSize - 1] = '\0';
  258. cout << buffer << endl;
  259. returnValue = true;
  260. }
  261. return returnValue;
  262. }
  263. GLuint GameEngine::compileProgram(GLuint& vShader, GLuint& fShader, const GLchar* vertex, const GLchar* fragment)
  264. {
  265. vShader = glCreateShader(GL_VERTEX_SHADER);
  266. glShaderSource(vShader, 1, &vertex, nullptr);
  267. glCompileShader(vShader);
  268. if(checkShaderErrors("vertex", vShader))
  269. {
  270. return 0;
  271. }
  272. fShader = glCreateShader(GL_FRAGMENT_SHADER);
  273. glShaderSource(fShader, 1, &fragment, nullptr);
  274. glCompileShader(fShader);
  275. if(checkShaderErrors("fragment", fShader))
  276. {
  277. return 0;
  278. }
  279. GLuint program = glCreateProgram();
  280. glAttachShader(program, vShader);
  281. glAttachShader(program, fShader);
  282. glLinkProgram(program);
  283. cout << "linking shaders to program ..." << endl;
  284. GLenum error = glGetError();
  285. if(error)
  286. {
  287. cout << "error: " << glGetError() << endl;
  288. return 0;
  289. }
  290. else
  291. {
  292. cout << "no error occured ..." << endl;
  293. }
  294. GLint compiled[1];
  295. glGetProgramiv(program, GL_LINK_STATUS, compiled);
  296. if(compiled[0])
  297. {
  298. cout << "shaders successfully linked" << endl;
  299. }
  300. else
  301. {
  302. cout << "linking of shaders failed:" << endl;
  303. GLchar buffer[512];
  304. GLsizei bufferSize = 512;
  305. GLsizei charsUsed = 0;
  306. glGetProgramInfoLog(program, bufferSize, &charsUsed, buffer);
  307. // glGetProgramInfoLog should be null terminated ...
  308. buffer[bufferSize - 1] = '\0';
  309. cout << buffer << endl;
  310. return 0;
  311. }
  312. glUseProgram(program);
  313. return program;
  314. }
  315. GLuint GameEngine::createProgram(GLuint& vShader, GLuint& fShader)
  316. {
  317. GLchar* vertex = readFile("shader/vertex.vs");
  318. if(vertex == nullptr)
  319. {
  320. cout << "cannot read vertex.vs" << endl;
  321. return 0;
  322. }
  323. GLchar* fragment = readFile("shader/fragment.fs");
  324. if(fragment == nullptr)
  325. {
  326. cout << "cannot read fragment.fs" << endl;
  327. delete[] vertex;
  328. return 0;
  329. }
  330. GLuint program = compileProgram(vShader, fShader, vertex, fragment);
  331. delete[] vertex;
  332. delete[] fragment;
  333. return program;
  334. }
  335. void GameEngine::printError()
  336. {
  337. GLenum error = glGetError();
  338. switch(error)
  339. {
  340. case GL_NO_ERROR:
  341. cout << "> No error has been recorded." << endl;
  342. break;
  343. case GL_INVALID_ENUM:
  344. cout << "> An unacceptable value is specified for an enumerated argument." << endl;
  345. break;
  346. case GL_INVALID_VALUE:
  347. cout << "> A numeric argument is out of range." << endl;
  348. break;
  349. case GL_INVALID_OPERATION:
  350. cout << "> The specified operation is not allowed in the current state." << endl;
  351. break;
  352. case GL_INVALID_FRAMEBUFFER_OPERATION:
  353. cout << "> The framebuffer object is not complete." << endl;
  354. break;
  355. case GL_OUT_OF_MEMORY:
  356. cout << "> There is not enough memory left to execute the command." << endl;
  357. break;
  358. case GL_STACK_UNDERFLOW:
  359. cout << "> An attempt has been made to perform an operation that would cause an internal stack to underflow." << endl;
  360. break;
  361. case GL_STACK_OVERFLOW:
  362. cout << "> An attempt has been made to perform an operation that would cause an internal stack to overflow." << endl;
  363. break;
  364. default:
  365. cout << "> Unknown OpenGL error: " << error << endl;
  366. }
  367. }
  368. void GameEngine::updateScale()
  369. {
  370. scale = 1;
  371. while(width / (scale + 1) >= 400 && height / (scale + 1) >= 300)
  372. {
  373. scale++;
  374. }
  375. }
  376. GameEngine* GameEngine::get()
  377. {
  378. return instance;
  379. }
  380. KeyManager& GameEngine::getKeyManager()
  381. {
  382. return keyManager;
  383. }
  384. MouseManager& GameEngine::getMouseManager()
  385. {
  386. return mouseManager;
  387. }
  388. Shader& GameEngine::getShader()
  389. {
  390. return shader;
  391. }
  392. DirectRenderer& GameEngine::getDirectRenderer()
  393. {
  394. return directRenderer;
  395. }
  396. double GameEngine::getTicksPerSecond() const
  397. {
  398. return tps.getUpdatesPerSecond();
  399. }
  400. double GameEngine::getFramesPerSecond() const
  401. {
  402. return fps.getUpdatesPerSecond();
  403. }
  404. int GameEngine::getScale() const
  405. {
  406. return scale;
  407. }
  408. int GameEngine::getWidth() const
  409. {
  410. return width;
  411. }
  412. int GameEngine::getHeight() const
  413. {
  414. return height;
  415. }
  416. GLint GameEngine::getUniformLocation(const GLchar* name) const
  417. {
  418. return glGetUniformLocation(program, name);
  419. }
  420. void GameEngine::setMatrix(GLint location, const GLfloat* m)
  421. {
  422. glUniformMatrix4fv(location, 1, 0, m);
  423. }
  424. void GameEngine::setInt(GLint location, GLint i)
  425. {
  426. glUniform1i(location, i);
  427. }
  428. void GameEngine::setFloat(GLint location, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4)
  429. {
  430. glUniform4f(location, f1, f2, f3, f4);
  431. }