imgui_context.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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] = (int)crown::KeyboardButton::TAB;
  164. io.KeyMap[ImGuiKey_LeftArrow] = (int)crown::KeyboardButton::LEFT;
  165. io.KeyMap[ImGuiKey_RightArrow] = (int)crown::KeyboardButton::RIGHT;
  166. io.KeyMap[ImGuiKey_UpArrow] = (int)crown::KeyboardButton::UP;
  167. io.KeyMap[ImGuiKey_DownArrow] = (int)crown::KeyboardButton::DOWN;
  168. io.KeyMap[ImGuiKey_Home] = (int)crown::KeyboardButton::HOME;
  169. io.KeyMap[ImGuiKey_End] = (int)crown::KeyboardButton::END;
  170. io.KeyMap[ImGuiKey_Delete] = (int)crown::KeyboardButton::DEL;
  171. io.KeyMap[ImGuiKey_Backspace] = (int)crown::KeyboardButton::BACKSPACE;
  172. io.KeyMap[ImGuiKey_Enter] = (int)crown::KeyboardButton::ENTER;
  173. io.KeyMap[ImGuiKey_Escape] = (int)crown::KeyboardButton::ESCAPE;
  174. io.KeyMap[ImGuiKey_A] = (int)crown::KeyboardButton::A;
  175. io.KeyMap[ImGuiKey_C] = (int)crown::KeyboardButton::C;
  176. io.KeyMap[ImGuiKey_V] = (int)crown::KeyboardButton::V;
  177. io.KeyMap[ImGuiKey_X] = (int)crown::KeyboardButton::X;
  178. io.KeyMap[ImGuiKey_Y] = (int)crown::KeyboardButton::Y;
  179. io.KeyMap[ImGuiKey_Z] = (int)crown::KeyboardButton::Z;
  180. bgfx::RendererType::Enum type = bgfx::getRendererType();
  181. u_imageLodEnabled = bgfx::createUniform("u_imageLodEnabled", bgfx::UniformType::Vec4);
  182. m_decl
  183. .begin()
  184. .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
  185. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  186. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  187. .end();
  188. s_tex = bgfx::createUniform("s_tex", bgfx::UniformType::Int1);
  189. uint8_t* data;
  190. int32_t width;
  191. int32_t height;
  192. {
  193. ImFontConfig config;
  194. config.FontDataOwnedByAtlas = false;
  195. config.MergeMode = false;
  196. // config.MergeGlyphCenterV = true;
  197. const ImWchar* ranges = io.Fonts->GetGlyphRangesCyrillic();
  198. m_font[ImGui::Font::Regular] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoRegularTtf, sizeof(s_robotoRegularTtf), _fontSize, &config, ranges);
  199. m_font[ImGui::Font::Mono ] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoMonoRegularTtf, sizeof(s_robotoMonoRegularTtf), _fontSize-3.0f, &config, ranges);
  200. config.MergeMode = true;
  201. config.DstFont = m_font[ImGui::Font::Regular];
  202. for (uint32_t ii = 0; ii < BX_COUNTOF(s_fontRangeMerge); ++ii)
  203. {
  204. const FontRangeMerge& frm = s_fontRangeMerge[ii];
  205. io.Fonts->AddFontFromMemoryTTF( (void*)frm.data
  206. , (int)frm.size
  207. , _fontSize-3.0f
  208. , &config
  209. , frm.ranges
  210. );
  211. }
  212. }
  213. io.Fonts->GetTexDataAsRGBA32(&data, &width, &height);
  214. m_texture = bgfx::createTexture2D(
  215. (uint16_t)width
  216. , (uint16_t)height
  217. , false
  218. , 1
  219. , bgfx::TextureFormat::BGRA8
  220. , 0
  221. , bgfx::copy(data, width*height*4)
  222. );
  223. ImGui::InitDockContext();
  224. }
  225. void destroy()
  226. {
  227. ImGui::ShutdownDockContext();
  228. ImGui::DestroyContext(m_imgui);
  229. bgfx::destroy(s_tex);
  230. bgfx::destroy(m_texture);
  231. bgfx::destroy(u_imageLodEnabled);
  232. m_allocator = NULL;
  233. }
  234. void setupStyle(bool _dark)
  235. {
  236. // Doug Binks' darl color scheme
  237. // https://gist.github.com/dougbinks/8089b4bbaccaaf6fa204236978d165a9
  238. ImGuiStyle& style = ImGui::GetStyle();
  239. if (_dark)
  240. {
  241. ImGui::StyleColorsDark(&style);
  242. }
  243. else
  244. {
  245. ImGui::StyleColorsLight(&style);
  246. }
  247. style.FrameRounding = 2.0f;
  248. style.ScrollbarRounding = 2.0f;
  249. style.ScrollbarSize = 13.0f;
  250. style.WindowBorderSize = 0.0f;
  251. style.WindowPadding = ImVec2(4.0f, 4.0f);
  252. style.WindowRounding = 2.0f;
  253. style.WindowTitleAlign = ImVec2(0.5f, 0.5f);
  254. }
  255. void beginFrame(uint8_t view_id, uint16_t width, uint16_t height)
  256. {
  257. m_viewId = view_id;
  258. ImGuiIO& io = ImGui::GetIO();
  259. io.DisplaySize = ImVec2(width, height);
  260. io.DeltaTime = 1.0f / 60.0f;
  261. ImGui::NewFrame();
  262. }
  263. void endFrame()
  264. {
  265. ImGui::Render();
  266. render(ImGui::GetDrawData());
  267. }
  268. ImGuiContext* m_imgui;
  269. bx::AllocatorI* m_allocator;
  270. bgfx::VertexDecl m_decl;
  271. bgfx::TextureHandle m_texture;
  272. bgfx::UniformHandle s_tex;
  273. bgfx::UniformHandle u_imageLodEnabled;
  274. ImFont* m_font[ImGui::Font::Count];
  275. bgfx::ViewId m_viewId;
  276. };
  277. static ImGuiContext s_ctx;
  278. static void* memAlloc(size_t _size, void* _userData)
  279. {
  280. BX_UNUSED(_userData);
  281. return BX_ALLOC(s_ctx.m_allocator, _size);
  282. }
  283. static void memFree(void* _ptr, void* _userData)
  284. {
  285. BX_UNUSED(_userData);
  286. BX_FREE(s_ctx.m_allocator, _ptr);
  287. }
  288. namespace ImGui
  289. {
  290. void PushFont(Font::Enum _font)
  291. {
  292. PushFont(s_ctx.m_font[_font]);
  293. }
  294. } // namespace ImGui
  295. namespace crown
  296. {
  297. void imgui_create(f32 _fontSize, bx::AllocatorI* _allocator)
  298. {
  299. s_ctx.create(_fontSize, _allocator);
  300. }
  301. void imgui_destroy()
  302. {
  303. s_ctx.destroy();
  304. }
  305. void imgui_begin_frame(uint8_t view_id, u16 width, u16 height)
  306. {
  307. s_ctx.beginFrame(view_id, width, height);
  308. }
  309. void imgui_end_frame()
  310. {
  311. s_ctx.endFrame();
  312. }
  313. } // namespace crown
  314. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4505); // error C4505: '' : unreferenced local function has been removed
  315. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-function"); // warning: ‘int rect_width_compare(const void*, const void*)’ defined but not used
  316. BX_PRAGMA_DIAGNOSTIC_PUSH();
  317. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG("-Wunknown-pragmas")
  318. //BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-but-set-variable"); // warning: variable ‘L1’ set but not used
  319. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wtype-limits"); // warning: comparison is always true due to limited range of data type
  320. #define STBTT_malloc(_size, _userData) memAlloc(_size, _userData)
  321. #define STBTT_free(_ptr, _userData) memFree(_ptr, _userData)
  322. #define STB_RECT_PACK_IMPLEMENTATION
  323. #include <stb/stb_rect_pack.h>
  324. #define STB_TRUETYPE_IMPLEMENTATION
  325. #include <stb/stb_truetype.h>
  326. BX_PRAGMA_DIAGNOSTIC_POP();