2
0

svt.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. /*
  2. * Copyright 2018 Ales Mlakar. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. /*
  6. * Reference(s):
  7. * - Sparse Virtual Textures by Sean Barrett
  8. * http://web.archive.org/web/20190103162611/http://silverspaceship.com/src/svt/
  9. * - Based on Virtual Texture Demo by Brad Blanchard
  10. * http://web.archive.org/web/20190103162638/http://linedef.com/virtual-texture-demo.html
  11. * - Mars texture
  12. * http://web.archive.org/web/20190103162730/http://www.celestiamotherlode.net/catalog/mars.php
  13. */
  14. #include "common.h"
  15. #include "bgfx_utils.h"
  16. #include "imgui/imgui.h"
  17. #include "camera.h"
  18. #include "vt.h"
  19. namespace
  20. {
  21. struct PosTexcoordVertex
  22. {
  23. float m_x;
  24. float m_y;
  25. float m_z;
  26. float m_u;
  27. float m_v;
  28. static void init()
  29. {
  30. ms_layout
  31. .begin()
  32. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  33. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  34. .end();
  35. };
  36. static bgfx::VertexLayout ms_layout;
  37. };
  38. bgfx::VertexLayout PosTexcoordVertex::ms_layout;
  39. static const float s_planeScale = 50.0f;
  40. static PosTexcoordVertex s_vplaneVertices[] =
  41. {
  42. { -s_planeScale, 0.0f, s_planeScale, 1.0f, 1.0f },
  43. { s_planeScale, 0.0f, s_planeScale, 1.0f, 0.0f },
  44. { -s_planeScale, 0.0f, -s_planeScale, 0.0f, 1.0f },
  45. { s_planeScale, 0.0f, -s_planeScale, 0.0f, 0.0f },
  46. };
  47. static const uint16_t s_planeIndices[] =
  48. {
  49. 0, 1, 2,
  50. 1, 3, 2,
  51. };
  52. class ExampleSVT : public entry::AppI
  53. {
  54. public:
  55. ExampleSVT(const char* _name, const char* _description, const char* _url)
  56. : entry::AppI(_name, _description, _url)
  57. {
  58. }
  59. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  60. {
  61. Args args(_argc, _argv);
  62. m_width = _width;
  63. m_height = _height;
  64. m_debug = BGFX_DEBUG_TEXT;
  65. m_reset = BGFX_RESET_VSYNC;
  66. bgfx::Init init;
  67. init.type = args.m_type;
  68. init.vendorId = args.m_pciId;
  69. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  70. init.platformData.ndt = entry::getNativeDisplayHandle();
  71. init.resolution.width = m_width;
  72. init.resolution.height = m_height;
  73. init.resolution.reset = m_reset;
  74. bgfx::init(init);
  75. // Enable m_debug text.
  76. bgfx::setDebug(m_debug);
  77. // Set views clear state (first pass to 0, second pass to some background color)
  78. for (uint16_t i = 0; i < 2; ++i)
  79. {
  80. bgfx::setViewClear(i
  81. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  82. , i == 0 ? 0 : 0x101050ff
  83. , 1.0f
  84. , 0
  85. );
  86. }
  87. // Create vertex stream declaration.
  88. PosTexcoordVertex::init();
  89. // Create static vertex buffer.
  90. m_vbh = bgfx::createVertexBuffer(
  91. bgfx::makeRef(s_vplaneVertices, sizeof(s_vplaneVertices))
  92. , PosTexcoordVertex::ms_layout
  93. );
  94. m_ibh = bgfx::createIndexBuffer(
  95. bgfx::makeRef(s_planeIndices, sizeof(s_planeIndices))
  96. );
  97. // Create program from shaders.
  98. m_vt_unlit = loadProgram("vs_vt_generic", "fs_vt_unlit");
  99. m_vt_mip = loadProgram("vs_vt_generic", "fs_vt_mip");
  100. // Imgui.
  101. imguiCreate();
  102. m_timeOffset = bx::getHPCounter();
  103. // Get renderer capabilities info.
  104. m_caps = bgfx::getCaps();
  105. m_scrollArea = 0;
  106. // Create and setup camera
  107. cameraCreate();
  108. cameraSetPosition({ 0.0f, 5.0f, 0.0f });
  109. cameraSetVerticalAngle(0.0f);
  110. // Set VirtualTexture system allocator
  111. vt::VirtualTexture::setAllocator(&m_vtAllocator);
  112. // Create Virtual texture info
  113. m_vti = new vt::VirtualTextureInfo();
  114. m_vti->m_virtualTextureSize = 8192; // The actual size will be read from the tile data file
  115. m_vti->m_tileSize = 128;
  116. m_vti->m_borderSize = 1;
  117. // Generate tile data file (if not yet created)
  118. {
  119. vt::TileGenerator tileGenerator(m_vti);
  120. tileGenerator.generate("textures/8k_mars.jpg");
  121. }
  122. // Load tile data file
  123. auto tileDataFile = new vt::TileDataFile("temp/8k_mars.vt", m_vti);
  124. tileDataFile->readInfo();
  125. // Create virtual texture and feedback buffer
  126. m_vt = new vt::VirtualTexture(tileDataFile, m_vti, 2048, 1);
  127. m_feedbackBuffer = new vt::FeedbackBuffer(m_vti, 64, 64);
  128. }
  129. virtual int shutdown() override
  130. {
  131. // Cleanup.
  132. bgfx::frame();
  133. cameraDestroy();
  134. imguiDestroy();
  135. bgfx::destroy(m_ibh);
  136. bgfx::destroy(m_vbh);
  137. bgfx::destroy(m_vt_unlit);
  138. bgfx::destroy(m_vt_mip);
  139. delete m_vti;
  140. delete m_vt;
  141. delete m_feedbackBuffer;
  142. // Shutdown bgfx.
  143. bgfx::shutdown();
  144. return 0;
  145. }
  146. bool update() override
  147. {
  148. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  149. {
  150. imguiBeginFrame(
  151. m_mouseState.m_mx
  152. , m_mouseState.m_my
  153. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  154. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  155. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  156. , m_mouseState.m_mz
  157. , uint16_t(m_width)
  158. , uint16_t(m_height)
  159. );
  160. showExampleDialog(this);
  161. int64_t now = bx::getHPCounter();
  162. static int64_t last = now;
  163. const int64_t frameTime = now - last;
  164. last = now;
  165. const double freq = double(bx::getHPFrequency());
  166. const float deltaTime = float(frameTime / freq);
  167. float time = (float)((now - m_timeOffset) / freq);
  168. if ((BGFX_CAPS_TEXTURE_BLIT | BGFX_CAPS_TEXTURE_READ_BACK) != (bgfx::getCaps()->supported & (BGFX_CAPS_TEXTURE_BLIT | BGFX_CAPS_TEXTURE_READ_BACK)))
  169. {
  170. // When texture read-back or blit is not supported by GPU blink!
  171. bool blink = uint32_t(time*3.0f) & 1;
  172. bgfx::dbgTextPrintf(0, 0, blink ? 0x4f : 0x04, " Texture read-back and/or blit not supported by GPU. ");
  173. // Set view 0 default viewport.
  174. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height));
  175. // This dummy draw call is here to make sure that view 0 is cleared
  176. // if no other draw calls are submitted to view 0.
  177. bgfx::touch(0);
  178. }
  179. else
  180. {
  181. ImGui::SetNextWindowPos(
  182. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  183. , ImGuiCond_FirstUseEver
  184. );
  185. ImGui::SetNextWindowSize(
  186. ImVec2(m_width / 5.0f, m_height - 10.0f)
  187. , ImGuiCond_FirstUseEver
  188. );
  189. ImGui::Begin("Settings"
  190. , NULL
  191. , 0
  192. );
  193. //ImGui::SliderFloat("intensity", &m_intensity, 0.0f, 3.0f);
  194. auto showBorders = m_vt->isShowBoardersEnabled();
  195. if (ImGui::Checkbox("Show borders", &showBorders))
  196. {
  197. m_vt->enableShowBoarders(showBorders);
  198. }
  199. auto colorMipLevels = m_vt->isColorMipLevelsEnabled();
  200. if (ImGui::Checkbox("Color mip levels", &colorMipLevels))
  201. {
  202. m_vt->enableColorMipLevels(colorMipLevels);
  203. }
  204. auto uploadsperframe = m_vt->getUploadsPerFrame();
  205. if (ImGui::InputInt("Updates per frame", &uploadsperframe, 1, 2))
  206. {
  207. uploadsperframe = bx::clamp(uploadsperframe, 1, 100);
  208. m_vt->setUploadsPerFrame(uploadsperframe);
  209. }
  210. ImGui::ImageButton(m_vt->getAtlastTexture(), ImVec2(m_width / 5.0f - 16.0f, m_width / 5.0f - 16.0f));
  211. ImGui::ImageButton(bgfx::getTexture(m_feedbackBuffer->getFrameBuffer()), ImVec2(m_width / 5.0f - 16.0f, m_width / 5.0f - 16.0f));
  212. ImGui::End();
  213. // Update camera.
  214. cameraUpdate(deltaTime, m_mouseState, ImGui::MouseOverArea() );
  215. float view[16];
  216. cameraGetViewMtx(view);
  217. float proj[16];
  218. bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 1000.0f, m_caps->homogeneousDepth);
  219. // Setup views
  220. for (uint16_t i = 0; i < 2; ++i)
  221. {
  222. uint16_t viewWidth = 0;
  223. uint16_t viewHeight = 0;
  224. // Setup pass, first pass is into mip-map feedback buffer, second pass is on screen
  225. if (i == 0)
  226. {
  227. bgfx::setViewFrameBuffer(i, m_feedbackBuffer->getFrameBuffer());
  228. viewWidth = uint16_t(m_feedbackBuffer->getWidth());
  229. viewHeight = uint16_t(m_feedbackBuffer->getHeight());
  230. }
  231. else
  232. {
  233. bgfx::FrameBufferHandle invalid = BGFX_INVALID_HANDLE;
  234. bgfx::setViewFrameBuffer(i, invalid);
  235. viewWidth = uint16_t(m_width);
  236. viewHeight = uint16_t(m_height);
  237. }
  238. bgfx::setViewRect(i, 0, 0, viewWidth, viewHeight);
  239. bgfx::setViewTransform(i, view, proj);
  240. float mtx[16];
  241. bx::mtxIdentity(mtx);
  242. // Set identity transform for draw call.
  243. bgfx::setTransform(mtx);
  244. // Set vertex and index buffer.
  245. bgfx::setVertexBuffer(0, m_vbh);
  246. bgfx::setIndexBuffer(m_ibh);
  247. // Set render states.
  248. bgfx::setState(0
  249. | BGFX_STATE_WRITE_RGB
  250. | BGFX_STATE_WRITE_A
  251. | BGFX_STATE_WRITE_Z
  252. | BGFX_STATE_DEPTH_TEST_LESS
  253. );
  254. // Set virtual texture uniforms
  255. m_vt->setUniforms();
  256. // Submit primitive for rendering to first pass (to feedback buffer, where mip levels and tile x/y will be rendered
  257. if (i == 0)
  258. {
  259. bgfx::submit(i, m_vt_mip);
  260. // Download previous frame feedback info
  261. m_feedbackBuffer->download();
  262. // Update and upload new requests
  263. m_vt->update(m_feedbackBuffer->getRequests(), 4);
  264. // Clear feedback
  265. m_feedbackBuffer->clear();
  266. // Copy new frame feedback buffer
  267. m_feedbackBuffer->copy(3);
  268. }
  269. else
  270. {
  271. // Submit primitive for rendering to second pass (to back buffer, where virtual texture page table and atlas will be used)
  272. bgfx::submit(i, m_vt_unlit);
  273. }
  274. }
  275. }
  276. imguiEndFrame();
  277. // Advance to next frame. Rendering thread will be kicked to
  278. // process submitted rendering primitives.
  279. bgfx::frame();
  280. return true;
  281. }
  282. return false;
  283. }
  284. bgfx::VertexBufferHandle m_vbh;
  285. bgfx::IndexBufferHandle m_ibh;
  286. bgfx::ProgramHandle m_vt_unlit;
  287. bgfx::ProgramHandle m_vt_mip;
  288. uint32_t m_width;
  289. uint32_t m_height;
  290. uint32_t m_debug;
  291. uint32_t m_reset;
  292. int32_t m_scrollArea;
  293. entry::MouseState m_mouseState;
  294. const bgfx::Caps* m_caps;
  295. int64_t m_timeOffset;
  296. bx::DefaultAllocator m_vtAllocator;
  297. vt::VirtualTextureInfo* m_vti;
  298. vt::VirtualTexture* m_vt;
  299. vt::FeedbackBuffer* m_feedbackBuffer;
  300. };
  301. } // namespace
  302. ENTRY_IMPLEMENT_MAIN(
  303. ExampleSVT
  304. , "40-svt"
  305. , "Sparse Virtual Textures."
  306. , "https://bkaradzic.github.io/bgfx/examples.html#svt"
  307. );