imgui.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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 <dear-imgui/imgui.h>
  11. #include "imgui.h"
  12. #include "../bgfx_utils.h"
  13. //#define USE_ENTRY 1
  14. #ifndef USE_ENTRY
  15. # define USE_ENTRY 0
  16. #endif // USE_ENTRY
  17. #if USE_ENTRY
  18. # include "../entry/entry.h"
  19. # include "../entry/input.h"
  20. #endif // USE_ENTRY
  21. #include "vs_ocornut_imgui.bin.h"
  22. #include "fs_ocornut_imgui.bin.h"
  23. #include "vs_imgui_image.bin.h"
  24. #include "fs_imgui_image.bin.h"
  25. #include "roboto_regular.ttf.h"
  26. #include "robotomono_regular.ttf.h"
  27. #include "icons_kenney.ttf.h"
  28. #include "icons_font_awesome.ttf.h"
  29. static const bgfx::EmbeddedShader s_embeddedShaders[] =
  30. {
  31. BGFX_EMBEDDED_SHADER(vs_ocornut_imgui),
  32. BGFX_EMBEDDED_SHADER(fs_ocornut_imgui),
  33. BGFX_EMBEDDED_SHADER(vs_imgui_image),
  34. BGFX_EMBEDDED_SHADER(fs_imgui_image),
  35. BGFX_EMBEDDED_SHADER_END()
  36. };
  37. struct FontRangeMerge
  38. {
  39. const void* data;
  40. size_t size;
  41. ImWchar ranges[3];
  42. };
  43. static FontRangeMerge s_fontRangeMerge[] =
  44. {
  45. { s_iconsKenneyTtf, sizeof(s_iconsKenneyTtf), { ICON_MIN_KI, ICON_MAX_KI, 0 } },
  46. { s_iconsFontAwesomeTtf, sizeof(s_iconsFontAwesomeTtf), { ICON_MIN_FA, ICON_MAX_FA, 0 } },
  47. };
  48. static void* memAlloc(size_t _size, void* _userData);
  49. static void memFree(void* _ptr, void* _userData);
  50. struct OcornutImguiContext
  51. {
  52. void render(ImDrawData* _drawData)
  53. {
  54. const ImGuiIO& io = ImGui::GetIO();
  55. const float width = io.DisplaySize.x;
  56. const float height = io.DisplaySize.y;
  57. bgfx::setViewName(m_viewId, "ImGui");
  58. bgfx::setViewMode(m_viewId, bgfx::ViewMode::Sequential);
  59. const bgfx::Caps* caps = bgfx::getCaps();
  60. {
  61. float ortho[16];
  62. bx::mtxOrtho(ortho, 0.0f, width, height, 0.0f, 0.0f, 1000.0f, 0.0f, caps->homogeneousDepth);
  63. bgfx::setViewTransform(m_viewId, NULL, ortho);
  64. bgfx::setViewRect(m_viewId, 0, 0, uint16_t(width), uint16_t(height) );
  65. }
  66. // Render command lists
  67. for (int32_t ii = 0, num = _drawData->CmdListsCount; ii < num; ++ii)
  68. {
  69. bgfx::TransientVertexBuffer tvb;
  70. bgfx::TransientIndexBuffer tib;
  71. const ImDrawList* drawList = _drawData->CmdLists[ii];
  72. uint32_t numVertices = (uint32_t)drawList->VtxBuffer.size();
  73. uint32_t numIndices = (uint32_t)drawList->IdxBuffer.size();
  74. if (!checkAvailTransientBuffers(numVertices, m_layout, numIndices) )
  75. {
  76. // not enough space in transient buffer just quit drawing the rest...
  77. break;
  78. }
  79. bgfx::allocTransientVertexBuffer(&tvb, numVertices, m_layout);
  80. bgfx::allocTransientIndexBuffer(&tib, numIndices);
  81. ImDrawVert* verts = (ImDrawVert*)tvb.data;
  82. bx::memCopy(verts, drawList->VtxBuffer.begin(), numVertices * sizeof(ImDrawVert) );
  83. ImDrawIdx* indices = (ImDrawIdx*)tib.data;
  84. bx::memCopy(indices, drawList->IdxBuffer.begin(), numIndices * sizeof(ImDrawIdx) );
  85. uint32_t offset = 0;
  86. for (const ImDrawCmd* cmd = drawList->CmdBuffer.begin(), *cmdEnd = drawList->CmdBuffer.end(); cmd != cmdEnd; ++cmd)
  87. {
  88. if (cmd->UserCallback)
  89. {
  90. cmd->UserCallback(drawList, cmd);
  91. }
  92. else if (0 != cmd->ElemCount)
  93. {
  94. uint64_t state = 0
  95. | BGFX_STATE_WRITE_RGB
  96. | BGFX_STATE_WRITE_A
  97. | BGFX_STATE_MSAA
  98. ;
  99. bgfx::TextureHandle th = m_texture;
  100. bgfx::ProgramHandle program = m_program;
  101. if (NULL != cmd->TextureId)
  102. {
  103. union { ImTextureID ptr; struct { bgfx::TextureHandle handle; uint8_t flags; uint8_t mip; } s; } texture = { cmd->TextureId };
  104. state |= 0 != (IMGUI_FLAGS_ALPHA_BLEND & texture.s.flags)
  105. ? BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA)
  106. : BGFX_STATE_NONE
  107. ;
  108. th = texture.s.handle;
  109. if (0 != texture.s.mip)
  110. {
  111. const float lodEnabled[4] = { float(texture.s.mip), 1.0f, 0.0f, 0.0f };
  112. bgfx::setUniform(u_imageLodEnabled, lodEnabled);
  113. program = m_imageProgram;
  114. }
  115. }
  116. else
  117. {
  118. state |= BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA);
  119. }
  120. const uint16_t xx = uint16_t(bx::max(cmd->ClipRect.x, 0.0f) );
  121. const uint16_t yy = uint16_t(bx::max(cmd->ClipRect.y, 0.0f) );
  122. bgfx::setScissor(xx, yy
  123. , uint16_t(bx::min(cmd->ClipRect.z, 65535.0f)-xx)
  124. , uint16_t(bx::min(cmd->ClipRect.w, 65535.0f)-yy)
  125. );
  126. bgfx::setState(state);
  127. bgfx::setTexture(0, s_tex, th);
  128. bgfx::setVertexBuffer(0, &tvb, 0, numVertices);
  129. bgfx::setIndexBuffer(&tib, offset, cmd->ElemCount);
  130. bgfx::submit(m_viewId, program);
  131. }
  132. offset += cmd->ElemCount;
  133. }
  134. }
  135. }
  136. void create(float _fontSize, bx::AllocatorI* _allocator)
  137. {
  138. m_allocator = _allocator;
  139. if (NULL == _allocator)
  140. {
  141. static bx::DefaultAllocator allocator;
  142. m_allocator = &allocator;
  143. }
  144. m_viewId = 255;
  145. m_lastScroll = 0;
  146. m_last = bx::getHPCounter();
  147. ImGui::SetAllocatorFunctions(memAlloc, memFree, NULL);
  148. m_imgui = ImGui::CreateContext();
  149. ImGuiIO& io = ImGui::GetIO();
  150. io.DisplaySize = ImVec2(1280.0f, 720.0f);
  151. io.DeltaTime = 1.0f / 60.0f;
  152. io.IniFilename = NULL;
  153. setupStyle(true);
  154. #if USE_ENTRY
  155. io.KeyMap[ImGuiKey_Tab] = (int)entry::Key::Tab;
  156. io.KeyMap[ImGuiKey_LeftArrow] = (int)entry::Key::Left;
  157. io.KeyMap[ImGuiKey_RightArrow] = (int)entry::Key::Right;
  158. io.KeyMap[ImGuiKey_UpArrow] = (int)entry::Key::Up;
  159. io.KeyMap[ImGuiKey_DownArrow] = (int)entry::Key::Down;
  160. io.KeyMap[ImGuiKey_PageUp] = (int)entry::Key::PageUp;
  161. io.KeyMap[ImGuiKey_PageDown] = (int)entry::Key::PageDown;
  162. io.KeyMap[ImGuiKey_Home] = (int)entry::Key::Home;
  163. io.KeyMap[ImGuiKey_End] = (int)entry::Key::End;
  164. io.KeyMap[ImGuiKey_Insert] = (int)entry::Key::Insert;
  165. io.KeyMap[ImGuiKey_Delete] = (int)entry::Key::Delete;
  166. io.KeyMap[ImGuiKey_Backspace] = (int)entry::Key::Backspace;
  167. io.KeyMap[ImGuiKey_Space] = (int)entry::Key::Space;
  168. io.KeyMap[ImGuiKey_Enter] = (int)entry::Key::Return;
  169. io.KeyMap[ImGuiKey_Escape] = (int)entry::Key::Esc;
  170. io.KeyMap[ImGuiKey_A] = (int)entry::Key::KeyA;
  171. io.KeyMap[ImGuiKey_C] = (int)entry::Key::KeyC;
  172. io.KeyMap[ImGuiKey_V] = (int)entry::Key::KeyV;
  173. io.KeyMap[ImGuiKey_X] = (int)entry::Key::KeyX;
  174. io.KeyMap[ImGuiKey_Y] = (int)entry::Key::KeyY;
  175. io.KeyMap[ImGuiKey_Z] = (int)entry::Key::KeyZ;
  176. io.ConfigFlags |= 0
  177. | ImGuiConfigFlags_NavEnableGamepad
  178. | ImGuiConfigFlags_NavEnableKeyboard
  179. ;
  180. io.NavInputs[ImGuiNavInput_Activate] = (int)entry::Key::GamepadA;
  181. io.NavInputs[ImGuiNavInput_Cancel] = (int)entry::Key::GamepadB;
  182. // io.NavInputs[ImGuiNavInput_Input] = (int)entry::Key::;
  183. // io.NavInputs[ImGuiNavInput_Menu] = (int)entry::Key::;
  184. io.NavInputs[ImGuiNavInput_DpadLeft] = (int)entry::Key::GamepadLeft;
  185. io.NavInputs[ImGuiNavInput_DpadRight] = (int)entry::Key::GamepadRight;
  186. io.NavInputs[ImGuiNavInput_DpadUp] = (int)entry::Key::GamepadUp;
  187. io.NavInputs[ImGuiNavInput_DpadDown] = (int)entry::Key::GamepadDown;
  188. // io.NavInputs[ImGuiNavInput_LStickLeft] = (int)entry::Key::;
  189. // io.NavInputs[ImGuiNavInput_LStickRight] = (int)entry::Key::;
  190. // io.NavInputs[ImGuiNavInput_LStickUp] = (int)entry::Key::;
  191. // io.NavInputs[ImGuiNavInput_LStickDown] = (int)entry::Key::;
  192. // io.NavInputs[ImGuiNavInput_FocusPrev] = (int)entry::Key::;
  193. // io.NavInputs[ImGuiNavInput_FocusNext] = (int)entry::Key::;
  194. // io.NavInputs[ImGuiNavInput_TweakSlow] = (int)entry::Key::;
  195. // io.NavInputs[ImGuiNavInput_TweakFast] = (int)entry::Key::;
  196. #endif // USE_ENTRY
  197. bgfx::RendererType::Enum type = bgfx::getRendererType();
  198. m_program = bgfx::createProgram(
  199. bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_ocornut_imgui")
  200. , bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_ocornut_imgui")
  201. , true
  202. );
  203. u_imageLodEnabled = bgfx::createUniform("u_imageLodEnabled", bgfx::UniformType::Vec4);
  204. m_imageProgram = bgfx::createProgram(
  205. bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_imgui_image")
  206. , bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_imgui_image")
  207. , true
  208. );
  209. m_layout
  210. .begin()
  211. .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
  212. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  213. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  214. .end();
  215. s_tex = bgfx::createUniform("s_tex", bgfx::UniformType::Sampler);
  216. uint8_t* data;
  217. int32_t width;
  218. int32_t height;
  219. {
  220. ImFontConfig config;
  221. config.FontDataOwnedByAtlas = false;
  222. config.MergeMode = false;
  223. // config.MergeGlyphCenterV = true;
  224. const ImWchar* ranges = io.Fonts->GetGlyphRangesCyrillic();
  225. m_font[ImGui::Font::Regular] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoRegularTtf, sizeof(s_robotoRegularTtf), _fontSize, &config, ranges);
  226. m_font[ImGui::Font::Mono ] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoMonoRegularTtf, sizeof(s_robotoMonoRegularTtf), _fontSize-3.0f, &config, ranges);
  227. config.MergeMode = true;
  228. config.DstFont = m_font[ImGui::Font::Regular];
  229. for (uint32_t ii = 0; ii < BX_COUNTOF(s_fontRangeMerge); ++ii)
  230. {
  231. const FontRangeMerge& frm = s_fontRangeMerge[ii];
  232. io.Fonts->AddFontFromMemoryTTF( (void*)frm.data
  233. , (int)frm.size
  234. , _fontSize-3.0f
  235. , &config
  236. , frm.ranges
  237. );
  238. }
  239. }
  240. io.Fonts->GetTexDataAsRGBA32(&data, &width, &height);
  241. m_texture = bgfx::createTexture2D(
  242. (uint16_t)width
  243. , (uint16_t)height
  244. , false
  245. , 1
  246. , bgfx::TextureFormat::BGRA8
  247. , 0
  248. , bgfx::copy(data, width*height*4)
  249. );
  250. ImGui::InitDockContext();
  251. }
  252. void destroy()
  253. {
  254. ImGui::ShutdownDockContext();
  255. ImGui::DestroyContext(m_imgui);
  256. bgfx::destroy(s_tex);
  257. bgfx::destroy(m_texture);
  258. bgfx::destroy(u_imageLodEnabled);
  259. bgfx::destroy(m_imageProgram);
  260. bgfx::destroy(m_program);
  261. m_allocator = NULL;
  262. }
  263. void setupStyle(bool _dark)
  264. {
  265. // Doug Binks' darl color scheme
  266. // https://gist.github.com/dougbinks/8089b4bbaccaaf6fa204236978d165a9
  267. ImGuiStyle& style = ImGui::GetStyle();
  268. if (_dark)
  269. {
  270. ImGui::StyleColorsDark(&style);
  271. }
  272. else
  273. {
  274. ImGui::StyleColorsLight(&style);
  275. }
  276. style.FrameRounding = 4.0f;
  277. style.WindowBorderSize = 0.0f;
  278. }
  279. void beginFrame(
  280. int32_t _mx
  281. , int32_t _my
  282. , uint8_t _button
  283. , int32_t _scroll
  284. , int _width
  285. , int _height
  286. , int _inputChar
  287. , bgfx::ViewId _viewId
  288. )
  289. {
  290. m_viewId = _viewId;
  291. ImGuiIO& io = ImGui::GetIO();
  292. if (_inputChar >= 0)
  293. {
  294. io.AddInputCharacter(_inputChar);
  295. }
  296. io.DisplaySize = ImVec2( (float)_width, (float)_height);
  297. const int64_t now = bx::getHPCounter();
  298. const int64_t frameTime = now - m_last;
  299. m_last = now;
  300. const double freq = double(bx::getHPFrequency() );
  301. io.DeltaTime = float(frameTime/freq);
  302. io.MousePos = ImVec2( (float)_mx, (float)_my);
  303. io.MouseDown[0] = 0 != (_button & IMGUI_MBUT_LEFT);
  304. io.MouseDown[1] = 0 != (_button & IMGUI_MBUT_RIGHT);
  305. io.MouseDown[2] = 0 != (_button & IMGUI_MBUT_MIDDLE);
  306. io.MouseWheel = (float)(_scroll - m_lastScroll);
  307. m_lastScroll = _scroll;
  308. #if USE_ENTRY
  309. uint8_t modifiers = inputGetModifiersState();
  310. io.KeyShift = 0 != (modifiers & (entry::Modifier::LeftShift | entry::Modifier::RightShift) );
  311. io.KeyCtrl = 0 != (modifiers & (entry::Modifier::LeftCtrl | entry::Modifier::RightCtrl ) );
  312. io.KeyAlt = 0 != (modifiers & (entry::Modifier::LeftAlt | entry::Modifier::RightAlt ) );
  313. for (int32_t ii = 0; ii < (int32_t)entry::Key::Count; ++ii)
  314. {
  315. io.KeysDown[ii] = inputGetKeyState(entry::Key::Enum(ii) );
  316. }
  317. #endif // USE_ENTRY
  318. ImGui::NewFrame();
  319. ImGuizmo::BeginFrame();
  320. }
  321. void endFrame()
  322. {
  323. ImGui::Render();
  324. render(ImGui::GetDrawData() );
  325. }
  326. ImGuiContext* m_imgui;
  327. bx::AllocatorI* m_allocator;
  328. bgfx::VertexLayout m_layout;
  329. bgfx::ProgramHandle m_program;
  330. bgfx::ProgramHandle m_imageProgram;
  331. bgfx::TextureHandle m_texture;
  332. bgfx::UniformHandle s_tex;
  333. bgfx::UniformHandle u_imageLodEnabled;
  334. ImFont* m_font[ImGui::Font::Count];
  335. int64_t m_last;
  336. int32_t m_lastScroll;
  337. bgfx::ViewId m_viewId;
  338. };
  339. static OcornutImguiContext s_ctx;
  340. static void* memAlloc(size_t _size, void* _userData)
  341. {
  342. BX_UNUSED(_userData);
  343. return BX_ALLOC(s_ctx.m_allocator, _size);
  344. }
  345. static void memFree(void* _ptr, void* _userData)
  346. {
  347. BX_UNUSED(_userData);
  348. BX_FREE(s_ctx.m_allocator, _ptr);
  349. }
  350. void imguiCreate(float _fontSize, bx::AllocatorI* _allocator)
  351. {
  352. s_ctx.create(_fontSize, _allocator);
  353. }
  354. void imguiDestroy()
  355. {
  356. s_ctx.destroy();
  357. }
  358. void imguiBeginFrame(int32_t _mx, int32_t _my, uint8_t _button, int32_t _scroll, uint16_t _width, uint16_t _height, int _inputChar, bgfx::ViewId _viewId)
  359. {
  360. s_ctx.beginFrame(_mx, _my, _button, _scroll, _width, _height, _inputChar, _viewId);
  361. }
  362. void imguiEndFrame()
  363. {
  364. s_ctx.endFrame();
  365. }
  366. namespace ImGui
  367. {
  368. void PushFont(Font::Enum _font)
  369. {
  370. PushFont(s_ctx.m_font[_font]);
  371. }
  372. } // namespace ImGui
  373. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4505); // error C4505: '' : unreferenced local function has been removed
  374. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-function"); // warning: 'int rect_width_compare(const void*, const void*)' defined but not used
  375. BX_PRAGMA_DIAGNOSTIC_PUSH();
  376. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG("-Wunknown-pragmas")
  377. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wtype-limits"); // warning: comparison is always true due to limited range of data type
  378. #define STBTT_malloc(_size, _userData) memAlloc(_size, _userData)
  379. #define STBTT_free(_ptr, _userData) memFree(_ptr, _userData)
  380. #define STB_RECT_PACK_IMPLEMENTATION
  381. #include <stb/stb_rect_pack.h>
  382. #define STB_TRUETYPE_IMPLEMENTATION
  383. #include <stb/stb_truetype.h>
  384. BX_PRAGMA_DIAGNOSTIC_POP();