rlImGui.cpp 26 KB

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