imgui.cpp 15 KB

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