imgui_context.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /*
  2. * Copyright 2014-2015 Daniel Collin. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include <bgfx/bgfx.h>
  6. #include <bgfx/embedded_shader.h>
  7. #include <bx/allocator.h>
  8. #include <bx/math.h>
  9. #include <bx/timer.h>
  10. #include <imgui.h>
  11. #include "data/roboto_regular.ttf.h"
  12. #include "data/robotomono_regular.ttf.h"
  13. #include "data/icons_kenney.ttf.h"
  14. #include "data/icons_font_awesome.ttf.h"
  15. #include "imgui_context.h"
  16. #include "device/device.h"
  17. #include "device/pipeline.h"
  18. #include "device/input_types.h"
  19. #include "device/input_device.h"
  20. #include "world/shader_manager.h"
  21. #include "core/strings/string_id.h"
  22. // From bgfx_utils.h
  23. inline bool checkAvailTransientBuffers(uint32_t _numVertices, const bgfx::VertexDecl& _decl, uint32_t _numIndices)
  24. {
  25. return _numVertices == bgfx::getAvailTransientVertexBuffer(_numVertices, _decl)
  26. && _numIndices == bgfx::getAvailTransientIndexBuffer(_numIndices)
  27. ;
  28. }
  29. struct FontRangeMerge
  30. {
  31. const void* data;
  32. size_t size;
  33. ImWchar ranges[3];
  34. };
  35. static FontRangeMerge s_fontRangeMerge[] =
  36. {
  37. { s_iconsKenneyTtf, sizeof(s_iconsKenneyTtf), { ICON_MIN_KI, ICON_MAX_KI, 0 } },
  38. { s_iconsFontAwesomeTtf, sizeof(s_iconsFontAwesomeTtf), { ICON_MIN_FA, ICON_MAX_FA, 0 } },
  39. };
  40. static void* memAlloc(size_t _size);
  41. static void memFree(void* _ptr);
  42. struct ImGuiContext
  43. {
  44. static void renderDrawLists(ImDrawData* _drawData);
  45. void render(ImDrawData* _drawData)
  46. {
  47. const ImGuiIO& io = ImGui::GetIO();
  48. const float width = io.DisplaySize.x;
  49. const float height = io.DisplaySize.y;
  50. bgfx::setViewName(m_viewId, "ImGui");
  51. bgfx::setViewMode(m_viewId, bgfx::ViewMode::Sequential);
  52. const bgfx::HMD* hmd = bgfx::getHMD();
  53. const bgfx::Caps* caps = bgfx::getCaps();
  54. if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) )
  55. {
  56. float proj[16];
  57. bx::mtxProj(proj, hmd->eye[0].fov, 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  58. static float time = 0.0f;
  59. time += 0.05f;
  60. const float dist = 10.0f;
  61. const float offset0 = -proj[8] + (hmd->eye[0].viewOffset[0] / dist * proj[0]);
  62. const float offset1 = -proj[8] + (hmd->eye[1].viewOffset[0] / dist * proj[0]);
  63. float ortho[2][16];
  64. const float viewOffset = width/4.0f;
  65. const float viewWidth = width/2.0f;
  66. bx::mtxOrtho(ortho[0], viewOffset, viewOffset + viewWidth, height, 0.0f, 0.0f, 1000.0f, offset0, caps->homogeneousDepth);
  67. bx::mtxOrtho(ortho[1], viewOffset, viewOffset + viewWidth, height, 0.0f, 0.0f, 1000.0f, offset1, caps->homogeneousDepth);
  68. bgfx::setViewTransform(m_viewId, NULL, ortho[0], BGFX_VIEW_STEREO, ortho[1]);
  69. bgfx::setViewRect(m_viewId, 0, 0, hmd->width, hmd->height);
  70. }
  71. else
  72. {
  73. float ortho[16];
  74. bx::mtxOrtho(ortho, 0.0f, width, height, 0.0f, 0.0f, 1000.0f, 0.0f, caps->homogeneousDepth);
  75. bgfx::setViewTransform(m_viewId, NULL, ortho);
  76. bgfx::setViewRect(m_viewId, 0, 0, uint16_t(width), uint16_t(height) );
  77. }
  78. // Render command lists
  79. for (int32_t ii = 0, num = _drawData->CmdListsCount; ii < num; ++ii)
  80. {
  81. bgfx::TransientVertexBuffer tvb;
  82. bgfx::TransientIndexBuffer tib;
  83. const ImDrawList* drawList = _drawData->CmdLists[ii];
  84. uint32_t numVertices = (uint32_t)drawList->VtxBuffer.size();
  85. uint32_t numIndices = (uint32_t)drawList->IdxBuffer.size();
  86. if (!checkAvailTransientBuffers(numVertices, m_decl, numIndices) )
  87. {
  88. // not enough space in transient buffer just quit drawing the rest...
  89. break;
  90. }
  91. bgfx::allocTransientVertexBuffer(&tvb, numVertices, m_decl);
  92. bgfx::allocTransientIndexBuffer(&tib, numIndices);
  93. ImDrawVert* verts = (ImDrawVert*)tvb.data;
  94. bx::memCopy(verts, drawList->VtxBuffer.begin(), numVertices * sizeof(ImDrawVert) );
  95. ImDrawIdx* indices = (ImDrawIdx*)tib.data;
  96. bx::memCopy(indices, drawList->IdxBuffer.begin(), numIndices * sizeof(ImDrawIdx) );
  97. uint32_t offset = 0;
  98. for (const ImDrawCmd* cmd = drawList->CmdBuffer.begin(), *cmdEnd = drawList->CmdBuffer.end(); cmd != cmdEnd; ++cmd)
  99. {
  100. if (cmd->UserCallback)
  101. {
  102. cmd->UserCallback(drawList, cmd);
  103. }
  104. else if (0 != cmd->ElemCount)
  105. {
  106. uint64_t state = 0
  107. | BGFX_STATE_RGB_WRITE
  108. | BGFX_STATE_ALPHA_WRITE
  109. | BGFX_STATE_MSAA
  110. ;
  111. bgfx::TextureHandle th = m_texture;
  112. crown::StringId32 program = crown::StringId32("ocornut_imgui");
  113. if (NULL != cmd->TextureId)
  114. {
  115. union { ImTextureID ptr; struct { bgfx::TextureHandle handle; uint8_t flags; uint8_t mip; } s; } texture = { cmd->TextureId };
  116. state |= 0 != (IMGUI_FLAGS_ALPHA_BLEND & texture.s.flags)
  117. ? BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA)
  118. : BGFX_STATE_NONE
  119. ;
  120. th = texture.s.handle;
  121. if (0 != texture.s.mip)
  122. {
  123. const float lodEnabled[4] = { float(texture.s.mip), 1.0f, 0.0f, 0.0f };
  124. bgfx::setUniform(u_imageLodEnabled, lodEnabled);
  125. program = crown::StringId32("imgui_image");
  126. }
  127. }
  128. else
  129. {
  130. state |= BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA);
  131. }
  132. const uint16_t xx = uint16_t(bx::max(cmd->ClipRect.x, 0.0f) );
  133. const uint16_t yy = uint16_t(bx::max(cmd->ClipRect.y, 0.0f) );
  134. bgfx::setScissor(xx, yy
  135. , uint16_t(bx::min(cmd->ClipRect.z, 65535.0f)-xx)
  136. , uint16_t(bx::min(cmd->ClipRect.w, 65535.0f)-yy)
  137. );
  138. bgfx::setState(state);
  139. bgfx::setTexture(0, s_tex, th);
  140. bgfx::setVertexBuffer(0, &tvb, 0, numVertices);
  141. bgfx::setIndexBuffer(&tib, offset, cmd->ElemCount);
  142. crown::device()->_shader_manager->submit(program, VIEW_IMGUI, 0, state);
  143. }
  144. offset += cmd->ElemCount;
  145. }
  146. }
  147. }
  148. void create(float _fontSize, bx::AllocatorI* _allocator)
  149. {
  150. m_allocator = _allocator;
  151. if (NULL == _allocator)
  152. {
  153. static bx::DefaultAllocator allocator;
  154. m_allocator = &allocator;
  155. }
  156. m_viewId = VIEW_IMGUI;
  157. ImGuiIO& io = ImGui::GetIO();
  158. io.RenderDrawListsFn = renderDrawLists;
  159. io.MemAllocFn = memAlloc;
  160. io.MemFreeFn = memFree;
  161. io.DisplaySize = ImVec2(1280.0f, 720.0f);
  162. io.DeltaTime = 1.0f / 60.0f;
  163. io.IniFilename = NULL;
  164. setupStyle(true);
  165. io.KeyMap[ImGuiKey_Tab] = (int)crown::KeyboardButton::TAB;
  166. io.KeyMap[ImGuiKey_LeftArrow] = (int)crown::KeyboardButton::LEFT;
  167. io.KeyMap[ImGuiKey_RightArrow] = (int)crown::KeyboardButton::RIGHT;
  168. io.KeyMap[ImGuiKey_UpArrow] = (int)crown::KeyboardButton::UP;
  169. io.KeyMap[ImGuiKey_DownArrow] = (int)crown::KeyboardButton::DOWN;
  170. io.KeyMap[ImGuiKey_Home] = (int)crown::KeyboardButton::HOME;
  171. io.KeyMap[ImGuiKey_End] = (int)crown::KeyboardButton::END;
  172. io.KeyMap[ImGuiKey_Delete] = (int)crown::KeyboardButton::DEL;
  173. io.KeyMap[ImGuiKey_Backspace] = (int)crown::KeyboardButton::BACKSPACE;
  174. io.KeyMap[ImGuiKey_Enter] = (int)crown::KeyboardButton::ENTER;
  175. io.KeyMap[ImGuiKey_Escape] = (int)crown::KeyboardButton::ESCAPE;
  176. io.KeyMap[ImGuiKey_A] = (int)crown::KeyboardButton::A;
  177. io.KeyMap[ImGuiKey_C] = (int)crown::KeyboardButton::C;
  178. io.KeyMap[ImGuiKey_V] = (int)crown::KeyboardButton::V;
  179. io.KeyMap[ImGuiKey_X] = (int)crown::KeyboardButton::X;
  180. io.KeyMap[ImGuiKey_Y] = (int)crown::KeyboardButton::Y;
  181. io.KeyMap[ImGuiKey_Z] = (int)crown::KeyboardButton::Z;
  182. bgfx::RendererType::Enum type = bgfx::getRendererType();
  183. u_imageLodEnabled = bgfx::createUniform("u_imageLodEnabled", bgfx::UniformType::Vec4);
  184. m_decl
  185. .begin()
  186. .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
  187. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  188. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  189. .end();
  190. s_tex = bgfx::createUniform("s_tex", bgfx::UniformType::Int1);
  191. uint8_t* data;
  192. int32_t width;
  193. int32_t height;
  194. {
  195. ImFontConfig config;
  196. config.FontDataOwnedByAtlas = false;
  197. config.MergeMode = false;
  198. // config.MergeGlyphCenterV = true;
  199. const ImWchar* ranges = io.Fonts->GetGlyphRangesCyrillic();
  200. m_font[ImGui::Font::Regular] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoRegularTtf, sizeof(s_robotoRegularTtf), _fontSize, &config, ranges);
  201. m_font[ImGui::Font::Mono ] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoMonoRegularTtf, sizeof(s_robotoMonoRegularTtf), _fontSize-3.0f, &config, ranges);
  202. config.MergeMode = true;
  203. config.DstFont = m_font[ImGui::Font::Regular];
  204. for (uint32_t ii = 0; ii < BX_COUNTOF(s_fontRangeMerge); ++ii)
  205. {
  206. const FontRangeMerge& frm = s_fontRangeMerge[ii];
  207. io.Fonts->AddFontFromMemoryTTF( (void*)frm.data
  208. , (int)frm.size
  209. , _fontSize-3.0f
  210. , &config
  211. , frm.ranges
  212. );
  213. }
  214. }
  215. io.Fonts->GetTexDataAsRGBA32(&data, &width, &height);
  216. m_texture = bgfx::createTexture2D(
  217. (uint16_t)width
  218. , (uint16_t)height
  219. , false
  220. , 1
  221. , bgfx::TextureFormat::BGRA8
  222. , 0
  223. , bgfx::copy(data, width*height*4)
  224. );
  225. ImGui::InitDockContext();
  226. }
  227. void destroy()
  228. {
  229. ImGui::ShutdownDockContext();
  230. ImGui::Shutdown();
  231. bgfx::destroy(s_tex);
  232. bgfx::destroy(m_texture);
  233. bgfx::destroy(u_imageLodEnabled);
  234. m_allocator = NULL;
  235. }
  236. void setupStyle(bool _dark)
  237. {
  238. // Doug Binks' darl color scheme
  239. // https://gist.github.com/dougbinks/8089b4bbaccaaf6fa204236978d165a9
  240. ImGuiStyle& style = ImGui::GetStyle();
  241. if (_dark)
  242. {
  243. ImGui::StyleColorsDark(&style);
  244. }
  245. else
  246. {
  247. ImGui::StyleColorsLight(&style);
  248. }
  249. style.FrameRounding = 2.0f;
  250. style.ScrollbarRounding = 2.0f;
  251. style.ScrollbarSize = 13.0f;
  252. style.WindowPadding = ImVec2(4.0f, 4.0f);
  253. style.WindowRounding = 2.0f;
  254. style.WindowTitleAlign = ImVec2(0.5f, 0.5f);
  255. }
  256. void beginFrame(uint8_t view_id, uint16_t width, uint16_t height)
  257. {
  258. m_viewId = view_id;
  259. ImGuiIO& io = ImGui::GetIO();
  260. io.DisplaySize = ImVec2(width, height);
  261. io.DeltaTime = 1.0f / 60.0f;
  262. ImGui::NewFrame();
  263. }
  264. void endFrame()
  265. {
  266. ImGui::Render();
  267. }
  268. bx::AllocatorI* m_allocator;
  269. bgfx::VertexDecl m_decl;
  270. bgfx::TextureHandle m_texture;
  271. bgfx::UniformHandle s_tex;
  272. bgfx::UniformHandle u_imageLodEnabled;
  273. ImFont* m_font[ImGui::Font::Count];
  274. bgfx::ViewId m_viewId;
  275. };
  276. static ImGuiContext s_ctx;
  277. static void* memAlloc(size_t _size)
  278. {
  279. return BX_ALLOC(s_ctx.m_allocator, _size);
  280. }
  281. static void memFree(void* _ptr)
  282. {
  283. BX_FREE(s_ctx.m_allocator, _ptr);
  284. }
  285. void ImGuiContext::renderDrawLists(ImDrawData* _drawData)
  286. {
  287. s_ctx.render(_drawData);
  288. }
  289. namespace ImGui
  290. {
  291. void PushFont(Font::Enum _font)
  292. {
  293. PushFont(s_ctx.m_font[_font]);
  294. }
  295. } // namespace ImGui
  296. namespace crown
  297. {
  298. void imgui_create(f32 _fontSize, bx::AllocatorI* _allocator)
  299. {
  300. s_ctx.create(_fontSize, _allocator);
  301. }
  302. void imgui_destroy()
  303. {
  304. s_ctx.destroy();
  305. }
  306. void imgui_begin_frame(uint8_t view_id, u16 width, u16 height)
  307. {
  308. s_ctx.beginFrame(view_id, width, height);
  309. }
  310. void imgui_end_frame()
  311. {
  312. s_ctx.endFrame();
  313. }
  314. } // namespace crown
  315. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4505); // error C4505: '' : unreferenced local function has been removed
  316. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-function"); // warning: ‘int rect_width_compare(const void*, const void*)’ defined but not used
  317. BX_PRAGMA_DIAGNOSTIC_PUSH();
  318. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG("-Wunknown-pragmas")
  319. //BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-but-set-variable"); // warning: variable ‘L1’ set but not used
  320. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wtype-limits"); // warning: comparison is always true due to limited range of data type
  321. #define STBTT_malloc(_size, _userData) memAlloc(_size)
  322. #define STBTT_free(_ptr, _userData) memFree(_ptr)
  323. #define STB_RECT_PACK_IMPLEMENTATION
  324. #include <stb/stb_rect_pack.h>
  325. #define STB_TRUETYPE_IMPLEMENTATION
  326. #include <stb/stb_truetype.h>
  327. BX_PRAGMA_DIAGNOSTIC_POP();