app.d 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. import std.stdio;
  2. import std.typecons;
  3. import three;
  4. import std.experimental.logger;
  5. //======================================================================================================================
  6. //
  7. //======================================================================================================================
  8. struct SOAVector3 {
  9. SoA!float x;
  10. SoA!float y;
  11. SoA!float z;
  12. }
  13. struct SOAQuaternion {
  14. SoA!float x;
  15. SoA!float y;
  16. SoA!float z;
  17. SoA!float w;
  18. }
  19. //======================================================================================================================
  20. //
  21. //======================================================================================================================
  22. void main() {
  23. Window window;
  24. Viewport viewport;
  25. Scene scene;
  26. Camera camera;
  27. RenderTarget renderTarget;
  28. OpenGlTiledDeferredRenderer renderer;
  29. bool keepRunning = true;
  30. //------------------------------------------------
  31. // Load and Construct Rendering Pipeline
  32. //------------------------------------------------
  33. DerelictGL3.load();
  34. DerelictGLFW3.load();
  35. DerelictFI.load();
  36. // DerelictFT.load();
  37. DerelictASSIMP3.load();
  38. DerelictAntTweakBar.load();
  39. if(!glfwInit()) throw new Exception("Initialising GLFW failed"); scope(exit) glfwTerminate();
  40. window.construct("Three.d", 1600, 900); scope(exit) window.destruct();
  41. try {
  42. GLVersion glVersion = DerelictGL3.reload();
  43. import std.conv : to;
  44. writeln("Reloaded OpenGL Version: ", to!string(glVersion));
  45. } catch(Exception e) {
  46. writeln("Reloading OpenGl failed: " ~ e.msg);
  47. }
  48. // static FT_Library _s_freeTypeLibrary
  49. // if(!FT_Init_FreeType(&_s_freeTypeLibrary)) throw new Exception("Initialising FreeType failed"); scope(exit) FT_Done_FreeType(_s_freeTypeLibrary);
  50. if(TwInit(TW_OPENGL_CORE, null) == 0) throw new Exception("Initialising AntTweakBar failed"); scope(exit) TwTerminate();
  51. viewport.construct(); scope(exit) window.destruct();
  52. scene.construct(); scope(exit) window.destruct();
  53. camera.construct(); scope(exit) window.destruct();
  54. renderTarget.construct(window.width, window.height); scope(exit) renderTarget.destruct();
  55. renderer.construct(window.width, window.height); scope(exit) renderer.destruct();
  56. //------------------------------------------------
  57. // Create Scene
  58. //------------------------------------------------
  59. scene.mesh.loadModel("C:/Coding/models/Collada/duck.dae");
  60. //------------------------------------------------
  61. // Generate TweakBar
  62. //------------------------------------------------
  63. TwWindowSize(window.width, window.height);
  64. auto tweakBar = TwNewBar("TweakBar");
  65. //------------------------------------------------
  66. // Connect Window callbacks
  67. //------------------------------------------------
  68. window.onKey = (ref Window rWindow, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  69. if(window is window && action == KeyAction.Pressed) {
  70. if(key == Key.Escape) {
  71. keepRunning = false;
  72. }
  73. }
  74. };
  75. window.onClose = (ref Window rWindow) {
  76. keepRunning = false;
  77. };
  78. window.onSize = (ref Window rWindow, int width, int height) {
  79. TwWindowSize(width, height);
  80. };
  81. window.onPosition = (ref Window rWindow, int x, int y) {
  82. };
  83. window.onButton = (ref Window rWindow , int button, ButtonAction action) {
  84. TwMouseAction twaction = action == ButtonAction.Pressed ? TW_MOUSE_PRESSED : TW_MOUSE_RELEASED;
  85. TwMouseButtonID twbutton;
  86. switch(button) {
  87. default:
  88. case GLFW_MOUSE_BUTTON_LEFT: twbutton = TW_MOUSE_LEFT; break;
  89. case GLFW_MOUSE_BUTTON_RIGHT: twbutton = TW_MOUSE_RIGHT; break;
  90. case GLFW_MOUSE_BUTTON_MIDDLE: twbutton = TW_MOUSE_MIDDLE; break;
  91. }
  92. TwMouseButton(twaction, twbutton);
  93. };
  94. window.onCursorPos = (ref Window rWindow, double x, double y) {
  95. TwMouseMotion(cast(int)x, window.height - cast(int)y);
  96. };
  97. //------------------------------------------------
  98. // Main Loop
  99. //------------------------------------------------
  100. ulong frameCount = 0;
  101. glfwSetTime(0);
  102. while(keepRunning) {
  103. window.pollEvents();
  104. window.makeAktiveRenderWindow();
  105. glCheck!glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  106. glCheck!glClearDepth(1.0f);
  107. glCheck!glClearColor(0, 0.3, 0, 1);
  108. renderer.renderOneFrame(scene, camera, renderTarget, viewport);
  109. TwDraw();
  110. debug{ renderer.blitGBufferToScreen(); }
  111. window.swapBuffers();
  112. ++frameCount;
  113. if(frameCount % 1000 == 0) {
  114. auto fps = cast(double)frameCount / glfwGetTime();
  115. log("FPS: ", fps);
  116. frameCount = 0;
  117. glfwSetTime(0);
  118. }
  119. }
  120. }
  121. /+++
  122. struct Vertex {
  123. float x, y, z;
  124. }
  125. struct Normal {
  126. float x, y, z;
  127. }
  128. struct UV {
  129. float u, v;
  130. }
  131. final class Mesh {
  132. public:
  133. Vertex[] vertexData;
  134. Normal[] normalData;
  135. UV[] textureData;
  136. RGBAf[] colorData;
  137. VertexArrayObject vao;
  138. VertexBufferObject!(VertexBufferObjectTarget.Array) vboVertexData;
  139. VertexBufferObject!(VertexBufferObjectTarget.Array) vboNormalData;
  140. VertexBufferObject!(VertexBufferObjectTarget.Array) vboTextureData;
  141. VertexBufferObject!(VertexBufferObjectTarget.Array) vboColorData;
  142. this(string filePath) {
  143. writeln("loading scene: ", filePath);
  144. auto scene = aiImportFile(filePath.toStringz(), aiProcess_Triangulate);
  145. writeln("meshes: ", scene.mNumMeshes);
  146. for(uint m = 0; m < scene.mNumMeshes; ++m) {
  147. const(aiMesh*) mesh = scene.mMeshes[m];
  148. assert(mesh !is null);
  149. writeln("mesh[", m, "] faces : ", mesh.mNumFaces);
  150. for (uint f = 0; f < mesh.mNumFaces; ++f) {
  151. const(aiFace*) face = &mesh.mFaces[f];
  152. assert(face !is null);
  153. for(uint v = 0; v < 3; ++v) {
  154. aiVector3D p, n, uv;
  155. assert(face.mNumIndices > v);
  156. uint vertex = face.mIndices[v];
  157. assert(mesh.mNumVertices > vertex);
  158. p = mesh.mVertices[vertex];
  159. n = mesh.mNormals[vertex];
  160. // check if the mesh has texture coordinates
  161. if(mesh.mTextureCoords[0] !is null) {
  162. uv = mesh.mTextureCoords[0][vertex];
  163. }
  164. vertexData ~= Vertex(p.x, p.y, p.z);
  165. normalData ~= Normal(n.x, n.y, n.z);
  166. textureData ~= UV(uv.x, uv.y);
  167. colorData ~= RGBAf(n.x, n.y, n.z, 1.0f);
  168. }
  169. }
  170. }
  171. writeln("unloading scene: ", filePath);
  172. aiReleaseImport(scene);
  173. //-----------------------------
  174. // upload
  175. writeln("uploading mesh: ", filePath);
  176. vao = new VertexArrayObject();
  177. vao.bind();
  178. writeln("vertex data");
  179. vboVertexData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  180. vboVertexData.bind();
  181. GLuint attribIndex = 0;
  182. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Vertex.sizeof * vertexData.length) , vertexData.ptr, GL_STATIC_DRAW);
  183. glEnableVertexAttribArray(attribIndex);
  184. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  185. vboVertexData.unbind();
  186. writeln("normal data");
  187. vboNormalData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  188. vboNormalData.bind();
  189. attribIndex = 1;
  190. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Normal.sizeof * normalData.length) , normalData.ptr, GL_STATIC_DRAW);
  191. glEnableVertexAttribArray(attribIndex);
  192. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  193. vboNormalData.unbind();
  194. writeln("uv data");
  195. vboTextureData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  196. vboTextureData.bind();
  197. attribIndex = 2;
  198. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(UV.sizeof * textureData.length) , textureData.ptr, GL_STATIC_DRAW);
  199. glEnableVertexAttribArray(attribIndex);
  200. glVertexAttribPointer(attribIndex, 2, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  201. vboTextureData.unbind();
  202. writeln("color data");
  203. vboColorData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  204. vboColorData.bind();
  205. attribIndex = 3;
  206. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(RGBAf.sizeof * colorData.length) , colorData.ptr, GL_STATIC_DRAW);
  207. glEnableVertexAttribArray(attribIndex);
  208. glVertexAttribPointer(attribIndex, 4, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  209. vboColorData.unbind();
  210. vao.unbind();
  211. writeln("done");
  212. }
  213. }
  214. void setupTweakbar() {
  215. writeln("creating TweakBar");
  216. double time = 0, dt; // Current time and enlapsed time
  217. double turn = 0; // Model turn counter
  218. double speed = 0.3; // Model rotation speed
  219. int wire = 0; // Draw model in wireframe?
  220. uint frameCount = 0;
  221. double fps = 0;
  222. float bgColor[3] = [0.1f, 0.2f, 0.4f]; // Background color
  223. ubyte cubeColor[4] = [255, 0, 0, 128]; // Model color (32bits RGBA)
  224. auto quat = Quaternionf(0,0,0,1);
  225. // auto w = this._window.getBounds()[2];
  226. // auto h = this._window.getBounds()[3];
  227. TwWindowSize(1600, 900);
  228. // // Create a tweak bar
  229. // auto bar = TwNewBar("TweakBar");
  230. // TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLFW and OpenGL.' "); // Message added to the help bar.
  231. // // Add 'speed' to 'bar': it is a modifable (RW) variable of type TW_TYPE_DOUBLE. Its key shortcuts are [s] and [S].
  232. // TwAddVarRW(bar, "speed", TW_TYPE_DOUBLE, &speed, " label='Rot speed' min=0 max=2 step=0.01 keyIncr=s keyDecr=S help='Rotation speed (turns/second)' ");
  233. // // Add 'wire' to 'bar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w].
  234. // TwAddVarRW(bar, "wire", TW_TYPE_BOOL32, &wire, " label='Wireframe mode' key=CTRL+w help='Toggle wireframe display mode.' ");
  235. // // Add 'time' to 'bar': it is a read-only (RO) variable of type TW_TYPE_DOUBLE, with 1 precision digit
  236. // TwAddVarRO(bar, "time", TW_TYPE_DOUBLE, &time, " label='Time' precision=1 help='Time (in seconds).' ");
  237. // //
  238. // TwAddVarRO(bar, "frameCount", TW_TYPE_UINT32, &frameCount, " label='FrameCount' precision=1 help='FrameCount (in counts).' ");
  239. // TwAddVarRO(bar, "fps", TW_TYPE_DOUBLE, &fps, " label='fps' precision=1 help='fps (in fps).' ");
  240. // // Add 'bgColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color)
  241. // TwAddVarRW(bar, "bgColor", TW_TYPE_COLOR3F, &bgColor, " label='Background color' ");
  242. // // Add 'cubeColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR32 (32 bits color) with alpha
  243. // TwAddVarRW(bar, "cubeColor", TW_TYPE_COLOR32, &cubeColor, " label='Cube color' alpha help='Color and transparency of the cube.' ");
  244. // //
  245. // TwAddVarRW(bar, "quaternion", TW_TYPE_QUAT4F, &quat, " label='Cubde color' alpha help='Color anwdwd transparency of the cube.' ");
  246. }
  247. //-----------------
  248. // Create Shaders
  249. enum vertexShaderSource = "
  250. #version 420 core
  251. layout(location = 0) in vec3 in_position;
  252. layout(location = 1) in vec3 in_normal;
  253. layout(location = 2) in vec2 in_texcoord;
  254. layout(location = 3) in vec4 in_color;
  255. out vec4 v_color;
  256. out gl_PerVertex
  257. {
  258. vec4 gl_Position;
  259. };
  260. void main()
  261. {
  262. gl_Position = vec4(0.005 * in_position.x, 0.005 * in_position.y, 0.005* in_position.z, 1.0);
  263. v_color = in_color;
  264. }
  265. ";
  266. enum fragmentShaderSource = "
  267. #version 420 core
  268. in vec4 v_color;
  269. out vec4 FragColor;
  270. void main()
  271. {
  272. FragColor = v_color;
  273. }
  274. ";
  275. auto createShaderPipeline(Shader!(ShaderType.Vertex) vertexShader, Shader!(ShaderType.Fragment) fragmentShader) {
  276. assert(vertexShader.isLinked, vertexShader.infoLog());
  277. assert(fragmentShader.isLinked, fragmentShader.infoLog());
  278. writeln("a: ");
  279. auto shaderPipeline = new ShaderPipeline();
  280. shaderPipeline.bind();
  281. shaderPipeline.use(vertexShader);
  282. shaderPipeline.use(fragmentShader);
  283. writeln("b: ");
  284. assert(shaderPipeline.isValidProgramPipeline, shaderPipeline.infoLog());
  285. shaderPipeline.unbind();
  286. writeln("c: ");
  287. return shaderPipeline;
  288. }
  289. class Tester {
  290. Window _window;
  291. bool _keepRunning = true;
  292. this() {
  293. this._window = initThree();
  294. this._window.onKey.connect!"_onKey"(this);
  295. this._window.onClose.connect!"_onClose"(this);
  296. }
  297. ~this() {
  298. import core.memory;
  299. writeln("GC.collect: ");
  300. GC.collect();
  301. //Collect window _AFTER_ everything else
  302. this._window = null;
  303. GC.collect();
  304. deinitThree();
  305. }
  306. void run() {
  307. RGBAf rgg;
  308. auto mesh = new Mesh("C:/Coding/models/Collada/duck.dae");
  309. setupTweakbar();
  310. writeln("creating shaders: ");
  311. auto vertexShader = new Shader!(ShaderType.Vertex)(vertexShaderSource);
  312. auto fragmentShader = new Shader!(ShaderType.Fragment)(fragmentShaderSource);
  313. writeln("creating shader pipeline: ");
  314. auto shaderPipeline = createShaderPipeline(vertexShader, fragmentShader);
  315. writeln("connectiong window callbacks: ");
  316. this._window.onSize.connect!"onSize"(this);
  317. this._window.onPosition.connect!"onPosition"(this);
  318. this._window.onButton.connect!"onButton"(this);
  319. this._window.onCursorPos.connect!"onCursorPos"(this);
  320. writeln("begin render loop: ");
  321. //-----------------
  322. // Render Loop
  323. glfwSetTime(0);
  324. while(this._keepRunning) {
  325. this._window.clear(0, 0, 0.5, 1);
  326. shaderPipeline.bind();
  327. mesh.vao.bind();
  328. //vboVertexData.bind();
  329. glDrawArrays(GL_TRIANGLES, 0, mesh.vertexData.length);
  330. //vbo.unbind();
  331. mesh.vao.unbind();
  332. shaderPipeline.unbind();
  333. TwDraw();
  334. this._window.swapBuffers();
  335. updateWindows();
  336. // ++frameCount;
  337. // //if(frameCount % 100 == 0) {
  338. // time = glfwGetTime();
  339. // fps = cast(double)frameCount / time;
  340. // //}
  341. }
  342. }
  343. void onSize(Window window, int width, int height) {
  344. TwWindowSize(width, height);
  345. }
  346. void onPosition(Window window, int x, int y) {
  347. }
  348. void onButton(Window window , int button, ButtonAction action) {
  349. TwMouseAction twaction = action == ButtonAction.Pressed ? TW_MOUSE_PRESSED : TW_MOUSE_RELEASED;
  350. TwMouseButtonID twbutton;
  351. switch(button) {
  352. default:
  353. case GLFW_MOUSE_BUTTON_LEFT: twbutton = TW_MOUSE_LEFT; break;
  354. case GLFW_MOUSE_BUTTON_RIGHT: twbutton = TW_MOUSE_RIGHT; break;
  355. case GLFW_MOUSE_BUTTON_MIDDLE: twbutton = TW_MOUSE_MIDDLE; break;
  356. }
  357. TwMouseButton(twaction, twbutton);
  358. }
  359. void onCursorPos(Window window, double x, double y) {
  360. TwMouseMotion(cast(int)x, this._window.getBounds()[3] - cast(int)y);
  361. }
  362. void stop() {
  363. this._keepRunning = false;
  364. }
  365. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  366. if(window is this._window && action == KeyAction.Pressed) {
  367. if(key == Key.Escape) {
  368. this.stop();
  369. }
  370. }
  371. }
  372. void _onClose(Window window) {
  373. this.stop();
  374. }
  375. }
  376. class InputHandler {
  377. private:
  378. Window _window;
  379. OpenGlRenderer _renderer;
  380. public:
  381. this(Window window, OpenGlRenderer renderer) {
  382. _window = window;
  383. _renderer = renderer;
  384. _window.onKey.connect!"_onKey"(this);
  385. _window.onClose.connect!"_onClose"(this);
  386. _window.onSize.connect!"_onSize"(this);
  387. _window.onPosition.connect!"_onPosition"(this);
  388. _window.onButton.connect!"_onButton"(this);
  389. _window.onCursorPos.connect!"_onCursorPos"(this);
  390. }
  391. private:
  392. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  393. if(window is _window && action == KeyAction.Pressed) {
  394. if(key == Key.Escape) {
  395. _renderer.stop();
  396. }
  397. }
  398. }
  399. void _onClose(Window window) {
  400. _renderer.stop();
  401. }
  402. void _onSize(Window window, int width, int height) {
  403. }
  404. void _onPosition(Window window, int x, int y) {
  405. }
  406. void _onButton(Window window , int button, ButtonAction action) {
  407. }
  408. void _onCursorPos(Window window, double x, double y) {
  409. }
  410. }
  411. void main() {
  412. auto window = initThree();
  413. {
  414. OpenGlRenderer renderer = new OpenGlRenderer(window);
  415. InputHandler inputHandler = new InputHandler(window, renderer);
  416. renderer.run();
  417. }
  418. import core.memory;
  419. GC.collect();
  420. //Collect window _AFTER_ everything else
  421. this._window = null;
  422. GC.collect();
  423. deinitThree();
  424. }
  425. +++/