imgui.cpp 15 KB

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