picking.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /*
  2. * Copyright 2016 Joseph Cherlin. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include "common.h"
  6. #include "bgfx_utils.h"
  7. #include "imgui/imgui.h"
  8. #include <bx/rng.h>
  9. #include <map>
  10. namespace
  11. {
  12. #define RENDER_PASS_SHADING 0 // Default forward rendered geo with simple shading
  13. #define RENDER_PASS_ID 1 // ID buffer for picking
  14. #define RENDER_PASS_BLIT 2 // Blit GPU render target to CPU texture
  15. #define ID_DIM 8 // Size of the ID buffer
  16. class ExamplePicking : public entry::AppI
  17. {
  18. public:
  19. ExamplePicking(const char* _name, const char* _description, const char* _url)
  20. : entry::AppI(_name, _description, _url)
  21. {
  22. }
  23. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  24. {
  25. Args args(_argc, _argv);
  26. m_width = _width;
  27. m_height = _height;
  28. m_debug = BGFX_DEBUG_NONE;
  29. m_reset = BGFX_RESET_VSYNC;
  30. bgfx::Init init;
  31. init.type = args.m_type;
  32. init.vendorId = args.m_pciId;
  33. init.resolution.width = m_width;
  34. init.resolution.height = m_height;
  35. init.resolution.reset = m_reset;
  36. bgfx::init(init);
  37. // Enable debug text.
  38. bgfx::setDebug(m_debug);
  39. // Set up screen clears
  40. bgfx::setViewClear(RENDER_PASS_SHADING
  41. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  42. , 0x303030ff
  43. , 1.0f
  44. , 0
  45. );
  46. // ID buffer clears to black, which represents clicking on nothing (background)
  47. bgfx::setViewClear(RENDER_PASS_ID
  48. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  49. , 0x000000ff
  50. , 1.0f
  51. , 0
  52. );
  53. // Create uniforms
  54. u_tint = bgfx::createUniform("u_tint", bgfx::UniformType::Vec4); // Tint for when you click on items
  55. u_id = bgfx::createUniform("u_id", bgfx::UniformType::Vec4); // ID for drawing into ID buffer
  56. // Create program from shaders.
  57. m_shadingProgram = loadProgram("vs_picking_shaded", "fs_picking_shaded"); // Blinn shading
  58. m_idProgram = loadProgram("vs_picking_shaded", "fs_picking_id"); // Shader for drawing into ID buffer
  59. static const char* meshPaths[] =
  60. {
  61. "meshes/orb.bin",
  62. "meshes/column.bin",
  63. "meshes/bunny.bin",
  64. "meshes/cube.bin",
  65. "meshes/tree.bin",
  66. "meshes/hollowcube.bin",
  67. };
  68. static const float meshScale[] =
  69. {
  70. 0.5f,
  71. 0.05f,
  72. 0.5f,
  73. 0.25f,
  74. 0.05f,
  75. 0.05f,
  76. };
  77. m_highlighted = UINT32_MAX;
  78. m_reading = 0;
  79. m_currFrame = UINT32_MAX;
  80. m_fov = 3.0f;
  81. m_cameraSpin = false;
  82. bx::RngMwc mwc; // Random number generator
  83. for (uint32_t ii = 0; ii < 12; ++ii)
  84. {
  85. m_meshes[ii] = meshLoad(meshPaths[ii % BX_COUNTOF(meshPaths)]);
  86. m_meshScale[ii] = meshScale[ii % BX_COUNTOF(meshPaths)];
  87. // For the sake of this example, we'll give each mesh a random color, so the debug output looks colorful.
  88. // In an actual app, you'd probably just want to count starting from 1
  89. uint32_t rr = mwc.gen() % 256;
  90. uint32_t gg = mwc.gen() % 256;
  91. uint32_t bb = mwc.gen() % 256;
  92. m_idsF[ii][0] = rr / 255.0f;
  93. m_idsF[ii][1] = gg / 255.0f;
  94. m_idsF[ii][2] = bb / 255.0f;
  95. m_idsF[ii][3] = 1.0f;
  96. m_idsU[ii] = rr + (gg << 8) + (bb << 16) + (255u << 24);
  97. }
  98. m_timeOffset = bx::getHPCounter();
  99. // Set up ID buffer, which has a color target and depth buffer
  100. m_pickingRT = bgfx::createTexture2D(ID_DIM, ID_DIM, false, 1, bgfx::TextureFormat::RGBA8, 0
  101. | BGFX_TEXTURE_RT
  102. | BGFX_SAMPLER_MIN_POINT
  103. | BGFX_SAMPLER_MAG_POINT
  104. | BGFX_SAMPLER_MIP_POINT
  105. | BGFX_SAMPLER_U_CLAMP
  106. | BGFX_SAMPLER_V_CLAMP
  107. );
  108. m_pickingRTDepth = bgfx::createTexture2D(ID_DIM, ID_DIM, false, 1, bgfx::TextureFormat::D32F, 0
  109. | BGFX_TEXTURE_RT
  110. | BGFX_SAMPLER_MIN_POINT
  111. | BGFX_SAMPLER_MAG_POINT
  112. | BGFX_SAMPLER_MIP_POINT
  113. | BGFX_SAMPLER_U_CLAMP
  114. | BGFX_SAMPLER_V_CLAMP
  115. );
  116. // CPU texture for blitting to and reading ID buffer so we can see what was clicked on.
  117. // Impossible to read directly from a render target, you *must* blit to a CPU texture
  118. // first. Algorithm Overview: Render on GPU -> Blit to CPU texture -> Read from CPU
  119. // texture.
  120. m_blitTex = bgfx::createTexture2D(ID_DIM, ID_DIM, false, 1, bgfx::TextureFormat::RGBA8, 0
  121. | BGFX_TEXTURE_BLIT_DST
  122. | BGFX_TEXTURE_READ_BACK
  123. | BGFX_SAMPLER_MIN_POINT
  124. | BGFX_SAMPLER_MAG_POINT
  125. | BGFX_SAMPLER_MIP_POINT
  126. | BGFX_SAMPLER_U_CLAMP
  127. | BGFX_SAMPLER_V_CLAMP
  128. );
  129. bgfx::TextureHandle rt[2] =
  130. {
  131. m_pickingRT,
  132. m_pickingRTDepth
  133. };
  134. m_pickingFB = bgfx::createFrameBuffer(BX_COUNTOF(rt), rt, true);
  135. imguiCreate();
  136. }
  137. int shutdown() override
  138. {
  139. for (uint32_t ii = 0; ii < 12; ++ii)
  140. {
  141. meshUnload(m_meshes[ii]);
  142. }
  143. // Cleanup.
  144. bgfx::destroy(m_shadingProgram);
  145. bgfx::destroy(m_idProgram);
  146. bgfx::destroy(u_tint);
  147. bgfx::destroy(u_id);
  148. bgfx::destroy(m_pickingFB);
  149. bgfx::destroy(m_pickingRT);
  150. bgfx::destroy(m_pickingRTDepth);
  151. bgfx::destroy(m_blitTex);
  152. imguiDestroy();
  153. // Shutdown bgfx.
  154. bgfx::shutdown();
  155. return 0;
  156. }
  157. bool update() override
  158. {
  159. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  160. {
  161. // Draw UI
  162. imguiBeginFrame(
  163. m_mouseState.m_mx
  164. , m_mouseState.m_my
  165. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  166. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  167. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  168. , m_mouseState.m_mz
  169. , uint16_t(m_width)
  170. , uint16_t(m_height)
  171. );
  172. const bgfx::Caps* caps = bgfx::getCaps();
  173. bool blitSupport = 0 != (caps->supported & BGFX_CAPS_TEXTURE_BLIT);
  174. showExampleDialog(this
  175. , !blitSupport
  176. ? "BGFX_CAPS_TEXTURE_BLIT is not supported."
  177. : NULL
  178. );
  179. if (blitSupport)
  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 / 2.0f)
  187. , ImGuiCond_FirstUseEver
  188. );
  189. ImGui::Begin("Settings"
  190. , NULL
  191. , 0
  192. );
  193. ImGui::Image(m_pickingRT, ImVec2(m_width / 5.0f - 16.0f, m_width / 5.0f - 16.0f) );
  194. ImGui::SliderFloat("Field of view", &m_fov, 1.0f, 60.0f);
  195. ImGui::Checkbox("Spin Camera", &m_cameraSpin);
  196. ImGui::End();
  197. bgfx::setViewFrameBuffer(RENDER_PASS_ID, m_pickingFB);
  198. float time = (float)( (bx::getHPCounter() - m_timeOffset) / double(bx::getHPFrequency() ) );
  199. // Set up matrices for basic forward renderer
  200. const float camSpeed = 0.25;
  201. float cameraSpin = (float)m_cameraSpin;
  202. float eyeDist = 2.5f;
  203. const bx::Vec3 at = { 0.0f, 0.0f, 0.0f };
  204. const bx::Vec3 eye =
  205. {
  206. -eyeDist * bx::sin(time*cameraSpin*camSpeed),
  207. 0.0f,
  208. -eyeDist * bx::cos(time*cameraSpin*camSpeed),
  209. };
  210. float view[16];
  211. bx::mtxLookAt(view, eye, at);
  212. float proj[16];
  213. bx::mtxProj(proj, 60.0f, float(m_width) / float(m_height), 0.1f, 100.0f, caps->homogeneousDepth);
  214. // Set up view rect and transform for the shaded pass
  215. bgfx::setViewRect(RENDER_PASS_SHADING, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  216. bgfx::setViewTransform(RENDER_PASS_SHADING, view, proj);
  217. // Set up picking pass
  218. float viewProj[16];
  219. bx::mtxMul(viewProj, view, proj);
  220. float invViewProj[16];
  221. bx::mtxInverse(invViewProj, viewProj);
  222. // Mouse coord in NDC
  223. float mouseXNDC = ( m_mouseState.m_mx / (float)m_width ) * 2.0f - 1.0f;
  224. float mouseYNDC = ((m_height - m_mouseState.m_my) / (float)m_height) * 2.0f - 1.0f;
  225. const bx::Vec3 pickEye = bx::mulH({ mouseXNDC, mouseYNDC, 0.0f }, invViewProj);
  226. const bx::Vec3 pickAt = bx::mulH({ mouseXNDC, mouseYNDC, 1.0f }, invViewProj);
  227. // Look at our unprojected point
  228. float pickView[16];
  229. bx::mtxLookAt(pickView, pickEye, pickAt);
  230. // Tight FOV is best for picking
  231. float pickProj[16];
  232. bx::mtxProj(pickProj, m_fov, 1, 0.1f, 100.0f, caps->homogeneousDepth);
  233. // View rect and transforms for picking pass
  234. bgfx::setViewRect(RENDER_PASS_ID, 0, 0, ID_DIM, ID_DIM);
  235. bgfx::setViewTransform(RENDER_PASS_ID, pickView, pickProj);
  236. // Now that our passes are set up, we can finally draw each mesh
  237. // Picking highlights a mesh so we'll set up this tint color
  238. const float tintBasic[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
  239. const float tintHighlighted[4] = { 0.3f, 0.3f, 2.0f, 1.0f };
  240. for (uint32_t mesh = 0; mesh < 12; ++mesh)
  241. {
  242. const float scale = m_meshScale[mesh];
  243. // Set up transform matrix for each mesh
  244. float mtx[16];
  245. bx::mtxSRT(mtx
  246. , scale, scale, scale
  247. , 0.0f
  248. , time*0.37f*(mesh % 2 ? 1.0f : -1.0f)
  249. , 0.0f
  250. , (mesh % 4) - 1.5f
  251. , (mesh / 4) - 1.25f
  252. , 0.0f
  253. );
  254. // Submit mesh to both of our render passes
  255. // Set uniform based on if this is the highlighted mesh
  256. bgfx::setUniform(u_tint
  257. , mesh == m_highlighted
  258. ? tintHighlighted
  259. : tintBasic
  260. );
  261. meshSubmit(m_meshes[mesh], RENDER_PASS_SHADING, m_shadingProgram, mtx);
  262. // Submit ID pass based on mesh ID
  263. bgfx::setUniform(u_id, m_idsF[mesh]);
  264. meshSubmit(m_meshes[mesh], RENDER_PASS_ID, m_idProgram, mtx);
  265. }
  266. // If the user previously clicked, and we're done reading data from GPU, look at ID buffer on CPU
  267. // Whatever mesh has the most pixels in the ID buffer is the one the user clicked on.
  268. if (m_reading == m_currFrame)
  269. {
  270. m_reading = 0;
  271. std::map<uint32_t, uint32_t> ids; // This contains all the IDs found in the buffer
  272. uint32_t maxAmount = 0;
  273. for (uint8_t *x = m_blitData; x < m_blitData + ID_DIM * ID_DIM * 4;)
  274. {
  275. uint8_t rr = *x++;
  276. uint8_t gg = *x++;
  277. uint8_t bb = *x++;
  278. uint8_t aa = *x++;
  279. if (bgfx::RendererType::Direct3D9 == caps->rendererType)
  280. {
  281. // Comes back as BGRA
  282. uint8_t temp = rr;
  283. rr = bb;
  284. bb = temp;
  285. }
  286. if (0 == (rr|gg|bb) ) // Skip background
  287. {
  288. continue;
  289. }
  290. uint32_t hashKey = rr + (gg << 8) + (bb << 16) + (aa << 24);
  291. std::map<uint32_t, uint32_t>::iterator mapIter = ids.find(hashKey);
  292. uint32_t amount = 1;
  293. if (mapIter != ids.end() )
  294. {
  295. amount = mapIter->second + 1;
  296. }
  297. ids[hashKey] = amount; // Amount of times this ID (color) has been clicked on in buffer
  298. maxAmount = maxAmount > amount
  299. ? maxAmount
  300. : amount
  301. ;
  302. }
  303. uint32_t idKey = 0;
  304. m_highlighted = UINT32_MAX;
  305. if (maxAmount)
  306. {
  307. for (std::map<uint32_t, uint32_t>::iterator mapIter = ids.begin(); mapIter != ids.end(); mapIter++)
  308. {
  309. if (mapIter->second == maxAmount)
  310. {
  311. idKey = mapIter->first;
  312. break;
  313. }
  314. }
  315. for (uint32_t ii = 0; ii < 12; ++ii)
  316. {
  317. if (m_idsU[ii] == idKey)
  318. {
  319. m_highlighted = ii;
  320. break;
  321. }
  322. }
  323. }
  324. }
  325. // Start a new readback?
  326. if (!m_reading
  327. && m_mouseState.m_buttons[entry::MouseButton::Left])
  328. {
  329. // Blit and read
  330. bgfx::blit(RENDER_PASS_BLIT, m_blitTex, 0, 0, m_pickingRT);
  331. m_reading = bgfx::readTexture(m_blitTex, m_blitData);
  332. }
  333. }
  334. imguiEndFrame();
  335. // Advance to next frame. Rendering thread will be kicked to
  336. // process submitted rendering primitives.
  337. m_currFrame = bgfx::frame();
  338. return true;
  339. }
  340. return false;
  341. }
  342. entry::MouseState m_mouseState;
  343. uint32_t m_width;
  344. uint32_t m_height;
  345. uint32_t m_debug;
  346. uint32_t m_reset;
  347. int64_t m_timeOffset;
  348. Mesh* m_meshes[12];
  349. float m_meshScale[12];
  350. float m_idsF[12][4];
  351. uint32_t m_idsU[12];
  352. uint32_t m_highlighted;
  353. // Resource handles
  354. bgfx::ProgramHandle m_shadingProgram;
  355. bgfx::ProgramHandle m_idProgram;
  356. bgfx::UniformHandle u_tint;
  357. bgfx::UniformHandle u_id;
  358. bgfx::TextureHandle m_pickingRT;
  359. bgfx::TextureHandle m_pickingRTDepth;
  360. bgfx::TextureHandle m_blitTex;
  361. bgfx::FrameBufferHandle m_pickingFB;
  362. uint8_t m_blitData[ID_DIM*ID_DIM * 4]; // Read blit into this
  363. uint32_t m_reading;
  364. uint32_t m_currFrame;
  365. float m_fov;
  366. bool m_cameraSpin;
  367. };
  368. } // namespace
  369. ENTRY_IMPLEMENT_MAIN(
  370. ExamplePicking
  371. , "30-picking"
  372. , "Mouse picking via GPU texture readback."
  373. , "https://bkaradzic.github.io/bgfx/examples.html#picking"
  374. );