imgui_context.cpp 12 KB

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