svt.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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.platformData.type = entry::getNativeWindowHandleType(entry::kDefaultWindowHandle);
  72. init.resolution.width = m_width;
  73. init.resolution.height = m_height;
  74. init.resolution.reset = m_reset;
  75. bgfx::init(init);
  76. // Enable m_debug text.
  77. bgfx::setDebug(m_debug);
  78. // Set views clear state (first pass to 0, second pass to some background color)
  79. for (uint16_t i = 0; i < 2; ++i)
  80. {
  81. bgfx::setViewClear(i
  82. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  83. , i == 0 ? 0 : 0x101050ff
  84. , 1.0f
  85. , 0
  86. );
  87. }
  88. // Create vertex stream declaration.
  89. PosTexcoordVertex::init();
  90. // Create static vertex buffer.
  91. m_vbh = bgfx::createVertexBuffer(
  92. bgfx::makeRef(s_vplaneVertices, sizeof(s_vplaneVertices))
  93. , PosTexcoordVertex::ms_layout
  94. );
  95. m_ibh = bgfx::createIndexBuffer(
  96. bgfx::makeRef(s_planeIndices, sizeof(s_planeIndices))
  97. );
  98. // Create program from shaders.
  99. m_vt_unlit = loadProgram("vs_vt_generic", "fs_vt_unlit");
  100. m_vt_mip = loadProgram("vs_vt_generic", "fs_vt_mip");
  101. // Imgui.
  102. imguiCreate();
  103. m_timeOffset = bx::getHPCounter();
  104. // Get renderer capabilities info.
  105. m_caps = bgfx::getCaps();
  106. m_scrollArea = 0;
  107. // Create and setup camera
  108. cameraCreate();
  109. cameraSetPosition({ 0.0f, 5.0f, 0.0f });
  110. cameraSetVerticalAngle(0.0f);
  111. // Set VirtualTexture system allocator
  112. vt::VirtualTexture::setAllocator(&m_vtAllocator);
  113. // Create Virtual texture info
  114. m_vti = new vt::VirtualTextureInfo();
  115. m_vti->m_virtualTextureSize = 8192; // The actual size will be read from the tile data file
  116. m_vti->m_tileSize = 128;
  117. m_vti->m_borderSize = 1;
  118. // Generate tile data file (if not yet created)
  119. {
  120. vt::TileGenerator tileGenerator(m_vti);
  121. tileGenerator.generate("textures/8k_mars.jpg");
  122. }
  123. // Load tile data file
  124. auto tileDataFile = new vt::TileDataFile("temp/8k_mars.vt", m_vti);
  125. tileDataFile->readInfo();
  126. // Create virtual texture and feedback buffer
  127. m_vt = new vt::VirtualTexture(tileDataFile, m_vti, 2048, 1);
  128. m_feedbackBuffer = new vt::FeedbackBuffer(m_vti, 64, 64);
  129. }
  130. virtual int shutdown() override
  131. {
  132. // Cleanup.
  133. bgfx::frame();
  134. cameraDestroy();
  135. imguiDestroy();
  136. bgfx::destroy(m_ibh);
  137. bgfx::destroy(m_vbh);
  138. bgfx::destroy(m_vt_unlit);
  139. bgfx::destroy(m_vt_mip);
  140. delete m_vti;
  141. delete m_vt;
  142. delete m_feedbackBuffer;
  143. // Shutdown bgfx.
  144. bgfx::shutdown();
  145. return 0;
  146. }
  147. bool update() override
  148. {
  149. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  150. {
  151. imguiBeginFrame(
  152. m_mouseState.m_mx
  153. , m_mouseState.m_my
  154. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  155. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  156. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  157. , m_mouseState.m_mz
  158. , uint16_t(m_width)
  159. , uint16_t(m_height)
  160. );
  161. showExampleDialog(this);
  162. int64_t now = bx::getHPCounter();
  163. static int64_t last = now;
  164. const int64_t frameTime = now - last;
  165. last = now;
  166. const double freq = double(bx::getHPFrequency());
  167. const float deltaTime = float(frameTime / freq);
  168. float time = (float)((now - m_timeOffset) / freq);
  169. if ((BGFX_CAPS_TEXTURE_BLIT | BGFX_CAPS_TEXTURE_READ_BACK) != (bgfx::getCaps()->supported & (BGFX_CAPS_TEXTURE_BLIT | BGFX_CAPS_TEXTURE_READ_BACK)))
  170. {
  171. // When texture read-back or blit is not supported by GPU blink!
  172. bool blink = uint32_t(time*3.0f) & 1;
  173. bgfx::dbgTextPrintf(0, 0, blink ? 0x4f : 0x04, " Texture read-back and/or blit not supported by GPU. ");
  174. // Set view 0 default viewport.
  175. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height));
  176. // This dummy draw call is here to make sure that view 0 is cleared
  177. // if no other draw calls are submitted to view 0.
  178. bgfx::touch(0);
  179. }
  180. else
  181. {
  182. ImGui::SetNextWindowPos(
  183. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  184. , ImGuiCond_FirstUseEver
  185. );
  186. ImGui::SetNextWindowSize(
  187. ImVec2(m_width / 5.0f, m_height - 10.0f)
  188. , ImGuiCond_FirstUseEver
  189. );
  190. ImGui::Begin("Settings"
  191. , NULL
  192. , 0
  193. );
  194. //ImGui::SliderFloat("intensity", &m_intensity, 0.0f, 3.0f);
  195. auto showBorders = m_vt->isShowBoardersEnabled();
  196. if (ImGui::Checkbox("Show borders", &showBorders))
  197. {
  198. m_vt->enableShowBoarders(showBorders);
  199. }
  200. auto colorMipLevels = m_vt->isColorMipLevelsEnabled();
  201. if (ImGui::Checkbox("Color mip levels", &colorMipLevels))
  202. {
  203. m_vt->enableColorMipLevels(colorMipLevels);
  204. }
  205. auto uploadsperframe = m_vt->getUploadsPerFrame();
  206. if (ImGui::InputInt("Updates per frame", &uploadsperframe, 1, 2))
  207. {
  208. uploadsperframe = bx::clamp(uploadsperframe, 1, 100);
  209. m_vt->setUploadsPerFrame(uploadsperframe);
  210. }
  211. ImGui::ImageButton(m_vt->getAtlastTexture(), ImVec2(m_width / 5.0f - 16.0f, m_width / 5.0f - 16.0f));
  212. ImGui::ImageButton(bgfx::getTexture(m_feedbackBuffer->getFrameBuffer()), ImVec2(m_width / 5.0f - 16.0f, m_width / 5.0f - 16.0f));
  213. ImGui::End();
  214. // Update camera.
  215. cameraUpdate(deltaTime, m_mouseState, ImGui::MouseOverArea() );
  216. float view[16];
  217. cameraGetViewMtx(view);
  218. float proj[16];
  219. bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 1000.0f, m_caps->homogeneousDepth);
  220. // Setup views
  221. for (uint16_t i = 0; i < 2; ++i)
  222. {
  223. uint16_t viewWidth = 0;
  224. uint16_t viewHeight = 0;
  225. // Setup pass, first pass is into mip-map feedback buffer, second pass is on screen
  226. if (i == 0)
  227. {
  228. bgfx::setViewFrameBuffer(i, m_feedbackBuffer->getFrameBuffer());
  229. viewWidth = uint16_t(m_feedbackBuffer->getWidth());
  230. viewHeight = uint16_t(m_feedbackBuffer->getHeight());
  231. }
  232. else
  233. {
  234. bgfx::FrameBufferHandle invalid = BGFX_INVALID_HANDLE;
  235. bgfx::setViewFrameBuffer(i, invalid);
  236. viewWidth = uint16_t(m_width);
  237. viewHeight = uint16_t(m_height);
  238. }
  239. bgfx::setViewRect(i, 0, 0, viewWidth, viewHeight);
  240. bgfx::setViewTransform(i, view, proj);
  241. float mtx[16];
  242. bx::mtxIdentity(mtx);
  243. // Set identity transform for draw call.
  244. bgfx::setTransform(mtx);
  245. // Set vertex and index buffer.
  246. bgfx::setVertexBuffer(0, m_vbh);
  247. bgfx::setIndexBuffer(m_ibh);
  248. // Set render states.
  249. bgfx::setState(0
  250. | BGFX_STATE_WRITE_RGB
  251. | BGFX_STATE_WRITE_A
  252. | BGFX_STATE_WRITE_Z
  253. | BGFX_STATE_DEPTH_TEST_LESS
  254. );
  255. // Set virtual texture uniforms
  256. m_vt->setUniforms();
  257. // Submit primitive for rendering to first pass (to feedback buffer, where mip levels and tile x/y will be rendered
  258. if (i == 0)
  259. {
  260. bgfx::submit(i, m_vt_mip);
  261. // Download previous frame feedback info
  262. m_feedbackBuffer->download();
  263. // Update and upload new requests
  264. m_vt->update(m_feedbackBuffer->getRequests(), 4);
  265. // Clear feedback
  266. m_feedbackBuffer->clear();
  267. // Copy new frame feedback buffer
  268. m_feedbackBuffer->copy(3);
  269. }
  270. else
  271. {
  272. // Submit primitive for rendering to second pass (to back buffer, where virtual texture page table and atlas will be used)
  273. bgfx::submit(i, m_vt_unlit);
  274. }
  275. }
  276. }
  277. imguiEndFrame();
  278. // Advance to next frame. Rendering thread will be kicked to
  279. // process submitted rendering primitives.
  280. bgfx::frame();
  281. return true;
  282. }
  283. return false;
  284. }
  285. bgfx::VertexBufferHandle m_vbh;
  286. bgfx::IndexBufferHandle m_ibh;
  287. bgfx::ProgramHandle m_vt_unlit;
  288. bgfx::ProgramHandle m_vt_mip;
  289. uint32_t m_width;
  290. uint32_t m_height;
  291. uint32_t m_debug;
  292. uint32_t m_reset;
  293. int32_t m_scrollArea;
  294. entry::MouseState m_mouseState;
  295. const bgfx::Caps* m_caps;
  296. int64_t m_timeOffset;
  297. bx::DefaultAllocator m_vtAllocator;
  298. vt::VirtualTextureInfo* m_vti;
  299. vt::VirtualTexture* m_vt;
  300. vt::FeedbackBuffer* m_feedbackBuffer;
  301. };
  302. } // namespace
  303. ENTRY_IMPLEMENT_MAIN(
  304. ExampleSVT
  305. , "40-svt"
  306. , "Sparse Virtual Textures."
  307. , "https://bkaradzic.github.io/bgfx/examples.html#svt"
  308. );