rlImGui.cpp 27 KB

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