picking.cpp 11 KB

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