Wrapper.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. #include "Wrapper.h"
  2. #include <cmath>
  3. #include <chrono>
  4. #include <thread>
  5. DummyClient DummyClient::dummy;
  6. IClient* Engine::client = &DummyClient::dummy;
  7. // window data
  8. GLFWwindow* Engine::window = nullptr;
  9. int Engine::scale = 1;
  10. int Engine::width = 0;
  11. int Engine::height = 0;
  12. int Engine::resizeTicks = -1;
  13. // projection data
  14. float Engine::fovY = 60;
  15. float Engine::nearClip = 0.1f;
  16. float Engine::farClip = 1000.0f;
  17. Matrix3D Engine::projMatrix;
  18. // rectangle for framebuffer drawing
  19. FramebufferRectangle Engine::rectangle;
  20. // shader stage 0 - world shadow mapping
  21. WorldShadowShader Engine::worldShadowShader;
  22. // shader stage 1 - world
  23. WorldShader Engine::worldShader;
  24. // shader stage 2 - world ssao
  25. SSAOShader Engine::ssaoShader;
  26. // shader stage 3 - world ssao blur
  27. SSAOBlurShader Engine::ssaoBlurShader;
  28. // shader stage 4 - world post
  29. WorldPostShader Engine::worldPostShader;
  30. // shader stage 5 - 2D overlay
  31. OverlayShader Engine::overlayShader;
  32. bool Engine::init(int width, int height, const char* name)
  33. {
  34. Engine::width = width;
  35. Engine::height = height;
  36. updateScale();
  37. if(!glfwInit())
  38. {
  39. cout << "could not initialize GLFW" << endl;
  40. return false;
  41. }
  42. glfwDefaultWindowHints();
  43. glfwWindowHint(GLFW_VISIBLE, 0);
  44. glfwWindowHint(GLFW_RESIZABLE, 1);
  45. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
  46. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
  47. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  48. window = glfwCreateWindow(width, height, name, nullptr, nullptr);
  49. if(!window)
  50. {
  51. cout << "could not create window" << endl;
  52. glfwTerminate();
  53. return false;
  54. }
  55. glfwMakeContextCurrent(window);
  56. glfwSwapInterval(1);
  57. glfwShowWindow(window);
  58. GLenum err = glewInit();
  59. if(GLEW_OK != err)
  60. {
  61. cout << "could not initialize GLEW: " << glewGetErrorString(err) << endl;
  62. return false;
  63. }
  64. cout << "Status: Using GLEW " << glewGetString(GLEW_VERSION) << endl;
  65. if(!worldShader.init() || !ssaoShader.init() || !ssaoBlurShader.init() ||
  66. !worldPostShader.init() || !overlayShader.init() || !rectangle.init() ||
  67. !worldShadowShader.init())
  68. {
  69. glfwDestroyWindow(window);
  70. glfwTerminate();
  71. return false;
  72. }
  73. glfwSetKeyCallback(window, onKeyEvent);
  74. glfwSetMouseButtonCallback(window, onMouseClick);
  75. glfwSetFramebufferSizeCallback(window, onWindowResize);
  76. glfwSetCursorPosCallback(window, onMouseMove);
  77. return true;
  78. }
  79. void Engine::sleep(uint64_t nanos)
  80. {
  81. uint64_t end = glfwGetTimerValue() + nanos - 10000;
  82. // non busy wait until a close range
  83. while(end > glfwGetTimerValue() + 1000000)
  84. {
  85. this_thread::sleep_for(chrono::nanoseconds(1000000));
  86. }
  87. while(end > glfwGetTimerValue() + 100000)
  88. {
  89. this_thread::sleep_for(chrono::nanoseconds(100000));
  90. }
  91. // busy wait for higher accuracy at the end
  92. while(end > glfwGetTimerValue());
  93. }
  94. void Engine::start(IClient* client)
  95. {
  96. if(client != nullptr)
  97. {
  98. Engine::client = client;
  99. }
  100. glEnable(GL_CULL_FACE);
  101. glDepthFunc(GL_LEQUAL);
  102. uint64_t newTime = glfwGetTimerValue();
  103. uint64_t oldTime = newTime;
  104. uint64_t lag = 0;
  105. uint64_t frameLag = 0;
  106. uint64_t lastFrame = 0;
  107. while(!glfwWindowShouldClose(window))
  108. {
  109. oldTime = newTime;
  110. newTime = glfwGetTimerValue();
  111. lag += newTime - oldTime;
  112. frameLag += newTime - oldTime;
  113. if(lag >= NANOS_PER_TICK || frameLag >= NANOS_PER_FRAME)
  114. {
  115. int ticksPerFrame = 0;
  116. while(lag >= NANOS_PER_TICK)
  117. {
  118. lag -= NANOS_PER_TICK;
  119. Engine::client->tick();
  120. ticksPerFrame++;
  121. resizeTicks -= (resizeTicks >= 0);
  122. if(resizeTicks == 0)
  123. {
  124. glViewport(0, 0, width, height);
  125. updateScale();
  126. worldShader.resize();
  127. ssaoShader.resize();
  128. ssaoBlurShader.resize();
  129. worldPostShader.resize();
  130. worldShadowShader.resize();
  131. }
  132. if(ticksPerFrame >= MAX_TICKS_PER_FRAME)
  133. {
  134. long skip = lag / NANOS_PER_TICK;
  135. lag -= skip * NANOS_PER_TICK;
  136. if(skip > 0)
  137. {
  138. cout << "skipped " << skip << " game ticks " << lag << endl;
  139. }
  140. break;
  141. }
  142. }
  143. if(frameLag >= NANOS_PER_FRAME)
  144. {
  145. frameLag -= NANOS_PER_FRAME;
  146. // make sure no frames are rendered immediately after each other
  147. // this happens if the game tick takes too long
  148. if(lastFrame + NANOS_PER_FRAME - 1000000 < glfwGetTimerValue())
  149. {
  150. lastFrame = glfwGetTimerValue();
  151. if(resizeTicks == -1)
  152. {
  153. onRenderTick((float) lag / NANOS_PER_TICK);
  154. glfwSwapBuffers(window);
  155. }
  156. }
  157. }
  158. glfwPollEvents();
  159. }
  160. else
  161. {
  162. // wait until next frame
  163. long waitingTime = min(NANOS_PER_FRAME - frameLag, NANOS_PER_TICK - lag);
  164. sleep(waitingTime);
  165. }
  166. }
  167. glfwDestroyWindow(window);
  168. glfwTerminate();
  169. }
  170. void Engine::stop()
  171. {
  172. glfwSetWindowShouldClose(window, 1);
  173. }
  174. void Engine::onKeyEvent(GLFWwindow* w, int key, int scancode, int action, int mods)
  175. {
  176. client->onKeyEvent(key, scancode, action, mods);
  177. }
  178. void Engine::onMouseMove(GLFWwindow* w, double x, double y)
  179. {
  180. client->onMouseMove(x, y);
  181. }
  182. void Engine::onMouseClick(GLFWwindow* w, int button, int action, int mods)
  183. {
  184. client->onMouseClick(button, action, mods);
  185. }
  186. void Engine::onWindowResize(GLFWwindow* w, int width, int height)
  187. {
  188. Engine::width = width;
  189. Engine::height = height;
  190. resizeTicks = 10;
  191. }
  192. void Engine::updateScale()
  193. {
  194. scale = 1;
  195. while(width / (scale + 1) >= 400 && height / (scale + 1) >= 300)
  196. {
  197. scale++;
  198. }
  199. }
  200. int Engine::getScale()
  201. {
  202. return scale;
  203. }
  204. int Engine::getWidth()
  205. {
  206. return width;
  207. }
  208. int Engine::getHeight()
  209. {
  210. return height;
  211. }
  212. float Engine::getFieldOfView()
  213. {
  214. return fovY;
  215. }
  216. float Engine::getNearClip()
  217. {
  218. return nearClip;
  219. }
  220. float Engine::getFarClip()
  221. {
  222. return farClip;
  223. }
  224. void Engine::printError()
  225. {
  226. GLenum error = glGetError();
  227. switch(error)
  228. {
  229. case GL_NO_ERROR:
  230. //cout << "> No error has been recorded." << endl;
  231. break;
  232. case GL_INVALID_ENUM:
  233. cout << "> An unacceptable value is specified for an enumerated argument." << endl;
  234. break;
  235. case GL_INVALID_VALUE:
  236. cout << "> A numeric argument is out of range." << endl;
  237. break;
  238. case GL_INVALID_OPERATION:
  239. cout << "> The specified operation is not allowed in the current state." << endl;
  240. break;
  241. case GL_INVALID_FRAMEBUFFER_OPERATION:
  242. cout << "> The framebuffer object is not complete." << endl;
  243. break;
  244. case GL_OUT_OF_MEMORY:
  245. cout << "> There is not enough memory left to execute the command." << endl;
  246. break;
  247. case GL_STACK_UNDERFLOW:
  248. cout << "> An attempt has been made to perform an operation that would cause an internal stack to underflow." << endl;
  249. break;
  250. case GL_STACK_OVERFLOW:
  251. cout << "> An attempt has been made to perform an operation that would cause an internal stack to overflow." << endl;
  252. break;
  253. default:
  254. cout << "> Unknown OpenGL error: " << error << endl;
  255. }
  256. }
  257. void Engine::onRenderTick(float lag)
  258. {
  259. // update projection matrix
  260. float tan = tanf((0.5f * fovY) * M_PI / 180.0f);
  261. float q = 1.0f / tan;
  262. float aspect = (float) width / height;
  263. projMatrix.set(0, 0, q / aspect);
  264. projMatrix.set(1, 1, q);
  265. projMatrix.set(2, 2, (nearClip + farClip) / (nearClip - farClip));
  266. projMatrix.set(3, 2, -1.0f);
  267. projMatrix.set(2, 3, (2.0f * nearClip * farClip) / (nearClip - farClip));
  268. projMatrix.set(3, 3, 0);
  269. // -------------------------------------------------------------------------
  270. // shader stage 0 - world shadow mapping
  271. // -------------------------------------------------------------------------
  272. /*worldShadowShader.preRender(projMatrix.getValues());
  273. Matrix3D sunView;
  274. Vector3D front;
  275. front.setAngles(60, 60);
  276. // back
  277. Vector3D back;
  278. back.setInverse(front);
  279. // right
  280. Vector3D right;
  281. right.set(front);
  282. right.cross(0.0f, 1.0f, 0.0f);
  283. right.normalize();
  284. // left
  285. Vector3D left;
  286. left.setInverse(right);
  287. // up
  288. Vector3D up;
  289. up.set(front);
  290. up.cross(left);
  291. up.normalize();
  292. Vector3D interCamera(16, 16, 16);
  293. sunView.set(0, 0, right.getX());
  294. sunView.set(0, 1, right.getY());
  295. sunView.set(0, 2, right.getZ());
  296. sunView.set(0, 3, right.dotInverse(interCamera));
  297. sunView.set(1, 0, up.getX());
  298. sunView.set(1, 1, up.getY());
  299. sunView.set(1, 2, up.getZ());
  300. sunView.set(1, 3, up.dotInverse(interCamera));
  301. sunView.set(2, 0, back.getX());
  302. sunView.set(2, 1, back.getY());
  303. sunView.set(2, 2, back.getZ());
  304. sunView.set(2, 3, back.dotInverse(interCamera));
  305. sunView.set(3, 0, 0.0f);
  306. sunView.set(3, 1, 0.0f);
  307. sunView.set(3, 0, 0.0f);
  308. sunView.set(3, 3, 1.0f);
  309. worldShadowShader.setViewMatrix(sunView.getValues());
  310. client->render3DShadowTick(lag);*/
  311. // -------------------------------------------------------------------------
  312. // shader stage 1 - world
  313. // -------------------------------------------------------------------------
  314. worldShader.preRender(projMatrix.getValues());
  315. // call render tick for further drawing
  316. client->render3DTick(lag);
  317. // -------------------------------------------------------------------------
  318. // shader stage 2 - world ssao
  319. // -------------------------------------------------------------------------
  320. ssaoShader.preRender(projMatrix.getValues());
  321. // bind previously generated texture data buffers
  322. worldShader.bindPositionTexture(1);
  323. worldShader.bindNormalTexture(2);
  324. worldShader.bindColorTexture(3);
  325. worldShader.bindDepthTexture(4);
  326. ssaoShader.bindNoiseTexture(5);
  327. worldShadowShader.bindDepthTexture(6);
  328. rectangle.draw();
  329. // -------------------------------------------------------------------------
  330. // shader stage 3 - world ssao blur
  331. // -------------------------------------------------------------------------
  332. ssaoBlurShader.preRender();
  333. ssaoShader.bindTexture(6);
  334. rectangle.draw();
  335. // -------------------------------------------------------------------------
  336. // shader stage 4 - world post
  337. // -------------------------------------------------------------------------
  338. worldPostShader.preRender();
  339. ssaoBlurShader.bindTexture(7);
  340. rectangle.draw();
  341. // -------------------------------------------------------------------------
  342. // shader stage 5 - 2D overlay
  343. // -------------------------------------------------------------------------
  344. overlayShader.preRender();
  345. worldPostShader.bindTexture(0);
  346. rectangle.draw();
  347. overlayShader.setViewMatrix();
  348. overlayShader.setUseColor(true);
  349. overlayShader.setUseTexture(true);
  350. glEnable(GL_BLEND);
  351. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  352. glBlendEquation(GL_FUNC_ADD);
  353. client->render2DTick(lag);
  354. glDisable(GL_BLEND);
  355. }
  356. void Engine::setWorldViewMatrix(const float* data)
  357. {
  358. worldShader.setViewMatrix(data);
  359. }
  360. void Engine::setWorldModelMatrix(const float* data)
  361. {
  362. worldShader.setModelMatrix(data);
  363. worldShadowShader.setModelMatrix(data);
  364. }
  365. void Engine::setOverlayModelMatrix(const float* data)
  366. {
  367. overlayShader.setModelMatrix(data);
  368. }
  369. void Engine::setMouseTrapped(bool mode)
  370. {
  371. if(mode)
  372. {
  373. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
  374. }
  375. else
  376. {
  377. glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
  378. }
  379. }