rlImGui.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. /**********************************************************************************************
  2. *
  3. * raylibExtras * Utilities and Shared Components for Raylib
  4. *
  5. * rlImGui * basic ImGui integration
  6. *
  7. * LICENSE: ZLIB
  8. *
  9. * Copyright (c) 2024 Jeffery Myers
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in all
  19. * copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  27. * SOFTWARE.
  28. *
  29. **********************************************************************************************/
  30. #include "rlImGui.h"
  31. #include "imgui_impl_raylib.h"
  32. #include "raylib.h"
  33. #include "rlgl.h"
  34. #include "imgui.h"
  35. #include <math.h>
  36. #include <map>
  37. #include <limits>
  38. #include <cstdint>
  39. #ifndef NO_FONT_AWESOME
  40. #include "extras/FA6FreeSolidFontData.h"
  41. #endif
  42. static ImGuiMouseCursor CurrentMouseCursor = ImGuiMouseCursor_COUNT;
  43. static MouseCursor MouseCursorMap[ImGuiMouseCursor_COUNT];
  44. ImGuiContext* GlobalContext = nullptr;
  45. static std::map<KeyboardKey, ImGuiKey> RaylibKeyMap;
  46. static bool LastFrameFocused = false;
  47. static bool LastControlPressed = false;
  48. static bool LastShiftPressed = false;
  49. static bool LastAltPressed = false;
  50. static bool LastSuperPressed = false;
  51. // internal only functions
  52. bool rlImGuiIsControlDown() { return IsKeyDown(KEY_RIGHT_CONTROL) || IsKeyDown(KEY_LEFT_CONTROL); }
  53. bool rlImGuiIsShiftDown() { return IsKeyDown(KEY_RIGHT_SHIFT) || IsKeyDown(KEY_LEFT_SHIFT); }
  54. bool rlImGuiIsAltDown() { return IsKeyDown(KEY_RIGHT_ALT) || IsKeyDown(KEY_LEFT_ALT); }
  55. bool rlImGuiIsSuperDown() { return IsKeyDown(KEY_RIGHT_SUPER) || IsKeyDown(KEY_LEFT_SUPER); }
  56. struct ImGui_ImplRaylib_Data
  57. {
  58. };
  59. ImGui_ImplRaylib_Data* ImGui_ImplRaylib_GetBackendData()
  60. {
  61. return ImGui::GetCurrentContext() ? static_cast<ImGui_ImplRaylib_Data*>(ImGui::GetPlatformIO().Renderer_RenderState) : nullptr;
  62. }
  63. void ImGui_ImplRaylib_CreateBackendData()
  64. {
  65. if (!ImGui::GetCurrentContext() || ImGui::GetPlatformIO().Renderer_RenderState)
  66. return;
  67. ImGui::GetPlatformIO().Renderer_RenderState = MemAlloc(sizeof(ImGui_ImplRaylib_Data));
  68. }
  69. void ImGui_ImplRaylib_FreeBackendData()
  70. {
  71. if (!ImGui::GetCurrentContext())
  72. return;
  73. MemFree(ImGui::GetPlatformIO().Renderer_RenderState);
  74. }
  75. Vector2 GetDisplayScale()
  76. {
  77. #if defined(__EMSCRIPTEN__)
  78. return Vector2Ones;
  79. #else
  80. return GetWindowScaleDPI();
  81. #endif
  82. }
  83. static const char* GetClipTextCallback(ImGuiContext*)
  84. {
  85. return GetClipboardText();
  86. }
  87. static void SetClipTextCallback(ImGuiContext*, const char* text)
  88. {
  89. SetClipboardText(text);
  90. }
  91. static void ImGuiNewFrame(float deltaTime)
  92. {
  93. ImGuiIO& io = ImGui::GetIO();
  94. auto* platData = ImGui_ImplRaylib_GetBackendData();
  95. if (!platData)
  96. {
  97. ImGui_ImplRaylib_CreateBackendData();
  98. platData = ImGui_ImplRaylib_GetBackendData();
  99. if (!platData)
  100. return;
  101. }
  102. Vector2 resolutionScale = GetDisplayScale();
  103. #ifndef PLATFORM_DRM
  104. if (IsWindowFullscreen())
  105. {
  106. int monitor = GetCurrentMonitor();
  107. io.DisplaySize.x = float(GetMonitorWidth(monitor));
  108. io.DisplaySize.y = float(GetMonitorHeight(monitor));
  109. }
  110. else
  111. {
  112. io.DisplaySize.x = float(GetScreenWidth());
  113. io.DisplaySize.y = float(GetScreenHeight());
  114. }
  115. #if !defined(__APPLE__)
  116. if (!IsWindowState(FLAG_WINDOW_HIGHDPI))
  117. resolutionScale = Vector2{ 1,1 };
  118. #endif
  119. #else
  120. io.DisplaySize.x = float(GetScreenWidth());
  121. io.DisplaySize.y = float(GetScreenHeight());
  122. #endif
  123. io.DisplayFramebufferScale = ImVec2(resolutionScale.x, resolutionScale.y);
  124. if (deltaTime <= 0)
  125. deltaTime = 0.001f;
  126. io.DeltaTime = deltaTime;
  127. if (ImGui::GetIO().BackendFlags & ImGuiBackendFlags_HasMouseCursors)
  128. {
  129. if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) == 0)
  130. {
  131. ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
  132. if (imgui_cursor != CurrentMouseCursor || io.MouseDrawCursor)
  133. {
  134. CurrentMouseCursor = imgui_cursor;
  135. if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
  136. {
  137. HideCursor();
  138. }
  139. else
  140. {
  141. ShowCursor();
  142. if (!(io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange))
  143. {
  144. SetMouseCursor((imgui_cursor > -1 && imgui_cursor < ImGuiMouseCursor_COUNT) ? MouseCursorMap[imgui_cursor] : MOUSE_CURSOR_DEFAULT);
  145. }
  146. }
  147. }
  148. }
  149. }
  150. }
  151. static void ImGuiTriangleVert(const ImDrawVert& idx_vert)
  152. {
  153. #ifdef __cpp_designated_initializers
  154. Color c {
  155. .r = static_cast<unsigned char>(idx_vert.col>>0),
  156. .g = static_cast<unsigned char>(idx_vert.col>>8),
  157. .b = static_cast<unsigned char>(idx_vert.col>>16),
  158. .a = static_cast<unsigned char>(idx_vert.col>>24),
  159. };
  160. #else
  161. Color c {
  162. static_cast<unsigned char>(idx_vert.col>>0),
  163. static_cast<unsigned char>(idx_vert.col>>8),
  164. static_cast<unsigned char>(idx_vert.col>>16),
  165. static_cast<unsigned char>(idx_vert.col>>24),
  166. };
  167. #endif
  168. rlColor4ub(c.r, c.g, c.b, c.a);
  169. rlTexCoord2f(idx_vert.uv.x, idx_vert.uv.y);
  170. rlVertex2f(idx_vert.pos.x, idx_vert.pos.y);
  171. }
  172. static void ImGuiRenderTriangles(unsigned int count, int indexStart, const ImVector<ImDrawIdx>& indexBuffer, const ImVector<ImDrawVert>& vertBuffer, ImTextureID texturePtr)
  173. {
  174. if (count < 3)
  175. return;
  176. unsigned int textureId = static_cast<unsigned int>(texturePtr);
  177. rlBegin(RL_TRIANGLES);
  178. rlSetTexture(textureId);
  179. for (unsigned int i = 0; i <= (count - 3); i += 3)
  180. {
  181. ImDrawIdx indexA = indexBuffer[indexStart + i];
  182. ImDrawIdx indexB = indexBuffer[indexStart + i + 1];
  183. ImDrawIdx indexC = indexBuffer[indexStart + i + 2];
  184. ImDrawVert vertexA = vertBuffer[indexA];
  185. ImDrawVert vertexB = vertBuffer[indexB];
  186. ImDrawVert vertexC = vertBuffer[indexC];
  187. ImGuiTriangleVert(vertexA);
  188. ImGuiTriangleVert(vertexB);
  189. ImGuiTriangleVert(vertexC);
  190. }
  191. rlEnd();
  192. }
  193. static void EnableScissor(float x, float y, float width, float height)
  194. {
  195. rlEnableScissorTest();
  196. ImGuiIO& io = ImGui::GetIO();
  197. ImVec2 scale = io.DisplayFramebufferScale;
  198. #if !defined(__APPLE__)
  199. if (!IsWindowState(FLAG_WINDOW_HIGHDPI))
  200. {
  201. scale.x = 1;
  202. scale.y = 1;
  203. }
  204. #endif
  205. rlScissor((int)(x * scale.x),
  206. int((io.DisplaySize.y - (int)(y + height)) * scale.y),
  207. (int)(width * scale.x),
  208. (int)(height * scale.y));
  209. }
  210. static void SetupMouseCursors(void)
  211. {
  212. MouseCursorMap[ImGuiMouseCursor_Arrow] = MOUSE_CURSOR_ARROW;
  213. MouseCursorMap[ImGuiMouseCursor_TextInput] = MOUSE_CURSOR_IBEAM;
  214. MouseCursorMap[ImGuiMouseCursor_Hand] = MOUSE_CURSOR_POINTING_HAND;
  215. MouseCursorMap[ImGuiMouseCursor_ResizeAll] = MOUSE_CURSOR_RESIZE_ALL;
  216. MouseCursorMap[ImGuiMouseCursor_ResizeEW] = MOUSE_CURSOR_RESIZE_EW;
  217. MouseCursorMap[ImGuiMouseCursor_ResizeNESW] = MOUSE_CURSOR_RESIZE_NESW;
  218. MouseCursorMap[ImGuiMouseCursor_ResizeNS] = MOUSE_CURSOR_RESIZE_NS;
  219. MouseCursorMap[ImGuiMouseCursor_ResizeNWSE] = MOUSE_CURSOR_RESIZE_NWSE;
  220. MouseCursorMap[ImGuiMouseCursor_NotAllowed] = MOUSE_CURSOR_NOT_ALLOWED;
  221. }
  222. void SetupFontAwesome(void)
  223. {
  224. #ifndef NO_FONT_AWESOME
  225. static const ImWchar icons_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
  226. ImFontConfig icons_config;
  227. icons_config.MergeMode = true;
  228. icons_config.PixelSnapH = true;
  229. icons_config.FontDataOwnedByAtlas = false;
  230. icons_config.GlyphMaxAdvanceX = std::numeric_limits<float>::max();
  231. icons_config.RasterizerMultiply = 1.0f;
  232. icons_config.OversampleH = 2;
  233. icons_config.OversampleV = 1;
  234. icons_config.GlyphRanges = icons_ranges;
  235. ImGuiIO& io = ImGui::GetIO();
  236. float size = FONT_AWESOME_ICON_SIZE;
  237. #if !defined(__APPLE__)
  238. if (!IsWindowState(FLAG_WINDOW_HIGHDPI))
  239. size *= GetDisplayScale().y;
  240. icons_config.RasterizerMultiply = GetDisplayScale().y;
  241. #endif
  242. io.Fonts->AddFontFromMemoryCompressedTTF((void*)fa_solid_900_compressed_data, fa_solid_900_compressed_size, size, &icons_config, icons_ranges);
  243. #endif
  244. }
  245. void SetupBackend(void)
  246. {
  247. ImGuiIO& io = ImGui::GetIO();
  248. io.BackendPlatformName = "imgui_impl_raylib";
  249. io.BackendFlags |= ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_RendererHasTextures;
  250. #ifndef PLATFORM_DRM
  251. io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;
  252. #endif
  253. io.MousePos = ImVec2(0, 0);
  254. ImGuiPlatformIO& platformIO = ImGui::GetPlatformIO();
  255. platformIO.Platform_SetClipboardTextFn = SetClipTextCallback;
  256. platformIO.Platform_GetClipboardTextFn = GetClipTextCallback;
  257. platformIO.Platform_ClipboardUserData = nullptr;
  258. ImGui_ImplRaylib_CreateBackendData();
  259. }
  260. void rlImGuiEndInitImGui(void)
  261. {
  262. ImGui::SetCurrentContext(GlobalContext);
  263. SetupFontAwesome();
  264. SetupMouseCursors();
  265. SetupBackend();
  266. }
  267. static void SetupKeymap(void)
  268. {
  269. if (!RaylibKeyMap.empty())
  270. return;
  271. // build up a map of raylib keys to ImGuiKeys
  272. RaylibKeyMap[KEY_APOSTROPHE] = ImGuiKey_Apostrophe;
  273. RaylibKeyMap[KEY_COMMA] = ImGuiKey_Comma;
  274. RaylibKeyMap[KEY_MINUS] = ImGuiKey_Minus;
  275. RaylibKeyMap[KEY_PERIOD] = ImGuiKey_Period;
  276. RaylibKeyMap[KEY_SLASH] = ImGuiKey_Slash;
  277. RaylibKeyMap[KEY_ZERO] = ImGuiKey_0;
  278. RaylibKeyMap[KEY_ONE] = ImGuiKey_1;
  279. RaylibKeyMap[KEY_TWO] = ImGuiKey_2;
  280. RaylibKeyMap[KEY_THREE] = ImGuiKey_3;
  281. RaylibKeyMap[KEY_FOUR] = ImGuiKey_4;
  282. RaylibKeyMap[KEY_FIVE] = ImGuiKey_5;
  283. RaylibKeyMap[KEY_SIX] = ImGuiKey_6;
  284. RaylibKeyMap[KEY_SEVEN] = ImGuiKey_7;
  285. RaylibKeyMap[KEY_EIGHT] = ImGuiKey_8;
  286. RaylibKeyMap[KEY_NINE] = ImGuiKey_9;
  287. RaylibKeyMap[KEY_SEMICOLON] = ImGuiKey_Semicolon;
  288. RaylibKeyMap[KEY_EQUAL] = ImGuiKey_Equal;
  289. RaylibKeyMap[KEY_A] = ImGuiKey_A;
  290. RaylibKeyMap[KEY_B] = ImGuiKey_B;
  291. RaylibKeyMap[KEY_C] = ImGuiKey_C;
  292. RaylibKeyMap[KEY_D] = ImGuiKey_D;
  293. RaylibKeyMap[KEY_E] = ImGuiKey_E;
  294. RaylibKeyMap[KEY_F] = ImGuiKey_F;
  295. RaylibKeyMap[KEY_G] = ImGuiKey_G;
  296. RaylibKeyMap[KEY_H] = ImGuiKey_H;
  297. RaylibKeyMap[KEY_I] = ImGuiKey_I;
  298. RaylibKeyMap[KEY_J] = ImGuiKey_J;
  299. RaylibKeyMap[KEY_K] = ImGuiKey_K;
  300. RaylibKeyMap[KEY_L] = ImGuiKey_L;
  301. RaylibKeyMap[KEY_M] = ImGuiKey_M;
  302. RaylibKeyMap[KEY_N] = ImGuiKey_N;
  303. RaylibKeyMap[KEY_O] = ImGuiKey_O;
  304. RaylibKeyMap[KEY_P] = ImGuiKey_P;
  305. RaylibKeyMap[KEY_Q] = ImGuiKey_Q;
  306. RaylibKeyMap[KEY_R] = ImGuiKey_R;
  307. RaylibKeyMap[KEY_S] = ImGuiKey_S;
  308. RaylibKeyMap[KEY_T] = ImGuiKey_T;
  309. RaylibKeyMap[KEY_U] = ImGuiKey_U;
  310. RaylibKeyMap[KEY_V] = ImGuiKey_V;
  311. RaylibKeyMap[KEY_W] = ImGuiKey_W;
  312. RaylibKeyMap[KEY_X] = ImGuiKey_X;
  313. RaylibKeyMap[KEY_Y] = ImGuiKey_Y;
  314. RaylibKeyMap[KEY_Z] = ImGuiKey_Z;
  315. RaylibKeyMap[KEY_SPACE] = ImGuiKey_Space;
  316. RaylibKeyMap[KEY_ESCAPE] = ImGuiKey_Escape;
  317. RaylibKeyMap[KEY_ENTER] = ImGuiKey_Enter;
  318. RaylibKeyMap[KEY_TAB] = ImGuiKey_Tab;
  319. RaylibKeyMap[KEY_BACKSPACE] = ImGuiKey_Backspace;
  320. RaylibKeyMap[KEY_INSERT] = ImGuiKey_Insert;
  321. RaylibKeyMap[KEY_DELETE] = ImGuiKey_Delete;
  322. RaylibKeyMap[KEY_RIGHT] = ImGuiKey_RightArrow;
  323. RaylibKeyMap[KEY_LEFT] = ImGuiKey_LeftArrow;
  324. RaylibKeyMap[KEY_DOWN] = ImGuiKey_DownArrow;
  325. RaylibKeyMap[KEY_UP] = ImGuiKey_UpArrow;
  326. RaylibKeyMap[KEY_PAGE_UP] = ImGuiKey_PageUp;
  327. RaylibKeyMap[KEY_PAGE_DOWN] = ImGuiKey_PageDown;
  328. RaylibKeyMap[KEY_HOME] = ImGuiKey_Home;
  329. RaylibKeyMap[KEY_END] = ImGuiKey_End;
  330. RaylibKeyMap[KEY_CAPS_LOCK] = ImGuiKey_CapsLock;
  331. RaylibKeyMap[KEY_SCROLL_LOCK] = ImGuiKey_ScrollLock;
  332. RaylibKeyMap[KEY_NUM_LOCK] = ImGuiKey_NumLock;
  333. RaylibKeyMap[KEY_PRINT_SCREEN] = ImGuiKey_PrintScreen;
  334. RaylibKeyMap[KEY_PAUSE] = ImGuiKey_Pause;
  335. RaylibKeyMap[KEY_F1] = ImGuiKey_F1;
  336. RaylibKeyMap[KEY_F2] = ImGuiKey_F2;
  337. RaylibKeyMap[KEY_F3] = ImGuiKey_F3;
  338. RaylibKeyMap[KEY_F4] = ImGuiKey_F4;
  339. RaylibKeyMap[KEY_F5] = ImGuiKey_F5;
  340. RaylibKeyMap[KEY_F6] = ImGuiKey_F6;
  341. RaylibKeyMap[KEY_F7] = ImGuiKey_F7;
  342. RaylibKeyMap[KEY_F8] = ImGuiKey_F8;
  343. RaylibKeyMap[KEY_F9] = ImGuiKey_F9;
  344. RaylibKeyMap[KEY_F10] = ImGuiKey_F10;
  345. RaylibKeyMap[KEY_F11] = ImGuiKey_F11;
  346. RaylibKeyMap[KEY_F12] = ImGuiKey_F12;
  347. RaylibKeyMap[KEY_LEFT_SHIFT] = ImGuiKey_LeftShift;
  348. RaylibKeyMap[KEY_LEFT_CONTROL] = ImGuiKey_LeftCtrl;
  349. RaylibKeyMap[KEY_LEFT_ALT] = ImGuiKey_LeftAlt;
  350. RaylibKeyMap[KEY_LEFT_SUPER] = ImGuiKey_LeftSuper;
  351. RaylibKeyMap[KEY_RIGHT_SHIFT] = ImGuiKey_RightShift;
  352. RaylibKeyMap[KEY_RIGHT_CONTROL] = ImGuiKey_RightCtrl;
  353. RaylibKeyMap[KEY_RIGHT_ALT] = ImGuiKey_RightAlt;
  354. RaylibKeyMap[KEY_RIGHT_SUPER] = ImGuiKey_RightSuper;
  355. RaylibKeyMap[KEY_KB_MENU] = ImGuiKey_Menu;
  356. RaylibKeyMap[KEY_LEFT_BRACKET] = ImGuiKey_LeftBracket;
  357. RaylibKeyMap[KEY_BACKSLASH] = ImGuiKey_Backslash;
  358. RaylibKeyMap[KEY_RIGHT_BRACKET] = ImGuiKey_RightBracket;
  359. RaylibKeyMap[KEY_GRAVE] = ImGuiKey_GraveAccent;
  360. RaylibKeyMap[KEY_KP_0] = ImGuiKey_Keypad0;
  361. RaylibKeyMap[KEY_KP_1] = ImGuiKey_Keypad1;
  362. RaylibKeyMap[KEY_KP_2] = ImGuiKey_Keypad2;
  363. RaylibKeyMap[KEY_KP_3] = ImGuiKey_Keypad3;
  364. RaylibKeyMap[KEY_KP_4] = ImGuiKey_Keypad4;
  365. RaylibKeyMap[KEY_KP_5] = ImGuiKey_Keypad5;
  366. RaylibKeyMap[KEY_KP_6] = ImGuiKey_Keypad6;
  367. RaylibKeyMap[KEY_KP_7] = ImGuiKey_Keypad7;
  368. RaylibKeyMap[KEY_KP_8] = ImGuiKey_Keypad8;
  369. RaylibKeyMap[KEY_KP_9] = ImGuiKey_Keypad9;
  370. RaylibKeyMap[KEY_KP_DECIMAL] = ImGuiKey_KeypadDecimal;
  371. RaylibKeyMap[KEY_KP_DIVIDE] = ImGuiKey_KeypadDivide;
  372. RaylibKeyMap[KEY_KP_MULTIPLY] = ImGuiKey_KeypadMultiply;
  373. RaylibKeyMap[KEY_KP_SUBTRACT] = ImGuiKey_KeypadSubtract;
  374. RaylibKeyMap[KEY_KP_ADD] = ImGuiKey_KeypadAdd;
  375. RaylibKeyMap[KEY_KP_ENTER] = ImGuiKey_KeypadEnter;
  376. RaylibKeyMap[KEY_KP_EQUAL] = ImGuiKey_KeypadEqual;
  377. }
  378. static void SetupGlobals(void)
  379. {
  380. LastFrameFocused = IsWindowFocused();
  381. LastControlPressed = false;
  382. LastShiftPressed = false;
  383. LastAltPressed = false;
  384. LastSuperPressed = false;
  385. }
  386. void rlImGuiBeginInitImGui(void)
  387. {
  388. SetupGlobals();
  389. if (GlobalContext == nullptr)
  390. GlobalContext = ImGui::CreateContext(nullptr);
  391. SetupKeymap();
  392. ImGuiIO& io = ImGui::GetIO();
  393. ImFontConfig defaultConfig;
  394. static constexpr int DefaultFonSize = 13;
  395. defaultConfig.SizePixels = DefaultFonSize;
  396. #if !defined(__APPLE__)
  397. if (!IsWindowState(FLAG_WINDOW_HIGHDPI))
  398. defaultConfig.SizePixels = ceilf(defaultConfig.SizePixels * GetDisplayScale().y);
  399. defaultConfig.RasterizerMultiply = GetDisplayScale().y;
  400. #endif
  401. defaultConfig.PixelSnapH = true;
  402. io.Fonts->AddFontDefault(&defaultConfig);
  403. }
  404. void rlImGuiSetup(bool dark)
  405. {
  406. rlImGuiBeginInitImGui();
  407. if (dark)
  408. ImGui::StyleColorsDark();
  409. else
  410. ImGui::StyleColorsLight();
  411. rlImGuiEndInitImGui();
  412. }
  413. void rlImGuiBegin(void)
  414. {
  415. ImGui::SetCurrentContext(GlobalContext);
  416. rlImGuiBeginDelta(GetFrameTime());
  417. }
  418. void rlImGuiBeginDelta(float deltaTime)
  419. {
  420. ImGui::SetCurrentContext(GlobalContext);
  421. ImGuiNewFrame(deltaTime);
  422. ImGui_ImplRaylib_ProcessEvents();
  423. ImGui::NewFrame();
  424. }
  425. void rlImGuiEnd(void)
  426. {
  427. ImGui::SetCurrentContext(GlobalContext);
  428. ImGui::Render();
  429. ImGui_ImplRaylib_RenderDrawData(ImGui::GetDrawData());
  430. }
  431. void rlImGuiShutdown(void)
  432. {
  433. if (GlobalContext == nullptr)
  434. return;
  435. ImGui::SetCurrentContext(GlobalContext);
  436. ImGui_ImplRaylib_Shutdown();
  437. ImGui::DestroyContext(GlobalContext);
  438. GlobalContext = nullptr;
  439. }
  440. void rlImGuiImage(const Texture* image)
  441. {
  442. if (!image)
  443. return;
  444. if (GlobalContext)
  445. ImGui::SetCurrentContext(GlobalContext);
  446. ImGui::Image(ImTextureID(image->id), ImVec2(float(image->width), float(image->height)));
  447. }
  448. bool rlImGuiImageButton(const char* name, const Texture* image)
  449. {
  450. if (!image)
  451. return false;
  452. if (GlobalContext)
  453. ImGui::SetCurrentContext(GlobalContext);
  454. return ImGui::ImageButton(name, ImTextureID(image->id), ImVec2(float(image->width), float(image->height)));
  455. }
  456. bool rlImGuiImageButtonSize(const char* name, const Texture* image, Vector2 size)
  457. {
  458. if (!image)
  459. return false;
  460. if (GlobalContext)
  461. ImGui::SetCurrentContext(GlobalContext);
  462. return ImGui::ImageButton(name, ImTextureID(image->id), ImVec2(size.x, size.y));
  463. }
  464. void rlImGuiImageSize(const Texture* image, int width, int height)
  465. {
  466. if (!image)
  467. return;
  468. if (GlobalContext)
  469. ImGui::SetCurrentContext(GlobalContext);
  470. ImGui::Image(ImTextureID(image->id), ImVec2(float(width), float(height)));
  471. }
  472. void rlImGuiImageSizeV(const Texture* image, Vector2 size)
  473. {
  474. if (!image)
  475. return;
  476. if (GlobalContext)
  477. ImGui::SetCurrentContext(GlobalContext);
  478. ImGui::Image(ImTextureID(image->id), ImVec2(size.x, size.y));
  479. }
  480. void rlImGuiImageRect(const Texture* image, int destWidth, int destHeight, Rectangle sourceRect)
  481. {
  482. if (!image)
  483. return;
  484. if (GlobalContext)
  485. ImGui::SetCurrentContext(GlobalContext);
  486. ImVec2 uv0;
  487. ImVec2 uv1;
  488. if (sourceRect.width < 0)
  489. {
  490. uv0.x = -sourceRect.x / image->width;
  491. uv1.x = (uv0.x - float(fabs(sourceRect.width) / image->width));
  492. }
  493. else
  494. {
  495. uv0.x = sourceRect.x / image->width;
  496. uv1.x = uv0.x + float(sourceRect.width / image->width);
  497. }
  498. if (sourceRect.height < 0)
  499. {
  500. uv0.y = -sourceRect.y / image->height;
  501. uv1.y = (uv0.y - fabsf(sourceRect.height) / image->height);
  502. }
  503. else
  504. {
  505. uv0.y = sourceRect.y / image->height;
  506. uv1.y = uv0.y + sourceRect.height / image->height;
  507. }
  508. ImGui::Image((ImTextureID)image->id, ImVec2(float(destWidth), float(destHeight)), uv0, uv1);
  509. }
  510. void rlImGuiImageRenderTexture(const RenderTexture* image)
  511. {
  512. if (!image)
  513. return;
  514. if (GlobalContext)
  515. ImGui::SetCurrentContext(GlobalContext);
  516. rlImGuiImageRect(&image->texture, image->texture.width, image->texture.height, Rectangle{ 0,0, float(image->texture.width), -float(image->texture.height) });
  517. }
  518. void rlImGuiImageRenderTextureFit(const RenderTexture* image, bool center)
  519. {
  520. if (!image)
  521. return;
  522. if (GlobalContext)
  523. ImGui::SetCurrentContext(GlobalContext);
  524. ImVec2 area = ImGui::GetContentRegionAvail();
  525. float scale = area.x / image->texture.width;
  526. float y = image->texture.height * scale;
  527. if (y > area.y)
  528. {
  529. scale = area.y / image->texture.height;
  530. }
  531. int sizeX = int(image->texture.width * scale);
  532. int sizeY = int(image->texture.height * scale);
  533. if (center)
  534. {
  535. ImGui::SetCursorPosX(0);
  536. ImGui::SetCursorPosX(area.x/2 - sizeX/2);
  537. ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (area.y / 2 - sizeY / 2));
  538. }
  539. rlImGuiImageRect(&image->texture, sizeX, sizeY, Rectangle{ 0,0, float(image->texture.width), -float(image->texture.height) });
  540. }
  541. // raw ImGui backend API
  542. bool ImGui_ImplRaylib_Init(void)
  543. {
  544. SetupGlobals();
  545. SetupKeymap();
  546. SetupMouseCursors();
  547. SetupBackend();
  548. return true;
  549. }
  550. void ImGui_ImplRaylib_Shutdown()
  551. {
  552. ImGuiIO& io =ImGui::GetIO();
  553. for (auto& texture : ImGui::GetPlatformIO().Textures)
  554. {
  555. if (texture->Status != ImTextureStatus_Destroyed)
  556. {
  557. Texture* backendData = (Texture*)texture->BackendUserData;
  558. if (backendData && IsTextureValid(*backendData))
  559. {
  560. UnloadTexture(*backendData);
  561. }
  562. texture->Status = ImTextureStatus_Destroyed;
  563. }
  564. }
  565. ImGui_ImplRaylib_FreeBackendData();
  566. }
  567. void ImGui_ImplRaylib_NewFrame(void)
  568. {
  569. ImGuiNewFrame(GetFrameTime());
  570. }
  571. void ImGui_ImplRaylib_UpdateTexture(ImTextureData* tex)
  572. {
  573. switch (tex->Status)
  574. {
  575. case ImTextureStatus_OK:
  576. case ImTextureStatus_Destroyed:
  577. default:
  578. break;
  579. case ImTextureStatus_WantCreate:
  580. {
  581. Image img = { 0 };
  582. img.width = tex->Width;
  583. img.height = tex->Height;
  584. img.format = tex->Format == ImTextureFormat_Alpha8 ? PIXELFORMAT_UNCOMPRESSED_GRAYSCALE : PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
  585. img.mipmaps = 1;
  586. img.data = tex->GetPixels();
  587. Texture* texture = (Texture*)MemAlloc(sizeof(Texture));
  588. tex->BackendUserData = texture;;
  589. *texture = LoadTextureFromImage(img);
  590. tex->SetTexID(ImTextureID(texture->id));
  591. tex->Status = ImTextureStatus_OK;
  592. }
  593. break;
  594. case ImTextureStatus_WantUpdates:
  595. {
  596. Texture* texture = (Texture*)tex->BackendUserData;
  597. if (!texture)
  598. break;
  599. UpdateTexture(*texture, tex->GetPixels());
  600. tex->Status = ImTextureStatus_OK;
  601. }
  602. break;
  603. case ImTextureStatus_WantDestroy:
  604. {
  605. Texture* texture = (Texture*)tex->BackendUserData;
  606. if (!texture)
  607. break;
  608. UnloadTexture(*texture);
  609. tex->Status = ImTextureStatus_Destroyed;
  610. }
  611. break;
  612. }
  613. }
  614. void ImGui_ImplRaylib_RenderDrawData(ImDrawData* draw_data)
  615. {
  616. if (draw_data->Textures != nullptr)
  617. {
  618. for (ImTextureData* tex : *draw_data->Textures)
  619. {
  620. if (tex->Status != ImTextureStatus_OK)
  621. ImGui_ImplRaylib_UpdateTexture(tex);
  622. }
  623. }
  624. rlDrawRenderBatchActive();
  625. rlDisableBackfaceCulling();
  626. for (int l = 0; l < draw_data->CmdListsCount; ++l)
  627. {
  628. const ImDrawList* commandList = draw_data->CmdLists[l];
  629. for (const auto& cmd : commandList->CmdBuffer)
  630. {
  631. EnableScissor(cmd.ClipRect.x - draw_data->DisplayPos.x, cmd.ClipRect.y - draw_data->DisplayPos.y, cmd.ClipRect.z - (cmd.ClipRect.x - draw_data->DisplayPos.x), cmd.ClipRect.w - (cmd.ClipRect.y - draw_data->DisplayPos.y));
  632. if (cmd.UserCallback != nullptr)
  633. {
  634. cmd.UserCallback(commandList, &cmd);
  635. continue;
  636. }
  637. ImGuiRenderTriangles(cmd.ElemCount, cmd.IdxOffset, commandList->IdxBuffer, commandList->VtxBuffer, cmd.GetTexID());
  638. rlDrawRenderBatchActive();
  639. }
  640. }
  641. rlSetTexture(0);
  642. rlDisableScissorTest();
  643. rlEnableBackfaceCulling();
  644. }
  645. void HandleGamepadButtonEvent(ImGuiIO& io, GamepadButton button, ImGuiKey key)
  646. {
  647. if (IsGamepadButtonPressed(0, button))
  648. io.AddKeyEvent(key, true);
  649. else if (IsGamepadButtonReleased(0, button))
  650. io.AddKeyEvent(key, false);
  651. }
  652. void HandleGamepadStickEvent(ImGuiIO& io, GamepadAxis axis, ImGuiKey negKey, ImGuiKey posKey)
  653. {
  654. constexpr float deadZone = 0.20f;
  655. float axisValue = GetGamepadAxisMovement(0, axis);
  656. io.AddKeyAnalogEvent(negKey, axisValue < -deadZone, axisValue < -deadZone ? -axisValue : 0);
  657. io.AddKeyAnalogEvent(posKey, axisValue > deadZone, axisValue > deadZone ? axisValue : 0);
  658. }
  659. bool ImGui_ImplRaylib_ProcessEvents(void)
  660. {
  661. ImGuiIO& io = ImGui::GetIO();
  662. bool focused = IsWindowFocused();
  663. if (focused != LastFrameFocused)
  664. io.AddFocusEvent(focused);
  665. LastFrameFocused = focused;
  666. // handle the modifyer key events so that shortcuts work
  667. bool ctrlDown = rlImGuiIsControlDown();
  668. if (ctrlDown != LastControlPressed)
  669. io.AddKeyEvent(ImGuiMod_Ctrl, ctrlDown);
  670. LastControlPressed = ctrlDown;
  671. bool shiftDown = rlImGuiIsShiftDown();
  672. if (shiftDown != LastShiftPressed)
  673. io.AddKeyEvent(ImGuiMod_Shift, shiftDown);
  674. LastShiftPressed = shiftDown;
  675. bool altDown = rlImGuiIsAltDown();
  676. if (altDown != LastAltPressed)
  677. io.AddKeyEvent(ImGuiMod_Alt, altDown);
  678. LastAltPressed = altDown;
  679. bool superDown = rlImGuiIsSuperDown();
  680. if (superDown != LastSuperPressed)
  681. io.AddKeyEvent(ImGuiMod_Super, superDown);
  682. LastSuperPressed = superDown;
  683. // walk the keymap and check for up and down events
  684. for (const auto keyItr : RaylibKeyMap)
  685. {
  686. if (IsKeyReleased(keyItr.first))
  687. io.AddKeyEvent(keyItr.second, false);
  688. else if(IsKeyPressed(keyItr.first))
  689. io.AddKeyEvent(keyItr.second, true);
  690. }
  691. if (io.WantCaptureKeyboard)
  692. {
  693. // add the text input in order
  694. unsigned int pressed = GetCharPressed();
  695. while (pressed != 0)
  696. {
  697. io.AddInputCharacter(pressed);
  698. pressed = GetCharPressed();
  699. }
  700. }
  701. bool processsMouse = focused;
  702. #if defined(RLIMGUI_ALWAYS_TRACK_MOUSE)
  703. processsMouse = true;
  704. #endif
  705. if (processsMouse)
  706. {
  707. if (!io.WantSetMousePos)
  708. {
  709. io.AddMousePosEvent(float(GetMouseX()), float(GetMouseY()));
  710. }
  711. auto setMouseEvent = [&io](int rayMouse, int imGuiMouse)
  712. {
  713. if (IsMouseButtonPressed(rayMouse))
  714. io.AddMouseButtonEvent(imGuiMouse, true);
  715. else if (IsMouseButtonReleased(rayMouse))
  716. io.AddMouseButtonEvent(imGuiMouse, false);
  717. };
  718. setMouseEvent(MOUSE_BUTTON_LEFT, ImGuiMouseButton_Left);
  719. setMouseEvent(MOUSE_BUTTON_RIGHT, ImGuiMouseButton_Right);
  720. setMouseEvent(MOUSE_BUTTON_MIDDLE, ImGuiMouseButton_Middle);
  721. setMouseEvent(MOUSE_BUTTON_FORWARD, ImGuiMouseButton_Middle + 1);
  722. setMouseEvent(MOUSE_BUTTON_BACK, ImGuiMouseButton_Middle + 2);
  723. {
  724. Vector2 mouseWheel = GetMouseWheelMoveV();
  725. io.AddMouseWheelEvent(mouseWheel.x, mouseWheel.y);
  726. }
  727. }
  728. else
  729. {
  730. io.AddMousePosEvent(std::numeric_limits<float>::min(), std::numeric_limits<float>::min());
  731. }
  732. if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad && IsGamepadAvailable(0))
  733. {
  734. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_FACE_UP, ImGuiKey_GamepadDpadUp);
  735. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_FACE_RIGHT, ImGuiKey_GamepadDpadRight);
  736. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_FACE_DOWN, ImGuiKey_GamepadDpadDown);
  737. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_FACE_LEFT, ImGuiKey_GamepadDpadLeft);
  738. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_FACE_UP, ImGuiKey_GamepadFaceUp);
  739. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, ImGuiKey_GamepadFaceLeft);
  740. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_FACE_DOWN, ImGuiKey_GamepadFaceDown);
  741. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_FACE_LEFT, ImGuiKey_GamepadFaceRight);
  742. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_TRIGGER_1, ImGuiKey_GamepadL1);
  743. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_TRIGGER_2, ImGuiKey_GamepadL2);
  744. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_TRIGGER_1, ImGuiKey_GamepadR1);
  745. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_TRIGGER_2, ImGuiKey_GamepadR2);
  746. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_THUMB, ImGuiKey_GamepadL3);
  747. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_THUMB, ImGuiKey_GamepadR3);
  748. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_MIDDLE_LEFT, ImGuiKey_GamepadStart);
  749. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_MIDDLE_RIGHT, ImGuiKey_GamepadBack);
  750. // left stick
  751. HandleGamepadStickEvent(io, GAMEPAD_AXIS_LEFT_X, ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight);
  752. HandleGamepadStickEvent(io, GAMEPAD_AXIS_LEFT_Y, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
  753. // right stick
  754. HandleGamepadStickEvent(io, GAMEPAD_AXIS_RIGHT_X, ImGuiKey_GamepadRStickLeft, ImGuiKey_GamepadRStickRight);
  755. HandleGamepadStickEvent(io, GAMEPAD_AXIS_RIGHT_Y, ImGuiKey_GamepadRStickUp, ImGuiKey_GamepadRStickDown);
  756. }
  757. return true;
  758. }