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