imgui_context.cpp 11 KB

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