app.d 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. import std.stdio;
  2. import std.typecons;
  3. import three;
  4. import std.experimental.logger;
  5. public import derelict.opengl3.gl3;
  6. public import derelict.glfw3.glfw3;
  7. public import derelict.anttweakbar.anttweakbar;
  8. public import derelict.freeimage.freeimage;
  9. public import derelict.freetype.ft;
  10. public import derelict.assimp3.assimp;
  11. public import std.experimental.logger;
  12. import three.gl.renderer;
  13. import three.window;
  14. import three.viewport;
  15. import three.camera;
  16. import three.scene;
  17. void main() {
  18. Window window;
  19. Viewport viewport;
  20. Scene scene;
  21. Camera camera;
  22. GlRenderTarget renderTarget;
  23. // OpenGlTiledDeferredRenderer renderer;
  24. Renderer renderer;
  25. bool keepRunning = true;
  26. //------------------------------------------------
  27. // Load and Construct Rendering Pipeline
  28. //------------------------------------------------
  29. DerelictGL3.load();
  30. DerelictGLFW3.load();
  31. DerelictFI.load();
  32. // DerelictFT.load();
  33. DerelictASSIMP3.load();
  34. DerelictAntTweakBar.load();
  35. if(!glfwInit()) throw new Exception("Initialising GLFW failed"); scope(exit) glfwTerminate();
  36. window.construct("Three.d", 1600, 900); scope(exit) window.destruct();
  37. try {
  38. GLVersion glVersion = DerelictGL3.reload();
  39. import std.conv : to;
  40. writeln("Reloaded OpenGL Version: ", to!string(glVersion));
  41. } catch(Exception e) {
  42. writeln("Reloading OpenGl failed: " ~ e.msg);
  43. }
  44. // static FT_Library _s_freeTypeLibrary
  45. // if(!FT_Init_FreeType(&_s_freeTypeLibrary)) throw new Exception("Initialising FreeType failed"); scope(exit) FT_Done_FreeType(_s_freeTypeLibrary);
  46. if(TwInit(TW_OPENGL_CORE, null) == 0) throw new Exception("Initialising AntTweakBar failed"); scope(exit) TwTerminate();
  47. viewport.construct(); scope(exit) viewport.destruct();
  48. scene.construct(); scope(exit) scene.destruct();
  49. camera.construct(); scope(exit) camera.destruct();
  50. renderTarget.construct(window.width, window.height); scope(exit) renderTarget.destruct();
  51. renderer.construct(window.width, window.height); scope(exit) renderer.destruct();
  52. //------------------------------------------------
  53. // Create Scene
  54. //------------------------------------------------
  55. scene.modelData = loadModelData("C:/Coding/models/Collada/duck.dae");
  56. log("Model: ", scene.modelData.filePath);
  57. log("vertexCount: ", scene.modelData.vertexCount);
  58. log("indexCount: ", scene.modelData.indexCount);
  59. log("meshCount: ", scene.modelData.meshCount);
  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. renderer.renderOneFrame(scene, camera, renderTarget, viewport);
  106. debug{ renderer.blitGBufferToScreen(); }
  107. // TwDraw();
  108. window.swapBuffers();
  109. ++frameCount;
  110. if(frameCount % 10 == 0) {
  111. auto fps = cast(double)frameCount / glfwGetTime();
  112. log("FPS: ", fps);
  113. frameCount = 0;
  114. glfwSetTime(0);
  115. }
  116. }
  117. }
  118. /+++++++
  119. //======================================================================================================================
  120. //
  121. //======================================================================================================================
  122. struct Slice(T) {
  123. T* data;
  124. size_t length;
  125. }
  126. //======================================================================================================================
  127. //
  128. //======================================================================================================================
  129. struct PersistentlyMappedBuffer(T) {
  130. GLuint bo;
  131. GLenum target;
  132. Slice!T data;
  133. alias Atom = T;
  134. }
  135. void create(T)(out PersistentlyMappedBuffer!T pmb, GLuint count, GLenum target, GLbitfield createFlags, GLbitfield mapFlags) {
  136. pmb.target = target;
  137. glCheck!glGenBuffers(1, &pmb.bo);
  138. glCheck!glBindBuffer(target, pmb.bo);
  139. glCheck!glBufferStorage(target, T.sizeof * count, null, createFlags);
  140. pmb.data.data = cast(T*)glMapBufferRange(target, 0, T.sizeof * count, mapFlags);
  141. pmb.data.length = count;
  142. if (!pmb.data.data) {
  143. throw new Exception("glMapBufferRange failed, probable bug.");
  144. }
  145. }
  146. void destroy(T)(ref PersistentlyMappedBuffer!T pmb) {
  147. glCheck!glBindBuffer(pmb.target, mName);
  148. glCheck!glUnmapBuffer(pmb.target);
  149. glCheck!glDeleteBuffers(1, &mName);
  150. pmb = GlPersistentlyMappedBuffer!T.init;
  151. }
  152. //
  153. ////======================================================================================================================
  154. ////
  155. ////======================================================================================================================
  156. //struct GlCircularBufferView(T) {
  157. // GlPersistentlyMappedBuffer!T _buffer;
  158. // GLsizeiptr _head;
  159. //}
  160. //======================================================================================================================
  161. //
  162. //======================================================================================================================
  163. struct DrawArraysIndirectCommand {
  164. GLuint vertexCount;
  165. GLuint instanceCount;
  166. GLuint firstVertex;
  167. GLuint baseInstance;
  168. }
  169. struct DrawElementsIndirectCommand {
  170. GLuint count;
  171. GLuint instanceCount;
  172. GLuint firstIndex;
  173. GLuint baseVertex;
  174. GLuint baseInstance;
  175. }
  176. struct PerInstanceRenderData {
  177. }
  178. struct MeshDataRef {
  179. }
  180. struct PerInstanceDataRef {
  181. }
  182. struct Mesh {
  183. size_t meshDataRef;
  184. InstanceData[] instanceData;
  185. }
  186. struct MeshInstance {
  187. size_t meshRef;
  188. size_t meshInstanceRef;
  189. }
  190. struct Renderer {
  191. MeshData[] meshData;
  192. Mesh[] meshes;
  193. MeshInstance[] meshInstances;
  194. PersistentlyMappedBuffer!DrawElementsIndirectCommand commandBuffer;
  195. PersistentlyMappedBuffer!TransformationMatrix perInstanceBuffer;
  196. void renderOneFrame(Instances instances) {
  197. auto instanceCount = 0;
  198. // write draw commands
  199. DrawElementsIndirectCommand* cmds = commandBuffer.reserve(instanceCount);
  200. foreach(size_t i = 0; i < instanceCount; ++i) {
  201. DrawElementsIndirectCommand* cmd = &cmds[u];
  202. cmd->count = mIndexCount;
  203. cmd->instanceCount = 1;
  204. cmd->firstIndex = 0;
  205. cmd->baseVertex = 0;
  206. cmd->baseInstance = mUseShaderDrawParameters ? 0 : u;
  207. }
  208. // write per instance
  209. perInstanceBuffer.reserve(instances.length);
  210. foreach() {
  211. }
  212. glCheck!glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_SHORT, mCommands.GetHeadOffset(), xformCount, 0);
  213. }
  214. }
  215. /++++
  216. struct GlPeristentBuffer {
  217. }
  218. struct GlRingBuffer {
  219. GLuint bo;
  220. }
  221. struct ParamPerInstanceRingBuffer {
  222. GLuint bo;
  223. }
  224. struct Renderer {
  225. CommandRingBuffer commandRb;
  226. ParamPerInstanceRingBuffer paramPerInstanceRb;
  227. }
  228. struct MeshStorageManager(MeshLayout = DefaultVertexLayout) {
  229. struct Slice {
  230. size_t offset;
  231. size_t length;
  232. }
  233. struct MeshStorage {
  234. Slice vertexSlice;
  235. Slice indexSlice;
  236. }
  237. GLuint vao;
  238. GLuint vbo;
  239. GLuint ibo;
  240. MeshStorage[] meshes;
  241. }
  242. struct MeshInstance {
  243. }
  244. struct MappedPersistentBuffer {
  245. GLuint vbo;
  246. void* data;
  247. }
  248. void create(out MappedPersistentBuffer mpb, GLsizeiptr bufferSize) {
  249. glCheck!glGenVertexArrays(1, &mpb.vbo);
  250. GLbitfield mapFlags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;
  251. GLbitfield createFlags = mapFlags | GL_MAP_DYNAMIC_STORAGE_BIT;
  252. glCheck!glBindBuffer(GL_ARRAY_BUFFER, mpb.vbo);
  253. glCheck!glBufferStorage(GL_ARRAY_BUFFER, bufferSize, null, createFlags);
  254. mpb.data = glCheck!glMapBufferRange(GL_ARRAY_BUFFER, 0, bufferSize, mapFlags);
  255. }
  256. ++++/
  257. //======================================================================================================================
  258. //
  259. //======================================================================================================================
  260. struct SOAVector3 {
  261. SoA!float x;
  262. SoA!float y;
  263. SoA!float z;
  264. }
  265. struct SOAQuaternion {
  266. SoA!float x;
  267. SoA!float y;
  268. SoA!float z;
  269. SoA!float w;
  270. }
  271. //======================================================================================================================
  272. //
  273. //======================================================================================================================
  274. void main() {
  275. Window window;
  276. Viewport viewport;
  277. Scene scene;
  278. Camera camera;
  279. RenderTarget renderTarget;
  280. OpenGlTiledDeferredRenderer renderer;
  281. bool keepRunning = true;
  282. //------------------------------------------------
  283. // Load and Construct Rendering Pipeline
  284. //------------------------------------------------
  285. DerelictGL3.load();
  286. DerelictGLFW3.load();
  287. DerelictFI.load();
  288. // DerelictFT.load();
  289. DerelictASSIMP3.load();
  290. DerelictAntTweakBar.load();
  291. if(!glfwInit()) throw new Exception("Initialising GLFW failed"); scope(exit) glfwTerminate();
  292. window.construct("Three.d", 1600, 900); scope(exit) window.destruct();
  293. try {
  294. GLVersion glVersion = DerelictGL3.reload();
  295. import std.conv : to;
  296. writeln("Reloaded OpenGL Version: ", to!string(glVersion));
  297. } catch(Exception e) {
  298. writeln("Reloading OpenGl failed: " ~ e.msg);
  299. }
  300. // static FT_Library _s_freeTypeLibrary
  301. // if(!FT_Init_FreeType(&_s_freeTypeLibrary)) throw new Exception("Initialising FreeType failed"); scope(exit) FT_Done_FreeType(_s_freeTypeLibrary);
  302. if(TwInit(TW_OPENGL_CORE, null) == 0) throw new Exception("Initialising AntTweakBar failed"); scope(exit) TwTerminate();
  303. viewport.construct(); scope(exit) window.destruct();
  304. scene.construct(); scope(exit) window.destruct();
  305. camera.construct(); scope(exit) window.destruct();
  306. renderTarget.construct(window.width, window.height); scope(exit) renderTarget.destruct();
  307. renderer.construct(window.width, window.height); scope(exit) renderer.destruct();
  308. //############################
  309. //############################
  310. //############################
  311. //############################
  312. GlPersistentlyMappedBuffer!DefaultVertexData vertexBuffer;
  313. vertexBuffer.create(1024, GL_ARRAY_BUFFER, 0, 0);
  314. //############################
  315. //############################
  316. //############################
  317. //############################
  318. //------------------------------------------------
  319. // Create Scene
  320. //------------------------------------------------
  321. scene.mesh.loadModel("C:/Coding/models/Collada/duck.dae");
  322. //------------------------------------------------
  323. // Generate TweakBar
  324. //------------------------------------------------
  325. TwWindowSize(window.width, window.height);
  326. auto tweakBar = TwNewBar("TweakBar");
  327. //------------------------------------------------
  328. // Connect Window callbacks
  329. //------------------------------------------------
  330. window.onKey = (ref Window rWindow, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  331. if(window is window && action == KeyAction.Pressed) {
  332. if(key == Key.Escape) {
  333. keepRunning = false;
  334. }
  335. }
  336. };
  337. window.onClose = (ref Window rWindow) {
  338. keepRunning = false;
  339. };
  340. window.onSize = (ref Window rWindow, int width, int height) {
  341. TwWindowSize(width, height);
  342. };
  343. window.onPosition = (ref Window rWindow, int x, int y) {
  344. };
  345. window.onButton = (ref Window rWindow , int button, ButtonAction action) {
  346. TwMouseAction twaction = action == ButtonAction.Pressed ? TW_MOUSE_PRESSED : TW_MOUSE_RELEASED;
  347. TwMouseButtonID twbutton;
  348. switch(button) {
  349. default:
  350. case GLFW_MOUSE_BUTTON_LEFT: twbutton = TW_MOUSE_LEFT; break;
  351. case GLFW_MOUSE_BUTTON_RIGHT: twbutton = TW_MOUSE_RIGHT; break;
  352. case GLFW_MOUSE_BUTTON_MIDDLE: twbutton = TW_MOUSE_MIDDLE; break;
  353. }
  354. TwMouseButton(twaction, twbutton);
  355. };
  356. window.onCursorPos = (ref Window rWindow, double x, double y) {
  357. TwMouseMotion(cast(int)x, window.height - cast(int)y);
  358. };
  359. //------------------------------------------------
  360. // Main Loop
  361. //------------------------------------------------
  362. ulong frameCount = 0;
  363. glfwSetTime(0);
  364. while(keepRunning) {
  365. window.pollEvents();
  366. window.makeAktiveRenderWindow();
  367. glCheck!glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  368. glCheck!glClearDepth(1.0f);
  369. glCheck!glClearColor(0, 0.3, 0, 1);
  370. /*
  371. foreach(renderTarget) //framebuffer
  372. foreach(pass)
  373. foreach(material) //shaders
  374. foreach(materialInstance) //textures
  375. foreach(vertexFormat) //vertex buffers
  376. foreach(object) {
  377. write uniform data;
  378. glDrawElementsBaseVertex
  379. }
  380. */
  381. renderer.renderOneFrame(scene, camera, renderTarget, viewport);
  382. TwDraw();
  383. debug{ renderer.blitGBufferToScreen(); }
  384. window.swapBuffers();
  385. ++frameCount;
  386. if(frameCount % 1000 == 0) {
  387. auto fps = cast(double)frameCount / glfwGetTime();
  388. log("FPS: ", fps);
  389. frameCount = 0;
  390. glfwSetTime(0);
  391. }
  392. }
  393. }
  394. /+++
  395. struct Vertex {
  396. float x, y, z;
  397. }
  398. struct Normal {
  399. float x, y, z;
  400. }
  401. struct UV {
  402. float u, v;
  403. }
  404. final class Mesh {
  405. public:
  406. Vertex[] vertexData;
  407. Normal[] normalData;
  408. UV[] textureData;
  409. RGBAf[] colorData;
  410. VertexArrayObject vao;
  411. VertexBufferObject!(VertexBufferObjectTarget.Array) vboVertexData;
  412. VertexBufferObject!(VertexBufferObjectTarget.Array) vboNormalData;
  413. VertexBufferObject!(VertexBufferObjectTarget.Array) vboTextureData;
  414. VertexBufferObject!(VertexBufferObjectTarget.Array) vboColorData;
  415. this(string filePath) {
  416. writeln("loading scene: ", filePath);
  417. auto scene = aiImportFile(filePath.toStringz(), aiProcess_Triangulate);
  418. writeln("meshes: ", scene.mNumMeshes);
  419. for(uint m = 0; m < scene.mNumMeshes; ++m) {
  420. const(aiMesh*) mesh = scene.mMeshes[m];
  421. assert(mesh !is null);
  422. writeln("mesh[", m, "] faces : ", mesh.mNumFaces);
  423. for (uint f = 0; f < mesh.mNumFaces; ++f) {
  424. const(aiFace*) face = &mesh.mFaces[f];
  425. assert(face !is null);
  426. for(uint v = 0; v < 3; ++v) {
  427. aiVector3D p, n, uv;
  428. assert(face.mNumIndices > v);
  429. uint vertex = face.mIndices[v];
  430. assert(mesh.mNumVertices > vertex);
  431. p = mesh.mVertices[vertex];
  432. n = mesh.mNormals[vertex];
  433. // check if the mesh has texture coordinates
  434. if(mesh.mTextureCoords[0] !is null) {
  435. uv = mesh.mTextureCoords[0][vertex];
  436. }
  437. vertexData ~= Vertex(p.x, p.y, p.z);
  438. normalData ~= Normal(n.x, n.y, n.z);
  439. textureData ~= UV(uv.x, uv.y);
  440. colorData ~= RGBAf(n.x, n.y, n.z, 1.0f);
  441. }
  442. }
  443. }
  444. writeln("unloading scene: ", filePath);
  445. aiReleaseImport(scene);
  446. //-----------------------------
  447. // upload
  448. writeln("uploading mesh: ", filePath);
  449. vao = new VertexArrayObject();
  450. vao.bind();
  451. writeln("vertex data");
  452. vboVertexData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  453. vboVertexData.bind();
  454. GLuint attribIndex = 0;
  455. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Vertex.sizeof * vertexData.length) , vertexData.ptr, GL_STATIC_DRAW);
  456. glEnableVertexAttribArray(attribIndex);
  457. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  458. vboVertexData.unbind();
  459. writeln("normal data");
  460. vboNormalData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  461. vboNormalData.bind();
  462. attribIndex = 1;
  463. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Normal.sizeof * normalData.length) , normalData.ptr, GL_STATIC_DRAW);
  464. glEnableVertexAttribArray(attribIndex);
  465. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  466. vboNormalData.unbind();
  467. writeln("uv data");
  468. vboTextureData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  469. vboTextureData.bind();
  470. attribIndex = 2;
  471. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(UV.sizeof * textureData.length) , textureData.ptr, GL_STATIC_DRAW);
  472. glEnableVertexAttribArray(attribIndex);
  473. glVertexAttribPointer(attribIndex, 2, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  474. vboTextureData.unbind();
  475. writeln("color data");
  476. vboColorData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  477. vboColorData.bind();
  478. attribIndex = 3;
  479. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(RGBAf.sizeof * colorData.length) , colorData.ptr, GL_STATIC_DRAW);
  480. glEnableVertexAttribArray(attribIndex);
  481. glVertexAttribPointer(attribIndex, 4, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  482. vboColorData.unbind();
  483. vao.unbind();
  484. writeln("done");
  485. }
  486. }
  487. void setupTweakbar() {
  488. writeln("creating TweakBar");
  489. double time = 0, dt; // Current time and enlapsed time
  490. double turn = 0; // Model turn counter
  491. double speed = 0.3; // Model rotation speed
  492. int wire = 0; // Draw model in wireframe?
  493. uint frameCount = 0;
  494. double fps = 0;
  495. float bgColor[3] = [0.1f, 0.2f, 0.4f]; // Background color
  496. ubyte cubeColor[4] = [255, 0, 0, 128]; // Model color (32bits RGBA)
  497. auto quat = Quaternionf(0,0,0,1);
  498. // auto w = this._window.getBounds()[2];
  499. // auto h = this._window.getBounds()[3];
  500. TwWindowSize(1600, 900);
  501. // // Create a tweak bar
  502. // auto bar = TwNewBar("TweakBar");
  503. // TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLFW and OpenGL.' "); // Message added to the help bar.
  504. // // Add 'speed' to 'bar': it is a modifable (RW) variable of type TW_TYPE_DOUBLE. Its key shortcuts are [s] and [S].
  505. // 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)' ");
  506. // // Add 'wire' to 'bar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w].
  507. // TwAddVarRW(bar, "wire", TW_TYPE_BOOL32, &wire, " label='Wireframe mode' key=CTRL+w help='Toggle wireframe display mode.' ");
  508. // // Add 'time' to 'bar': it is a read-only (RO) variable of type TW_TYPE_DOUBLE, with 1 precision digit
  509. // TwAddVarRO(bar, "time", TW_TYPE_DOUBLE, &time, " label='Time' precision=1 help='Time (in seconds).' ");
  510. // //
  511. // TwAddVarRO(bar, "frameCount", TW_TYPE_UINT32, &frameCount, " label='FrameCount' precision=1 help='FrameCount (in counts).' ");
  512. // TwAddVarRO(bar, "fps", TW_TYPE_DOUBLE, &fps, " label='fps' precision=1 help='fps (in fps).' ");
  513. // // Add 'bgColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color)
  514. // TwAddVarRW(bar, "bgColor", TW_TYPE_COLOR3F, &bgColor, " label='Background color' ");
  515. // // Add 'cubeColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR32 (32 bits color) with alpha
  516. // TwAddVarRW(bar, "cubeColor", TW_TYPE_COLOR32, &cubeColor, " label='Cube color' alpha help='Color and transparency of the cube.' ");
  517. // //
  518. // TwAddVarRW(bar, "quaternion", TW_TYPE_QUAT4F, &quat, " label='Cubde color' alpha help='Color anwdwd transparency of the cube.' ");
  519. }
  520. //-----------------
  521. // Create Shaders
  522. enum vertexShaderSource = "
  523. #version 420 core
  524. layout(location = 0) in vec3 in_position;
  525. layout(location = 1) in vec3 in_normal;
  526. layout(location = 2) in vec2 in_texcoord;
  527. layout(location = 3) in vec4 in_color;
  528. out vec4 v_color;
  529. out gl_PerVertex
  530. {
  531. vec4 gl_Position;
  532. };
  533. void main()
  534. {
  535. gl_Position = vec4(0.005 * in_position.x, 0.005 * in_position.y, 0.005* in_position.z, 1.0);
  536. v_color = in_color;
  537. }
  538. ";
  539. enum fragmentShaderSource = "
  540. #version 420 core
  541. in vec4 v_color;
  542. out vec4 FragColor;
  543. void main()
  544. {
  545. FragColor = v_color;
  546. }
  547. ";
  548. auto createShaderPipeline(Shader!(ShaderType.Vertex) vertexShader, Shader!(ShaderType.Fragment) fragmentShader) {
  549. assert(vertexShader.isLinked, vertexShader.infoLog());
  550. assert(fragmentShader.isLinked, fragmentShader.infoLog());
  551. writeln("a: ");
  552. auto shaderPipeline = new ShaderPipeline();
  553. shaderPipeline.bind();
  554. shaderPipeline.use(vertexShader);
  555. shaderPipeline.use(fragmentShader);
  556. writeln("b: ");
  557. assert(shaderPipeline.isValidProgramPipeline, shaderPipeline.infoLog());
  558. shaderPipeline.unbind();
  559. writeln("c: ");
  560. return shaderPipeline;
  561. }
  562. class Tester {
  563. Window _window;
  564. bool _keepRunning = true;
  565. this() {
  566. this._window = initThree();
  567. this._window.onKey.connect!"_onKey"(this);
  568. this._window.onClose.connect!"_onClose"(this);
  569. }
  570. ~this() {
  571. import core.memory;
  572. writeln("GC.collect: ");
  573. GC.collect();
  574. //Collect window _AFTER_ everything else
  575. this._window = null;
  576. GC.collect();
  577. deinitThree();
  578. }
  579. void run() {
  580. RGBAf rgg;
  581. auto mesh = new Mesh("C:/Coding/models/Collada/duck.dae");
  582. setupTweakbar();
  583. writeln("creating shaders: ");
  584. auto vertexShader = new Shader!(ShaderType.Vertex)(vertexShaderSource);
  585. auto fragmentShader = new Shader!(ShaderType.Fragment)(fragmentShaderSource);
  586. writeln("creating shader pipeline: ");
  587. auto shaderPipeline = createShaderPipeline(vertexShader, fragmentShader);
  588. writeln("connectiong window callbacks: ");
  589. this._window.onSize.connect!"onSize"(this);
  590. this._window.onPosition.connect!"onPosition"(this);
  591. this._window.onButton.connect!"onButton"(this);
  592. this._window.onCursorPos.connect!"onCursorPos"(this);
  593. writeln("begin render loop: ");
  594. //-----------------
  595. // Render Loop
  596. glfwSetTime(0);
  597. while(this._keepRunning) {
  598. this._window.clear(0, 0, 0.5, 1);
  599. shaderPipeline.bind();
  600. mesh.vao.bind();
  601. //vboVertexData.bind();
  602. glDrawArrays(GL_TRIANGLES, 0, mesh.vertexData.length);
  603. //vbo.unbind();
  604. mesh.vao.unbind();
  605. shaderPipeline.unbind();
  606. TwDraw();
  607. this._window.swapBuffers();
  608. updateWindows();
  609. // ++frameCount;
  610. // //if(frameCount % 100 == 0) {
  611. // time = glfwGetTime();
  612. // fps = cast(double)frameCount / time;
  613. // //}
  614. }
  615. }
  616. void onSize(Window window, int width, int height) {
  617. TwWindowSize(width, height);
  618. }
  619. void onPosition(Window window, int x, int y) {
  620. }
  621. void onButton(Window window , int button, ButtonAction action) {
  622. TwMouseAction twaction = action == ButtonAction.Pressed ? TW_MOUSE_PRESSED : TW_MOUSE_RELEASED;
  623. TwMouseButtonID twbutton;
  624. switch(button) {
  625. default:
  626. case GLFW_MOUSE_BUTTON_LEFT: twbutton = TW_MOUSE_LEFT; break;
  627. case GLFW_MOUSE_BUTTON_RIGHT: twbutton = TW_MOUSE_RIGHT; break;
  628. case GLFW_MOUSE_BUTTON_MIDDLE: twbutton = TW_MOUSE_MIDDLE; break;
  629. }
  630. TwMouseButton(twaction, twbutton);
  631. }
  632. void onCursorPos(Window window, double x, double y) {
  633. TwMouseMotion(cast(int)x, this._window.getBounds()[3] - cast(int)y);
  634. }
  635. void stop() {
  636. this._keepRunning = false;
  637. }
  638. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  639. if(window is this._window && action == KeyAction.Pressed) {
  640. if(key == Key.Escape) {
  641. this.stop();
  642. }
  643. }
  644. }
  645. void _onClose(Window window) {
  646. this.stop();
  647. }
  648. }
  649. class InputHandler {
  650. private:
  651. Window _window;
  652. OpenGlRenderer _renderer;
  653. public:
  654. this(Window window, OpenGlRenderer renderer) {
  655. _window = window;
  656. _renderer = renderer;
  657. _window.onKey.connect!"_onKey"(this);
  658. _window.onClose.connect!"_onClose"(this);
  659. _window.onSize.connect!"_onSize"(this);
  660. _window.onPosition.connect!"_onPosition"(this);
  661. _window.onButton.connect!"_onButton"(this);
  662. _window.onCursorPos.connect!"_onCursorPos"(this);
  663. }
  664. private:
  665. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  666. if(window is _window && action == KeyAction.Pressed) {
  667. if(key == Key.Escape) {
  668. _renderer.stop();
  669. }
  670. }
  671. }
  672. void _onClose(Window window) {
  673. _renderer.stop();
  674. }
  675. void _onSize(Window window, int width, int height) {
  676. }
  677. void _onPosition(Window window, int x, int y) {
  678. }
  679. void _onButton(Window window , int button, ButtonAction action) {
  680. }
  681. void _onCursorPos(Window window, double x, double y) {
  682. }
  683. }
  684. void main() {
  685. auto window = initThree();
  686. {
  687. OpenGlRenderer renderer = new OpenGlRenderer(window);
  688. InputHandler inputHandler = new InputHandler(window, renderer);
  689. renderer.run();
  690. }
  691. import core.memory;
  692. GC.collect();
  693. //Collect window _AFTER_ everything else
  694. this._window = null;
  695. GC.collect();
  696. deinitThree();
  697. }
  698. +++/
  699. +++++++/