fasdfsa commited on
Commit
c5602e2
·
1 Parent(s): 347aff8
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. 3rdparty/imgui/backends/imgui_impl_allegro5.cpp +621 -0
  2. 3rdparty/imgui/backends/imgui_impl_allegro5.h +40 -0
  3. 3rdparty/imgui/backends/imgui_impl_android.cpp +309 -0
  4. 3rdparty/imgui/backends/imgui_impl_android.h +38 -0
  5. 3rdparty/imgui/backends/imgui_impl_dx10.cpp +736 -0
  6. 3rdparty/imgui/backends/imgui_impl_dx10.h +33 -0
  7. 3rdparty/imgui/backends/imgui_impl_dx11.cpp +763 -0
  8. 3rdparty/imgui/backends/imgui_impl_dx11.h +46 -0
  9. 3rdparty/imgui/backends/imgui_impl_dx12.cpp +1157 -0
  10. 3rdparty/imgui/backends/imgui_impl_dx12.h +75 -0
  11. 3rdparty/imgui/backends/imgui_impl_dx9.cpp +585 -0
  12. 3rdparty/imgui/backends/imgui_impl_dx9.h +34 -0
  13. 3rdparty/imgui/backends/imgui_impl_glfw.cpp +1453 -0
  14. 3rdparty/imgui/backends/imgui_impl_glfw.h +67 -0
  15. 3rdparty/imgui/backends/imgui_impl_glut.cpp +310 -0
  16. 3rdparty/imgui/backends/imgui_impl_glut.h +48 -0
  17. 3rdparty/imgui/backends/imgui_impl_metal.h +75 -0
  18. 3rdparty/imgui/backends/imgui_impl_metal.mm +751 -0
  19. 3rdparty/imgui/backends/imgui_impl_opengl2.cpp +351 -0
  20. 3rdparty/imgui/backends/imgui_impl_opengl2.h +42 -0
  21. 3rdparty/imgui/backends/imgui_impl_opengl3.cpp +1005 -0
  22. 3rdparty/imgui/backends/imgui_impl_opengl3.h +67 -0
  23. 3rdparty/imgui/backends/imgui_impl_opengl3_loader.h +916 -0
  24. 3rdparty/imgui/backends/imgui_impl_osx.h +57 -0
  25. 3rdparty/imgui/backends/imgui_impl_osx.mm +1157 -0
  26. 3rdparty/imgui/backends/imgui_impl_sdl2.cpp +1206 -0
  27. 3rdparty/imgui/backends/imgui_impl_sdl2.h +50 -0
  28. 3rdparty/imgui/backends/imgui_impl_sdl3.cpp +1155 -0
  29. 3rdparty/imgui/backends/imgui_impl_sdl3.h +51 -0
  30. 3rdparty/imgui/backends/imgui_impl_sdlrenderer2.cpp +277 -0
  31. 3rdparty/imgui/backends/imgui_impl_sdlrenderer2.h +51 -0
  32. 3rdparty/imgui/backends/imgui_impl_sdlrenderer3.cpp +296 -0
  33. 3rdparty/imgui/backends/imgui_impl_sdlrenderer3.h +53 -0
  34. 3rdparty/imgui/backends/imgui_impl_vulkan.cpp +0 -0
  35. 3rdparty/imgui/backends/imgui_impl_vulkan.h +211 -0
  36. 3rdparty/imgui/backends/imgui_impl_wgpu.cpp +860 -0
  37. 3rdparty/imgui/backends/imgui_impl_wgpu.h +69 -0
  38. 3rdparty/imgui/backends/imgui_impl_win32.cpp +1419 -0
  39. 3rdparty/imgui/backends/imgui_impl_win32.h +54 -0
  40. 3rdparty/imgui/backends/vulkan/generate_spv.sh +6 -0
  41. 3rdparty/imgui/backends/vulkan/glsl_shader.frag +14 -0
  42. 3rdparty/imgui/backends/vulkan/glsl_shader.vert +25 -0
  43. 3rdparty/imgui/imconfig.h +142 -0
  44. 3rdparty/imgui/imgui.cpp +0 -0
  45. 3rdparty/imgui/imgui.h +0 -0
  46. 3rdparty/imgui/imgui.vcxproj +162 -0
  47. 3rdparty/imgui/imgui_demo.cpp +0 -0
  48. 3rdparty/imgui/imgui_draw.cpp +0 -0
  49. 3rdparty/imgui/imgui_internal.h +0 -0
  50. 3rdparty/imgui/imgui_tables.cpp +0 -0
3rdparty/imgui/backends/imgui_impl_allegro5.cpp ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer + Platform Backend for Allegro 5
2
+ // (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
7
+ // [X] Platform: Clipboard support (from Allegro 5.1.12).
8
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
9
+ // Missing features or Issues:
10
+ // [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually.
11
+ // [ ] Platform: Missing gamepad support.
12
+ // [ ] Renderer: Multi-viewport support (multiple windows).
13
+
14
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
15
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
16
+ // Learn about Dear ImGui:
17
+ // - FAQ https://dearimgui.com/faq
18
+ // - Getting Started https://dearimgui.com/getting-started
19
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
20
+ // - Introduction, links and more at the top of imgui.cpp
21
+
22
+ // CHANGELOG
23
+ // (minor and older changes stripped away, please see git history for details)
24
+ // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
25
+ // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
26
+ // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
27
+ // 2022-11-30: Renderer: Restoring using al_draw_indexed_prim() when Allegro version is >= 5.2.5.
28
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
29
+ // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
30
+ // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
31
+ // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
32
+ // 2022-01-17: Inputs: always calling io.AddKeyModsEvent() next and before key event (not in NewFrame) to fix input queue with very low framerates.
33
+ // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
34
+ // 2021-12-08: Renderer: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86.
35
+ // 2021-08-17: Calling io.AddFocusEvent() on ALLEGRO_EVENT_DISPLAY_SWITCH_OUT/ALLEGRO_EVENT_DISPLAY_SWITCH_IN events.
36
+ // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
37
+ // 2021-05-19: Renderer: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
38
+ // 2021-02-18: Change blending equation to preserve alpha in output buffer.
39
+ // 2020-08-10: Inputs: Fixed horizontal mouse wheel direction.
40
+ // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
41
+ // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
42
+ // 2019-05-11: Inputs: Don't filter character value from ALLEGRO_EVENT_KEY_CHAR before calling AddInputCharacter().
43
+ // 2019-04-30: Renderer: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
44
+ // 2018-11-30: Platform: Added touchscreen support.
45
+ // 2018-11-30: Misc: Setting up io.BackendPlatformName/io.BackendRendererName so they can be displayed in the About Window.
46
+ // 2018-06-13: Platform: Added clipboard support (from Allegro 5.1.12).
47
+ // 2018-06-13: Renderer: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
48
+ // 2018-06-13: Renderer: Stopped using al_draw_indexed_prim() as it is buggy in Allegro's DX9 backend.
49
+ // 2018-06-13: Renderer: Backup/restore transform and clipping rectangle.
50
+ // 2018-06-11: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
51
+ // 2018-04-18: Misc: Renamed file from imgui_impl_a5.cpp to imgui_impl_allegro5.cpp.
52
+ // 2018-04-18: Misc: Added support for 32-bit vertex indices to avoid conversion at runtime. Added imconfig_allegro5.h to enforce 32-bit indices when included from imgui.h.
53
+ // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplAllegro5_RenderDrawData() in the .h file so you can call it yourself.
54
+ // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
55
+ // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
56
+
57
+ #include "imgui.h"
58
+ #ifndef IMGUI_DISABLE
59
+ #include "imgui_impl_allegro5.h"
60
+ #include <stdint.h> // uint64_t
61
+ #include <cstring> // memcpy
62
+
63
+ // Allegro
64
+ #include <allegro5/allegro.h>
65
+ #include <allegro5/allegro_primitives.h>
66
+ #ifdef _WIN32
67
+ #include <allegro5/allegro_windows.h>
68
+ #endif
69
+ #define ALLEGRO_HAS_CLIPBOARD ((ALLEGRO_VERSION_INT & ~ALLEGRO_UNSTABLE_BIT) >= ((5 << 24) | (1 << 16) | (12 << 8))) // Clipboard only supported from Allegro 5.1.12
70
+ #define ALLEGRO_HAS_DRAW_INDEXED_PRIM ((ALLEGRO_VERSION_INT & ~ALLEGRO_UNSTABLE_BIT) >= ((5 << 24) | (2 << 16) | ( 5 << 8))) // DX9 implementation of al_draw_indexed_prim() got fixed in Allegro 5.2.5
71
+
72
+ // Visual Studio warnings
73
+ #ifdef _MSC_VER
74
+ #pragma warning (disable: 4127) // condition expression is constant
75
+ #endif
76
+
77
+ struct ImDrawVertAllegro
78
+ {
79
+ ImVec2 pos;
80
+ ImVec2 uv;
81
+ ALLEGRO_COLOR col;
82
+ };
83
+
84
+ // FIXME-OPT: Unfortunately Allegro doesn't support 32-bit packed colors so we have to convert them to 4 float as well..
85
+ // FIXME-OPT: Consider inlining al_map_rgba()?
86
+ // see https://github.com/liballeg/allegro5/blob/master/src/pixels.c#L554
87
+ // and https://github.com/liballeg/allegro5/blob/master/include/allegro5/internal/aintern_pixels.h
88
+ #define DRAW_VERT_IMGUI_TO_ALLEGRO(DST, SRC) { (DST)->pos = (SRC)->pos; (DST)->uv = (SRC)->uv; unsigned char* c = (unsigned char*)&(SRC)->col; (DST)->col = al_map_rgba(c[0], c[1], c[2], c[3]); }
89
+
90
+ // Allegro Data
91
+ struct ImGui_ImplAllegro5_Data
92
+ {
93
+ ALLEGRO_DISPLAY* Display;
94
+ ALLEGRO_BITMAP* Texture;
95
+ double Time;
96
+ ALLEGRO_MOUSE_CURSOR* MouseCursorInvisible;
97
+ ALLEGRO_VERTEX_DECL* VertexDecl;
98
+ char* ClipboardTextData;
99
+
100
+ ImVector<ImDrawVertAllegro> BufVertices;
101
+ ImVector<int> BufIndices;
102
+
103
+ ImGui_ImplAllegro5_Data() { memset((void*)this, 0, sizeof(*this)); }
104
+ };
105
+
106
+ // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
107
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
108
+ // FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
109
+ static ImGui_ImplAllegro5_Data* ImGui_ImplAllegro5_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplAllegro5_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; }
110
+
111
+ static void ImGui_ImplAllegro5_SetupRenderState(ImDrawData* draw_data)
112
+ {
113
+ // Setup blending
114
+ al_set_separate_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
115
+
116
+ // Setup orthographic projection matrix
117
+ // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
118
+ {
119
+ float L = draw_data->DisplayPos.x;
120
+ float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
121
+ float T = draw_data->DisplayPos.y;
122
+ float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
123
+ ALLEGRO_TRANSFORM transform;
124
+ al_identity_transform(&transform);
125
+ al_use_transform(&transform);
126
+ al_orthographic_transform(&transform, L, T, 1.0f, R, B, -1.0f);
127
+ al_use_projection_transform(&transform);
128
+ }
129
+ }
130
+
131
+ // Render function.
132
+ void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data)
133
+ {
134
+ // Avoid rendering when minimized
135
+ if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
136
+ return;
137
+
138
+ // Backup Allegro state that will be modified
139
+ ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
140
+ ALLEGRO_TRANSFORM last_transform = *al_get_current_transform();
141
+ ALLEGRO_TRANSFORM last_projection_transform = *al_get_current_projection_transform();
142
+ int last_clip_x, last_clip_y, last_clip_w, last_clip_h;
143
+ al_get_clipping_rectangle(&last_clip_x, &last_clip_y, &last_clip_w, &last_clip_h);
144
+ int last_blender_op, last_blender_src, last_blender_dst;
145
+ al_get_blender(&last_blender_op, &last_blender_src, &last_blender_dst);
146
+
147
+ // Setup desired render state
148
+ ImGui_ImplAllegro5_SetupRenderState(draw_data);
149
+
150
+ // Render command lists
151
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
152
+ {
153
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
154
+
155
+ ImVector<ImDrawVertAllegro>& vertices = bd->BufVertices;
156
+ #if ALLEGRO_HAS_DRAW_INDEXED_PRIM
157
+ vertices.resize(draw_list->VtxBuffer.Size);
158
+ for (int i = 0; i < draw_list->VtxBuffer.Size; i++)
159
+ {
160
+ const ImDrawVert* src_v = &draw_list->VtxBuffer[i];
161
+ ImDrawVertAllegro* dst_v = &vertices[i];
162
+ DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v);
163
+ }
164
+ const int* indices = nullptr;
165
+ if (sizeof(ImDrawIdx) == 2)
166
+ {
167
+ // FIXME-OPT: Allegro doesn't support 16-bit indices.
168
+ // You can '#define ImDrawIdx int' in imconfig.h to request Dear ImGui to output 32-bit indices.
169
+ // Otherwise, we convert them from 16-bit to 32-bit at runtime here, which works perfectly but is a little wasteful.
170
+ bd->BufIndices.resize(draw_list->IdxBuffer.Size);
171
+ for (int i = 0; i < draw_list->IdxBuffer.Size; ++i)
172
+ bd->BufIndices[i] = (int)draw_list->IdxBuffer.Data[i];
173
+ indices = bd->BufIndices.Data;
174
+ }
175
+ else if (sizeof(ImDrawIdx) == 4)
176
+ {
177
+ indices = (const int*)draw_list->IdxBuffer.Data;
178
+ }
179
+ #else
180
+ // Allegro's implementation of al_draw_indexed_prim() for DX9 was broken until 5.2.5. Unindex buffers ourselves while converting vertex format.
181
+ vertices.resize(draw_list->IdxBuffer.Size);
182
+ for (int i = 0; i < draw_list->IdxBuffer.Size; i++)
183
+ {
184
+ const ImDrawVert* src_v = &draw_list->VtxBuffer[draw_list->IdxBuffer[i]];
185
+ ImDrawVertAllegro* dst_v = &vertices[i];
186
+ DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v);
187
+ }
188
+ #endif
189
+
190
+ // Render command lists
191
+ ImVec2 clip_off = draw_data->DisplayPos;
192
+ for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
193
+ {
194
+ const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
195
+ if (pcmd->UserCallback)
196
+ {
197
+ // User callback, registered via ImDrawList::AddCallback()
198
+ // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
199
+ if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
200
+ ImGui_ImplAllegro5_SetupRenderState(draw_data);
201
+ else
202
+ pcmd->UserCallback(draw_list, pcmd);
203
+ }
204
+ else
205
+ {
206
+ // Project scissor/clipping rectangles into framebuffer space
207
+ ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
208
+ ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
209
+ if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
210
+ continue;
211
+
212
+ // Apply scissor/clipping rectangle, Draw
213
+ ALLEGRO_BITMAP* texture = (ALLEGRO_BITMAP*)pcmd->GetTexID();
214
+ al_set_clipping_rectangle(clip_min.x, clip_min.y, clip_max.x - clip_min.x, clip_max.y - clip_min.y);
215
+ #if ALLEGRO_HAS_DRAW_INDEXED_PRIM
216
+ al_draw_indexed_prim(&vertices[0], bd->VertexDecl, texture, &indices[pcmd->IdxOffset], pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST);
217
+ #else
218
+ al_draw_prim(&vertices[0], bd->VertexDecl, texture, pcmd->IdxOffset, pcmd->IdxOffset + pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST);
219
+ #endif
220
+ }
221
+ }
222
+ }
223
+
224
+ // Restore modified Allegro state
225
+ al_set_blender(last_blender_op, last_blender_src, last_blender_dst);
226
+ al_set_clipping_rectangle(last_clip_x, last_clip_y, last_clip_w, last_clip_h);
227
+ al_use_transform(&last_transform);
228
+ al_use_projection_transform(&last_projection_transform);
229
+ }
230
+
231
+ bool ImGui_ImplAllegro5_CreateDeviceObjects()
232
+ {
233
+ // Build texture atlas
234
+ ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
235
+ ImGuiIO& io = ImGui::GetIO();
236
+ unsigned char* pixels;
237
+ int width, height;
238
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
239
+
240
+ // Create texture
241
+ // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
242
+ int flags = al_get_new_bitmap_flags();
243
+ int fmt = al_get_new_bitmap_format();
244
+ al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR);
245
+ al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE);
246
+ ALLEGRO_BITMAP* img = al_create_bitmap(width, height);
247
+ al_set_new_bitmap_flags(flags);
248
+ al_set_new_bitmap_format(fmt);
249
+ if (!img)
250
+ return false;
251
+
252
+ ALLEGRO_LOCKED_REGION* locked_img = al_lock_bitmap(img, al_get_bitmap_format(img), ALLEGRO_LOCK_WRITEONLY);
253
+ if (!locked_img)
254
+ {
255
+ al_destroy_bitmap(img);
256
+ return false;
257
+ }
258
+ memcpy(locked_img->data, pixels, sizeof(int) * width * height);
259
+ al_unlock_bitmap(img);
260
+
261
+ // Convert software texture to hardware texture.
262
+ ALLEGRO_BITMAP* cloned_img = al_clone_bitmap(img);
263
+ al_destroy_bitmap(img);
264
+ if (!cloned_img)
265
+ return false;
266
+
267
+ // Store our identifier
268
+ io.Fonts->SetTexID((ImTextureID)(intptr_t)cloned_img);
269
+ bd->Texture = cloned_img;
270
+
271
+ // Create an invisible mouse cursor
272
+ // Because al_hide_mouse_cursor() seems to mess up with the actual inputs..
273
+ ALLEGRO_BITMAP* mouse_cursor = al_create_bitmap(8, 8);
274
+ bd->MouseCursorInvisible = al_create_mouse_cursor(mouse_cursor, 0, 0);
275
+ al_destroy_bitmap(mouse_cursor);
276
+
277
+ return true;
278
+ }
279
+
280
+ void ImGui_ImplAllegro5_InvalidateDeviceObjects()
281
+ {
282
+ ImGuiIO& io = ImGui::GetIO();
283
+ ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
284
+ if (bd->Texture)
285
+ {
286
+ io.Fonts->SetTexID(0);
287
+ al_destroy_bitmap(bd->Texture);
288
+ bd->Texture = nullptr;
289
+ }
290
+ if (bd->MouseCursorInvisible)
291
+ {
292
+ al_destroy_mouse_cursor(bd->MouseCursorInvisible);
293
+ bd->MouseCursorInvisible = nullptr;
294
+ }
295
+ }
296
+
297
+ #if ALLEGRO_HAS_CLIPBOARD
298
+ static const char* ImGui_ImplAllegro5_GetClipboardText(ImGuiContext*)
299
+ {
300
+ ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
301
+ if (bd->ClipboardTextData)
302
+ al_free(bd->ClipboardTextData);
303
+ bd->ClipboardTextData = al_get_clipboard_text(bd->Display);
304
+ return bd->ClipboardTextData;
305
+ }
306
+
307
+ static void ImGui_ImplAllegro5_SetClipboardText(ImGuiContext*, const char* text)
308
+ {
309
+ ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
310
+ al_set_clipboard_text(bd->Display, text);
311
+ }
312
+ #endif
313
+
314
+ // Not static to allow third-party code to use that if they want to (but undocumented)
315
+ ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code);
316
+ ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code)
317
+ {
318
+ switch (key_code)
319
+ {
320
+ case ALLEGRO_KEY_TAB: return ImGuiKey_Tab;
321
+ case ALLEGRO_KEY_LEFT: return ImGuiKey_LeftArrow;
322
+ case ALLEGRO_KEY_RIGHT: return ImGuiKey_RightArrow;
323
+ case ALLEGRO_KEY_UP: return ImGuiKey_UpArrow;
324
+ case ALLEGRO_KEY_DOWN: return ImGuiKey_DownArrow;
325
+ case ALLEGRO_KEY_PGUP: return ImGuiKey_PageUp;
326
+ case ALLEGRO_KEY_PGDN: return ImGuiKey_PageDown;
327
+ case ALLEGRO_KEY_HOME: return ImGuiKey_Home;
328
+ case ALLEGRO_KEY_END: return ImGuiKey_End;
329
+ case ALLEGRO_KEY_INSERT: return ImGuiKey_Insert;
330
+ case ALLEGRO_KEY_DELETE: return ImGuiKey_Delete;
331
+ case ALLEGRO_KEY_BACKSPACE: return ImGuiKey_Backspace;
332
+ case ALLEGRO_KEY_SPACE: return ImGuiKey_Space;
333
+ case ALLEGRO_KEY_ENTER: return ImGuiKey_Enter;
334
+ case ALLEGRO_KEY_ESCAPE: return ImGuiKey_Escape;
335
+ case ALLEGRO_KEY_QUOTE: return ImGuiKey_Apostrophe;
336
+ case ALLEGRO_KEY_COMMA: return ImGuiKey_Comma;
337
+ case ALLEGRO_KEY_MINUS: return ImGuiKey_Minus;
338
+ case ALLEGRO_KEY_FULLSTOP: return ImGuiKey_Period;
339
+ case ALLEGRO_KEY_SLASH: return ImGuiKey_Slash;
340
+ case ALLEGRO_KEY_SEMICOLON: return ImGuiKey_Semicolon;
341
+ case ALLEGRO_KEY_EQUALS: return ImGuiKey_Equal;
342
+ case ALLEGRO_KEY_OPENBRACE: return ImGuiKey_LeftBracket;
343
+ case ALLEGRO_KEY_BACKSLASH: return ImGuiKey_Backslash;
344
+ case ALLEGRO_KEY_CLOSEBRACE: return ImGuiKey_RightBracket;
345
+ case ALLEGRO_KEY_TILDE: return ImGuiKey_GraveAccent;
346
+ case ALLEGRO_KEY_CAPSLOCK: return ImGuiKey_CapsLock;
347
+ case ALLEGRO_KEY_SCROLLLOCK: return ImGuiKey_ScrollLock;
348
+ case ALLEGRO_KEY_NUMLOCK: return ImGuiKey_NumLock;
349
+ case ALLEGRO_KEY_PRINTSCREEN: return ImGuiKey_PrintScreen;
350
+ case ALLEGRO_KEY_PAUSE: return ImGuiKey_Pause;
351
+ case ALLEGRO_KEY_PAD_0: return ImGuiKey_Keypad0;
352
+ case ALLEGRO_KEY_PAD_1: return ImGuiKey_Keypad1;
353
+ case ALLEGRO_KEY_PAD_2: return ImGuiKey_Keypad2;
354
+ case ALLEGRO_KEY_PAD_3: return ImGuiKey_Keypad3;
355
+ case ALLEGRO_KEY_PAD_4: return ImGuiKey_Keypad4;
356
+ case ALLEGRO_KEY_PAD_5: return ImGuiKey_Keypad5;
357
+ case ALLEGRO_KEY_PAD_6: return ImGuiKey_Keypad6;
358
+ case ALLEGRO_KEY_PAD_7: return ImGuiKey_Keypad7;
359
+ case ALLEGRO_KEY_PAD_8: return ImGuiKey_Keypad8;
360
+ case ALLEGRO_KEY_PAD_9: return ImGuiKey_Keypad9;
361
+ case ALLEGRO_KEY_PAD_DELETE: return ImGuiKey_KeypadDecimal;
362
+ case ALLEGRO_KEY_PAD_SLASH: return ImGuiKey_KeypadDivide;
363
+ case ALLEGRO_KEY_PAD_ASTERISK: return ImGuiKey_KeypadMultiply;
364
+ case ALLEGRO_KEY_PAD_MINUS: return ImGuiKey_KeypadSubtract;
365
+ case ALLEGRO_KEY_PAD_PLUS: return ImGuiKey_KeypadAdd;
366
+ case ALLEGRO_KEY_PAD_ENTER: return ImGuiKey_KeypadEnter;
367
+ case ALLEGRO_KEY_PAD_EQUALS: return ImGuiKey_KeypadEqual;
368
+ case ALLEGRO_KEY_LCTRL: return ImGuiKey_LeftCtrl;
369
+ case ALLEGRO_KEY_LSHIFT: return ImGuiKey_LeftShift;
370
+ case ALLEGRO_KEY_ALT: return ImGuiKey_LeftAlt;
371
+ case ALLEGRO_KEY_LWIN: return ImGuiKey_LeftSuper;
372
+ case ALLEGRO_KEY_RCTRL: return ImGuiKey_RightCtrl;
373
+ case ALLEGRO_KEY_RSHIFT: return ImGuiKey_RightShift;
374
+ case ALLEGRO_KEY_ALTGR: return ImGuiKey_RightAlt;
375
+ case ALLEGRO_KEY_RWIN: return ImGuiKey_RightSuper;
376
+ case ALLEGRO_KEY_MENU: return ImGuiKey_Menu;
377
+ case ALLEGRO_KEY_0: return ImGuiKey_0;
378
+ case ALLEGRO_KEY_1: return ImGuiKey_1;
379
+ case ALLEGRO_KEY_2: return ImGuiKey_2;
380
+ case ALLEGRO_KEY_3: return ImGuiKey_3;
381
+ case ALLEGRO_KEY_4: return ImGuiKey_4;
382
+ case ALLEGRO_KEY_5: return ImGuiKey_5;
383
+ case ALLEGRO_KEY_6: return ImGuiKey_6;
384
+ case ALLEGRO_KEY_7: return ImGuiKey_7;
385
+ case ALLEGRO_KEY_8: return ImGuiKey_8;
386
+ case ALLEGRO_KEY_9: return ImGuiKey_9;
387
+ case ALLEGRO_KEY_A: return ImGuiKey_A;
388
+ case ALLEGRO_KEY_B: return ImGuiKey_B;
389
+ case ALLEGRO_KEY_C: return ImGuiKey_C;
390
+ case ALLEGRO_KEY_D: return ImGuiKey_D;
391
+ case ALLEGRO_KEY_E: return ImGuiKey_E;
392
+ case ALLEGRO_KEY_F: return ImGuiKey_F;
393
+ case ALLEGRO_KEY_G: return ImGuiKey_G;
394
+ case ALLEGRO_KEY_H: return ImGuiKey_H;
395
+ case ALLEGRO_KEY_I: return ImGuiKey_I;
396
+ case ALLEGRO_KEY_J: return ImGuiKey_J;
397
+ case ALLEGRO_KEY_K: return ImGuiKey_K;
398
+ case ALLEGRO_KEY_L: return ImGuiKey_L;
399
+ case ALLEGRO_KEY_M: return ImGuiKey_M;
400
+ case ALLEGRO_KEY_N: return ImGuiKey_N;
401
+ case ALLEGRO_KEY_O: return ImGuiKey_O;
402
+ case ALLEGRO_KEY_P: return ImGuiKey_P;
403
+ case ALLEGRO_KEY_Q: return ImGuiKey_Q;
404
+ case ALLEGRO_KEY_R: return ImGuiKey_R;
405
+ case ALLEGRO_KEY_S: return ImGuiKey_S;
406
+ case ALLEGRO_KEY_T: return ImGuiKey_T;
407
+ case ALLEGRO_KEY_U: return ImGuiKey_U;
408
+ case ALLEGRO_KEY_V: return ImGuiKey_V;
409
+ case ALLEGRO_KEY_W: return ImGuiKey_W;
410
+ case ALLEGRO_KEY_X: return ImGuiKey_X;
411
+ case ALLEGRO_KEY_Y: return ImGuiKey_Y;
412
+ case ALLEGRO_KEY_Z: return ImGuiKey_Z;
413
+ case ALLEGRO_KEY_F1: return ImGuiKey_F1;
414
+ case ALLEGRO_KEY_F2: return ImGuiKey_F2;
415
+ case ALLEGRO_KEY_F3: return ImGuiKey_F3;
416
+ case ALLEGRO_KEY_F4: return ImGuiKey_F4;
417
+ case ALLEGRO_KEY_F5: return ImGuiKey_F5;
418
+ case ALLEGRO_KEY_F6: return ImGuiKey_F6;
419
+ case ALLEGRO_KEY_F7: return ImGuiKey_F7;
420
+ case ALLEGRO_KEY_F8: return ImGuiKey_F8;
421
+ case ALLEGRO_KEY_F9: return ImGuiKey_F9;
422
+ case ALLEGRO_KEY_F10: return ImGuiKey_F10;
423
+ case ALLEGRO_KEY_F11: return ImGuiKey_F11;
424
+ case ALLEGRO_KEY_F12: return ImGuiKey_F12;
425
+ default: return ImGuiKey_None;
426
+ }
427
+ }
428
+
429
+ bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display)
430
+ {
431
+ ImGuiIO& io = ImGui::GetIO();
432
+ IMGUI_CHECKVERSION();
433
+ IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
434
+
435
+ // Setup backend capabilities flags
436
+ ImGui_ImplAllegro5_Data* bd = IM_NEW(ImGui_ImplAllegro5_Data)();
437
+ io.BackendPlatformUserData = (void*)bd;
438
+ io.BackendPlatformName = io.BackendRendererName = "imgui_impl_allegro5";
439
+ io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
440
+
441
+ bd->Display = display;
442
+
443
+ // Create custom vertex declaration.
444
+ // Unfortunately Allegro doesn't support 32-bit packed colors so we have to convert them to 4 floats.
445
+ // We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion.
446
+ ALLEGRO_VERTEX_ELEMENT elems[] =
447
+ {
448
+ { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, pos) },
449
+ { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, uv) },
450
+ { ALLEGRO_PRIM_COLOR_ATTR, 0, offsetof(ImDrawVertAllegro, col) },
451
+ { 0, 0, 0 }
452
+ };
453
+ bd->VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro));
454
+
455
+ #if ALLEGRO_HAS_CLIPBOARD
456
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
457
+ platform_io.Platform_SetClipboardTextFn = ImGui_ImplAllegro5_SetClipboardText;
458
+ platform_io.Platform_GetClipboardTextFn = ImGui_ImplAllegro5_GetClipboardText;
459
+ #endif
460
+
461
+ return true;
462
+ }
463
+
464
+ void ImGui_ImplAllegro5_Shutdown()
465
+ {
466
+ ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
467
+ IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
468
+ ImGuiIO& io = ImGui::GetIO();
469
+
470
+ ImGui_ImplAllegro5_InvalidateDeviceObjects();
471
+ if (bd->VertexDecl)
472
+ al_destroy_vertex_decl(bd->VertexDecl);
473
+ if (bd->ClipboardTextData)
474
+ al_free(bd->ClipboardTextData);
475
+
476
+ io.BackendPlatformName = io.BackendRendererName = nullptr;
477
+ io.BackendPlatformUserData = nullptr;
478
+ io.BackendFlags &= ~ImGuiBackendFlags_HasMouseCursors;
479
+ IM_DELETE(bd);
480
+ }
481
+
482
+ // ev->keyboard.modifiers seems always zero so using that...
483
+ static void ImGui_ImplAllegro5_UpdateKeyModifiers()
484
+ {
485
+ ImGuiIO& io = ImGui::GetIO();
486
+ ALLEGRO_KEYBOARD_STATE keys;
487
+ al_get_keyboard_state(&keys);
488
+ io.AddKeyEvent(ImGuiMod_Ctrl, al_key_down(&keys, ALLEGRO_KEY_LCTRL) || al_key_down(&keys, ALLEGRO_KEY_RCTRL));
489
+ io.AddKeyEvent(ImGuiMod_Shift, al_key_down(&keys, ALLEGRO_KEY_LSHIFT) || al_key_down(&keys, ALLEGRO_KEY_RSHIFT));
490
+ io.AddKeyEvent(ImGuiMod_Alt, al_key_down(&keys, ALLEGRO_KEY_ALT) || al_key_down(&keys, ALLEGRO_KEY_ALTGR));
491
+ io.AddKeyEvent(ImGuiMod_Super, al_key_down(&keys, ALLEGRO_KEY_LWIN) || al_key_down(&keys, ALLEGRO_KEY_RWIN));
492
+ }
493
+
494
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
495
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
496
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
497
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
498
+ bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev)
499
+ {
500
+ ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
501
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?");
502
+ ImGuiIO& io = ImGui::GetIO();
503
+
504
+ switch (ev->type)
505
+ {
506
+ case ALLEGRO_EVENT_MOUSE_AXES:
507
+ if (ev->mouse.display == bd->Display)
508
+ {
509
+ io.AddMousePosEvent(ev->mouse.x, ev->mouse.y);
510
+ io.AddMouseWheelEvent(-ev->mouse.dw, ev->mouse.dz);
511
+ }
512
+ return true;
513
+ case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
514
+ case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
515
+ if (ev->mouse.display == bd->Display && ev->mouse.button > 0 && ev->mouse.button <= 5)
516
+ io.AddMouseButtonEvent(ev->mouse.button - 1, ev->type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN);
517
+ return true;
518
+ case ALLEGRO_EVENT_TOUCH_MOVE:
519
+ if (ev->touch.display == bd->Display)
520
+ io.AddMousePosEvent(ev->touch.x, ev->touch.y);
521
+ return true;
522
+ case ALLEGRO_EVENT_TOUCH_BEGIN:
523
+ case ALLEGRO_EVENT_TOUCH_END:
524
+ case ALLEGRO_EVENT_TOUCH_CANCEL:
525
+ if (ev->touch.display == bd->Display && ev->touch.primary)
526
+ io.AddMouseButtonEvent(0, ev->type == ALLEGRO_EVENT_TOUCH_BEGIN);
527
+ return true;
528
+ case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY:
529
+ if (ev->mouse.display == bd->Display)
530
+ io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
531
+ return true;
532
+ case ALLEGRO_EVENT_KEY_CHAR:
533
+ if (ev->keyboard.display == bd->Display)
534
+ if (ev->keyboard.unichar != 0)
535
+ io.AddInputCharacter((unsigned int)ev->keyboard.unichar);
536
+ return true;
537
+ case ALLEGRO_EVENT_KEY_DOWN:
538
+ case ALLEGRO_EVENT_KEY_UP:
539
+ if (ev->keyboard.display == bd->Display)
540
+ {
541
+ ImGui_ImplAllegro5_UpdateKeyModifiers();
542
+ ImGuiKey key = ImGui_ImplAllegro5_KeyCodeToImGuiKey(ev->keyboard.keycode);
543
+ io.AddKeyEvent(key, (ev->type == ALLEGRO_EVENT_KEY_DOWN));
544
+ io.SetKeyEventNativeData(key, ev->keyboard.keycode, -1); // To support legacy indexing (<1.87 user code)
545
+ }
546
+ return true;
547
+ case ALLEGRO_EVENT_DISPLAY_SWITCH_OUT:
548
+ if (ev->display.source == bd->Display)
549
+ io.AddFocusEvent(false);
550
+ return true;
551
+ case ALLEGRO_EVENT_DISPLAY_SWITCH_IN:
552
+ if (ev->display.source == bd->Display)
553
+ {
554
+ io.AddFocusEvent(true);
555
+ #if defined(ALLEGRO_UNSTABLE)
556
+ al_clear_keyboard_state(bd->Display);
557
+ #endif
558
+ }
559
+ return true;
560
+ }
561
+ return false;
562
+ }
563
+
564
+ static void ImGui_ImplAllegro5_UpdateMouseCursor()
565
+ {
566
+ ImGuiIO& io = ImGui::GetIO();
567
+ if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
568
+ return;
569
+
570
+ ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
571
+ ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
572
+ if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
573
+ {
574
+ // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
575
+ al_set_mouse_cursor(bd->Display, bd->MouseCursorInvisible);
576
+ }
577
+ else
578
+ {
579
+ ALLEGRO_SYSTEM_MOUSE_CURSOR cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT;
580
+ switch (imgui_cursor)
581
+ {
582
+ case ImGuiMouseCursor_TextInput: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_EDIT; break;
583
+ case ImGuiMouseCursor_ResizeAll: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_MOVE; break;
584
+ case ImGuiMouseCursor_ResizeNS: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_N; break;
585
+ case ImGuiMouseCursor_ResizeEW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E; break;
586
+ case ImGuiMouseCursor_ResizeNESW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE; break;
587
+ case ImGuiMouseCursor_ResizeNWSE: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW; break;
588
+ case ImGuiMouseCursor_NotAllowed: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_UNAVAILABLE; break;
589
+ }
590
+ al_set_system_mouse_cursor(bd->Display, cursor_id);
591
+ }
592
+ }
593
+
594
+ void ImGui_ImplAllegro5_NewFrame()
595
+ {
596
+ ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
597
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?");
598
+
599
+ if (!bd->Texture)
600
+ ImGui_ImplAllegro5_CreateDeviceObjects();
601
+
602
+ ImGuiIO& io = ImGui::GetIO();
603
+
604
+ // Setup display size (every frame to accommodate for window resizing)
605
+ int w, h;
606
+ w = al_get_display_width(bd->Display);
607
+ h = al_get_display_height(bd->Display);
608
+ io.DisplaySize = ImVec2((float)w, (float)h);
609
+
610
+ // Setup time step
611
+ double current_time = al_get_time();
612
+ io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f);
613
+ bd->Time = current_time;
614
+
615
+ // Setup mouse cursor shape
616
+ ImGui_ImplAllegro5_UpdateMouseCursor();
617
+ }
618
+
619
+ //-----------------------------------------------------------------------------
620
+
621
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_allegro5.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer + Platform Backend for Allegro 5
2
+ // (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
7
+ // [X] Platform: Clipboard support (from Allegro 5.1.12).
8
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
9
+ // Missing features or Issues:
10
+ // [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually.
11
+ // [ ] Platform: Missing gamepad support.
12
+ // [ ] Renderer: Multi-viewport support (multiple windows).
13
+
14
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
15
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
16
+ // Learn about Dear ImGui:
17
+ // - FAQ https://dearimgui.com/faq
18
+ // - Getting Started https://dearimgui.com/getting-started
19
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
20
+ // - Introduction, links and more at the top of imgui.cpp
21
+
22
+ #pragma once
23
+ #include "imgui.h" // IMGUI_IMPL_API
24
+ #ifndef IMGUI_DISABLE
25
+
26
+ struct ALLEGRO_DISPLAY;
27
+ union ALLEGRO_EVENT;
28
+
29
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
30
+ IMGUI_IMPL_API bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display);
31
+ IMGUI_IMPL_API void ImGui_ImplAllegro5_Shutdown();
32
+ IMGUI_IMPL_API void ImGui_ImplAllegro5_NewFrame();
33
+ IMGUI_IMPL_API void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data);
34
+ IMGUI_IMPL_API bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* event);
35
+
36
+ // Use if you want to reset your rendering device without losing Dear ImGui state.
37
+ IMGUI_IMPL_API bool ImGui_ImplAllegro5_CreateDeviceObjects();
38
+ IMGUI_IMPL_API void ImGui_ImplAllegro5_InvalidateDeviceObjects();
39
+
40
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_android.cpp ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Binding for Android native app
2
+ // This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3)
3
+
4
+ // Implemented features:
5
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
6
+ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
7
+ // Missing features or Issues:
8
+ // [ ] Platform: Clipboard support.
9
+ // [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
10
+ // [ ] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android.
11
+ // [ ] Platform: Multi-viewport support (multiple windows). Not meaningful on Android.
12
+ // Important:
13
+ // - Consider using SDL or GLFW backend on Android, which will be more full-featured than this.
14
+ // - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446)
15
+ // - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446)
16
+
17
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
18
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
19
+ // Learn about Dear ImGui:
20
+ // - FAQ https://dearimgui.com/faq
21
+ // - Getting Started https://dearimgui.com/getting-started
22
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
23
+ // - Introduction, links and more at the top of imgui.cpp
24
+
25
+ // CHANGELOG
26
+ // (minor and older changes stripped away, please see git history for details)
27
+ // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
28
+ // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
29
+ // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
30
+ // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
31
+ // 2021-03-04: Initial version.
32
+
33
+ #include "imgui.h"
34
+ #ifndef IMGUI_DISABLE
35
+ #include "imgui_impl_android.h"
36
+ #include <time.h>
37
+ #include <android/native_window.h>
38
+ #include <android/input.h>
39
+ #include <android/keycodes.h>
40
+ #include <android/log.h>
41
+
42
+ // Android data
43
+ static double g_Time = 0.0;
44
+ static ANativeWindow* g_Window;
45
+ static char g_LogTag[] = "ImGuiExample";
46
+
47
+ static ImGuiKey ImGui_ImplAndroid_KeyCodeToImGuiKey(int32_t key_code)
48
+ {
49
+ switch (key_code)
50
+ {
51
+ case AKEYCODE_TAB: return ImGuiKey_Tab;
52
+ case AKEYCODE_DPAD_LEFT: return ImGuiKey_LeftArrow;
53
+ case AKEYCODE_DPAD_RIGHT: return ImGuiKey_RightArrow;
54
+ case AKEYCODE_DPAD_UP: return ImGuiKey_UpArrow;
55
+ case AKEYCODE_DPAD_DOWN: return ImGuiKey_DownArrow;
56
+ case AKEYCODE_PAGE_UP: return ImGuiKey_PageUp;
57
+ case AKEYCODE_PAGE_DOWN: return ImGuiKey_PageDown;
58
+ case AKEYCODE_MOVE_HOME: return ImGuiKey_Home;
59
+ case AKEYCODE_MOVE_END: return ImGuiKey_End;
60
+ case AKEYCODE_INSERT: return ImGuiKey_Insert;
61
+ case AKEYCODE_FORWARD_DEL: return ImGuiKey_Delete;
62
+ case AKEYCODE_DEL: return ImGuiKey_Backspace;
63
+ case AKEYCODE_SPACE: return ImGuiKey_Space;
64
+ case AKEYCODE_ENTER: return ImGuiKey_Enter;
65
+ case AKEYCODE_ESCAPE: return ImGuiKey_Escape;
66
+ case AKEYCODE_APOSTROPHE: return ImGuiKey_Apostrophe;
67
+ case AKEYCODE_COMMA: return ImGuiKey_Comma;
68
+ case AKEYCODE_MINUS: return ImGuiKey_Minus;
69
+ case AKEYCODE_PERIOD: return ImGuiKey_Period;
70
+ case AKEYCODE_SLASH: return ImGuiKey_Slash;
71
+ case AKEYCODE_SEMICOLON: return ImGuiKey_Semicolon;
72
+ case AKEYCODE_EQUALS: return ImGuiKey_Equal;
73
+ case AKEYCODE_LEFT_BRACKET: return ImGuiKey_LeftBracket;
74
+ case AKEYCODE_BACKSLASH: return ImGuiKey_Backslash;
75
+ case AKEYCODE_RIGHT_BRACKET: return ImGuiKey_RightBracket;
76
+ case AKEYCODE_GRAVE: return ImGuiKey_GraveAccent;
77
+ case AKEYCODE_CAPS_LOCK: return ImGuiKey_CapsLock;
78
+ case AKEYCODE_SCROLL_LOCK: return ImGuiKey_ScrollLock;
79
+ case AKEYCODE_NUM_LOCK: return ImGuiKey_NumLock;
80
+ case AKEYCODE_SYSRQ: return ImGuiKey_PrintScreen;
81
+ case AKEYCODE_BREAK: return ImGuiKey_Pause;
82
+ case AKEYCODE_NUMPAD_0: return ImGuiKey_Keypad0;
83
+ case AKEYCODE_NUMPAD_1: return ImGuiKey_Keypad1;
84
+ case AKEYCODE_NUMPAD_2: return ImGuiKey_Keypad2;
85
+ case AKEYCODE_NUMPAD_3: return ImGuiKey_Keypad3;
86
+ case AKEYCODE_NUMPAD_4: return ImGuiKey_Keypad4;
87
+ case AKEYCODE_NUMPAD_5: return ImGuiKey_Keypad5;
88
+ case AKEYCODE_NUMPAD_6: return ImGuiKey_Keypad6;
89
+ case AKEYCODE_NUMPAD_7: return ImGuiKey_Keypad7;
90
+ case AKEYCODE_NUMPAD_8: return ImGuiKey_Keypad8;
91
+ case AKEYCODE_NUMPAD_9: return ImGuiKey_Keypad9;
92
+ case AKEYCODE_NUMPAD_DOT: return ImGuiKey_KeypadDecimal;
93
+ case AKEYCODE_NUMPAD_DIVIDE: return ImGuiKey_KeypadDivide;
94
+ case AKEYCODE_NUMPAD_MULTIPLY: return ImGuiKey_KeypadMultiply;
95
+ case AKEYCODE_NUMPAD_SUBTRACT: return ImGuiKey_KeypadSubtract;
96
+ case AKEYCODE_NUMPAD_ADD: return ImGuiKey_KeypadAdd;
97
+ case AKEYCODE_NUMPAD_ENTER: return ImGuiKey_KeypadEnter;
98
+ case AKEYCODE_NUMPAD_EQUALS: return ImGuiKey_KeypadEqual;
99
+ case AKEYCODE_CTRL_LEFT: return ImGuiKey_LeftCtrl;
100
+ case AKEYCODE_SHIFT_LEFT: return ImGuiKey_LeftShift;
101
+ case AKEYCODE_ALT_LEFT: return ImGuiKey_LeftAlt;
102
+ case AKEYCODE_META_LEFT: return ImGuiKey_LeftSuper;
103
+ case AKEYCODE_CTRL_RIGHT: return ImGuiKey_RightCtrl;
104
+ case AKEYCODE_SHIFT_RIGHT: return ImGuiKey_RightShift;
105
+ case AKEYCODE_ALT_RIGHT: return ImGuiKey_RightAlt;
106
+ case AKEYCODE_META_RIGHT: return ImGuiKey_RightSuper;
107
+ case AKEYCODE_MENU: return ImGuiKey_Menu;
108
+ case AKEYCODE_0: return ImGuiKey_0;
109
+ case AKEYCODE_1: return ImGuiKey_1;
110
+ case AKEYCODE_2: return ImGuiKey_2;
111
+ case AKEYCODE_3: return ImGuiKey_3;
112
+ case AKEYCODE_4: return ImGuiKey_4;
113
+ case AKEYCODE_5: return ImGuiKey_5;
114
+ case AKEYCODE_6: return ImGuiKey_6;
115
+ case AKEYCODE_7: return ImGuiKey_7;
116
+ case AKEYCODE_8: return ImGuiKey_8;
117
+ case AKEYCODE_9: return ImGuiKey_9;
118
+ case AKEYCODE_A: return ImGuiKey_A;
119
+ case AKEYCODE_B: return ImGuiKey_B;
120
+ case AKEYCODE_C: return ImGuiKey_C;
121
+ case AKEYCODE_D: return ImGuiKey_D;
122
+ case AKEYCODE_E: return ImGuiKey_E;
123
+ case AKEYCODE_F: return ImGuiKey_F;
124
+ case AKEYCODE_G: return ImGuiKey_G;
125
+ case AKEYCODE_H: return ImGuiKey_H;
126
+ case AKEYCODE_I: return ImGuiKey_I;
127
+ case AKEYCODE_J: return ImGuiKey_J;
128
+ case AKEYCODE_K: return ImGuiKey_K;
129
+ case AKEYCODE_L: return ImGuiKey_L;
130
+ case AKEYCODE_M: return ImGuiKey_M;
131
+ case AKEYCODE_N: return ImGuiKey_N;
132
+ case AKEYCODE_O: return ImGuiKey_O;
133
+ case AKEYCODE_P: return ImGuiKey_P;
134
+ case AKEYCODE_Q: return ImGuiKey_Q;
135
+ case AKEYCODE_R: return ImGuiKey_R;
136
+ case AKEYCODE_S: return ImGuiKey_S;
137
+ case AKEYCODE_T: return ImGuiKey_T;
138
+ case AKEYCODE_U: return ImGuiKey_U;
139
+ case AKEYCODE_V: return ImGuiKey_V;
140
+ case AKEYCODE_W: return ImGuiKey_W;
141
+ case AKEYCODE_X: return ImGuiKey_X;
142
+ case AKEYCODE_Y: return ImGuiKey_Y;
143
+ case AKEYCODE_Z: return ImGuiKey_Z;
144
+ case AKEYCODE_F1: return ImGuiKey_F1;
145
+ case AKEYCODE_F2: return ImGuiKey_F2;
146
+ case AKEYCODE_F3: return ImGuiKey_F3;
147
+ case AKEYCODE_F4: return ImGuiKey_F4;
148
+ case AKEYCODE_F5: return ImGuiKey_F5;
149
+ case AKEYCODE_F6: return ImGuiKey_F6;
150
+ case AKEYCODE_F7: return ImGuiKey_F7;
151
+ case AKEYCODE_F8: return ImGuiKey_F8;
152
+ case AKEYCODE_F9: return ImGuiKey_F9;
153
+ case AKEYCODE_F10: return ImGuiKey_F10;
154
+ case AKEYCODE_F11: return ImGuiKey_F11;
155
+ case AKEYCODE_F12: return ImGuiKey_F12;
156
+ default: return ImGuiKey_None;
157
+ }
158
+ }
159
+
160
+ int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event)
161
+ {
162
+ ImGuiIO& io = ImGui::GetIO();
163
+ int32_t event_type = AInputEvent_getType(input_event);
164
+ switch (event_type)
165
+ {
166
+ case AINPUT_EVENT_TYPE_KEY:
167
+ {
168
+ int32_t event_key_code = AKeyEvent_getKeyCode(input_event);
169
+ int32_t event_scan_code = AKeyEvent_getScanCode(input_event);
170
+ int32_t event_action = AKeyEvent_getAction(input_event);
171
+ int32_t event_meta_state = AKeyEvent_getMetaState(input_event);
172
+
173
+ io.AddKeyEvent(ImGuiMod_Ctrl, (event_meta_state & AMETA_CTRL_ON) != 0);
174
+ io.AddKeyEvent(ImGuiMod_Shift, (event_meta_state & AMETA_SHIFT_ON) != 0);
175
+ io.AddKeyEvent(ImGuiMod_Alt, (event_meta_state & AMETA_ALT_ON) != 0);
176
+ io.AddKeyEvent(ImGuiMod_Super, (event_meta_state & AMETA_META_ON) != 0);
177
+
178
+ switch (event_action)
179
+ {
180
+ // FIXME: AKEY_EVENT_ACTION_DOWN and AKEY_EVENT_ACTION_UP occur at once as soon as a touch pointer
181
+ // goes up from a key. We use a simple key event queue/ and process one event per key per frame in
182
+ // ImGui_ImplAndroid_NewFrame()...or consider using IO queue, if suitable: https://github.com/ocornut/imgui/issues/2787
183
+ case AKEY_EVENT_ACTION_DOWN:
184
+ case AKEY_EVENT_ACTION_UP:
185
+ {
186
+ ImGuiKey key = ImGui_ImplAndroid_KeyCodeToImGuiKey(event_key_code);
187
+ if (key != ImGuiKey_None)
188
+ {
189
+ io.AddKeyEvent(key, event_action == AKEY_EVENT_ACTION_DOWN);
190
+ io.SetKeyEventNativeData(key, event_key_code, event_scan_code);
191
+ }
192
+
193
+ break;
194
+ }
195
+ default:
196
+ break;
197
+ }
198
+ break;
199
+ }
200
+ case AINPUT_EVENT_TYPE_MOTION:
201
+ {
202
+ int32_t event_action = AMotionEvent_getAction(input_event);
203
+ int32_t event_pointer_index = (event_action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
204
+ event_action &= AMOTION_EVENT_ACTION_MASK;
205
+
206
+ switch (AMotionEvent_getToolType(input_event, event_pointer_index))
207
+ {
208
+ case AMOTION_EVENT_TOOL_TYPE_MOUSE:
209
+ io.AddMouseSourceEvent(ImGuiMouseSource_Mouse);
210
+ break;
211
+ case AMOTION_EVENT_TOOL_TYPE_STYLUS:
212
+ case AMOTION_EVENT_TOOL_TYPE_ERASER:
213
+ io.AddMouseSourceEvent(ImGuiMouseSource_Pen);
214
+ break;
215
+ case AMOTION_EVENT_TOOL_TYPE_FINGER:
216
+ default:
217
+ io.AddMouseSourceEvent(ImGuiMouseSource_TouchScreen);
218
+ break;
219
+ }
220
+
221
+ switch (event_action)
222
+ {
223
+ case AMOTION_EVENT_ACTION_DOWN:
224
+ case AMOTION_EVENT_ACTION_UP:
225
+ {
226
+ // Physical mouse buttons (and probably other physical devices) also invoke the actions AMOTION_EVENT_ACTION_DOWN/_UP,
227
+ // but we have to process them separately to identify the actual button pressed. This is done below via
228
+ // AMOTION_EVENT_ACTION_BUTTON_PRESS/_RELEASE. Here, we only process "FINGER" input (and "UNKNOWN", as a fallback).
229
+ int tool_type = AMotionEvent_getToolType(input_event, event_pointer_index);
230
+ if (tool_type == AMOTION_EVENT_TOOL_TYPE_FINGER || tool_type == AMOTION_EVENT_TOOL_TYPE_UNKNOWN)
231
+ {
232
+ io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index));
233
+ io.AddMouseButtonEvent(0, event_action == AMOTION_EVENT_ACTION_DOWN);
234
+ }
235
+ break;
236
+ }
237
+ case AMOTION_EVENT_ACTION_BUTTON_PRESS:
238
+ case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
239
+ {
240
+ int32_t button_state = AMotionEvent_getButtonState(input_event);
241
+ io.AddMouseButtonEvent(0, (button_state & AMOTION_EVENT_BUTTON_PRIMARY) != 0);
242
+ io.AddMouseButtonEvent(1, (button_state & AMOTION_EVENT_BUTTON_SECONDARY) != 0);
243
+ io.AddMouseButtonEvent(2, (button_state & AMOTION_EVENT_BUTTON_TERTIARY) != 0);
244
+ break;
245
+ }
246
+ case AMOTION_EVENT_ACTION_HOVER_MOVE: // Hovering: Tool moves while NOT pressed (such as a physical mouse)
247
+ case AMOTION_EVENT_ACTION_MOVE: // Touch pointer moves while DOWN
248
+ io.AddMousePosEvent(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index));
249
+ break;
250
+ case AMOTION_EVENT_ACTION_SCROLL:
251
+ io.AddMouseWheelEvent(AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_HSCROLL, event_pointer_index), AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_VSCROLL, event_pointer_index));
252
+ break;
253
+ default:
254
+ break;
255
+ }
256
+ }
257
+ return 1;
258
+ default:
259
+ break;
260
+ }
261
+
262
+ return 0;
263
+ }
264
+
265
+ bool ImGui_ImplAndroid_Init(ANativeWindow* window)
266
+ {
267
+ IMGUI_CHECKVERSION();
268
+
269
+ g_Window = window;
270
+ g_Time = 0.0;
271
+
272
+ // Setup backend capabilities flags
273
+ ImGuiIO& io = ImGui::GetIO();
274
+ io.BackendPlatformName = "imgui_impl_android";
275
+
276
+ return true;
277
+ }
278
+
279
+ void ImGui_ImplAndroid_Shutdown()
280
+ {
281
+ ImGuiIO& io = ImGui::GetIO();
282
+ io.BackendPlatformName = nullptr;
283
+ }
284
+
285
+ void ImGui_ImplAndroid_NewFrame()
286
+ {
287
+ ImGuiIO& io = ImGui::GetIO();
288
+
289
+ // Setup display size (every frame to accommodate for window resizing)
290
+ int32_t window_width = ANativeWindow_getWidth(g_Window);
291
+ int32_t window_height = ANativeWindow_getHeight(g_Window);
292
+ int display_width = window_width;
293
+ int display_height = window_height;
294
+
295
+ io.DisplaySize = ImVec2((float)window_width, (float)window_height);
296
+ if (window_width > 0 && window_height > 0)
297
+ io.DisplayFramebufferScale = ImVec2((float)display_width / window_width, (float)display_height / window_height);
298
+
299
+ // Setup time step
300
+ struct timespec current_timespec;
301
+ clock_gettime(CLOCK_MONOTONIC, &current_timespec);
302
+ double current_time = (double)(current_timespec.tv_sec) + (current_timespec.tv_nsec / 1000000000.0);
303
+ io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
304
+ g_Time = current_time;
305
+ }
306
+
307
+ //-----------------------------------------------------------------------------
308
+
309
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_android.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Binding for Android native app
2
+ // This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3)
3
+
4
+ // Implemented features:
5
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy AKEYCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
6
+ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
7
+ // Missing features or Issues:
8
+ // [ ] Platform: Clipboard support.
9
+ // [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
10
+ // [ ] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android.
11
+ // [ ] Platform: Multi-viewport support (multiple windows). Not meaningful on Android.
12
+ // Important:
13
+ // - Consider using SDL or GLFW backend on Android, which will be more full-featured than this.
14
+ // - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446)
15
+ // - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446)
16
+
17
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
18
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
19
+ // Learn about Dear ImGui:
20
+ // - FAQ https://dearimgui.com/faq
21
+ // - Getting Started https://dearimgui.com/getting-started
22
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
23
+ // - Introduction, links and more at the top of imgui.cpp
24
+
25
+ #pragma once
26
+ #include "imgui.h" // IMGUI_IMPL_API
27
+ #ifndef IMGUI_DISABLE
28
+
29
+ struct ANativeWindow;
30
+ struct AInputEvent;
31
+
32
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
33
+ IMGUI_IMPL_API bool ImGui_ImplAndroid_Init(ANativeWindow* window);
34
+ IMGUI_IMPL_API int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event);
35
+ IMGUI_IMPL_API void ImGui_ImplAndroid_Shutdown();
36
+ IMGUI_IMPL_API void ImGui_ImplAndroid_NewFrame();
37
+
38
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_dx10.cpp ADDED
@@ -0,0 +1,736 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for DirectX10
2
+ // This needs to be used along with a Platform Backend (e.g. Win32)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
8
+
9
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
10
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
11
+ // Learn about Dear ImGui:
12
+ // - FAQ https://dearimgui.com/faq
13
+ // - Getting Started https://dearimgui.com/getting-started
14
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
15
+ // - Introduction, links and more at the top of imgui.cpp
16
+
17
+ // CHANGELOG
18
+ // (minor and older changes stripped away, please see git history for details)
19
+ // 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
20
+ // 2024-10-07: DirectX10: Changed default texture sampler to Clamp instead of Repeat/Wrap.
21
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
22
+ // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
23
+ // 2021-05-19: DirectX10: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
24
+ // 2021-02-18: DirectX10: Change blending equation to preserve alpha in output buffer.
25
+ // 2019-07-21: DirectX10: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX10_RenderDrawData().
26
+ // 2019-05-29: DirectX10: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
27
+ // 2019-04-30: DirectX10: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
28
+ // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
29
+ // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
30
+ // 2018-07-13: DirectX10: Fixed unreleased resources in Init and Shutdown functions.
31
+ // 2018-06-08: Misc: Extracted imgui_impl_dx10.cpp/.h away from the old combined DX10+Win32 example.
32
+ // 2018-06-08: DirectX10: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
33
+ // 2018-04-09: Misc: Fixed erroneous call to io.Fonts->ClearInputData() + ClearTexData() that was left in DX10 example but removed in 1.47 (Nov 2015) on other backends.
34
+ // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX10_RenderDrawData() in the .h file so you can call it yourself.
35
+ // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
36
+ // 2016-05-07: DirectX10: Disabling depth-write.
37
+
38
+ #include "imgui.h"
39
+ #ifndef IMGUI_DISABLE
40
+ #include "imgui_impl_dx10.h"
41
+
42
+ // DirectX
43
+ #include <stdio.h>
44
+ #include <d3d10_1.h>
45
+ #include <d3d10.h>
46
+ #include <d3dcompiler.h>
47
+ #ifdef _MSC_VER
48
+ #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
49
+ #endif
50
+
51
+ // DirectX data
52
+ struct ImGui_ImplDX10_Data
53
+ {
54
+ ID3D10Device* pd3dDevice;
55
+ IDXGIFactory* pFactory;
56
+ ID3D10Buffer* pVB;
57
+ ID3D10Buffer* pIB;
58
+ ID3D10VertexShader* pVertexShader;
59
+ ID3D10InputLayout* pInputLayout;
60
+ ID3D10Buffer* pVertexConstantBuffer;
61
+ ID3D10PixelShader* pPixelShader;
62
+ ID3D10SamplerState* pFontSampler;
63
+ ID3D10ShaderResourceView* pFontTextureView;
64
+ ID3D10RasterizerState* pRasterizerState;
65
+ ID3D10BlendState* pBlendState;
66
+ ID3D10DepthStencilState* pDepthStencilState;
67
+ int VertexBufferSize;
68
+ int IndexBufferSize;
69
+
70
+ ImGui_ImplDX10_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
71
+ };
72
+
73
+ struct VERTEX_CONSTANT_BUFFER_DX10
74
+ {
75
+ float mvp[4][4];
76
+ };
77
+
78
+ // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
79
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
80
+ static ImGui_ImplDX10_Data* ImGui_ImplDX10_GetBackendData()
81
+ {
82
+ return ImGui::GetCurrentContext() ? (ImGui_ImplDX10_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
83
+ }
84
+
85
+ // Forward Declarations
86
+ static void ImGui_ImplDX10_InitMultiViewportSupport();
87
+ static void ImGui_ImplDX10_ShutdownMultiViewportSupport();
88
+
89
+ // Functions
90
+ static void ImGui_ImplDX10_SetupRenderState(ImDrawData* draw_data, ID3D10Device* device)
91
+ {
92
+ ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
93
+
94
+ // Setup viewport
95
+ D3D10_VIEWPORT vp;
96
+ memset(&vp, 0, sizeof(D3D10_VIEWPORT));
97
+ vp.Width = (UINT)draw_data->DisplaySize.x;
98
+ vp.Height = (UINT)draw_data->DisplaySize.y;
99
+ vp.MinDepth = 0.0f;
100
+ vp.MaxDepth = 1.0f;
101
+ vp.TopLeftX = vp.TopLeftY = 0;
102
+ device->RSSetViewports(1, &vp);
103
+
104
+ // Bind shader and vertex buffers
105
+ unsigned int stride = sizeof(ImDrawVert);
106
+ unsigned int offset = 0;
107
+ device->IASetInputLayout(bd->pInputLayout);
108
+ device->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
109
+ device->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
110
+ device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
111
+ device->VSSetShader(bd->pVertexShader);
112
+ device->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
113
+ device->PSSetShader(bd->pPixelShader);
114
+ device->PSSetSamplers(0, 1, &bd->pFontSampler);
115
+ device->GSSetShader(nullptr);
116
+
117
+ // Setup render state
118
+ const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
119
+ device->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
120
+ device->OMSetDepthStencilState(bd->pDepthStencilState, 0);
121
+ device->RSSetState(bd->pRasterizerState);
122
+ }
123
+
124
+ // Render function
125
+ void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data)
126
+ {
127
+ // Avoid rendering when minimized
128
+ if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
129
+ return;
130
+
131
+ ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
132
+ ID3D10Device* device = bd->pd3dDevice;
133
+
134
+ // Create and grow vertex/index buffers if needed
135
+ if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
136
+ {
137
+ if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
138
+ bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
139
+ D3D10_BUFFER_DESC desc;
140
+ memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
141
+ desc.Usage = D3D10_USAGE_DYNAMIC;
142
+ desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert);
143
+ desc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
144
+ desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
145
+ desc.MiscFlags = 0;
146
+ if (device->CreateBuffer(&desc, nullptr, &bd->pVB) < 0)
147
+ return;
148
+ }
149
+
150
+ if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
151
+ {
152
+ if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
153
+ bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
154
+ D3D10_BUFFER_DESC desc;
155
+ memset(&desc, 0, sizeof(D3D10_BUFFER_DESC));
156
+ desc.Usage = D3D10_USAGE_DYNAMIC;
157
+ desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx);
158
+ desc.BindFlags = D3D10_BIND_INDEX_BUFFER;
159
+ desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
160
+ if (device->CreateBuffer(&desc, nullptr, &bd->pIB) < 0)
161
+ return;
162
+ }
163
+
164
+ // Copy and convert all vertices into a single contiguous buffer
165
+ ImDrawVert* vtx_dst = nullptr;
166
+ ImDrawIdx* idx_dst = nullptr;
167
+ bd->pVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&vtx_dst);
168
+ bd->pIB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&idx_dst);
169
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
170
+ {
171
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
172
+ memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
173
+ memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
174
+ vtx_dst += draw_list->VtxBuffer.Size;
175
+ idx_dst += draw_list->IdxBuffer.Size;
176
+ }
177
+ bd->pVB->Unmap();
178
+ bd->pIB->Unmap();
179
+
180
+ // Setup orthographic projection matrix into our constant buffer
181
+ // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
182
+ {
183
+ void* mapped_resource;
184
+ if (bd->pVertexConstantBuffer->Map(D3D10_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
185
+ return;
186
+ VERTEX_CONSTANT_BUFFER_DX10* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX10*)mapped_resource;
187
+ float L = draw_data->DisplayPos.x;
188
+ float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
189
+ float T = draw_data->DisplayPos.y;
190
+ float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
191
+ float mvp[4][4] =
192
+ {
193
+ { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
194
+ { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
195
+ { 0.0f, 0.0f, 0.5f, 0.0f },
196
+ { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
197
+ };
198
+ memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
199
+ bd->pVertexConstantBuffer->Unmap();
200
+ }
201
+
202
+ // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
203
+ struct BACKUP_DX10_STATE
204
+ {
205
+ UINT ScissorRectsCount, ViewportsCount;
206
+ D3D10_RECT ScissorRects[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
207
+ D3D10_VIEWPORT Viewports[D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
208
+ ID3D10RasterizerState* RS;
209
+ ID3D10BlendState* BlendState;
210
+ FLOAT BlendFactor[4];
211
+ UINT SampleMask;
212
+ UINT StencilRef;
213
+ ID3D10DepthStencilState* DepthStencilState;
214
+ ID3D10ShaderResourceView* PSShaderResource;
215
+ ID3D10SamplerState* PSSampler;
216
+ ID3D10PixelShader* PS;
217
+ ID3D10VertexShader* VS;
218
+ ID3D10GeometryShader* GS;
219
+ D3D10_PRIMITIVE_TOPOLOGY PrimitiveTopology;
220
+ ID3D10Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
221
+ UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
222
+ DXGI_FORMAT IndexBufferFormat;
223
+ ID3D10InputLayout* InputLayout;
224
+ };
225
+ BACKUP_DX10_STATE old = {};
226
+ old.ScissorRectsCount = old.ViewportsCount = D3D10_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
227
+ device->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
228
+ device->RSGetViewports(&old.ViewportsCount, old.Viewports);
229
+ device->RSGetState(&old.RS);
230
+ device->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
231
+ device->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
232
+ device->PSGetShaderResources(0, 1, &old.PSShaderResource);
233
+ device->PSGetSamplers(0, 1, &old.PSSampler);
234
+ device->PSGetShader(&old.PS);
235
+ device->VSGetShader(&old.VS);
236
+ device->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
237
+ device->GSGetShader(&old.GS);
238
+ device->IAGetPrimitiveTopology(&old.PrimitiveTopology);
239
+ device->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
240
+ device->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
241
+ device->IAGetInputLayout(&old.InputLayout);
242
+
243
+ // Setup desired DX state
244
+ ImGui_ImplDX10_SetupRenderState(draw_data, device);
245
+
246
+ // Render command lists
247
+ // (Because we merged all buffers into a single one, we maintain our own offset into them)
248
+ int global_vtx_offset = 0;
249
+ int global_idx_offset = 0;
250
+ ImVec2 clip_off = draw_data->DisplayPos;
251
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
252
+ {
253
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
254
+ for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
255
+ {
256
+ const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
257
+ if (pcmd->UserCallback)
258
+ {
259
+ // User callback, registered via ImDrawList::AddCallback()
260
+ // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
261
+ if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
262
+ ImGui_ImplDX10_SetupRenderState(draw_data, device);
263
+ else
264
+ pcmd->UserCallback(draw_list, pcmd);
265
+ }
266
+ else
267
+ {
268
+ // Project scissor/clipping rectangles into framebuffer space
269
+ ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
270
+ ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
271
+ if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
272
+ continue;
273
+
274
+ // Apply scissor/clipping rectangle
275
+ const D3D10_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
276
+ device->RSSetScissorRects(1, &r);
277
+
278
+ // Bind texture, Draw
279
+ ID3D10ShaderResourceView* texture_srv = (ID3D10ShaderResourceView*)pcmd->GetTexID();
280
+ device->PSSetShaderResources(0, 1, &texture_srv);
281
+ device->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
282
+ }
283
+ }
284
+ global_idx_offset += draw_list->IdxBuffer.Size;
285
+ global_vtx_offset += draw_list->VtxBuffer.Size;
286
+ }
287
+
288
+ // Restore modified DX state
289
+ device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
290
+ device->RSSetViewports(old.ViewportsCount, old.Viewports);
291
+ device->RSSetState(old.RS); if (old.RS) old.RS->Release();
292
+ device->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
293
+ device->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
294
+ device->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
295
+ device->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
296
+ device->PSSetShader(old.PS); if (old.PS) old.PS->Release();
297
+ device->VSSetShader(old.VS); if (old.VS) old.VS->Release();
298
+ device->GSSetShader(old.GS); if (old.GS) old.GS->Release();
299
+ device->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
300
+ device->IASetPrimitiveTopology(old.PrimitiveTopology);
301
+ device->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
302
+ device->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
303
+ device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
304
+ }
305
+
306
+ static void ImGui_ImplDX10_CreateFontsTexture()
307
+ {
308
+ // Build texture atlas
309
+ ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
310
+ ImGuiIO& io = ImGui::GetIO();
311
+ unsigned char* pixels;
312
+ int width, height;
313
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
314
+
315
+ // Upload texture to graphics system
316
+ {
317
+ D3D10_TEXTURE2D_DESC desc;
318
+ ZeroMemory(&desc, sizeof(desc));
319
+ desc.Width = width;
320
+ desc.Height = height;
321
+ desc.MipLevels = 1;
322
+ desc.ArraySize = 1;
323
+ desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
324
+ desc.SampleDesc.Count = 1;
325
+ desc.Usage = D3D10_USAGE_DEFAULT;
326
+ desc.BindFlags = D3D10_BIND_SHADER_RESOURCE;
327
+ desc.CPUAccessFlags = 0;
328
+
329
+ ID3D10Texture2D* pTexture = nullptr;
330
+ D3D10_SUBRESOURCE_DATA subResource;
331
+ subResource.pSysMem = pixels;
332
+ subResource.SysMemPitch = desc.Width * 4;
333
+ subResource.SysMemSlicePitch = 0;
334
+ bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
335
+ IM_ASSERT(pTexture != nullptr);
336
+
337
+ // Create texture view
338
+ D3D10_SHADER_RESOURCE_VIEW_DESC srv_desc;
339
+ ZeroMemory(&srv_desc, sizeof(srv_desc));
340
+ srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
341
+ srv_desc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
342
+ srv_desc.Texture2D.MipLevels = desc.MipLevels;
343
+ srv_desc.Texture2D.MostDetailedMip = 0;
344
+ bd->pd3dDevice->CreateShaderResourceView(pTexture, &srv_desc, &bd->pFontTextureView);
345
+ pTexture->Release();
346
+ }
347
+
348
+ // Store our identifier
349
+ io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView);
350
+ }
351
+
352
+ static void ImGui_ImplDX10_DestroyFontsTexture()
353
+ {
354
+ ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
355
+ if (bd->pFontTextureView)
356
+ {
357
+ bd->pFontTextureView->Release();
358
+ bd->pFontTextureView = nullptr;
359
+ ImGui::GetIO().Fonts->SetTexID(0); // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
360
+ }
361
+ }
362
+
363
+ bool ImGui_ImplDX10_CreateDeviceObjects()
364
+ {
365
+ ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
366
+ if (!bd->pd3dDevice)
367
+ return false;
368
+ if (bd->pFontSampler)
369
+ ImGui_ImplDX10_InvalidateDeviceObjects();
370
+
371
+ // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
372
+ // If you would like to use this DX10 sample code but remove this dependency you can:
373
+ // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
374
+ // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
375
+ // See https://github.com/ocornut/imgui/pull/638 for sources and details.
376
+
377
+ // Create the vertex shader
378
+ {
379
+ static const char* vertexShader =
380
+ "cbuffer vertexBuffer : register(b0) \
381
+ {\
382
+ float4x4 ProjectionMatrix; \
383
+ };\
384
+ struct VS_INPUT\
385
+ {\
386
+ float2 pos : POSITION;\
387
+ float4 col : COLOR0;\
388
+ float2 uv : TEXCOORD0;\
389
+ };\
390
+ \
391
+ struct PS_INPUT\
392
+ {\
393
+ float4 pos : SV_POSITION;\
394
+ float4 col : COLOR0;\
395
+ float2 uv : TEXCOORD0;\
396
+ };\
397
+ \
398
+ PS_INPUT main(VS_INPUT input)\
399
+ {\
400
+ PS_INPUT output;\
401
+ output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
402
+ output.col = input.col;\
403
+ output.uv = input.uv;\
404
+ return output;\
405
+ }";
406
+
407
+ ID3DBlob* vertexShaderBlob;
408
+ if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr)))
409
+ return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
410
+ if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pVertexShader) != S_OK)
411
+ {
412
+ vertexShaderBlob->Release();
413
+ return false;
414
+ }
415
+
416
+ // Create the input layout
417
+ D3D10_INPUT_ELEMENT_DESC local_layout[] =
418
+ {
419
+ { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D10_INPUT_PER_VERTEX_DATA, 0 },
420
+ { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D10_INPUT_PER_VERTEX_DATA, 0 },
421
+ { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D10_INPUT_PER_VERTEX_DATA, 0 },
422
+ };
423
+ if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
424
+ {
425
+ vertexShaderBlob->Release();
426
+ return false;
427
+ }
428
+ vertexShaderBlob->Release();
429
+
430
+ // Create the constant buffer
431
+ {
432
+ D3D10_BUFFER_DESC desc;
433
+ desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX10);
434
+ desc.Usage = D3D10_USAGE_DYNAMIC;
435
+ desc.BindFlags = D3D10_BIND_CONSTANT_BUFFER;
436
+ desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
437
+ desc.MiscFlags = 0;
438
+ bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer);
439
+ }
440
+ }
441
+
442
+ // Create the pixel shader
443
+ {
444
+ static const char* pixelShader =
445
+ "struct PS_INPUT\
446
+ {\
447
+ float4 pos : SV_POSITION;\
448
+ float4 col : COLOR0;\
449
+ float2 uv : TEXCOORD0;\
450
+ };\
451
+ sampler sampler0;\
452
+ Texture2D texture0;\
453
+ \
454
+ float4 main(PS_INPUT input) : SV_Target\
455
+ {\
456
+ float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
457
+ return out_col; \
458
+ }";
459
+
460
+ ID3DBlob* pixelShaderBlob;
461
+ if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr)))
462
+ return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
463
+ if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), &bd->pPixelShader) != S_OK)
464
+ {
465
+ pixelShaderBlob->Release();
466
+ return false;
467
+ }
468
+ pixelShaderBlob->Release();
469
+ }
470
+
471
+ // Create the blending setup
472
+ {
473
+ D3D10_BLEND_DESC desc;
474
+ ZeroMemory(&desc, sizeof(desc));
475
+ desc.AlphaToCoverageEnable = false;
476
+ desc.BlendEnable[0] = true;
477
+ desc.SrcBlend = D3D10_BLEND_SRC_ALPHA;
478
+ desc.DestBlend = D3D10_BLEND_INV_SRC_ALPHA;
479
+ desc.BlendOp = D3D10_BLEND_OP_ADD;
480
+ desc.SrcBlendAlpha = D3D10_BLEND_ONE;
481
+ desc.DestBlendAlpha = D3D10_BLEND_INV_SRC_ALPHA;
482
+ desc.BlendOpAlpha = D3D10_BLEND_OP_ADD;
483
+ desc.RenderTargetWriteMask[0] = D3D10_COLOR_WRITE_ENABLE_ALL;
484
+ bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState);
485
+ }
486
+
487
+ // Create the rasterizer state
488
+ {
489
+ D3D10_RASTERIZER_DESC desc;
490
+ ZeroMemory(&desc, sizeof(desc));
491
+ desc.FillMode = D3D10_FILL_SOLID;
492
+ desc.CullMode = D3D10_CULL_NONE;
493
+ desc.ScissorEnable = true;
494
+ desc.DepthClipEnable = true;
495
+ bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState);
496
+ }
497
+
498
+ // Create depth-stencil State
499
+ {
500
+ D3D10_DEPTH_STENCIL_DESC desc;
501
+ ZeroMemory(&desc, sizeof(desc));
502
+ desc.DepthEnable = false;
503
+ desc.DepthWriteMask = D3D10_DEPTH_WRITE_MASK_ALL;
504
+ desc.DepthFunc = D3D10_COMPARISON_ALWAYS;
505
+ desc.StencilEnable = false;
506
+ desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D10_STENCIL_OP_KEEP;
507
+ desc.FrontFace.StencilFunc = D3D10_COMPARISON_ALWAYS;
508
+ desc.BackFace = desc.FrontFace;
509
+ bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
510
+ }
511
+
512
+ // Create texture sampler
513
+ // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
514
+ {
515
+ D3D10_SAMPLER_DESC desc;
516
+ ZeroMemory(&desc, sizeof(desc));
517
+ desc.Filter = D3D10_FILTER_MIN_MAG_MIP_LINEAR;
518
+ desc.AddressU = D3D10_TEXTURE_ADDRESS_CLAMP;
519
+ desc.AddressV = D3D10_TEXTURE_ADDRESS_CLAMP;
520
+ desc.AddressW = D3D10_TEXTURE_ADDRESS_CLAMP;
521
+ desc.MipLODBias = 0.f;
522
+ desc.ComparisonFunc = D3D10_COMPARISON_ALWAYS;
523
+ desc.MinLOD = 0.f;
524
+ desc.MaxLOD = 0.f;
525
+ bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
526
+ }
527
+
528
+ ImGui_ImplDX10_CreateFontsTexture();
529
+
530
+ return true;
531
+ }
532
+
533
+ void ImGui_ImplDX10_InvalidateDeviceObjects()
534
+ {
535
+ ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
536
+ if (!bd->pd3dDevice)
537
+ return;
538
+
539
+ ImGui_ImplDX10_DestroyFontsTexture();
540
+
541
+ if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; }
542
+ if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
543
+ if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
544
+ if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; }
545
+ if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; }
546
+ if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; }
547
+ if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; }
548
+ if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; }
549
+ if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; }
550
+ if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; }
551
+ }
552
+
553
+ bool ImGui_ImplDX10_Init(ID3D10Device* device)
554
+ {
555
+ ImGuiIO& io = ImGui::GetIO();
556
+ IMGUI_CHECKVERSION();
557
+ IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
558
+
559
+ // Setup backend capabilities flags
560
+ ImGui_ImplDX10_Data* bd = IM_NEW(ImGui_ImplDX10_Data)();
561
+ io.BackendRendererUserData = (void*)bd;
562
+ io.BackendRendererName = "imgui_impl_dx10";
563
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
564
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
565
+
566
+ // Get factory from device
567
+ IDXGIDevice* pDXGIDevice = nullptr;
568
+ IDXGIAdapter* pDXGIAdapter = nullptr;
569
+ IDXGIFactory* pFactory = nullptr;
570
+ if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
571
+ if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
572
+ if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
573
+ {
574
+ bd->pd3dDevice = device;
575
+ bd->pFactory = pFactory;
576
+ }
577
+ if (pDXGIDevice) pDXGIDevice->Release();
578
+ if (pDXGIAdapter) pDXGIAdapter->Release();
579
+ bd->pd3dDevice->AddRef();
580
+
581
+ ImGui_ImplDX10_InitMultiViewportSupport();
582
+
583
+ return true;
584
+ }
585
+
586
+ void ImGui_ImplDX10_Shutdown()
587
+ {
588
+ ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
589
+ IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
590
+ ImGuiIO& io = ImGui::GetIO();
591
+
592
+ ImGui_ImplDX10_ShutdownMultiViewportSupport();
593
+ ImGui_ImplDX10_InvalidateDeviceObjects();
594
+ if (bd->pFactory) { bd->pFactory->Release(); }
595
+ if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
596
+ io.BackendRendererName = nullptr;
597
+ io.BackendRendererUserData = nullptr;
598
+ io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
599
+ IM_DELETE(bd);
600
+ }
601
+
602
+ void ImGui_ImplDX10_NewFrame()
603
+ {
604
+ ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
605
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX10_Init()?");
606
+
607
+ if (!bd->pVertexShader)
608
+ ImGui_ImplDX10_CreateDeviceObjects();
609
+ }
610
+
611
+ //--------------------------------------------------------------------------------------------------------
612
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
613
+ // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
614
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
615
+ //--------------------------------------------------------------------------------------------------------
616
+
617
+ // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
618
+ struct ImGui_ImplDX10_ViewportData
619
+ {
620
+ IDXGISwapChain* SwapChain;
621
+ ID3D10RenderTargetView* RTView;
622
+
623
+ ImGui_ImplDX10_ViewportData() { SwapChain = nullptr; RTView = nullptr; }
624
+ ~ImGui_ImplDX10_ViewportData() { IM_ASSERT(SwapChain == nullptr && RTView == nullptr); }
625
+ };
626
+
627
+ static void ImGui_ImplDX10_CreateWindow(ImGuiViewport* viewport)
628
+ {
629
+ ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
630
+ ImGui_ImplDX10_ViewportData* vd = IM_NEW(ImGui_ImplDX10_ViewportData)();
631
+ viewport->RendererUserData = vd;
632
+
633
+ // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
634
+ // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
635
+ HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
636
+ IM_ASSERT(hwnd != 0);
637
+
638
+ // Create swap chain
639
+ DXGI_SWAP_CHAIN_DESC sd;
640
+ ZeroMemory(&sd, sizeof(sd));
641
+ sd.BufferDesc.Width = (UINT)viewport->Size.x;
642
+ sd.BufferDesc.Height = (UINT)viewport->Size.y;
643
+ sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
644
+ sd.SampleDesc.Count = 1;
645
+ sd.SampleDesc.Quality = 0;
646
+ sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
647
+ sd.BufferCount = 1;
648
+ sd.OutputWindow = hwnd;
649
+ sd.Windowed = TRUE;
650
+ sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
651
+ sd.Flags = 0;
652
+
653
+ IM_ASSERT(vd->SwapChain == nullptr && vd->RTView == nullptr);
654
+ bd->pFactory->CreateSwapChain(bd->pd3dDevice, &sd, &vd->SwapChain);
655
+
656
+ // Create the render target
657
+ if (vd->SwapChain)
658
+ {
659
+ ID3D10Texture2D* pBackBuffer;
660
+ vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
661
+ bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
662
+ pBackBuffer->Release();
663
+ }
664
+ }
665
+
666
+ static void ImGui_ImplDX10_DestroyWindow(ImGuiViewport* viewport)
667
+ {
668
+ // The main viewport (owned by the application) will always have RendererUserData == 0 here since we didn't create the data for it.
669
+ if (ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData)
670
+ {
671
+ if (vd->SwapChain)
672
+ vd->SwapChain->Release();
673
+ vd->SwapChain = nullptr;
674
+ if (vd->RTView)
675
+ vd->RTView->Release();
676
+ vd->RTView = nullptr;
677
+ IM_DELETE(vd);
678
+ }
679
+ viewport->RendererUserData = nullptr;
680
+ }
681
+
682
+ static void ImGui_ImplDX10_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
683
+ {
684
+ ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
685
+ ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData;
686
+ if (vd->RTView)
687
+ {
688
+ vd->RTView->Release();
689
+ vd->RTView = nullptr;
690
+ }
691
+ if (vd->SwapChain)
692
+ {
693
+ ID3D10Texture2D* pBackBuffer = nullptr;
694
+ vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
695
+ vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
696
+ if (pBackBuffer == nullptr) { fprintf(stderr, "ImGui_ImplDX10_SetWindowSize() failed creating buffers.\n"); return; }
697
+ bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
698
+ pBackBuffer->Release();
699
+ }
700
+ }
701
+
702
+ static void ImGui_ImplDX10_RenderViewport(ImGuiViewport* viewport, void*)
703
+ {
704
+ ImGui_ImplDX10_Data* bd = ImGui_ImplDX10_GetBackendData();
705
+ ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData;
706
+ ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
707
+ bd->pd3dDevice->OMSetRenderTargets(1, &vd->RTView, nullptr);
708
+ if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
709
+ bd->pd3dDevice->ClearRenderTargetView(vd->RTView, (float*)&clear_color);
710
+ ImGui_ImplDX10_RenderDrawData(viewport->DrawData);
711
+ }
712
+
713
+ static void ImGui_ImplDX10_SwapBuffers(ImGuiViewport* viewport, void*)
714
+ {
715
+ ImGui_ImplDX10_ViewportData* vd = (ImGui_ImplDX10_ViewportData*)viewport->RendererUserData;
716
+ vd->SwapChain->Present(0, 0); // Present without vsync
717
+ }
718
+
719
+ void ImGui_ImplDX10_InitMultiViewportSupport()
720
+ {
721
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
722
+ platform_io.Renderer_CreateWindow = ImGui_ImplDX10_CreateWindow;
723
+ platform_io.Renderer_DestroyWindow = ImGui_ImplDX10_DestroyWindow;
724
+ platform_io.Renderer_SetWindowSize = ImGui_ImplDX10_SetWindowSize;
725
+ platform_io.Renderer_RenderWindow = ImGui_ImplDX10_RenderViewport;
726
+ platform_io.Renderer_SwapBuffers = ImGui_ImplDX10_SwapBuffers;
727
+ }
728
+
729
+ void ImGui_ImplDX10_ShutdownMultiViewportSupport()
730
+ {
731
+ ImGui::DestroyPlatformWindows();
732
+ }
733
+
734
+ //-----------------------------------------------------------------------------
735
+
736
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_dx10.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for DirectX10
2
+ // This needs to be used along with a Platform Backend (e.g. Win32)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
8
+
9
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
10
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
11
+ // Learn about Dear ImGui:
12
+ // - FAQ https://dearimgui.com/faq
13
+ // - Getting Started https://dearimgui.com/getting-started
14
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
15
+ // - Introduction, links and more at the top of imgui.cpp
16
+
17
+ #pragma once
18
+ #include "imgui.h" // IMGUI_IMPL_API
19
+ #ifndef IMGUI_DISABLE
20
+
21
+ struct ID3D10Device;
22
+
23
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
24
+ IMGUI_IMPL_API bool ImGui_ImplDX10_Init(ID3D10Device* device);
25
+ IMGUI_IMPL_API void ImGui_ImplDX10_Shutdown();
26
+ IMGUI_IMPL_API void ImGui_ImplDX10_NewFrame();
27
+ IMGUI_IMPL_API void ImGui_ImplDX10_RenderDrawData(ImDrawData* draw_data);
28
+
29
+ // Use if you want to reset your rendering device without losing Dear ImGui state.
30
+ IMGUI_IMPL_API bool ImGui_ImplDX10_CreateDeviceObjects();
31
+ IMGUI_IMPL_API void ImGui_ImplDX10_InvalidateDeviceObjects();
32
+
33
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_dx11.cpp ADDED
@@ -0,0 +1,763 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for DirectX11
2
+ // This needs to be used along with a Platform Backend (e.g. Win32)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7
+ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
8
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
9
+
10
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
11
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
12
+ // Learn about Dear ImGui:
13
+ // - FAQ https://dearimgui.com/faq
14
+ // - Getting Started https://dearimgui.com/getting-started
15
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
16
+ // - Introduction, links and more at the top of imgui.cpp
17
+
18
+ // CHANGELOG
19
+ // (minor and older changes stripped away, please see git history for details)
20
+ // 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
21
+ // 2024-10-07: DirectX11: Changed default texture sampler to Clamp instead of Repeat/Wrap.
22
+ // 2024-10-07: DirectX11: Expose selected render state in ImGui_ImplDX11_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
23
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
24
+ // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
25
+ // 2021-05-19: DirectX11: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
26
+ // 2021-02-18: DirectX11: Change blending equation to preserve alpha in output buffer.
27
+ // 2019-08-01: DirectX11: Fixed code querying the Geometry Shader state (would generally error with Debug layer enabled).
28
+ // 2019-07-21: DirectX11: Backup, clear and restore Geometry Shader is any is bound when calling ImGui_ImplDX11_RenderDrawData. Clearing Hull/Domain/Compute shaders without backup/restore.
29
+ // 2019-05-29: DirectX11: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
30
+ // 2019-04-30: DirectX11: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
31
+ // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
32
+ // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
33
+ // 2018-08-01: DirectX11: Querying for IDXGIFactory instead of IDXGIFactory1 to increase compatibility.
34
+ // 2018-07-13: DirectX11: Fixed unreleased resources in Init and Shutdown functions.
35
+ // 2018-06-08: Misc: Extracted imgui_impl_dx11.cpp/.h away from the old combined DX11+Win32 example.
36
+ // 2018-06-08: DirectX11: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
37
+ // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself.
38
+ // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
39
+ // 2016-05-07: DirectX11: Disabling depth-write.
40
+
41
+ #include "imgui.h"
42
+ #ifndef IMGUI_DISABLE
43
+ #include "imgui_impl_dx11.h"
44
+
45
+ // DirectX
46
+ #include <stdio.h>
47
+ #include <d3d11.h>
48
+ #include <d3dcompiler.h>
49
+ #ifdef _MSC_VER
50
+ #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
51
+ #endif
52
+
53
+ // DirectX11 data
54
+ struct ImGui_ImplDX11_Data
55
+ {
56
+ ID3D11Device* pd3dDevice;
57
+ ID3D11DeviceContext* pd3dDeviceContext;
58
+ IDXGIFactory* pFactory;
59
+ ID3D11Buffer* pVB;
60
+ ID3D11Buffer* pIB;
61
+ ID3D11VertexShader* pVertexShader;
62
+ ID3D11InputLayout* pInputLayout;
63
+ ID3D11Buffer* pVertexConstantBuffer;
64
+ ID3D11PixelShader* pPixelShader;
65
+ ID3D11SamplerState* pFontSampler;
66
+ ID3D11ShaderResourceView* pFontTextureView;
67
+ ID3D11RasterizerState* pRasterizerState;
68
+ ID3D11BlendState* pBlendState;
69
+ ID3D11DepthStencilState* pDepthStencilState;
70
+ int VertexBufferSize;
71
+ int IndexBufferSize;
72
+
73
+ ImGui_ImplDX11_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
74
+ };
75
+
76
+ struct VERTEX_CONSTANT_BUFFER_DX11
77
+ {
78
+ float mvp[4][4];
79
+ };
80
+
81
+ // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
82
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
83
+ static ImGui_ImplDX11_Data* ImGui_ImplDX11_GetBackendData()
84
+ {
85
+ return ImGui::GetCurrentContext() ? (ImGui_ImplDX11_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
86
+ }
87
+
88
+ // Forward Declarations
89
+ static void ImGui_ImplDX11_InitMultiViewportSupport();
90
+ static void ImGui_ImplDX11_ShutdownMultiViewportSupport();
91
+
92
+ // Functions
93
+ static void ImGui_ImplDX11_SetupRenderState(ImDrawData* draw_data, ID3D11DeviceContext* device_ctx)
94
+ {
95
+ ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
96
+
97
+ // Setup viewport
98
+ D3D11_VIEWPORT vp;
99
+ memset(&vp, 0, sizeof(D3D11_VIEWPORT));
100
+ vp.Width = draw_data->DisplaySize.x;
101
+ vp.Height = draw_data->DisplaySize.y;
102
+ vp.MinDepth = 0.0f;
103
+ vp.MaxDepth = 1.0f;
104
+ vp.TopLeftX = vp.TopLeftY = 0;
105
+ device_ctx->RSSetViewports(1, &vp);
106
+
107
+ // Setup shader and vertex buffers
108
+ unsigned int stride = sizeof(ImDrawVert);
109
+ unsigned int offset = 0;
110
+ device_ctx->IASetInputLayout(bd->pInputLayout);
111
+ device_ctx->IASetVertexBuffers(0, 1, &bd->pVB, &stride, &offset);
112
+ device_ctx->IASetIndexBuffer(bd->pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
113
+ device_ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
114
+ device_ctx->VSSetShader(bd->pVertexShader, nullptr, 0);
115
+ device_ctx->VSSetConstantBuffers(0, 1, &bd->pVertexConstantBuffer);
116
+ device_ctx->PSSetShader(bd->pPixelShader, nullptr, 0);
117
+ device_ctx->PSSetSamplers(0, 1, &bd->pFontSampler);
118
+ device_ctx->GSSetShader(nullptr, nullptr, 0);
119
+ device_ctx->HSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
120
+ device_ctx->DSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
121
+ device_ctx->CSSetShader(nullptr, nullptr, 0); // In theory we should backup and restore this as well.. very infrequently used..
122
+
123
+ // Setup blend state
124
+ const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
125
+ device_ctx->OMSetBlendState(bd->pBlendState, blend_factor, 0xffffffff);
126
+ device_ctx->OMSetDepthStencilState(bd->pDepthStencilState, 0);
127
+ device_ctx->RSSetState(bd->pRasterizerState);
128
+ }
129
+
130
+ // Render function
131
+ void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data)
132
+ {
133
+ // Avoid rendering when minimized
134
+ if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
135
+ return;
136
+
137
+ ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
138
+ ID3D11DeviceContext* device = bd->pd3dDeviceContext;
139
+
140
+ // Create and grow vertex/index buffers if needed
141
+ if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
142
+ {
143
+ if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
144
+ bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
145
+ D3D11_BUFFER_DESC desc;
146
+ memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
147
+ desc.Usage = D3D11_USAGE_DYNAMIC;
148
+ desc.ByteWidth = bd->VertexBufferSize * sizeof(ImDrawVert);
149
+ desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
150
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
151
+ desc.MiscFlags = 0;
152
+ if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVB) < 0)
153
+ return;
154
+ }
155
+ if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
156
+ {
157
+ if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
158
+ bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
159
+ D3D11_BUFFER_DESC desc;
160
+ memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
161
+ desc.Usage = D3D11_USAGE_DYNAMIC;
162
+ desc.ByteWidth = bd->IndexBufferSize * sizeof(ImDrawIdx);
163
+ desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
164
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
165
+ if (bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pIB) < 0)
166
+ return;
167
+ }
168
+
169
+ // Upload vertex/index data into a single contiguous GPU buffer
170
+ D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
171
+ if (device->Map(bd->pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
172
+ return;
173
+ if (device->Map(bd->pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
174
+ return;
175
+ ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
176
+ ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
177
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
178
+ {
179
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
180
+ memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
181
+ memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
182
+ vtx_dst += draw_list->VtxBuffer.Size;
183
+ idx_dst += draw_list->IdxBuffer.Size;
184
+ }
185
+ device->Unmap(bd->pVB, 0);
186
+ device->Unmap(bd->pIB, 0);
187
+
188
+ // Setup orthographic projection matrix into our constant buffer
189
+ // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
190
+ {
191
+ D3D11_MAPPED_SUBRESOURCE mapped_resource;
192
+ if (device->Map(bd->pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
193
+ return;
194
+ VERTEX_CONSTANT_BUFFER_DX11* constant_buffer = (VERTEX_CONSTANT_BUFFER_DX11*)mapped_resource.pData;
195
+ float L = draw_data->DisplayPos.x;
196
+ float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
197
+ float T = draw_data->DisplayPos.y;
198
+ float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
199
+ float mvp[4][4] =
200
+ {
201
+ { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
202
+ { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
203
+ { 0.0f, 0.0f, 0.5f, 0.0f },
204
+ { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
205
+ };
206
+ memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
207
+ device->Unmap(bd->pVertexConstantBuffer, 0);
208
+ }
209
+
210
+ // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
211
+ struct BACKUP_DX11_STATE
212
+ {
213
+ UINT ScissorRectsCount, ViewportsCount;
214
+ D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
215
+ D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
216
+ ID3D11RasterizerState* RS;
217
+ ID3D11BlendState* BlendState;
218
+ FLOAT BlendFactor[4];
219
+ UINT SampleMask;
220
+ UINT StencilRef;
221
+ ID3D11DepthStencilState* DepthStencilState;
222
+ ID3D11ShaderResourceView* PSShaderResource;
223
+ ID3D11SamplerState* PSSampler;
224
+ ID3D11PixelShader* PS;
225
+ ID3D11VertexShader* VS;
226
+ ID3D11GeometryShader* GS;
227
+ UINT PSInstancesCount, VSInstancesCount, GSInstancesCount;
228
+ ID3D11ClassInstance *PSInstances[256], *VSInstances[256], *GSInstances[256]; // 256 is max according to PSSetShader documentation
229
+ D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
230
+ ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
231
+ UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
232
+ DXGI_FORMAT IndexBufferFormat;
233
+ ID3D11InputLayout* InputLayout;
234
+ };
235
+ BACKUP_DX11_STATE old = {};
236
+ old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
237
+ device->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
238
+ device->RSGetViewports(&old.ViewportsCount, old.Viewports);
239
+ device->RSGetState(&old.RS);
240
+ device->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
241
+ device->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
242
+ device->PSGetShaderResources(0, 1, &old.PSShaderResource);
243
+ device->PSGetSamplers(0, 1, &old.PSSampler);
244
+ old.PSInstancesCount = old.VSInstancesCount = old.GSInstancesCount = 256;
245
+ device->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
246
+ device->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
247
+ device->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
248
+ device->GSGetShader(&old.GS, old.GSInstances, &old.GSInstancesCount);
249
+
250
+ device->IAGetPrimitiveTopology(&old.PrimitiveTopology);
251
+ device->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
252
+ device->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
253
+ device->IAGetInputLayout(&old.InputLayout);
254
+
255
+ // Setup desired DX state
256
+ ImGui_ImplDX11_SetupRenderState(draw_data, device);
257
+
258
+ // Setup render state structure (for callbacks and custom texture bindings)
259
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
260
+ ImGui_ImplDX11_RenderState render_state;
261
+ render_state.Device = bd->pd3dDevice;
262
+ render_state.DeviceContext = bd->pd3dDeviceContext;
263
+ render_state.SamplerDefault = bd->pFontSampler;
264
+ platform_io.Renderer_RenderState = &render_state;
265
+
266
+ // Render command lists
267
+ // (Because we merged all buffers into a single one, we maintain our own offset into them)
268
+ int global_idx_offset = 0;
269
+ int global_vtx_offset = 0;
270
+ ImVec2 clip_off = draw_data->DisplayPos;
271
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
272
+ {
273
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
274
+ for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
275
+ {
276
+ const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
277
+ if (pcmd->UserCallback != nullptr)
278
+ {
279
+ // User callback, registered via ImDrawList::AddCallback()
280
+ // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
281
+ if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
282
+ ImGui_ImplDX11_SetupRenderState(draw_data, device);
283
+ else
284
+ pcmd->UserCallback(draw_list, pcmd);
285
+ }
286
+ else
287
+ {
288
+ // Project scissor/clipping rectangles into framebuffer space
289
+ ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
290
+ ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
291
+ if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
292
+ continue;
293
+
294
+ // Apply scissor/clipping rectangle
295
+ const D3D11_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
296
+ device->RSSetScissorRects(1, &r);
297
+
298
+ // Bind texture, Draw
299
+ ID3D11ShaderResourceView* texture_srv = (ID3D11ShaderResourceView*)pcmd->GetTexID();
300
+ device->PSSetShaderResources(0, 1, &texture_srv);
301
+ device->DrawIndexed(pcmd->ElemCount, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset);
302
+ }
303
+ }
304
+ global_idx_offset += draw_list->IdxBuffer.Size;
305
+ global_vtx_offset += draw_list->VtxBuffer.Size;
306
+ }
307
+ platform_io.Renderer_RenderState = nullptr;
308
+
309
+ // Restore modified DX state
310
+ device->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
311
+ device->RSSetViewports(old.ViewportsCount, old.Viewports);
312
+ device->RSSetState(old.RS); if (old.RS) old.RS->Release();
313
+ device->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
314
+ device->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
315
+ device->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
316
+ device->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
317
+ device->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
318
+ for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
319
+ device->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
320
+ device->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
321
+ device->GSSetShader(old.GS, old.GSInstances, old.GSInstancesCount); if (old.GS) old.GS->Release();
322
+ for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
323
+ device->IASetPrimitiveTopology(old.PrimitiveTopology);
324
+ device->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
325
+ device->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
326
+ device->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
327
+ }
328
+
329
+ static void ImGui_ImplDX11_CreateFontsTexture()
330
+ {
331
+ // Build texture atlas
332
+ ImGuiIO& io = ImGui::GetIO();
333
+ ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
334
+ unsigned char* pixels;
335
+ int width, height;
336
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
337
+
338
+ // Upload texture to graphics system
339
+ {
340
+ D3D11_TEXTURE2D_DESC desc;
341
+ ZeroMemory(&desc, sizeof(desc));
342
+ desc.Width = width;
343
+ desc.Height = height;
344
+ desc.MipLevels = 1;
345
+ desc.ArraySize = 1;
346
+ desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
347
+ desc.SampleDesc.Count = 1;
348
+ desc.Usage = D3D11_USAGE_DEFAULT;
349
+ desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
350
+ desc.CPUAccessFlags = 0;
351
+
352
+ ID3D11Texture2D* pTexture = nullptr;
353
+ D3D11_SUBRESOURCE_DATA subResource;
354
+ subResource.pSysMem = pixels;
355
+ subResource.SysMemPitch = desc.Width * 4;
356
+ subResource.SysMemSlicePitch = 0;
357
+ bd->pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture);
358
+ IM_ASSERT(pTexture != nullptr);
359
+
360
+ // Create texture view
361
+ D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
362
+ ZeroMemory(&srvDesc, sizeof(srvDesc));
363
+ srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
364
+ srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
365
+ srvDesc.Texture2D.MipLevels = desc.MipLevels;
366
+ srvDesc.Texture2D.MostDetailedMip = 0;
367
+ bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &bd->pFontTextureView);
368
+ pTexture->Release();
369
+ }
370
+
371
+ // Store our identifier
372
+ io.Fonts->SetTexID((ImTextureID)bd->pFontTextureView);
373
+ }
374
+
375
+ static void ImGui_ImplDX11_DestroyFontsTexture()
376
+ {
377
+ ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
378
+ if (bd->pFontTextureView)
379
+ {
380
+ bd->pFontTextureView->Release();
381
+ bd->pFontTextureView = nullptr;
382
+ ImGui::GetIO().Fonts->SetTexID(0); // We copied data->pFontTextureView to io.Fonts->TexID so let's clear that as well.
383
+ }
384
+ }
385
+
386
+ bool ImGui_ImplDX11_CreateDeviceObjects()
387
+ {
388
+ ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
389
+ if (!bd->pd3dDevice)
390
+ return false;
391
+ if (bd->pFontSampler)
392
+ ImGui_ImplDX11_InvalidateDeviceObjects();
393
+
394
+ // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
395
+ // If you would like to use this DX11 sample code but remove this dependency you can:
396
+ // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution]
397
+ // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
398
+ // See https://github.com/ocornut/imgui/pull/638 for sources and details.
399
+
400
+ // Create the vertex shader
401
+ {
402
+ static const char* vertexShader =
403
+ "cbuffer vertexBuffer : register(b0) \
404
+ {\
405
+ float4x4 ProjectionMatrix; \
406
+ };\
407
+ struct VS_INPUT\
408
+ {\
409
+ float2 pos : POSITION;\
410
+ float4 col : COLOR0;\
411
+ float2 uv : TEXCOORD0;\
412
+ };\
413
+ \
414
+ struct PS_INPUT\
415
+ {\
416
+ float4 pos : SV_POSITION;\
417
+ float4 col : COLOR0;\
418
+ float2 uv : TEXCOORD0;\
419
+ };\
420
+ \
421
+ PS_INPUT main(VS_INPUT input)\
422
+ {\
423
+ PS_INPUT output;\
424
+ output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
425
+ output.col = input.col;\
426
+ output.uv = input.uv;\
427
+ return output;\
428
+ }";
429
+
430
+ ID3DBlob* vertexShaderBlob;
431
+ if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr)))
432
+ return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
433
+ if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), nullptr, &bd->pVertexShader) != S_OK)
434
+ {
435
+ vertexShaderBlob->Release();
436
+ return false;
437
+ }
438
+
439
+ // Create the input layout
440
+ D3D11_INPUT_ELEMENT_DESC local_layout[] =
441
+ {
442
+ { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
443
+ { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
444
+ { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
445
+ };
446
+ if (bd->pd3dDevice->CreateInputLayout(local_layout, 3, vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), &bd->pInputLayout) != S_OK)
447
+ {
448
+ vertexShaderBlob->Release();
449
+ return false;
450
+ }
451
+ vertexShaderBlob->Release();
452
+
453
+ // Create the constant buffer
454
+ {
455
+ D3D11_BUFFER_DESC desc;
456
+ desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER_DX11);
457
+ desc.Usage = D3D11_USAGE_DYNAMIC;
458
+ desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
459
+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
460
+ desc.MiscFlags = 0;
461
+ bd->pd3dDevice->CreateBuffer(&desc, nullptr, &bd->pVertexConstantBuffer);
462
+ }
463
+ }
464
+
465
+ // Create the pixel shader
466
+ {
467
+ static const char* pixelShader =
468
+ "struct PS_INPUT\
469
+ {\
470
+ float4 pos : SV_POSITION;\
471
+ float4 col : COLOR0;\
472
+ float2 uv : TEXCOORD0;\
473
+ };\
474
+ sampler sampler0;\
475
+ Texture2D texture0;\
476
+ \
477
+ float4 main(PS_INPUT input) : SV_Target\
478
+ {\
479
+ float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
480
+ return out_col; \
481
+ }";
482
+
483
+ ID3DBlob* pixelShaderBlob;
484
+ if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr)))
485
+ return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
486
+ if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), nullptr, &bd->pPixelShader) != S_OK)
487
+ {
488
+ pixelShaderBlob->Release();
489
+ return false;
490
+ }
491
+ pixelShaderBlob->Release();
492
+ }
493
+
494
+ // Create the blending setup
495
+ {
496
+ D3D11_BLEND_DESC desc;
497
+ ZeroMemory(&desc, sizeof(desc));
498
+ desc.AlphaToCoverageEnable = false;
499
+ desc.RenderTarget[0].BlendEnable = true;
500
+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
501
+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
502
+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
503
+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
504
+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
505
+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
506
+ desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
507
+ bd->pd3dDevice->CreateBlendState(&desc, &bd->pBlendState);
508
+ }
509
+
510
+ // Create the rasterizer state
511
+ {
512
+ D3D11_RASTERIZER_DESC desc;
513
+ ZeroMemory(&desc, sizeof(desc));
514
+ desc.FillMode = D3D11_FILL_SOLID;
515
+ desc.CullMode = D3D11_CULL_NONE;
516
+ desc.ScissorEnable = true;
517
+ desc.DepthClipEnable = true;
518
+ bd->pd3dDevice->CreateRasterizerState(&desc, &bd->pRasterizerState);
519
+ }
520
+
521
+ // Create depth-stencil State
522
+ {
523
+ D3D11_DEPTH_STENCIL_DESC desc;
524
+ ZeroMemory(&desc, sizeof(desc));
525
+ desc.DepthEnable = false;
526
+ desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
527
+ desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
528
+ desc.StencilEnable = false;
529
+ desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
530
+ desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
531
+ desc.BackFace = desc.FrontFace;
532
+ bd->pd3dDevice->CreateDepthStencilState(&desc, &bd->pDepthStencilState);
533
+ }
534
+
535
+ // Create texture sampler
536
+ // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
537
+ {
538
+ D3D11_SAMPLER_DESC desc;
539
+ ZeroMemory(&desc, sizeof(desc));
540
+ desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
541
+ desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
542
+ desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
543
+ desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
544
+ desc.MipLODBias = 0.f;
545
+ desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
546
+ desc.MinLOD = 0.f;
547
+ desc.MaxLOD = 0.f;
548
+ bd->pd3dDevice->CreateSamplerState(&desc, &bd->pFontSampler);
549
+ }
550
+
551
+ ImGui_ImplDX11_CreateFontsTexture();
552
+
553
+ return true;
554
+ }
555
+
556
+ void ImGui_ImplDX11_InvalidateDeviceObjects()
557
+ {
558
+ ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
559
+ if (!bd->pd3dDevice)
560
+ return;
561
+
562
+ ImGui_ImplDX11_DestroyFontsTexture();
563
+
564
+ if (bd->pFontSampler) { bd->pFontSampler->Release(); bd->pFontSampler = nullptr; }
565
+ if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
566
+ if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
567
+ if (bd->pBlendState) { bd->pBlendState->Release(); bd->pBlendState = nullptr; }
568
+ if (bd->pDepthStencilState) { bd->pDepthStencilState->Release(); bd->pDepthStencilState = nullptr; }
569
+ if (bd->pRasterizerState) { bd->pRasterizerState->Release(); bd->pRasterizerState = nullptr; }
570
+ if (bd->pPixelShader) { bd->pPixelShader->Release(); bd->pPixelShader = nullptr; }
571
+ if (bd->pVertexConstantBuffer) { bd->pVertexConstantBuffer->Release(); bd->pVertexConstantBuffer = nullptr; }
572
+ if (bd->pInputLayout) { bd->pInputLayout->Release(); bd->pInputLayout = nullptr; }
573
+ if (bd->pVertexShader) { bd->pVertexShader->Release(); bd->pVertexShader = nullptr; }
574
+ }
575
+
576
+ bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context)
577
+ {
578
+ ImGuiIO& io = ImGui::GetIO();
579
+ IMGUI_CHECKVERSION();
580
+ IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
581
+
582
+ // Setup backend capabilities flags
583
+ ImGui_ImplDX11_Data* bd = IM_NEW(ImGui_ImplDX11_Data)();
584
+ io.BackendRendererUserData = (void*)bd;
585
+ io.BackendRendererName = "imgui_impl_dx11";
586
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
587
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
588
+
589
+ // Get factory from device
590
+ IDXGIDevice* pDXGIDevice = nullptr;
591
+ IDXGIAdapter* pDXGIAdapter = nullptr;
592
+ IDXGIFactory* pFactory = nullptr;
593
+
594
+ if (device->QueryInterface(IID_PPV_ARGS(&pDXGIDevice)) == S_OK)
595
+ if (pDXGIDevice->GetParent(IID_PPV_ARGS(&pDXGIAdapter)) == S_OK)
596
+ if (pDXGIAdapter->GetParent(IID_PPV_ARGS(&pFactory)) == S_OK)
597
+ {
598
+ bd->pd3dDevice = device;
599
+ bd->pd3dDeviceContext = device_context;
600
+ bd->pFactory = pFactory;
601
+ }
602
+ if (pDXGIDevice) pDXGIDevice->Release();
603
+ if (pDXGIAdapter) pDXGIAdapter->Release();
604
+ bd->pd3dDevice->AddRef();
605
+ bd->pd3dDeviceContext->AddRef();
606
+
607
+ ImGui_ImplDX11_InitMultiViewportSupport();
608
+
609
+ return true;
610
+ }
611
+
612
+ void ImGui_ImplDX11_Shutdown()
613
+ {
614
+ ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
615
+ IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
616
+ ImGuiIO& io = ImGui::GetIO();
617
+
618
+ ImGui_ImplDX11_ShutdownMultiViewportSupport();
619
+ ImGui_ImplDX11_InvalidateDeviceObjects();
620
+ if (bd->pFactory) { bd->pFactory->Release(); }
621
+ if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
622
+ if (bd->pd3dDeviceContext) { bd->pd3dDeviceContext->Release(); }
623
+ io.BackendRendererName = nullptr;
624
+ io.BackendRendererUserData = nullptr;
625
+ io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
626
+ IM_DELETE(bd);
627
+ }
628
+
629
+ void ImGui_ImplDX11_NewFrame()
630
+ {
631
+ ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
632
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX11_Init()?");
633
+
634
+ if (!bd->pFontSampler)
635
+ ImGui_ImplDX11_CreateDeviceObjects();
636
+ }
637
+
638
+ //--------------------------------------------------------------------------------------------------------
639
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
640
+ // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
641
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
642
+ //--------------------------------------------------------------------------------------------------------
643
+
644
+ // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
645
+ struct ImGui_ImplDX11_ViewportData
646
+ {
647
+ IDXGISwapChain* SwapChain;
648
+ ID3D11RenderTargetView* RTView;
649
+
650
+ ImGui_ImplDX11_ViewportData() { SwapChain = nullptr; RTView = nullptr; }
651
+ ~ImGui_ImplDX11_ViewportData() { IM_ASSERT(SwapChain == nullptr && RTView == nullptr); }
652
+ };
653
+
654
+ static void ImGui_ImplDX11_CreateWindow(ImGuiViewport* viewport)
655
+ {
656
+ ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
657
+ ImGui_ImplDX11_ViewportData* vd = IM_NEW(ImGui_ImplDX11_ViewportData)();
658
+ viewport->RendererUserData = vd;
659
+
660
+ // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
661
+ // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
662
+ HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
663
+ IM_ASSERT(hwnd != 0);
664
+
665
+ // Create swap chain
666
+ DXGI_SWAP_CHAIN_DESC sd;
667
+ ZeroMemory(&sd, sizeof(sd));
668
+ sd.BufferDesc.Width = (UINT)viewport->Size.x;
669
+ sd.BufferDesc.Height = (UINT)viewport->Size.y;
670
+ sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
671
+ sd.SampleDesc.Count = 1;
672
+ sd.SampleDesc.Quality = 0;
673
+ sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
674
+ sd.BufferCount = 1;
675
+ sd.OutputWindow = hwnd;
676
+ sd.Windowed = TRUE;
677
+ sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
678
+ sd.Flags = 0;
679
+
680
+ IM_ASSERT(vd->SwapChain == nullptr && vd->RTView == nullptr);
681
+ bd->pFactory->CreateSwapChain(bd->pd3dDevice, &sd, &vd->SwapChain);
682
+
683
+ // Create the render target
684
+ if (vd->SwapChain)
685
+ {
686
+ ID3D11Texture2D* pBackBuffer;
687
+ vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
688
+ bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
689
+ pBackBuffer->Release();
690
+ }
691
+ }
692
+
693
+ static void ImGui_ImplDX11_DestroyWindow(ImGuiViewport* viewport)
694
+ {
695
+ // The main viewport (owned by the application) will always have RendererUserData == nullptr since we didn't create the data for it.
696
+ if (ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData)
697
+ {
698
+ if (vd->SwapChain)
699
+ vd->SwapChain->Release();
700
+ vd->SwapChain = nullptr;
701
+ if (vd->RTView)
702
+ vd->RTView->Release();
703
+ vd->RTView = nullptr;
704
+ IM_DELETE(vd);
705
+ }
706
+ viewport->RendererUserData = nullptr;
707
+ }
708
+
709
+ static void ImGui_ImplDX11_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
710
+ {
711
+ ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
712
+ ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData;
713
+ if (vd->RTView)
714
+ {
715
+ vd->RTView->Release();
716
+ vd->RTView = nullptr;
717
+ }
718
+ if (vd->SwapChain)
719
+ {
720
+ ID3D11Texture2D* pBackBuffer = nullptr;
721
+ vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
722
+ vd->SwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
723
+ if (pBackBuffer == nullptr) { fprintf(stderr, "ImGui_ImplDX11_SetWindowSize() failed creating buffers.\n"); return; }
724
+ bd->pd3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, &vd->RTView);
725
+ pBackBuffer->Release();
726
+ }
727
+ }
728
+
729
+ static void ImGui_ImplDX11_RenderWindow(ImGuiViewport* viewport, void*)
730
+ {
731
+ ImGui_ImplDX11_Data* bd = ImGui_ImplDX11_GetBackendData();
732
+ ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData;
733
+ ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
734
+ bd->pd3dDeviceContext->OMSetRenderTargets(1, &vd->RTView, nullptr);
735
+ if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
736
+ bd->pd3dDeviceContext->ClearRenderTargetView(vd->RTView, (float*)&clear_color);
737
+ ImGui_ImplDX11_RenderDrawData(viewport->DrawData);
738
+ }
739
+
740
+ static void ImGui_ImplDX11_SwapBuffers(ImGuiViewport* viewport, void*)
741
+ {
742
+ ImGui_ImplDX11_ViewportData* vd = (ImGui_ImplDX11_ViewportData*)viewport->RendererUserData;
743
+ vd->SwapChain->Present(0, 0); // Present without vsync
744
+ }
745
+
746
+ static void ImGui_ImplDX11_InitMultiViewportSupport()
747
+ {
748
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
749
+ platform_io.Renderer_CreateWindow = ImGui_ImplDX11_CreateWindow;
750
+ platform_io.Renderer_DestroyWindow = ImGui_ImplDX11_DestroyWindow;
751
+ platform_io.Renderer_SetWindowSize = ImGui_ImplDX11_SetWindowSize;
752
+ platform_io.Renderer_RenderWindow = ImGui_ImplDX11_RenderWindow;
753
+ platform_io.Renderer_SwapBuffers = ImGui_ImplDX11_SwapBuffers;
754
+ }
755
+
756
+ static void ImGui_ImplDX11_ShutdownMultiViewportSupport()
757
+ {
758
+ ImGui::DestroyPlatformWindows();
759
+ }
760
+
761
+ //-----------------------------------------------------------------------------
762
+
763
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_dx11.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for DirectX11
2
+ // This needs to be used along with a Platform Backend (e.g. Win32)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7
+ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
8
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
9
+
10
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
11
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
12
+ // Learn about Dear ImGui:
13
+ // - FAQ https://dearimgui.com/faq
14
+ // - Getting Started https://dearimgui.com/getting-started
15
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
16
+ // - Introduction, links and more at the top of imgui.cpp
17
+
18
+ #pragma once
19
+ #include "imgui.h" // IMGUI_IMPL_API
20
+ #ifndef IMGUI_DISABLE
21
+
22
+ struct ID3D11Device;
23
+ struct ID3D11DeviceContext;
24
+ struct ID3D11SamplerState;
25
+
26
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
27
+ IMGUI_IMPL_API bool ImGui_ImplDX11_Init(ID3D11Device* device, ID3D11DeviceContext* device_context);
28
+ IMGUI_IMPL_API void ImGui_ImplDX11_Shutdown();
29
+ IMGUI_IMPL_API void ImGui_ImplDX11_NewFrame();
30
+ IMGUI_IMPL_API void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data);
31
+
32
+ // Use if you want to reset your rendering device without losing Dear ImGui state.
33
+ IMGUI_IMPL_API bool ImGui_ImplDX11_CreateDeviceObjects();
34
+ IMGUI_IMPL_API void ImGui_ImplDX11_InvalidateDeviceObjects();
35
+
36
+ // [BETA] Selected render state data shared with callbacks.
37
+ // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX11_RenderDrawData() call.
38
+ // (Please open an issue if you feel you need access to more data)
39
+ struct ImGui_ImplDX11_RenderState
40
+ {
41
+ ID3D11Device* Device;
42
+ ID3D11DeviceContext* DeviceContext;
43
+ ID3D11SamplerState* SamplerDefault;
44
+ };
45
+
46
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_dx12.cpp ADDED
@@ -0,0 +1,1157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for DirectX12
2
+ // This needs to be used along with a Platform Backend (e.g. Win32)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7
+ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
8
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
9
+ // FIXME: The transition from removing a viewport and moving the window in an existing hosted viewport tends to flicker.
10
+
11
+ // The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
12
+ // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
13
+
14
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
15
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
16
+ // Learn about Dear ImGui:
17
+ // - FAQ https://dearimgui.com/faq
18
+ // - Getting Started https://dearimgui.com/getting-started
19
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
20
+ // - Introduction, links and more at the top of imgui.cpp
21
+
22
+ // CHANGELOG
23
+ // (minor and older changes stripped away, please see git history for details)
24
+ // 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
25
+ // 2024-12-09: DirectX12: Let user specifies the DepthStencilView format by setting ImGui_ImplDX12_InitInfo::DSVFormat.
26
+ // 2024-11-15: DirectX12: *BREAKING CHANGE* Changed ImGui_ImplDX12_Init() signature to take a ImGui_ImplDX12_InitInfo struct. Legacy ImGui_ImplDX12_Init() signature is still supported (will obsolete).
27
+ // 2024-11-15: DirectX12: *BREAKING CHANGE* User is now required to pass function pointers to allocate/free SRV Descriptors. We provide convenience legacy fields to pass a single descriptor, matching the old API, but upcoming features will want multiple.
28
+ // 2024-10-23: DirectX12: Unmap() call specify written range. The range is informational and may be used by debug tools.
29
+ // 2024-10-07: DirectX12: Changed default texture sampler to Clamp instead of Repeat/Wrap.
30
+ // 2024-10-07: DirectX12: Expose selected render state in ImGui_ImplDX12_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
31
+ // 2024-10-07: DirectX12: Compiling with '#define ImTextureID=ImU64' is unnecessary now that dear imgui defaults ImTextureID to u64 instead of void*.
32
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
33
+ // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
34
+ // 2021-05-19: DirectX12: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
35
+ // 2021-02-18: DirectX12: Change blending equation to preserve alpha in output buffer.
36
+ // 2021-01-11: DirectX12: Improve Windows 7 compatibility (for D3D12On7) by loading d3d12.dll dynamically.
37
+ // 2020-09-16: DirectX12: Avoid rendering calls with zero-sized scissor rectangle since it generates a validation layer warning.
38
+ // 2020-09-08: DirectX12: Clarified support for building on 32-bit systems by redefining ImTextureID.
39
+ // 2019-10-18: DirectX12: *BREAKING CHANGE* Added extra ID3D12DescriptorHeap parameter to ImGui_ImplDX12_Init() function.
40
+ // 2019-05-29: DirectX12: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
41
+ // 2019-04-30: DirectX12: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
42
+ // 2019-03-29: Misc: Various minor tidying up.
43
+ // 2018-12-03: Misc: Added #pragma comment statement to automatically link with d3dcompiler.lib when using D3DCompile().
44
+ // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
45
+ // 2018-06-12: DirectX12: Moved the ID3D12GraphicsCommandList* parameter from NewFrame() to RenderDrawData().
46
+ // 2018-06-08: Misc: Extracted imgui_impl_dx12.cpp/.h away from the old combined DX12+Win32 example.
47
+ // 2018-06-08: DirectX12: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle (to ease support for future multi-viewport).
48
+ // 2018-02-22: Merged into master with all Win32 code synchronized to other examples.
49
+
50
+ #include "imgui.h"
51
+ #ifndef IMGUI_DISABLE
52
+ #include "imgui_impl_dx12.h"
53
+
54
+ // DirectX
55
+ #include <d3d12.h>
56
+ #include <dxgi1_4.h>
57
+ #include <d3dcompiler.h>
58
+ #ifdef _MSC_VER
59
+ #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
60
+ #endif
61
+
62
+ // DirectX12 data
63
+ struct ImGui_ImplDX12_RenderBuffers;
64
+
65
+ struct ImGui_ImplDX12_Texture
66
+ {
67
+ ID3D12Resource* pTextureResource;
68
+ D3D12_CPU_DESCRIPTOR_HANDLE hFontSrvCpuDescHandle;
69
+ D3D12_GPU_DESCRIPTOR_HANDLE hFontSrvGpuDescHandle;
70
+
71
+ ImGui_ImplDX12_Texture() { memset((void*)this, 0, sizeof(*this)); }
72
+ };
73
+
74
+ struct ImGui_ImplDX12_Data
75
+ {
76
+ ImGui_ImplDX12_InitInfo InitInfo;
77
+ ID3D12Device* pd3dDevice;
78
+ ID3D12RootSignature* pRootSignature;
79
+ ID3D12PipelineState* pPipelineState;
80
+ DXGI_FORMAT RTVFormat;
81
+ DXGI_FORMAT DSVFormat;
82
+ ID3D12DescriptorHeap* pd3dSrvDescHeap;
83
+ UINT numFramesInFlight;
84
+ ImGui_ImplDX12_Texture FontTexture;
85
+ bool LegacySingleDescriptorUsed;
86
+
87
+ ImGui_ImplDX12_Data() { memset((void*)this, 0, sizeof(*this)); }
88
+ };
89
+
90
+ // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
91
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
92
+ static ImGui_ImplDX12_Data* ImGui_ImplDX12_GetBackendData()
93
+ {
94
+ return ImGui::GetCurrentContext() ? (ImGui_ImplDX12_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
95
+ }
96
+
97
+ // Buffers used during the rendering of a frame
98
+ struct ImGui_ImplDX12_RenderBuffers
99
+ {
100
+ ID3D12Resource* IndexBuffer;
101
+ ID3D12Resource* VertexBuffer;
102
+ int IndexBufferSize;
103
+ int VertexBufferSize;
104
+ };
105
+
106
+ // Buffers used for secondary viewports created by the multi-viewports systems
107
+ struct ImGui_ImplDX12_FrameContext
108
+ {
109
+ ID3D12CommandAllocator* CommandAllocator;
110
+ ID3D12Resource* RenderTarget;
111
+ D3D12_CPU_DESCRIPTOR_HANDLE RenderTargetCpuDescriptors;
112
+ };
113
+
114
+ // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
115
+ // Main viewport created by application will only use the Resources field.
116
+ // Secondary viewports created by this backend will use all the fields (including Window fields),
117
+ struct ImGui_ImplDX12_ViewportData
118
+ {
119
+ // Window
120
+ ID3D12CommandQueue* CommandQueue;
121
+ ID3D12GraphicsCommandList* CommandList;
122
+ ID3D12DescriptorHeap* RtvDescHeap;
123
+ IDXGISwapChain3* SwapChain;
124
+ ID3D12Fence* Fence;
125
+ UINT64 FenceSignaledValue;
126
+ HANDLE FenceEvent;
127
+ UINT NumFramesInFlight;
128
+ ImGui_ImplDX12_FrameContext* FrameCtx;
129
+
130
+ // Render buffers
131
+ UINT FrameIndex;
132
+ ImGui_ImplDX12_RenderBuffers* FrameRenderBuffers;
133
+
134
+ ImGui_ImplDX12_ViewportData(UINT num_frames_in_flight)
135
+ {
136
+ CommandQueue = nullptr;
137
+ CommandList = nullptr;
138
+ RtvDescHeap = nullptr;
139
+ SwapChain = nullptr;
140
+ Fence = nullptr;
141
+ FenceSignaledValue = 0;
142
+ FenceEvent = nullptr;
143
+ NumFramesInFlight = num_frames_in_flight;
144
+ FrameCtx = new ImGui_ImplDX12_FrameContext[NumFramesInFlight];
145
+ FrameIndex = UINT_MAX;
146
+ FrameRenderBuffers = new ImGui_ImplDX12_RenderBuffers[NumFramesInFlight];
147
+
148
+ for (UINT i = 0; i < NumFramesInFlight; ++i)
149
+ {
150
+ FrameCtx[i].CommandAllocator = nullptr;
151
+ FrameCtx[i].RenderTarget = nullptr;
152
+
153
+ // Create buffers with a default size (they will later be grown as needed)
154
+ FrameRenderBuffers[i].IndexBuffer = nullptr;
155
+ FrameRenderBuffers[i].VertexBuffer = nullptr;
156
+ FrameRenderBuffers[i].VertexBufferSize = 5000;
157
+ FrameRenderBuffers[i].IndexBufferSize = 10000;
158
+ }
159
+ }
160
+ ~ImGui_ImplDX12_ViewportData()
161
+ {
162
+ IM_ASSERT(CommandQueue == nullptr && CommandList == nullptr);
163
+ IM_ASSERT(RtvDescHeap == nullptr);
164
+ IM_ASSERT(SwapChain == nullptr);
165
+ IM_ASSERT(Fence == nullptr);
166
+ IM_ASSERT(FenceEvent == nullptr);
167
+
168
+ for (UINT i = 0; i < NumFramesInFlight; ++i)
169
+ {
170
+ IM_ASSERT(FrameCtx[i].CommandAllocator == nullptr && FrameCtx[i].RenderTarget == nullptr);
171
+ IM_ASSERT(FrameRenderBuffers[i].IndexBuffer == nullptr && FrameRenderBuffers[i].VertexBuffer == nullptr);
172
+ }
173
+
174
+ delete[] FrameCtx; FrameCtx = nullptr;
175
+ delete[] FrameRenderBuffers; FrameRenderBuffers = nullptr;
176
+ }
177
+ };
178
+
179
+ struct VERTEX_CONSTANT_BUFFER_DX12
180
+ {
181
+ float mvp[4][4];
182
+ };
183
+
184
+ // Forward Declarations
185
+ static void ImGui_ImplDX12_InitPlatformInterface();
186
+ static void ImGui_ImplDX12_ShutdownPlatformInterface();
187
+
188
+ // Functions
189
+ static void ImGui_ImplDX12_SetupRenderState(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list, ImGui_ImplDX12_RenderBuffers* fr)
190
+ {
191
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
192
+
193
+ // Setup orthographic projection matrix into our constant buffer
194
+ // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
195
+ VERTEX_CONSTANT_BUFFER_DX12 vertex_constant_buffer;
196
+ {
197
+ float L = draw_data->DisplayPos.x;
198
+ float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
199
+ float T = draw_data->DisplayPos.y;
200
+ float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
201
+ float mvp[4][4] =
202
+ {
203
+ { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
204
+ { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
205
+ { 0.0f, 0.0f, 0.5f, 0.0f },
206
+ { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
207
+ };
208
+ memcpy(&vertex_constant_buffer.mvp, mvp, sizeof(mvp));
209
+ }
210
+
211
+ // Setup viewport
212
+ D3D12_VIEWPORT vp;
213
+ memset(&vp, 0, sizeof(D3D12_VIEWPORT));
214
+ vp.Width = draw_data->DisplaySize.x;
215
+ vp.Height = draw_data->DisplaySize.y;
216
+ vp.MinDepth = 0.0f;
217
+ vp.MaxDepth = 1.0f;
218
+ vp.TopLeftX = vp.TopLeftY = 0.0f;
219
+ command_list->RSSetViewports(1, &vp);
220
+
221
+ // Bind shader and vertex buffers
222
+ unsigned int stride = sizeof(ImDrawVert);
223
+ unsigned int offset = 0;
224
+ D3D12_VERTEX_BUFFER_VIEW vbv;
225
+ memset(&vbv, 0, sizeof(D3D12_VERTEX_BUFFER_VIEW));
226
+ vbv.BufferLocation = fr->VertexBuffer->GetGPUVirtualAddress() + offset;
227
+ vbv.SizeInBytes = fr->VertexBufferSize * stride;
228
+ vbv.StrideInBytes = stride;
229
+ command_list->IASetVertexBuffers(0, 1, &vbv);
230
+ D3D12_INDEX_BUFFER_VIEW ibv;
231
+ memset(&ibv, 0, sizeof(D3D12_INDEX_BUFFER_VIEW));
232
+ ibv.BufferLocation = fr->IndexBuffer->GetGPUVirtualAddress();
233
+ ibv.SizeInBytes = fr->IndexBufferSize * sizeof(ImDrawIdx);
234
+ ibv.Format = sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT;
235
+ command_list->IASetIndexBuffer(&ibv);
236
+ command_list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
237
+ command_list->SetPipelineState(bd->pPipelineState);
238
+ command_list->SetGraphicsRootSignature(bd->pRootSignature);
239
+ command_list->SetGraphicsRoot32BitConstants(0, 16, &vertex_constant_buffer, 0);
240
+
241
+ // Setup blend factor
242
+ const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
243
+ command_list->OMSetBlendFactor(blend_factor);
244
+ }
245
+
246
+ template<typename T>
247
+ static inline void SafeRelease(T*& res)
248
+ {
249
+ if (res)
250
+ res->Release();
251
+ res = nullptr;
252
+ }
253
+
254
+ // Render function
255
+ void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* command_list)
256
+ {
257
+ // Avoid rendering when minimized
258
+ if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
259
+ return;
260
+
261
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
262
+ ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)draw_data->OwnerViewport->RendererUserData;
263
+ vd->FrameIndex++;
264
+ ImGui_ImplDX12_RenderBuffers* fr = &vd->FrameRenderBuffers[vd->FrameIndex % bd->numFramesInFlight];
265
+
266
+ // Create and grow vertex/index buffers if needed
267
+ if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
268
+ {
269
+ SafeRelease(fr->VertexBuffer);
270
+ fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
271
+ D3D12_HEAP_PROPERTIES props;
272
+ memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
273
+ props.Type = D3D12_HEAP_TYPE_UPLOAD;
274
+ props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
275
+ props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
276
+ D3D12_RESOURCE_DESC desc;
277
+ memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
278
+ desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
279
+ desc.Width = fr->VertexBufferSize * sizeof(ImDrawVert);
280
+ desc.Height = 1;
281
+ desc.DepthOrArraySize = 1;
282
+ desc.MipLevels = 1;
283
+ desc.Format = DXGI_FORMAT_UNKNOWN;
284
+ desc.SampleDesc.Count = 1;
285
+ desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
286
+ desc.Flags = D3D12_RESOURCE_FLAG_NONE;
287
+ if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->VertexBuffer)) < 0)
288
+ return;
289
+ }
290
+ if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
291
+ {
292
+ SafeRelease(fr->IndexBuffer);
293
+ fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
294
+ D3D12_HEAP_PROPERTIES props;
295
+ memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
296
+ props.Type = D3D12_HEAP_TYPE_UPLOAD;
297
+ props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
298
+ props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
299
+ D3D12_RESOURCE_DESC desc;
300
+ memset(&desc, 0, sizeof(D3D12_RESOURCE_DESC));
301
+ desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
302
+ desc.Width = fr->IndexBufferSize * sizeof(ImDrawIdx);
303
+ desc.Height = 1;
304
+ desc.DepthOrArraySize = 1;
305
+ desc.MipLevels = 1;
306
+ desc.Format = DXGI_FORMAT_UNKNOWN;
307
+ desc.SampleDesc.Count = 1;
308
+ desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
309
+ desc.Flags = D3D12_RESOURCE_FLAG_NONE;
310
+ if (bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&fr->IndexBuffer)) < 0)
311
+ return;
312
+ }
313
+
314
+ // Upload vertex/index data into a single contiguous GPU buffer
315
+ // During Map() we specify a null read range (as per DX12 API, this is informational and for tooling only)
316
+ void* vtx_resource, *idx_resource;
317
+ D3D12_RANGE range = { 0, 0 };
318
+ if (fr->VertexBuffer->Map(0, &range, &vtx_resource) != S_OK)
319
+ return;
320
+ if (fr->IndexBuffer->Map(0, &range, &idx_resource) != S_OK)
321
+ return;
322
+ ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource;
323
+ ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource;
324
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
325
+ {
326
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
327
+ memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
328
+ memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
329
+ vtx_dst += draw_list->VtxBuffer.Size;
330
+ idx_dst += draw_list->IdxBuffer.Size;
331
+ }
332
+
333
+ // During Unmap() we specify the written range (as per DX12 API, this is informational and for tooling only)
334
+ range.End = (SIZE_T)((intptr_t)vtx_dst - (intptr_t)vtx_resource);
335
+ IM_ASSERT(range.End == draw_data->TotalVtxCount * sizeof(ImDrawVert));
336
+ fr->VertexBuffer->Unmap(0, &range);
337
+ range.End = (SIZE_T)((intptr_t)idx_dst - (intptr_t)idx_resource);
338
+ IM_ASSERT(range.End == draw_data->TotalIdxCount * sizeof(ImDrawIdx));
339
+ fr->IndexBuffer->Unmap(0, &range);
340
+
341
+ // Setup desired DX state
342
+ ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
343
+
344
+ // Setup render state structure (for callbacks and custom texture bindings)
345
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
346
+ ImGui_ImplDX12_RenderState render_state;
347
+ render_state.Device = bd->pd3dDevice;
348
+ render_state.CommandList = command_list;
349
+ platform_io.Renderer_RenderState = &render_state;
350
+
351
+ // Render command lists
352
+ // (Because we merged all buffers into a single one, we maintain our own offset into them)
353
+ int global_vtx_offset = 0;
354
+ int global_idx_offset = 0;
355
+ ImVec2 clip_off = draw_data->DisplayPos;
356
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
357
+ {
358
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
359
+ for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
360
+ {
361
+ const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
362
+ if (pcmd->UserCallback != nullptr)
363
+ {
364
+ // User callback, registered via ImDrawList::AddCallback()
365
+ // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
366
+ if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
367
+ ImGui_ImplDX12_SetupRenderState(draw_data, command_list, fr);
368
+ else
369
+ pcmd->UserCallback(draw_list, pcmd);
370
+ }
371
+ else
372
+ {
373
+ // Project scissor/clipping rectangles into framebuffer space
374
+ ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
375
+ ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
376
+ if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
377
+ continue;
378
+
379
+ // Apply scissor/clipping rectangle
380
+ const D3D12_RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
381
+ command_list->RSSetScissorRects(1, &r);
382
+
383
+ // Bind texture, Draw
384
+ D3D12_GPU_DESCRIPTOR_HANDLE texture_handle = {};
385
+ texture_handle.ptr = (UINT64)pcmd->GetTexID();
386
+ command_list->SetGraphicsRootDescriptorTable(1, texture_handle);
387
+ command_list->DrawIndexedInstanced(pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
388
+ }
389
+ }
390
+ global_idx_offset += draw_list->IdxBuffer.Size;
391
+ global_vtx_offset += draw_list->VtxBuffer.Size;
392
+ }
393
+ platform_io.Renderer_RenderState = nullptr;
394
+ }
395
+
396
+ static void ImGui_ImplDX12_CreateFontsTexture()
397
+ {
398
+ // Build texture atlas
399
+ ImGuiIO& io = ImGui::GetIO();
400
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
401
+ unsigned char* pixels;
402
+ int width, height;
403
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
404
+
405
+ // Upload texture to graphics system
406
+ ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture;
407
+ {
408
+ D3D12_HEAP_PROPERTIES props;
409
+ memset(&props, 0, sizeof(D3D12_HEAP_PROPERTIES));
410
+ props.Type = D3D12_HEAP_TYPE_DEFAULT;
411
+ props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
412
+ props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
413
+
414
+ D3D12_RESOURCE_DESC desc;
415
+ ZeroMemory(&desc, sizeof(desc));
416
+ desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
417
+ desc.Alignment = 0;
418
+ desc.Width = width;
419
+ desc.Height = height;
420
+ desc.DepthOrArraySize = 1;
421
+ desc.MipLevels = 1;
422
+ desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
423
+ desc.SampleDesc.Count = 1;
424
+ desc.SampleDesc.Quality = 0;
425
+ desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
426
+ desc.Flags = D3D12_RESOURCE_FLAG_NONE;
427
+
428
+ ID3D12Resource* pTexture = nullptr;
429
+ bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
430
+ D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pTexture));
431
+
432
+ UINT uploadPitch = (width * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1u);
433
+ UINT uploadSize = height * uploadPitch;
434
+ desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
435
+ desc.Alignment = 0;
436
+ desc.Width = uploadSize;
437
+ desc.Height = 1;
438
+ desc.DepthOrArraySize = 1;
439
+ desc.MipLevels = 1;
440
+ desc.Format = DXGI_FORMAT_UNKNOWN;
441
+ desc.SampleDesc.Count = 1;
442
+ desc.SampleDesc.Quality = 0;
443
+ desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
444
+ desc.Flags = D3D12_RESOURCE_FLAG_NONE;
445
+
446
+ props.Type = D3D12_HEAP_TYPE_UPLOAD;
447
+ props.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
448
+ props.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
449
+
450
+ ID3D12Resource* uploadBuffer = nullptr;
451
+ HRESULT hr = bd->pd3dDevice->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc,
452
+ D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&uploadBuffer));
453
+ IM_ASSERT(SUCCEEDED(hr));
454
+
455
+ void* mapped = nullptr;
456
+ D3D12_RANGE range = { 0, uploadSize };
457
+ hr = uploadBuffer->Map(0, &range, &mapped);
458
+ IM_ASSERT(SUCCEEDED(hr));
459
+ for (int y = 0; y < height; y++)
460
+ memcpy((void*) ((uintptr_t) mapped + y * uploadPitch), pixels + y * width * 4, width * 4);
461
+ uploadBuffer->Unmap(0, &range);
462
+
463
+ D3D12_TEXTURE_COPY_LOCATION srcLocation = {};
464
+ srcLocation.pResource = uploadBuffer;
465
+ srcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
466
+ srcLocation.PlacedFootprint.Footprint.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
467
+ srcLocation.PlacedFootprint.Footprint.Width = width;
468
+ srcLocation.PlacedFootprint.Footprint.Height = height;
469
+ srcLocation.PlacedFootprint.Footprint.Depth = 1;
470
+ srcLocation.PlacedFootprint.Footprint.RowPitch = uploadPitch;
471
+
472
+ D3D12_TEXTURE_COPY_LOCATION dstLocation = {};
473
+ dstLocation.pResource = pTexture;
474
+ dstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
475
+ dstLocation.SubresourceIndex = 0;
476
+
477
+ D3D12_RESOURCE_BARRIER barrier = {};
478
+ barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
479
+ barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
480
+ barrier.Transition.pResource = pTexture;
481
+ barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
482
+ barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST;
483
+ barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
484
+
485
+ ID3D12Fence* fence = nullptr;
486
+ hr = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence));
487
+ IM_ASSERT(SUCCEEDED(hr));
488
+
489
+ HANDLE event = CreateEvent(0, 0, 0, 0);
490
+ IM_ASSERT(event != nullptr);
491
+
492
+ D3D12_COMMAND_QUEUE_DESC queueDesc = {};
493
+ queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
494
+ queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
495
+ queueDesc.NodeMask = 1;
496
+
497
+ ID3D12CommandQueue* cmdQueue = nullptr;
498
+ hr = bd->pd3dDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&cmdQueue));
499
+ IM_ASSERT(SUCCEEDED(hr));
500
+
501
+ ID3D12CommandAllocator* cmdAlloc = nullptr;
502
+ hr = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&cmdAlloc));
503
+ IM_ASSERT(SUCCEEDED(hr));
504
+
505
+ ID3D12GraphicsCommandList* cmdList = nullptr;
506
+ hr = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, cmdAlloc, nullptr, IID_PPV_ARGS(&cmdList));
507
+ IM_ASSERT(SUCCEEDED(hr));
508
+
509
+ cmdList->CopyTextureRegion(&dstLocation, 0, 0, 0, &srcLocation, nullptr);
510
+ cmdList->ResourceBarrier(1, &barrier);
511
+
512
+ hr = cmdList->Close();
513
+ IM_ASSERT(SUCCEEDED(hr));
514
+
515
+ cmdQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmdList);
516
+ hr = cmdQueue->Signal(fence, 1);
517
+ IM_ASSERT(SUCCEEDED(hr));
518
+
519
+ fence->SetEventOnCompletion(1, event);
520
+ WaitForSingleObject(event, INFINITE);
521
+
522
+ cmdList->Release();
523
+ cmdAlloc->Release();
524
+ cmdQueue->Release();
525
+ CloseHandle(event);
526
+ fence->Release();
527
+ uploadBuffer->Release();
528
+
529
+ // Create texture view
530
+ D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc;
531
+ ZeroMemory(&srvDesc, sizeof(srvDesc));
532
+ srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
533
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
534
+ srvDesc.Texture2D.MipLevels = desc.MipLevels;
535
+ srvDesc.Texture2D.MostDetailedMip = 0;
536
+ srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
537
+ bd->pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, font_tex->hFontSrvCpuDescHandle);
538
+ SafeRelease(font_tex->pTextureResource);
539
+ font_tex->pTextureResource = pTexture;
540
+ }
541
+
542
+ // Store our identifier
543
+ io.Fonts->SetTexID((ImTextureID)font_tex->hFontSrvGpuDescHandle.ptr);
544
+ }
545
+
546
+ bool ImGui_ImplDX12_CreateDeviceObjects()
547
+ {
548
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
549
+ if (!bd || !bd->pd3dDevice)
550
+ return false;
551
+ if (bd->pPipelineState)
552
+ ImGui_ImplDX12_InvalidateDeviceObjects();
553
+
554
+ // Create the root signature
555
+ {
556
+ D3D12_DESCRIPTOR_RANGE descRange = {};
557
+ descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
558
+ descRange.NumDescriptors = 1;
559
+ descRange.BaseShaderRegister = 0;
560
+ descRange.RegisterSpace = 0;
561
+ descRange.OffsetInDescriptorsFromTableStart = 0;
562
+
563
+ D3D12_ROOT_PARAMETER param[2] = {};
564
+
565
+ param[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
566
+ param[0].Constants.ShaderRegister = 0;
567
+ param[0].Constants.RegisterSpace = 0;
568
+ param[0].Constants.Num32BitValues = 16;
569
+ param[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
570
+
571
+ param[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
572
+ param[1].DescriptorTable.NumDescriptorRanges = 1;
573
+ param[1].DescriptorTable.pDescriptorRanges = &descRange;
574
+ param[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
575
+
576
+ // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
577
+ D3D12_STATIC_SAMPLER_DESC staticSampler = {};
578
+ staticSampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
579
+ staticSampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
580
+ staticSampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
581
+ staticSampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
582
+ staticSampler.MipLODBias = 0.f;
583
+ staticSampler.MaxAnisotropy = 0;
584
+ staticSampler.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS;
585
+ staticSampler.BorderColor = D3D12_STATIC_BORDER_COLOR_TRANSPARENT_BLACK;
586
+ staticSampler.MinLOD = 0.f;
587
+ staticSampler.MaxLOD = 0.f;
588
+ staticSampler.ShaderRegister = 0;
589
+ staticSampler.RegisterSpace = 0;
590
+ staticSampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
591
+
592
+ D3D12_ROOT_SIGNATURE_DESC desc = {};
593
+ desc.NumParameters = _countof(param);
594
+ desc.pParameters = param;
595
+ desc.NumStaticSamplers = 1;
596
+ desc.pStaticSamplers = &staticSampler;
597
+ desc.Flags =
598
+ D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT |
599
+ D3D12_ROOT_SIGNATURE_FLAG_DENY_HULL_SHADER_ROOT_ACCESS |
600
+ D3D12_ROOT_SIGNATURE_FLAG_DENY_DOMAIN_SHADER_ROOT_ACCESS |
601
+ D3D12_ROOT_SIGNATURE_FLAG_DENY_GEOMETRY_SHADER_ROOT_ACCESS;
602
+
603
+ // Load d3d12.dll and D3D12SerializeRootSignature() function address dynamically to facilitate using with D3D12On7.
604
+ // See if any version of d3d12.dll is already loaded in the process. If so, give preference to that.
605
+ static HINSTANCE d3d12_dll = ::GetModuleHandleA("d3d12.dll");
606
+ if (d3d12_dll == nullptr)
607
+ {
608
+ // Attempt to load d3d12.dll from local directories. This will only succeed if
609
+ // (1) the current OS is Windows 7, and
610
+ // (2) there exists a version of d3d12.dll for Windows 7 (D3D12On7) in one of the following directories.
611
+ // See https://github.com/ocornut/imgui/pull/3696 for details.
612
+ const char* localD3d12Paths[] = { ".\\d3d12.dll", ".\\d3d12on7\\d3d12.dll", ".\\12on7\\d3d12.dll" }; // A. current directory, B. used by some games, C. used in Microsoft D3D12On7 sample
613
+ for (int i = 0; i < IM_ARRAYSIZE(localD3d12Paths); i++)
614
+ if ((d3d12_dll = ::LoadLibraryA(localD3d12Paths[i])) != nullptr)
615
+ break;
616
+
617
+ // If failed, we are on Windows >= 10.
618
+ if (d3d12_dll == nullptr)
619
+ d3d12_dll = ::LoadLibraryA("d3d12.dll");
620
+
621
+ if (d3d12_dll == nullptr)
622
+ return false;
623
+ }
624
+
625
+ PFN_D3D12_SERIALIZE_ROOT_SIGNATURE D3D12SerializeRootSignatureFn = (PFN_D3D12_SERIALIZE_ROOT_SIGNATURE)::GetProcAddress(d3d12_dll, "D3D12SerializeRootSignature");
626
+ if (D3D12SerializeRootSignatureFn == nullptr)
627
+ return false;
628
+
629
+ ID3DBlob* blob = nullptr;
630
+ if (D3D12SerializeRootSignatureFn(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr) != S_OK)
631
+ return false;
632
+
633
+ bd->pd3dDevice->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&bd->pRootSignature));
634
+ blob->Release();
635
+ }
636
+
637
+ // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
638
+ // If you would like to use this DX12 sample code but remove this dependency you can:
639
+ // 1) compile once, save the compiled shader blobs into a file or source code and assign them to psoDesc.VS/PS [preferred solution]
640
+ // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
641
+ // See https://github.com/ocornut/imgui/pull/638 for sources and details.
642
+
643
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
644
+ memset(&psoDesc, 0, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
645
+ psoDesc.NodeMask = 1;
646
+ psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
647
+ psoDesc.pRootSignature = bd->pRootSignature;
648
+ psoDesc.SampleMask = UINT_MAX;
649
+ psoDesc.NumRenderTargets = 1;
650
+ psoDesc.RTVFormats[0] = bd->RTVFormat;
651
+ psoDesc.DSVFormat = bd->DSVFormat;
652
+ psoDesc.SampleDesc.Count = 1;
653
+ psoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
654
+
655
+ ID3DBlob* vertexShaderBlob;
656
+ ID3DBlob* pixelShaderBlob;
657
+
658
+ // Create the vertex shader
659
+ {
660
+ static const char* vertexShader =
661
+ "cbuffer vertexBuffer : register(b0) \
662
+ {\
663
+ float4x4 ProjectionMatrix; \
664
+ };\
665
+ struct VS_INPUT\
666
+ {\
667
+ float2 pos : POSITION;\
668
+ float4 col : COLOR0;\
669
+ float2 uv : TEXCOORD0;\
670
+ };\
671
+ \
672
+ struct PS_INPUT\
673
+ {\
674
+ float4 pos : SV_POSITION;\
675
+ float4 col : COLOR0;\
676
+ float2 uv : TEXCOORD0;\
677
+ };\
678
+ \
679
+ PS_INPUT main(VS_INPUT input)\
680
+ {\
681
+ PS_INPUT output;\
682
+ output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
683
+ output.col = input.col;\
684
+ output.uv = input.uv;\
685
+ return output;\
686
+ }";
687
+
688
+ if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_5_0", 0, 0, &vertexShaderBlob, nullptr)))
689
+ return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
690
+ psoDesc.VS = { vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize() };
691
+
692
+ // Create the input layout
693
+ static D3D12_INPUT_ELEMENT_DESC local_layout[] =
694
+ {
695
+ { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, pos), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
696
+ { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (UINT)offsetof(ImDrawVert, uv), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
697
+ { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (UINT)offsetof(ImDrawVert, col), D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
698
+ };
699
+ psoDesc.InputLayout = { local_layout, 3 };
700
+ }
701
+
702
+ // Create the pixel shader
703
+ {
704
+ static const char* pixelShader =
705
+ "struct PS_INPUT\
706
+ {\
707
+ float4 pos : SV_POSITION;\
708
+ float4 col : COLOR0;\
709
+ float2 uv : TEXCOORD0;\
710
+ };\
711
+ SamplerState sampler0 : register(s0);\
712
+ Texture2D texture0 : register(t0);\
713
+ \
714
+ float4 main(PS_INPUT input) : SV_Target\
715
+ {\
716
+ float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
717
+ return out_col; \
718
+ }";
719
+
720
+ if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_5_0", 0, 0, &pixelShaderBlob, nullptr)))
721
+ {
722
+ vertexShaderBlob->Release();
723
+ return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
724
+ }
725
+ psoDesc.PS = { pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize() };
726
+ }
727
+
728
+ // Create the blending setup
729
+ {
730
+ D3D12_BLEND_DESC& desc = psoDesc.BlendState;
731
+ desc.AlphaToCoverageEnable = false;
732
+ desc.RenderTarget[0].BlendEnable = true;
733
+ desc.RenderTarget[0].SrcBlend = D3D12_BLEND_SRC_ALPHA;
734
+ desc.RenderTarget[0].DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
735
+ desc.RenderTarget[0].BlendOp = D3D12_BLEND_OP_ADD;
736
+ desc.RenderTarget[0].SrcBlendAlpha = D3D12_BLEND_ONE;
737
+ desc.RenderTarget[0].DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
738
+ desc.RenderTarget[0].BlendOpAlpha = D3D12_BLEND_OP_ADD;
739
+ desc.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
740
+ }
741
+
742
+ // Create the rasterizer state
743
+ {
744
+ D3D12_RASTERIZER_DESC& desc = psoDesc.RasterizerState;
745
+ desc.FillMode = D3D12_FILL_MODE_SOLID;
746
+ desc.CullMode = D3D12_CULL_MODE_NONE;
747
+ desc.FrontCounterClockwise = FALSE;
748
+ desc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
749
+ desc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
750
+ desc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
751
+ desc.DepthClipEnable = true;
752
+ desc.MultisampleEnable = FALSE;
753
+ desc.AntialiasedLineEnable = FALSE;
754
+ desc.ForcedSampleCount = 0;
755
+ desc.ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF;
756
+ }
757
+
758
+ // Create depth-stencil State
759
+ {
760
+ D3D12_DEPTH_STENCIL_DESC& desc = psoDesc.DepthStencilState;
761
+ desc.DepthEnable = false;
762
+ desc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
763
+ desc.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS;
764
+ desc.StencilEnable = false;
765
+ desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D12_STENCIL_OP_KEEP;
766
+ desc.FrontFace.StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS;
767
+ desc.BackFace = desc.FrontFace;
768
+ }
769
+
770
+ HRESULT result_pipeline_state = bd->pd3dDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&bd->pPipelineState));
771
+ vertexShaderBlob->Release();
772
+ pixelShaderBlob->Release();
773
+ if (result_pipeline_state != S_OK)
774
+ return false;
775
+
776
+ ImGui_ImplDX12_CreateFontsTexture();
777
+
778
+ return true;
779
+ }
780
+
781
+ static void ImGui_ImplDX12_DestroyRenderBuffers(ImGui_ImplDX12_RenderBuffers* render_buffers)
782
+ {
783
+ SafeRelease(render_buffers->IndexBuffer);
784
+ SafeRelease(render_buffers->VertexBuffer);
785
+ render_buffers->IndexBufferSize = render_buffers->VertexBufferSize = 0;
786
+ }
787
+
788
+ void ImGui_ImplDX12_InvalidateDeviceObjects()
789
+ {
790
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
791
+ if (!bd || !bd->pd3dDevice)
792
+ return;
793
+
794
+ ImGuiIO& io = ImGui::GetIO();
795
+ SafeRelease(bd->pRootSignature);
796
+ SafeRelease(bd->pPipelineState);
797
+
798
+ // Free SRV descriptor used by texture
799
+ ImGui_ImplDX12_Texture* font_tex = &bd->FontTexture;
800
+ bd->InitInfo.SrvDescriptorFreeFn(&bd->InitInfo, font_tex->hFontSrvCpuDescHandle, font_tex->hFontSrvGpuDescHandle);
801
+ SafeRelease(font_tex->pTextureResource);
802
+ io.Fonts->SetTexID(0); // We copied bd->hFontSrvGpuDescHandle to io.Fonts->TexID so let's clear that as well.
803
+ }
804
+
805
+ bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* init_info)
806
+ {
807
+ ImGuiIO& io = ImGui::GetIO();
808
+ IMGUI_CHECKVERSION();
809
+ IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
810
+
811
+ // Setup backend capabilities flags
812
+ ImGui_ImplDX12_Data* bd = IM_NEW(ImGui_ImplDX12_Data)();
813
+ bd->InitInfo = *init_info; // Deep copy
814
+ init_info = &bd->InitInfo;
815
+
816
+ bd->pd3dDevice = init_info->Device;
817
+ bd->RTVFormat = init_info->RTVFormat;
818
+ bd->DSVFormat = init_info->DSVFormat;
819
+ bd->numFramesInFlight = init_info->NumFramesInFlight;
820
+ bd->pd3dSrvDescHeap = init_info->SrvDescriptorHeap;
821
+
822
+ io.BackendRendererUserData = (void*)bd;
823
+ io.BackendRendererName = "imgui_impl_dx12";
824
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
825
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
826
+ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
827
+ ImGui_ImplDX12_InitPlatformInterface();
828
+
829
+ // Create a dummy ImGui_ImplDX12_ViewportData holder for the main viewport,
830
+ // Since this is created and managed by the application, we will only use the ->Resources[] fields.
831
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
832
+ main_viewport->RendererUserData = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight);
833
+
834
+ #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
835
+ if (init_info->SrvDescriptorAllocFn == nullptr)
836
+ {
837
+ // Wrap legacy behavior of passing space for a single descriptor
838
+ IM_ASSERT(init_info->LegacySingleSrvCpuDescriptor.ptr != 0 && init_info->LegacySingleSrvGpuDescriptor.ptr != 0);
839
+ init_info->SrvDescriptorAllocFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_handle)
840
+ {
841
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
842
+ IM_ASSERT(bd->LegacySingleDescriptorUsed == false);
843
+ *out_cpu_handle = bd->InitInfo.LegacySingleSrvCpuDescriptor;
844
+ *out_gpu_handle = bd->InitInfo.LegacySingleSrvGpuDescriptor;
845
+ bd->LegacySingleDescriptorUsed = true;
846
+ };
847
+ init_info->SrvDescriptorFreeFn = [](ImGui_ImplDX12_InitInfo*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_GPU_DESCRIPTOR_HANDLE)
848
+ {
849
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
850
+ IM_ASSERT(bd->LegacySingleDescriptorUsed == true);
851
+ bd->LegacySingleDescriptorUsed = false;
852
+ };
853
+ }
854
+ #endif
855
+
856
+ // Allocate 1 SRV descriptor for the font texture
857
+ IM_ASSERT(init_info->SrvDescriptorAllocFn != nullptr && init_info->SrvDescriptorFreeFn != nullptr);
858
+ init_info->SrvDescriptorAllocFn(&bd->InitInfo, &bd->FontTexture.hFontSrvCpuDescHandle, &bd->FontTexture.hFontSrvGpuDescHandle);
859
+
860
+ return true;
861
+ }
862
+
863
+ #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
864
+ // Legacy initialization API Obsoleted in 1.91.5
865
+ // font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture, they must be in 'srv_descriptor_heap'
866
+ bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* srv_descriptor_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle)
867
+ {
868
+ ImGui_ImplDX12_InitInfo init_info;
869
+ init_info.Device = device;
870
+ init_info.NumFramesInFlight = num_frames_in_flight;
871
+ init_info.RTVFormat = rtv_format;
872
+ init_info.SrvDescriptorHeap = srv_descriptor_heap;
873
+ init_info.LegacySingleSrvCpuDescriptor = font_srv_cpu_desc_handle;
874
+ init_info.LegacySingleSrvGpuDescriptor = font_srv_gpu_desc_handle;;
875
+ return ImGui_ImplDX12_Init(&init_info);
876
+ }
877
+ #endif
878
+
879
+ void ImGui_ImplDX12_Shutdown()
880
+ {
881
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
882
+ IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
883
+ ImGuiIO& io = ImGui::GetIO();
884
+
885
+ // Manually delete main viewport render resources in-case we haven't initialized for viewports
886
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
887
+ if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)main_viewport->RendererUserData)
888
+ {
889
+ // We could just call ImGui_ImplDX12_DestroyWindow(main_viewport) as a convenience but that would be misleading since we only use data->Resources[]
890
+ for (UINT i = 0; i < bd->numFramesInFlight; i++)
891
+ ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
892
+ IM_DELETE(vd);
893
+ main_viewport->RendererUserData = nullptr;
894
+ }
895
+
896
+ // Clean up windows and device objects
897
+ ImGui_ImplDX12_ShutdownPlatformInterface();
898
+ ImGui_ImplDX12_InvalidateDeviceObjects();
899
+
900
+ io.BackendRendererName = nullptr;
901
+ io.BackendRendererUserData = nullptr;
902
+ io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
903
+ IM_DELETE(bd);
904
+ }
905
+
906
+ void ImGui_ImplDX12_NewFrame()
907
+ {
908
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
909
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX12_Init()?");
910
+
911
+ if (!bd->pPipelineState)
912
+ ImGui_ImplDX12_CreateDeviceObjects();
913
+ }
914
+
915
+ //--------------------------------------------------------------------------------------------------------
916
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
917
+ // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
918
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
919
+ //--------------------------------------------------------------------------------------------------------
920
+
921
+ static void ImGui_ImplDX12_CreateWindow(ImGuiViewport* viewport)
922
+ {
923
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
924
+ ImGui_ImplDX12_ViewportData* vd = IM_NEW(ImGui_ImplDX12_ViewportData)(bd->numFramesInFlight);
925
+ viewport->RendererUserData = vd;
926
+
927
+ // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
928
+ // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
929
+ HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
930
+ IM_ASSERT(hwnd != 0);
931
+
932
+ vd->FrameIndex = UINT_MAX;
933
+
934
+ // Create command queue.
935
+ D3D12_COMMAND_QUEUE_DESC queue_desc = {};
936
+ queue_desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
937
+ queue_desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
938
+
939
+ HRESULT res = S_OK;
940
+ res = bd->pd3dDevice->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&vd->CommandQueue));
941
+ IM_ASSERT(res == S_OK);
942
+
943
+ // Create command allocator.
944
+ for (UINT i = 0; i < bd->numFramesInFlight; ++i)
945
+ {
946
+ res = bd->pd3dDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&vd->FrameCtx[i].CommandAllocator));
947
+ IM_ASSERT(res == S_OK);
948
+ }
949
+
950
+ // Create command list.
951
+ res = bd->pd3dDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, vd->FrameCtx[0].CommandAllocator, nullptr, IID_PPV_ARGS(&vd->CommandList));
952
+ IM_ASSERT(res == S_OK);
953
+ vd->CommandList->Close();
954
+
955
+ // Create fence.
956
+ res = bd->pd3dDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&vd->Fence));
957
+ IM_ASSERT(res == S_OK);
958
+
959
+ vd->FenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
960
+ IM_ASSERT(vd->FenceEvent != nullptr);
961
+
962
+ // Create swap chain
963
+ // FIXME-VIEWPORT: May want to copy/inherit swap chain settings from the user/application.
964
+ DXGI_SWAP_CHAIN_DESC1 sd1;
965
+ ZeroMemory(&sd1, sizeof(sd1));
966
+ sd1.BufferCount = bd->numFramesInFlight;
967
+ sd1.Width = (UINT)viewport->Size.x;
968
+ sd1.Height = (UINT)viewport->Size.y;
969
+ sd1.Format = bd->RTVFormat;
970
+ sd1.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
971
+ sd1.SampleDesc.Count = 1;
972
+ sd1.SampleDesc.Quality = 0;
973
+ sd1.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
974
+ sd1.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
975
+ sd1.Scaling = DXGI_SCALING_NONE;
976
+ sd1.Stereo = FALSE;
977
+
978
+ IDXGIFactory4* dxgi_factory = nullptr;
979
+ res = ::CreateDXGIFactory1(IID_PPV_ARGS(&dxgi_factory));
980
+ IM_ASSERT(res == S_OK);
981
+
982
+ IDXGISwapChain1* swap_chain = nullptr;
983
+ res = dxgi_factory->CreateSwapChainForHwnd(vd->CommandQueue, hwnd, &sd1, nullptr, nullptr, &swap_chain);
984
+ IM_ASSERT(res == S_OK);
985
+
986
+ dxgi_factory->Release();
987
+
988
+ // Or swapChain.As(&mSwapChain)
989
+ IM_ASSERT(vd->SwapChain == nullptr);
990
+ swap_chain->QueryInterface(IID_PPV_ARGS(&vd->SwapChain));
991
+ swap_chain->Release();
992
+
993
+ // Create the render targets
994
+ if (vd->SwapChain)
995
+ {
996
+ D3D12_DESCRIPTOR_HEAP_DESC desc = {};
997
+ desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
998
+ desc.NumDescriptors = bd->numFramesInFlight;
999
+ desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
1000
+ desc.NodeMask = 1;
1001
+
1002
+ HRESULT hr = bd->pd3dDevice->CreateDescriptorHeap(&desc, IID_PPV_ARGS(&vd->RtvDescHeap));
1003
+ IM_ASSERT(hr == S_OK);
1004
+
1005
+ SIZE_T rtv_descriptor_size = bd->pd3dDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
1006
+ D3D12_CPU_DESCRIPTOR_HANDLE rtv_handle = vd->RtvDescHeap->GetCPUDescriptorHandleForHeapStart();
1007
+ for (UINT i = 0; i < bd->numFramesInFlight; i++)
1008
+ {
1009
+ vd->FrameCtx[i].RenderTargetCpuDescriptors = rtv_handle;
1010
+ rtv_handle.ptr += rtv_descriptor_size;
1011
+ }
1012
+
1013
+ ID3D12Resource* back_buffer;
1014
+ for (UINT i = 0; i < bd->numFramesInFlight; i++)
1015
+ {
1016
+ IM_ASSERT(vd->FrameCtx[i].RenderTarget == nullptr);
1017
+ vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer));
1018
+ bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors);
1019
+ vd->FrameCtx[i].RenderTarget = back_buffer;
1020
+ }
1021
+ }
1022
+
1023
+ for (UINT i = 0; i < bd->numFramesInFlight; i++)
1024
+ ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
1025
+ }
1026
+
1027
+ static void ImGui_WaitForPendingOperations(ImGui_ImplDX12_ViewportData* vd)
1028
+ {
1029
+ HRESULT hr = S_FALSE;
1030
+ if (vd && vd->CommandQueue && vd->Fence && vd->FenceEvent)
1031
+ {
1032
+ hr = vd->CommandQueue->Signal(vd->Fence, ++vd->FenceSignaledValue);
1033
+ IM_ASSERT(hr == S_OK);
1034
+ ::WaitForSingleObject(vd->FenceEvent, 0); // Reset any forgotten waits
1035
+ hr = vd->Fence->SetEventOnCompletion(vd->FenceSignaledValue, vd->FenceEvent);
1036
+ IM_ASSERT(hr == S_OK);
1037
+ ::WaitForSingleObject(vd->FenceEvent, INFINITE);
1038
+ }
1039
+ }
1040
+
1041
+ static void ImGui_ImplDX12_DestroyWindow(ImGuiViewport* viewport)
1042
+ {
1043
+ // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it.
1044
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
1045
+ if (ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData)
1046
+ {
1047
+ ImGui_WaitForPendingOperations(vd);
1048
+
1049
+ SafeRelease(vd->CommandQueue);
1050
+ SafeRelease(vd->CommandList);
1051
+ SafeRelease(vd->SwapChain);
1052
+ SafeRelease(vd->RtvDescHeap);
1053
+ SafeRelease(vd->Fence);
1054
+ ::CloseHandle(vd->FenceEvent);
1055
+ vd->FenceEvent = nullptr;
1056
+
1057
+ for (UINT i = 0; i < bd->numFramesInFlight; i++)
1058
+ {
1059
+ SafeRelease(vd->FrameCtx[i].RenderTarget);
1060
+ SafeRelease(vd->FrameCtx[i].CommandAllocator);
1061
+ ImGui_ImplDX12_DestroyRenderBuffers(&vd->FrameRenderBuffers[i]);
1062
+ }
1063
+ IM_DELETE(vd);
1064
+ }
1065
+ viewport->RendererUserData = nullptr;
1066
+ }
1067
+
1068
+ static void ImGui_ImplDX12_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
1069
+ {
1070
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
1071
+ ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
1072
+
1073
+ ImGui_WaitForPendingOperations(vd);
1074
+
1075
+ for (UINT i = 0; i < bd->numFramesInFlight; i++)
1076
+ SafeRelease(vd->FrameCtx[i].RenderTarget);
1077
+
1078
+ if (vd->SwapChain)
1079
+ {
1080
+ ID3D12Resource* back_buffer = nullptr;
1081
+ vd->SwapChain->ResizeBuffers(0, (UINT)size.x, (UINT)size.y, DXGI_FORMAT_UNKNOWN, 0);
1082
+ for (UINT i = 0; i < bd->numFramesInFlight; i++)
1083
+ {
1084
+ vd->SwapChain->GetBuffer(i, IID_PPV_ARGS(&back_buffer));
1085
+ bd->pd3dDevice->CreateRenderTargetView(back_buffer, nullptr, vd->FrameCtx[i].RenderTargetCpuDescriptors);
1086
+ vd->FrameCtx[i].RenderTarget = back_buffer;
1087
+ }
1088
+ }
1089
+ }
1090
+
1091
+ static void ImGui_ImplDX12_RenderWindow(ImGuiViewport* viewport, void*)
1092
+ {
1093
+ ImGui_ImplDX12_Data* bd = ImGui_ImplDX12_GetBackendData();
1094
+ ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
1095
+
1096
+ ImGui_ImplDX12_FrameContext* frame_context = &vd->FrameCtx[vd->FrameIndex % bd->numFramesInFlight];
1097
+ UINT back_buffer_idx = vd->SwapChain->GetCurrentBackBufferIndex();
1098
+
1099
+ const ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
1100
+ D3D12_RESOURCE_BARRIER barrier = {};
1101
+ barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
1102
+ barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
1103
+ barrier.Transition.pResource = vd->FrameCtx[back_buffer_idx].RenderTarget;
1104
+ barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
1105
+ barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_PRESENT;
1106
+ barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_RENDER_TARGET;
1107
+
1108
+ // Draw
1109
+ ID3D12GraphicsCommandList* cmd_list = vd->CommandList;
1110
+
1111
+ frame_context->CommandAllocator->Reset();
1112
+ cmd_list->Reset(frame_context->CommandAllocator, nullptr);
1113
+ cmd_list->ResourceBarrier(1, &barrier);
1114
+ cmd_list->OMSetRenderTargets(1, &vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, FALSE, nullptr);
1115
+ if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
1116
+ cmd_list->ClearRenderTargetView(vd->FrameCtx[back_buffer_idx].RenderTargetCpuDescriptors, (float*)&clear_color, 0, nullptr);
1117
+ cmd_list->SetDescriptorHeaps(1, &bd->pd3dSrvDescHeap);
1118
+
1119
+ ImGui_ImplDX12_RenderDrawData(viewport->DrawData, cmd_list);
1120
+
1121
+ barrier.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
1122
+ barrier.Transition.StateAfter = D3D12_RESOURCE_STATE_PRESENT;
1123
+ cmd_list->ResourceBarrier(1, &barrier);
1124
+ cmd_list->Close();
1125
+
1126
+ vd->CommandQueue->Wait(vd->Fence, vd->FenceSignaledValue);
1127
+ vd->CommandQueue->ExecuteCommandLists(1, (ID3D12CommandList* const*)&cmd_list);
1128
+ vd->CommandQueue->Signal(vd->Fence, ++vd->FenceSignaledValue);
1129
+ }
1130
+
1131
+ static void ImGui_ImplDX12_SwapBuffers(ImGuiViewport* viewport, void*)
1132
+ {
1133
+ ImGui_ImplDX12_ViewportData* vd = (ImGui_ImplDX12_ViewportData*)viewport->RendererUserData;
1134
+
1135
+ vd->SwapChain->Present(0, 0);
1136
+ while (vd->Fence->GetCompletedValue() < vd->FenceSignaledValue)
1137
+ ::SwitchToThread();
1138
+ }
1139
+
1140
+ void ImGui_ImplDX12_InitPlatformInterface()
1141
+ {
1142
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
1143
+ platform_io.Renderer_CreateWindow = ImGui_ImplDX12_CreateWindow;
1144
+ platform_io.Renderer_DestroyWindow = ImGui_ImplDX12_DestroyWindow;
1145
+ platform_io.Renderer_SetWindowSize = ImGui_ImplDX12_SetWindowSize;
1146
+ platform_io.Renderer_RenderWindow = ImGui_ImplDX12_RenderWindow;
1147
+ platform_io.Renderer_SwapBuffers = ImGui_ImplDX12_SwapBuffers;
1148
+ }
1149
+
1150
+ void ImGui_ImplDX12_ShutdownPlatformInterface()
1151
+ {
1152
+ ImGui::DestroyPlatformWindows();
1153
+ }
1154
+
1155
+ //-----------------------------------------------------------------------------
1156
+
1157
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_dx12.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for DirectX12
2
+ // This needs to be used along with a Platform Backend (e.g. Win32)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'D3D12_GPU_DESCRIPTOR_HANDLE' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7
+ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
8
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
9
+
10
+ // The aim of imgui_impl_dx12.h/.cpp is to be usable in your engine without any modification.
11
+ // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
12
+
13
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
14
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
15
+ // Learn about Dear ImGui:
16
+ // - FAQ https://dearimgui.com/faq
17
+ // - Getting Started https://dearimgui.com/getting-started
18
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
19
+ // - Introduction, links and more at the top of imgui.cpp
20
+
21
+ #pragma once
22
+ #include "imgui.h" // IMGUI_IMPL_API
23
+ #ifndef IMGUI_DISABLE
24
+ #include <dxgiformat.h> // DXGI_FORMAT
25
+ #include <d3d12.h> // D3D12_CPU_DESCRIPTOR_HANDLE
26
+
27
+ // Initialization data, for ImGui_ImplDX12_Init()
28
+ struct ImGui_ImplDX12_InitInfo
29
+ {
30
+ ID3D12Device* Device;
31
+ ID3D12CommandQueue* CommandQueue;
32
+ int NumFramesInFlight;
33
+ DXGI_FORMAT RTVFormat; // RenderTarget format.
34
+ DXGI_FORMAT DSVFormat; // DepthStencilView format.
35
+ void* UserData;
36
+
37
+ // Allocating SRV descriptors for textures is up to the application, so we provide callbacks.
38
+ // (current version of the backend will only allocate one descriptor, future versions will need to allocate more)
39
+ ID3D12DescriptorHeap* SrvDescriptorHeap;
40
+ void (*SrvDescriptorAllocFn)(ImGui_ImplDX12_InitInfo* info, D3D12_CPU_DESCRIPTOR_HANDLE* out_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE* out_gpu_desc_handle);
41
+ void (*SrvDescriptorFreeFn)(ImGui_ImplDX12_InitInfo* info, D3D12_CPU_DESCRIPTOR_HANDLE cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE gpu_desc_handle);
42
+ #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
43
+ D3D12_CPU_DESCRIPTOR_HANDLE LegacySingleSrvCpuDescriptor; // To facilitate transition from single descriptor to allocator callback, you may use those.
44
+ D3D12_GPU_DESCRIPTOR_HANDLE LegacySingleSrvGpuDescriptor;
45
+ #endif
46
+
47
+ ImGui_ImplDX12_InitInfo() { memset(this, 0, sizeof(*this)); }
48
+ };
49
+
50
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
51
+ IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ImGui_ImplDX12_InitInfo* info);
52
+ IMGUI_IMPL_API void ImGui_ImplDX12_Shutdown();
53
+ IMGUI_IMPL_API void ImGui_ImplDX12_NewFrame();
54
+ IMGUI_IMPL_API void ImGui_ImplDX12_RenderDrawData(ImDrawData* draw_data, ID3D12GraphicsCommandList* graphics_command_list);
55
+
56
+ #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
57
+ // Legacy initialization API Obsoleted in 1.91.5
58
+ // font_srv_cpu_desc_handle and font_srv_gpu_desc_handle are handles to a single SRV descriptor to use for the internal font texture, they must be in 'srv_descriptor_heap'
59
+ IMGUI_IMPL_API bool ImGui_ImplDX12_Init(ID3D12Device* device, int num_frames_in_flight, DXGI_FORMAT rtv_format, ID3D12DescriptorHeap* srv_descriptor_heap, D3D12_CPU_DESCRIPTOR_HANDLE font_srv_cpu_desc_handle, D3D12_GPU_DESCRIPTOR_HANDLE font_srv_gpu_desc_handle);
60
+ #endif
61
+
62
+ // Use if you want to reset your rendering device without losing Dear ImGui state.
63
+ IMGUI_IMPL_API bool ImGui_ImplDX12_CreateDeviceObjects();
64
+ IMGUI_IMPL_API void ImGui_ImplDX12_InvalidateDeviceObjects();
65
+
66
+ // [BETA] Selected render state data shared with callbacks.
67
+ // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplDX12_RenderDrawData() call.
68
+ // (Please open an issue if you feel you need access to more data)
69
+ struct ImGui_ImplDX12_RenderState
70
+ {
71
+ ID3D12Device* Device;
72
+ ID3D12GraphicsCommandList* CommandList;
73
+ };
74
+
75
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_dx9.cpp ADDED
@@ -0,0 +1,585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for DirectX9
2
+ // This needs to be used along with a Platform Backend (e.g. Win32)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7
+ // [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR support, as this is the optimal color encoding for DirectX9.
8
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
9
+
10
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
11
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
12
+ // Learn about Dear ImGui:
13
+ // - FAQ https://dearimgui.com/faq
14
+ // - Getting Started https://dearimgui.com/getting-started
15
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
16
+ // - Introduction, links and more at the top of imgui.cpp
17
+
18
+ // CHANGELOG
19
+ // (minor and older changes stripped away, please see git history for details)
20
+ // 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
21
+ // 2024-10-07: DirectX9: Changed default texture sampler to Clamp instead of Repeat/Wrap.
22
+ // 2024-02-12: DirectX9: Using RGBA format when supported by the driver to avoid CPU side conversion. (#6575)
23
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
24
+ // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
25
+ // 2021-06-25: DirectX9: Explicitly disable texture state stages after >= 1.
26
+ // 2021-05-19: DirectX9: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
27
+ // 2021-04-23: DirectX9: Explicitly setting up more graphics states to increase compatibility with unusual non-default states.
28
+ // 2021-03-18: DirectX9: Calling IDirect3DStateBlock9::Capture() after CreateStateBlock() as a workaround for state restoring issues (see #3857).
29
+ // 2021-03-03: DirectX9: Added support for IMGUI_USE_BGRA_PACKED_COLOR in user's imconfig file.
30
+ // 2021-02-18: DirectX9: Change blending equation to preserve alpha in output buffer.
31
+ // 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
32
+ // 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
33
+ // 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects().
34
+ // 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288.
35
+ // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
36
+ // 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example.
37
+ // 2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
38
+ // 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud.
39
+ // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself.
40
+ // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
41
+
42
+ #include "imgui.h"
43
+ #ifndef IMGUI_DISABLE
44
+ #include "imgui_impl_dx9.h"
45
+
46
+ // DirectX
47
+ #include <d3d9.h>
48
+
49
+ // DirectX data
50
+ struct ImGui_ImplDX9_Data
51
+ {
52
+ LPDIRECT3DDEVICE9 pd3dDevice;
53
+ LPDIRECT3DVERTEXBUFFER9 pVB;
54
+ LPDIRECT3DINDEXBUFFER9 pIB;
55
+ LPDIRECT3DTEXTURE9 FontTexture;
56
+ int VertexBufferSize;
57
+ int IndexBufferSize;
58
+ bool HasRgbaSupport;
59
+
60
+ ImGui_ImplDX9_Data() { memset((void*)this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
61
+ };
62
+
63
+ struct CUSTOMVERTEX
64
+ {
65
+ float pos[3];
66
+ D3DCOLOR col;
67
+ float uv[2];
68
+ };
69
+ #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
70
+
71
+ #ifdef IMGUI_USE_BGRA_PACKED_COLOR
72
+ #define IMGUI_COL_TO_DX9_ARGB(_COL) (_COL)
73
+ #else
74
+ #define IMGUI_COL_TO_DX9_ARGB(_COL) (((_COL) & 0xFF00FF00) | (((_COL) & 0xFF0000) >> 16) | (((_COL) & 0xFF) << 16))
75
+ #endif
76
+
77
+ // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
78
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
79
+ static ImGui_ImplDX9_Data* ImGui_ImplDX9_GetBackendData()
80
+ {
81
+ return ImGui::GetCurrentContext() ? (ImGui_ImplDX9_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
82
+ }
83
+
84
+ // Forward Declarations
85
+ static void ImGui_ImplDX9_InitMultiViewportSupport();
86
+ static void ImGui_ImplDX9_ShutdownMultiViewportSupport();
87
+ static void ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows();
88
+ static void ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows();
89
+
90
+ // Functions
91
+ static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data)
92
+ {
93
+ ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
94
+
95
+ // Setup viewport
96
+ D3DVIEWPORT9 vp;
97
+ vp.X = vp.Y = 0;
98
+ vp.Width = (DWORD)draw_data->DisplaySize.x;
99
+ vp.Height = (DWORD)draw_data->DisplaySize.y;
100
+ vp.MinZ = 0.0f;
101
+ vp.MaxZ = 1.0f;
102
+
103
+ LPDIRECT3DDEVICE9 device = bd->pd3dDevice;
104
+ device->SetViewport(&vp);
105
+
106
+ // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient), bilinear sampling.
107
+ device->SetPixelShader(nullptr);
108
+ device->SetVertexShader(nullptr);
109
+ device->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
110
+ device->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
111
+ device->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
112
+ device->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
113
+ device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
114
+ device->SetRenderState(D3DRS_ZENABLE, FALSE);
115
+ device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
116
+ device->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
117
+ device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
118
+ device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
119
+ device->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
120
+ device->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE);
121
+ device->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA);
122
+ device->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
123
+ device->SetRenderState(D3DRS_FOGENABLE, FALSE);
124
+ device->SetRenderState(D3DRS_RANGEFOGENABLE, FALSE);
125
+ device->SetRenderState(D3DRS_SPECULARENABLE, FALSE);
126
+ device->SetRenderState(D3DRS_STENCILENABLE, FALSE);
127
+ device->SetRenderState(D3DRS_CLIPPING, TRUE);
128
+ device->SetRenderState(D3DRS_LIGHTING, FALSE);
129
+ device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
130
+ device->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
131
+ device->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
132
+ device->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
133
+ device->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
134
+ device->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
135
+ device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
136
+ device->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
137
+ device->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
138
+ device->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
139
+ device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);
140
+ device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);
141
+
142
+ // Setup orthographic projection matrix
143
+ // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
144
+ // Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH()
145
+ {
146
+ float L = draw_data->DisplayPos.x + 0.5f;
147
+ float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f;
148
+ float T = draw_data->DisplayPos.y + 0.5f;
149
+ float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f;
150
+ D3DMATRIX mat_identity = { { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } } };
151
+ D3DMATRIX mat_projection =
152
+ { { {
153
+ 2.0f/(R-L), 0.0f, 0.0f, 0.0f,
154
+ 0.0f, 2.0f/(T-B), 0.0f, 0.0f,
155
+ 0.0f, 0.0f, 0.5f, 0.0f,
156
+ (L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f
157
+ } } };
158
+ device->SetTransform(D3DTS_WORLD, &mat_identity);
159
+ device->SetTransform(D3DTS_VIEW, &mat_identity);
160
+ device->SetTransform(D3DTS_PROJECTION, &mat_projection);
161
+ }
162
+ }
163
+
164
+ // Render function.
165
+ void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
166
+ {
167
+ // Avoid rendering when minimized
168
+ if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
169
+ return;
170
+
171
+ ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
172
+ LPDIRECT3DDEVICE9 device = bd->pd3dDevice;
173
+
174
+ // Create and grow buffers if needed
175
+ if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
176
+ {
177
+ if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
178
+ bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
179
+ if (device->CreateVertexBuffer(bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, nullptr) < 0)
180
+ return;
181
+ }
182
+ if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
183
+ {
184
+ if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
185
+ bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
186
+ if (device->CreateIndexBuffer(bd->IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &bd->pIB, nullptr) < 0)
187
+ return;
188
+ }
189
+
190
+ // Backup the DX9 state
191
+ IDirect3DStateBlock9* state_block = nullptr;
192
+ if (device->CreateStateBlock(D3DSBT_ALL, &state_block) < 0)
193
+ return;
194
+ if (state_block->Capture() < 0)
195
+ {
196
+ state_block->Release();
197
+ return;
198
+ }
199
+
200
+ // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to)
201
+ D3DMATRIX last_world, last_view, last_projection;
202
+ device->GetTransform(D3DTS_WORLD, &last_world);
203
+ device->GetTransform(D3DTS_VIEW, &last_view);
204
+ device->GetTransform(D3DTS_PROJECTION, &last_projection);
205
+
206
+ // Allocate buffers
207
+ CUSTOMVERTEX* vtx_dst;
208
+ ImDrawIdx* idx_dst;
209
+ if (bd->pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
210
+ {
211
+ state_block->Release();
212
+ return;
213
+ }
214
+ if (bd->pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
215
+ {
216
+ bd->pVB->Unlock();
217
+ state_block->Release();
218
+ return;
219
+ }
220
+
221
+ // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format.
222
+ // FIXME-OPT: This is a minor waste of resource, the ideal is to use imconfig.h and
223
+ // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR
224
+ // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }
225
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
226
+ {
227
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
228
+ const ImDrawVert* vtx_src = draw_list->VtxBuffer.Data;
229
+ for (int i = 0; i < draw_list->VtxBuffer.Size; i++)
230
+ {
231
+ vtx_dst->pos[0] = vtx_src->pos.x;
232
+ vtx_dst->pos[1] = vtx_src->pos.y;
233
+ vtx_dst->pos[2] = 0.0f;
234
+ vtx_dst->col = IMGUI_COL_TO_DX9_ARGB(vtx_src->col);
235
+ vtx_dst->uv[0] = vtx_src->uv.x;
236
+ vtx_dst->uv[1] = vtx_src->uv.y;
237
+ vtx_dst++;
238
+ vtx_src++;
239
+ }
240
+ memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
241
+ idx_dst += draw_list->IdxBuffer.Size;
242
+ }
243
+ bd->pVB->Unlock();
244
+ bd->pIB->Unlock();
245
+ device->SetStreamSource(0, bd->pVB, 0, sizeof(CUSTOMVERTEX));
246
+ device->SetIndices(bd->pIB);
247
+ device->SetFVF(D3DFVF_CUSTOMVERTEX);
248
+
249
+ // Setup desired DX state
250
+ ImGui_ImplDX9_SetupRenderState(draw_data);
251
+
252
+ // Render command lists
253
+ // (Because we merged all buffers into a single one, we maintain our own offset into them)
254
+ int global_vtx_offset = 0;
255
+ int global_idx_offset = 0;
256
+ ImVec2 clip_off = draw_data->DisplayPos;
257
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
258
+ {
259
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
260
+ for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
261
+ {
262
+ const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
263
+ if (pcmd->UserCallback != nullptr)
264
+ {
265
+ // User callback, registered via ImDrawList::AddCallback()
266
+ // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
267
+ if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
268
+ ImGui_ImplDX9_SetupRenderState(draw_data);
269
+ else
270
+ pcmd->UserCallback(draw_list, pcmd);
271
+ }
272
+ else
273
+ {
274
+ // Project scissor/clipping rectangles into framebuffer space
275
+ ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
276
+ ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
277
+ if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
278
+ continue;
279
+
280
+ // Apply scissor/clipping rectangle
281
+ const RECT r = { (LONG)clip_min.x, (LONG)clip_min.y, (LONG)clip_max.x, (LONG)clip_max.y };
282
+ device->SetScissorRect(&r);
283
+
284
+ // Bind texture, Draw
285
+ const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->GetTexID();
286
+ device->SetTexture(0, texture);
287
+ device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)draw_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3);
288
+ }
289
+ }
290
+ global_idx_offset += draw_list->IdxBuffer.Size;
291
+ global_vtx_offset += draw_list->VtxBuffer.Size;
292
+ }
293
+
294
+ // When using multi-viewports, it appears that there's an odd logic in DirectX9 which prevent subsequent windows
295
+ // from rendering until the first window submits at least one draw call, even once. That's our workaround. (see #2560)
296
+ if (global_vtx_offset == 0)
297
+ bd->pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 0, 0, 0);
298
+
299
+ // Restore the DX9 transform
300
+ device->SetTransform(D3DTS_WORLD, &last_world);
301
+ device->SetTransform(D3DTS_VIEW, &last_view);
302
+ device->SetTransform(D3DTS_PROJECTION, &last_projection);
303
+
304
+ // Restore the DX9 state
305
+ state_block->Apply();
306
+ state_block->Release();
307
+ }
308
+
309
+ static bool ImGui_ImplDX9_CheckFormatSupport(LPDIRECT3DDEVICE9 pDevice, D3DFORMAT format)
310
+ {
311
+ LPDIRECT3D9 pd3d = nullptr;
312
+ if (pDevice->GetDirect3D(&pd3d) != D3D_OK)
313
+ return false;
314
+ D3DDEVICE_CREATION_PARAMETERS param = {};
315
+ D3DDISPLAYMODE mode = {};
316
+ if (pDevice->GetCreationParameters(&param) != D3D_OK || pDevice->GetDisplayMode(0, &mode) != D3D_OK)
317
+ {
318
+ pd3d->Release();
319
+ return false;
320
+ }
321
+ // Font texture should support linear filter, color blend and write to render-target
322
+ bool support = (pd3d->CheckDeviceFormat(param.AdapterOrdinal, param.DeviceType, mode.Format, D3DUSAGE_DYNAMIC | D3DUSAGE_QUERY_FILTER | D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, format)) == D3D_OK;
323
+ pd3d->Release();
324
+ return support;
325
+ }
326
+
327
+ bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
328
+ {
329
+ ImGuiIO& io = ImGui::GetIO();
330
+ IMGUI_CHECKVERSION();
331
+ IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
332
+
333
+ // Setup backend capabilities flags
334
+ ImGui_ImplDX9_Data* bd = IM_NEW(ImGui_ImplDX9_Data)();
335
+ io.BackendRendererUserData = (void*)bd;
336
+ io.BackendRendererName = "imgui_impl_dx9";
337
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
338
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
339
+
340
+ bd->pd3dDevice = device;
341
+ bd->pd3dDevice->AddRef();
342
+ bd->HasRgbaSupport = ImGui_ImplDX9_CheckFormatSupport(bd->pd3dDevice, D3DFMT_A8B8G8R8);
343
+
344
+ ImGui_ImplDX9_InitMultiViewportSupport();
345
+
346
+ return true;
347
+ }
348
+
349
+ void ImGui_ImplDX9_Shutdown()
350
+ {
351
+ ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
352
+ IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
353
+ ImGuiIO& io = ImGui::GetIO();
354
+
355
+ ImGui_ImplDX9_ShutdownMultiViewportSupport();
356
+ ImGui_ImplDX9_InvalidateDeviceObjects();
357
+ if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
358
+ io.BackendRendererName = nullptr;
359
+ io.BackendRendererUserData = nullptr;
360
+ io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
361
+ IM_DELETE(bd);
362
+ }
363
+
364
+ // Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices)
365
+ static void ImGui_ImplDX9_CopyTextureRegion(bool tex_use_colors, ImU32* src, int src_pitch, ImU32* dst, int dst_pitch, int w, int h)
366
+ {
367
+ #ifndef IMGUI_USE_BGRA_PACKED_COLOR
368
+ ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
369
+ const bool convert_rgba_to_bgra = (!bd->HasRgbaSupport && tex_use_colors);
370
+ #else
371
+ const bool convert_rgba_to_bgra = false;
372
+ IM_UNUSED(tex_use_colors);
373
+ #endif
374
+ for (int y = 0; y < h; y++)
375
+ {
376
+ ImU32* src_p = (ImU32*)((unsigned char*)src + src_pitch * y);
377
+ ImU32* dst_p = (ImU32*)((unsigned char*)dst + dst_pitch * y);
378
+ if (convert_rgba_to_bgra)
379
+ for (int x = w; x > 0; x--, src_p++, dst_p++) // Convert copy
380
+ *dst_p = IMGUI_COL_TO_DX9_ARGB(*src_p);
381
+ else
382
+ memcpy(dst_p, src_p, w * 4); // Raw copy
383
+ }
384
+ }
385
+
386
+ static bool ImGui_ImplDX9_CreateFontsTexture()
387
+ {
388
+ // Build texture atlas
389
+ ImGuiIO& io = ImGui::GetIO();
390
+ ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
391
+ unsigned char* pixels;
392
+ int width, height, bytes_per_pixel;
393
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel);
394
+
395
+ // Upload texture to graphics system
396
+ bd->FontTexture = nullptr;
397
+ if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, bd->HasRgbaSupport ? D3DFMT_A8B8G8R8 : D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, nullptr) < 0)
398
+ return false;
399
+ D3DLOCKED_RECT tex_locked_rect;
400
+ if (bd->FontTexture->LockRect(0, &tex_locked_rect, nullptr, 0) != D3D_OK)
401
+ return false;
402
+ ImGui_ImplDX9_CopyTextureRegion(io.Fonts->TexPixelsUseColors, (ImU32*)pixels, width * bytes_per_pixel, (ImU32*)tex_locked_rect.pBits, (int)tex_locked_rect.Pitch, width, height);
403
+ bd->FontTexture->UnlockRect(0);
404
+
405
+ // Store our identifier
406
+ io.Fonts->SetTexID((ImTextureID)bd->FontTexture);
407
+ return true;
408
+ }
409
+
410
+ bool ImGui_ImplDX9_CreateDeviceObjects()
411
+ {
412
+ ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
413
+ if (!bd || !bd->pd3dDevice)
414
+ return false;
415
+ if (!ImGui_ImplDX9_CreateFontsTexture())
416
+ return false;
417
+ ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows();
418
+ return true;
419
+ }
420
+
421
+ void ImGui_ImplDX9_InvalidateDeviceObjects()
422
+ {
423
+ ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
424
+ if (!bd || !bd->pd3dDevice)
425
+ return;
426
+ if (bd->pVB) { bd->pVB->Release(); bd->pVB = nullptr; }
427
+ if (bd->pIB) { bd->pIB->Release(); bd->pIB = nullptr; }
428
+ if (bd->FontTexture) { bd->FontTexture->Release(); bd->FontTexture = nullptr; ImGui::GetIO().Fonts->SetTexID(0); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
429
+ ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows();
430
+ }
431
+
432
+ void ImGui_ImplDX9_NewFrame()
433
+ {
434
+ ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
435
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplDX9_Init()?");
436
+
437
+ if (!bd->FontTexture)
438
+ ImGui_ImplDX9_CreateDeviceObjects();
439
+ }
440
+
441
+ //--------------------------------------------------------------------------------------------------------
442
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
443
+ // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
444
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
445
+ //--------------------------------------------------------------------------------------------------------
446
+
447
+ // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
448
+ struct ImGui_ImplDX9_ViewportData
449
+ {
450
+ IDirect3DSwapChain9* SwapChain;
451
+ D3DPRESENT_PARAMETERS d3dpp;
452
+
453
+ ImGui_ImplDX9_ViewportData() { SwapChain = nullptr; ZeroMemory(&d3dpp, sizeof(D3DPRESENT_PARAMETERS)); }
454
+ ~ImGui_ImplDX9_ViewportData() { IM_ASSERT(SwapChain == nullptr); }
455
+ };
456
+
457
+ static void ImGui_ImplDX9_CreateWindow(ImGuiViewport* viewport)
458
+ {
459
+ ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
460
+ ImGui_ImplDX9_ViewportData* vd = IM_NEW(ImGui_ImplDX9_ViewportData)();
461
+ viewport->RendererUserData = vd;
462
+
463
+ // PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
464
+ // Some backends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the HWND.
465
+ HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
466
+ IM_ASSERT(hwnd != 0);
467
+
468
+ ZeroMemory(&vd->d3dpp, sizeof(D3DPRESENT_PARAMETERS));
469
+ vd->d3dpp.Windowed = TRUE;
470
+ vd->d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
471
+ vd->d3dpp.BackBufferWidth = (UINT)viewport->Size.x;
472
+ vd->d3dpp.BackBufferHeight = (UINT)viewport->Size.y;
473
+ vd->d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
474
+ vd->d3dpp.hDeviceWindow = hwnd;
475
+ vd->d3dpp.EnableAutoDepthStencil = FALSE;
476
+ vd->d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
477
+ vd->d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync
478
+
479
+ HRESULT hr = bd->pd3dDevice->CreateAdditionalSwapChain(&vd->d3dpp, &vd->SwapChain); IM_UNUSED(hr);
480
+ IM_ASSERT(hr == D3D_OK);
481
+ IM_ASSERT(vd->SwapChain != nullptr);
482
+ }
483
+
484
+ static void ImGui_ImplDX9_DestroyWindow(ImGuiViewport* viewport)
485
+ {
486
+ // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it.
487
+ if (ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData)
488
+ {
489
+ if (vd->SwapChain)
490
+ vd->SwapChain->Release();
491
+ vd->SwapChain = nullptr;
492
+ ZeroMemory(&vd->d3dpp, sizeof(D3DPRESENT_PARAMETERS));
493
+ IM_DELETE(vd);
494
+ }
495
+ viewport->RendererUserData = nullptr;
496
+ }
497
+
498
+ static void ImGui_ImplDX9_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
499
+ {
500
+ ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
501
+ ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
502
+ if (vd->SwapChain)
503
+ {
504
+ vd->SwapChain->Release();
505
+ vd->SwapChain = nullptr;
506
+ vd->d3dpp.BackBufferWidth = (UINT)size.x;
507
+ vd->d3dpp.BackBufferHeight = (UINT)size.y;
508
+ HRESULT hr = bd->pd3dDevice->CreateAdditionalSwapChain(&vd->d3dpp, &vd->SwapChain); IM_UNUSED(hr);
509
+ IM_ASSERT(hr == D3D_OK);
510
+ }
511
+ }
512
+
513
+ static void ImGui_ImplDX9_RenderWindow(ImGuiViewport* viewport, void*)
514
+ {
515
+ ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
516
+ ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
517
+ ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
518
+
519
+ LPDIRECT3DSURFACE9 render_target = nullptr;
520
+ LPDIRECT3DSURFACE9 last_render_target = nullptr;
521
+ LPDIRECT3DSURFACE9 last_depth_stencil = nullptr;
522
+ vd->SwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &render_target);
523
+ bd->pd3dDevice->GetRenderTarget(0, &last_render_target);
524
+ bd->pd3dDevice->GetDepthStencilSurface(&last_depth_stencil);
525
+ bd->pd3dDevice->SetRenderTarget(0, render_target);
526
+ bd->pd3dDevice->SetDepthStencilSurface(nullptr);
527
+
528
+ if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
529
+ {
530
+ D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*255.0f), (int)(clear_color.y*255.0f), (int)(clear_color.z*255.0f), (int)(clear_color.w*255.0f));
531
+ bd->pd3dDevice->Clear(0, nullptr, D3DCLEAR_TARGET, clear_col_dx, 1.0f, 0);
532
+ }
533
+
534
+ ImGui_ImplDX9_RenderDrawData(viewport->DrawData);
535
+
536
+ // Restore render target
537
+ bd->pd3dDevice->SetRenderTarget(0, last_render_target);
538
+ bd->pd3dDevice->SetDepthStencilSurface(last_depth_stencil);
539
+ render_target->Release();
540
+ last_render_target->Release();
541
+ if (last_depth_stencil) last_depth_stencil->Release();
542
+ }
543
+
544
+ static void ImGui_ImplDX9_SwapBuffers(ImGuiViewport* viewport, void*)
545
+ {
546
+ ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
547
+ HRESULT hr = vd->SwapChain->Present(nullptr, nullptr, vd->d3dpp.hDeviceWindow, nullptr, 0);
548
+ // Let main application handle D3DERR_DEVICELOST by resetting the device.
549
+ IM_ASSERT(SUCCEEDED(hr) || hr == D3DERR_DEVICELOST);
550
+ }
551
+
552
+ static void ImGui_ImplDX9_InitMultiViewportSupport()
553
+ {
554
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
555
+ platform_io.Renderer_CreateWindow = ImGui_ImplDX9_CreateWindow;
556
+ platform_io.Renderer_DestroyWindow = ImGui_ImplDX9_DestroyWindow;
557
+ platform_io.Renderer_SetWindowSize = ImGui_ImplDX9_SetWindowSize;
558
+ platform_io.Renderer_RenderWindow = ImGui_ImplDX9_RenderWindow;
559
+ platform_io.Renderer_SwapBuffers = ImGui_ImplDX9_SwapBuffers;
560
+ }
561
+
562
+ static void ImGui_ImplDX9_ShutdownMultiViewportSupport()
563
+ {
564
+ ImGui::DestroyPlatformWindows();
565
+ }
566
+
567
+ static void ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows()
568
+ {
569
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
570
+ for (int i = 1; i < platform_io.Viewports.Size; i++)
571
+ if (!platform_io.Viewports[i]->RendererUserData)
572
+ ImGui_ImplDX9_CreateWindow(platform_io.Viewports[i]);
573
+ }
574
+
575
+ static void ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows()
576
+ {
577
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
578
+ for (int i = 1; i < platform_io.Viewports.Size; i++)
579
+ if (platform_io.Viewports[i]->RendererUserData)
580
+ ImGui_ImplDX9_DestroyWindow(platform_io.Viewports[i]);
581
+ }
582
+
583
+ //-----------------------------------------------------------------------------
584
+
585
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_dx9.h ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for DirectX9
2
+ // This needs to be used along with a Platform Backend (e.g. Win32)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7
+ // [X] Renderer: IMGUI_USE_BGRA_PACKED_COLOR support, as this is the optimal color encoding for DirectX9.
8
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
9
+
10
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
11
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
12
+ // Learn about Dear ImGui:
13
+ // - FAQ https://dearimgui.com/faq
14
+ // - Getting Started https://dearimgui.com/getting-started
15
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
16
+ // - Introduction, links and more at the top of imgui.cpp
17
+
18
+ #pragma once
19
+ #include "imgui.h" // IMGUI_IMPL_API
20
+ #ifndef IMGUI_DISABLE
21
+
22
+ struct IDirect3DDevice9;
23
+
24
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
25
+ IMGUI_IMPL_API bool ImGui_ImplDX9_Init(IDirect3DDevice9* device);
26
+ IMGUI_IMPL_API void ImGui_ImplDX9_Shutdown();
27
+ IMGUI_IMPL_API void ImGui_ImplDX9_NewFrame();
28
+ IMGUI_IMPL_API void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data);
29
+
30
+ // Use if you want to reset your rendering device without losing Dear ImGui state.
31
+ IMGUI_IMPL_API bool ImGui_ImplDX9_CreateDeviceObjects();
32
+ IMGUI_IMPL_API void ImGui_ImplDX9_InvalidateDeviceObjects();
33
+
34
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_glfw.cpp ADDED
@@ -0,0 +1,1453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for GLFW
2
+ // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..)
3
+ // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
4
+ // (Requires: GLFW 3.1+. Prefer GLFW 3.3+ or GLFW 3.4+ for full feature support.)
5
+
6
+ // Implemented features:
7
+ // [X] Platform: Clipboard support.
8
+ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only).
9
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
10
+ // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
11
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
12
+ // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
13
+ // Missing features or Issues:
14
+ // [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor).
15
+
16
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
17
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
18
+ // Learn about Dear ImGui:
19
+ // - FAQ https://dearimgui.com/faq
20
+ // - Getting Started https://dearimgui.com/getting-started
21
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
22
+ // - Introduction, links and more at the top of imgui.cpp
23
+
24
+ // About Emscripten support:
25
+ // - Emscripten provides its own GLFW (3.2.1) implementation (syntax: "-sUSE_GLFW=3"), but Joystick is broken and several features are not supported (multiple windows, clipboard, timer, etc.)
26
+ // - A third-party Emscripten GLFW (3.4.0) implementation (syntax: "--use-port=contrib.glfw3") fixes the Joystick issue and implements all relevant features for the browser.
27
+ // See https://github.com/pongasoft/emscripten-glfw/blob/master/docs/Comparison.md for details.
28
+
29
+ // CHANGELOG
30
+ // (minor and older changes stripped away, please see git history for details)
31
+ // 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
32
+ // 2024-11-05: [Docking] Added Linux workaround for spurious mouse up events emitted while dragging and creating new viewport. (#3158, #7733, #7922)
33
+ // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
34
+ // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
35
+ // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
36
+ // - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn
37
+ // 2024-07-31: Added ImGui_ImplGlfw_Sleep() helper function for usage by our examples app, since GLFW doesn't provide one.
38
+ // 2024-07-08: *BREAKING* Renamed ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback to ImGui_ImplGlfw_InstallEmscriptenCallbacks(), added GLFWWindow* parameter.
39
+ // 2024-07-08: Emscripten: Added support for GLFW3 contrib port (GLFW 3.4.0 features + bug fixes): to enable, replace -sUSE_GLFW=3 with --use-port=contrib.glfw3 (requires emscripten 3.1.59+) (https://github.com/pongasoft/emscripten-glfw)
40
+ // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions.
41
+ // 2023-12-19: Emscripten: Added ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback() to register canvas selector and auto-resize GLFW window.
42
+ // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys.
43
+ // 2023-07-18: Inputs: Revert ignoring mouse data on GLFW_CURSOR_DISABLED as it can be used differently. User may set ImGuiConfigFLags_NoMouse if desired. (#5625, #6609)
44
+ // 2023-06-12: Accept glfwGetTime() not returning a monotonically increasing value. This seems to happens on some Windows setup when peripherals disconnect, and is likely to also happen on browser + Emscripten. (#6491)
45
+ // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen on Windows ONLY, using a custom WndProc hook. (#2702)
46
+ // 2023-03-16: Inputs: Fixed key modifiers handling on secondary viewports (docking branch). Broken on 2023/01/04. (#6248, #6034)
47
+ // 2023-03-14: Emscripten: Avoid using glfwGetError() and glfwGetGamepadState() which are not correctly implemented in Emscripten emulation. (#6240)
48
+ // 2023-02-03: Emscripten: Registering custom low-level mouse wheel handler to get more accurate scrolling impulses on Emscripten. (#4019, #6096)
49
+ // 2023-01-18: Handle unsupported glfwGetVideoMode() call on e.g. Emscripten.
50
+ // 2023-01-04: Inputs: Fixed mods state on Linux when using Alt-GR text input (e.g. German keyboard layout), could lead to broken text input. Revert a 2022/01/17 change were we resumed using mods provided by GLFW, turns out they were faulty.
51
+ // 2022-11-22: Perform a dummy glfwGetError() read to cancel missing names with glfwGetKeyName(). (#5908)
52
+ // 2022-10-18: Perform a dummy glfwGetError() read to cancel missing mouse cursors errors. Using GLFW_VERSION_COMBINED directly. (#5785)
53
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
54
+ // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
55
+ // 2022-09-01: Inputs: Honor GLFW_CURSOR_DISABLED by not setting mouse position *EDIT* Reverted 2023-07-18.
56
+ // 2022-04-30: Inputs: Fixed ImGui_ImplGlfw_TranslateUntranslatedKey() for lower case letters on OSX.
57
+ // 2022-03-23: Inputs: Fixed a regression in 1.87 which resulted in keyboard modifiers events being reported incorrectly on Linux/X11.
58
+ // 2022-02-07: Added ImGui_ImplGlfw_InstallCallbacks()/ImGui_ImplGlfw_RestoreCallbacks() helpers to facilitate user installing callbacks after initializing backend.
59
+ // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
60
+ // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
61
+ // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
62
+ // 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates.
63
+ // 2022-01-12: *BREAKING CHANGE*: Now using glfwSetCursorPosCallback(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetCursorPosCallback() and forward it to the backend via ImGui_ImplGlfw_CursorPosCallback().
64
+ // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
65
+ // 2022-01-05: Inputs: Converting GLFW untranslated keycodes back to translated keycodes (in the ImGui_ImplGlfw_KeyCallback() function) in order to match the behavior of every other backend, and facilitate the use of GLFW with lettered-shortcuts API.
66
+ // 2021-08-17: *BREAKING CHANGE*: Now using glfwSetWindowFocusCallback() to calling io.AddFocusEvent(). If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() and forward it to the backend via ImGui_ImplGlfw_WindowFocusCallback().
67
+ // 2021-07-29: *BREAKING CHANGE*: Now using glfwSetCursorEnterCallback(). MousePos is correctly reported when the host platform window is hovered but not focused. If you called ImGui_ImplGlfw_InitXXX() with install_callbacks = false, you MUST install glfwSetWindowFocusCallback() callback and forward it to the backend via ImGui_ImplGlfw_CursorEnterCallback().
68
+ // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
69
+ // 2020-01-17: Inputs: Disable error callback while assigning mouse cursors because some X11 setup don't have them and it generates errors.
70
+ // 2019-12-05: Inputs: Added support for new mouse cursors added in GLFW 3.4+ (resizing cursors, not allowed cursor).
71
+ // 2019-10-18: Misc: Previously installed user callbacks are now restored on shutdown.
72
+ // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
73
+ // 2019-05-11: Inputs: Don't filter value from character callback before calling AddInputCharacter().
74
+ // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
75
+ // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
76
+ // 2018-11-07: Inputs: When installing our GLFW callbacks, we save user's previously installed ones - if any - and chain call them.
77
+ // 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
78
+ // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
79
+ // 2018-06-08: Misc: Extracted imgui_impl_glfw.cpp/.h away from the old combined GLFW+OpenGL/Vulkan examples.
80
+ // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
81
+ // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value, passed to glfwSetCursor()).
82
+ // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
83
+ // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
84
+ // 2018-01-25: Inputs: Added gamepad support if ImGuiConfigFlags_NavEnableGamepad is set.
85
+ // 2018-01-25: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
86
+ // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
87
+ // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
88
+ // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
89
+ // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
90
+
91
+ #include "../imgui.h"
92
+ #ifndef IMGUI_DISABLE
93
+ #include "imgui_impl_glfw.h"
94
+
95
+ // Clang warnings with -Weverything
96
+ #if defined(__clang__)
97
+ #pragma clang diagnostic push
98
+ #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
99
+ #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
100
+ #endif
101
+
102
+ // GLFW
103
+ #include <GLFW/glfw3.h>
104
+
105
+ #ifdef _WIN32
106
+ #undef APIENTRY
107
+ #ifndef GLFW_EXPOSE_NATIVE_WIN32
108
+ #define GLFW_EXPOSE_NATIVE_WIN32
109
+ #endif
110
+ #include <GLFW/glfw3native.h> // for glfwGetWin32Window()
111
+ #endif
112
+ #ifdef __APPLE__
113
+ #ifndef GLFW_EXPOSE_NATIVE_COCOA
114
+ #define GLFW_EXPOSE_NATIVE_COCOA
115
+ #endif
116
+ #include <GLFW/glfw3native.h> // for glfwGetCocoaWindow()
117
+ #endif
118
+ #ifndef _WIN32
119
+ #include <unistd.h> // for usleep()
120
+ #endif
121
+
122
+ #ifdef __EMSCRIPTEN__
123
+ #include <emscripten.h>
124
+ #include <emscripten/html5.h>
125
+ #ifdef EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3
126
+ #include <GLFW/emscripten_glfw3.h>
127
+ #else
128
+ #define EMSCRIPTEN_USE_EMBEDDED_GLFW3
129
+ #endif
130
+ #endif
131
+
132
+ // We gather version tests as define in order to easily see which features are version-dependent.
133
+ #define GLFW_VERSION_COMBINED (GLFW_VERSION_MAJOR * 1000 + GLFW_VERSION_MINOR * 100 + GLFW_VERSION_REVISION)
134
+ #define GLFW_HAS_WINDOW_TOPMOST (GLFW_VERSION_COMBINED >= 3200) // 3.2+ GLFW_FLOATING
135
+ #define GLFW_HAS_WINDOW_HOVERED (GLFW_VERSION_COMBINED >= 3300) // 3.3+ GLFW_HOVERED
136
+ #define GLFW_HAS_WINDOW_ALPHA (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwSetWindowOpacity
137
+ #define GLFW_HAS_PER_MONITOR_DPI (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetMonitorContentScale
138
+ #if defined(__EMSCRIPTEN__) || defined(__SWITCH__) // no Vulkan support in GLFW for Emscripten or homebrew Nintendo Switch
139
+ #define GLFW_HAS_VULKAN (0)
140
+ #else
141
+ #define GLFW_HAS_VULKAN (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwCreateWindowSurface
142
+ #endif
143
+ #define GLFW_HAS_FOCUS_WINDOW (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwFocusWindow
144
+ #define GLFW_HAS_FOCUS_ON_SHOW (GLFW_VERSION_COMBINED >= 3300) // 3.3+ GLFW_FOCUS_ON_SHOW
145
+ #define GLFW_HAS_MONITOR_WORK_AREA (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetMonitorWorkarea
146
+ #define GLFW_HAS_OSX_WINDOW_POS_FIX (GLFW_VERSION_COMBINED >= 3301) // 3.3.1+ Fixed: Resizing window repositions it on MacOS #1553
147
+ #ifdef GLFW_RESIZE_NESW_CURSOR // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2019-11-29 (cursors defines) // FIXME: Remove when GLFW 3.4 is released?
148
+ #define GLFW_HAS_NEW_CURSORS (GLFW_VERSION_COMBINED >= 3400) // 3.4+ GLFW_RESIZE_ALL_CURSOR, GLFW_RESIZE_NESW_CURSOR, GLFW_RESIZE_NWSE_CURSOR, GLFW_NOT_ALLOWED_CURSOR
149
+ #else
150
+ #define GLFW_HAS_NEW_CURSORS (0)
151
+ #endif
152
+ #ifdef GLFW_MOUSE_PASSTHROUGH // Let's be nice to people who pulled GLFW between 2019-04-16 (3.4 define) and 2020-07-17 (passthrough)
153
+ #define GLFW_HAS_MOUSE_PASSTHROUGH (GLFW_VERSION_COMBINED >= 3400) // 3.4+ GLFW_MOUSE_PASSTHROUGH
154
+ #else
155
+ #define GLFW_HAS_MOUSE_PASSTHROUGH (0)
156
+ #endif
157
+ #define GLFW_HAS_GAMEPAD_API (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetGamepadState() new api
158
+ #define GLFW_HAS_GETKEYNAME (GLFW_VERSION_COMBINED >= 3200) // 3.2+ glfwGetKeyName()
159
+ #define GLFW_HAS_GETERROR (GLFW_VERSION_COMBINED >= 3300) // 3.3+ glfwGetError()
160
+
161
+ // GLFW data
162
+ enum GlfwClientApi
163
+ {
164
+ GlfwClientApi_Unknown,
165
+ GlfwClientApi_OpenGL,
166
+ GlfwClientApi_Vulkan,
167
+ };
168
+
169
+ struct ImGui_ImplGlfw_Data
170
+ {
171
+ GLFWwindow* Window;
172
+ GlfwClientApi ClientApi;
173
+ double Time;
174
+ GLFWwindow* MouseWindow;
175
+ GLFWcursor* MouseCursors[ImGuiMouseCursor_COUNT];
176
+ bool MouseIgnoreButtonUpWaitForFocusLoss;
177
+ bool MouseIgnoreButtonUp;
178
+ ImVec2 LastValidMousePos;
179
+ GLFWwindow* KeyOwnerWindows[GLFW_KEY_LAST];
180
+ bool InstalledCallbacks;
181
+ bool CallbacksChainForAllWindows;
182
+ bool WantUpdateMonitors;
183
+ #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
184
+ const char* CanvasSelector;
185
+ #endif
186
+
187
+ // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
188
+ GLFWwindowfocusfun PrevUserCallbackWindowFocus;
189
+ GLFWcursorposfun PrevUserCallbackCursorPos;
190
+ GLFWcursorenterfun PrevUserCallbackCursorEnter;
191
+ GLFWmousebuttonfun PrevUserCallbackMousebutton;
192
+ GLFWscrollfun PrevUserCallbackScroll;
193
+ GLFWkeyfun PrevUserCallbackKey;
194
+ GLFWcharfun PrevUserCallbackChar;
195
+ GLFWmonitorfun PrevUserCallbackMonitor;
196
+ #ifdef _WIN32
197
+ WNDPROC PrevWndProc;
198
+ #endif
199
+
200
+ ImGui_ImplGlfw_Data() { memset((void*)this, 0, sizeof(*this)); }
201
+ };
202
+
203
+ // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
204
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
205
+ // FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
206
+ // - Because glfwPollEvents() process all windows and some events may be called outside of it, you will need to register your own callbacks
207
+ // (passing install_callbacks=false in ImGui_ImplGlfw_InitXXX functions), set the current dear imgui context and then call our callbacks.
208
+ // - Otherwise we may need to store a GLFWWindow* -> ImGuiContext* map and handle this in the backend, adding a little bit of extra complexity to it.
209
+ // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
210
+ static ImGui_ImplGlfw_Data* ImGui_ImplGlfw_GetBackendData()
211
+ {
212
+ return ImGui::GetCurrentContext() ? (ImGui_ImplGlfw_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
213
+ }
214
+
215
+ // Forward Declarations
216
+ static void ImGui_ImplGlfw_UpdateMonitors();
217
+ static void ImGui_ImplGlfw_InitMultiViewportSupport();
218
+ static void ImGui_ImplGlfw_ShutdownMultiViewportSupport();
219
+
220
+ // Functions
221
+
222
+ // Not static to allow third-party code to use that if they want to (but undocumented)
223
+ ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode);
224
+ ImGuiKey ImGui_ImplGlfw_KeyToImGuiKey(int keycode, int scancode)
225
+ {
226
+ IM_UNUSED(scancode);
227
+ switch (keycode)
228
+ {
229
+ case GLFW_KEY_TAB: return ImGuiKey_Tab;
230
+ case GLFW_KEY_LEFT: return ImGuiKey_LeftArrow;
231
+ case GLFW_KEY_RIGHT: return ImGuiKey_RightArrow;
232
+ case GLFW_KEY_UP: return ImGuiKey_UpArrow;
233
+ case GLFW_KEY_DOWN: return ImGuiKey_DownArrow;
234
+ case GLFW_KEY_PAGE_UP: return ImGuiKey_PageUp;
235
+ case GLFW_KEY_PAGE_DOWN: return ImGuiKey_PageDown;
236
+ case GLFW_KEY_HOME: return ImGuiKey_Home;
237
+ case GLFW_KEY_END: return ImGuiKey_End;
238
+ case GLFW_KEY_INSERT: return ImGuiKey_Insert;
239
+ case GLFW_KEY_DELETE: return ImGuiKey_Delete;
240
+ case GLFW_KEY_BACKSPACE: return ImGuiKey_Backspace;
241
+ case GLFW_KEY_SPACE: return ImGuiKey_Space;
242
+ case GLFW_KEY_ENTER: return ImGuiKey_Enter;
243
+ case GLFW_KEY_ESCAPE: return ImGuiKey_Escape;
244
+ case GLFW_KEY_APOSTROPHE: return ImGuiKey_Apostrophe;
245
+ case GLFW_KEY_COMMA: return ImGuiKey_Comma;
246
+ case GLFW_KEY_MINUS: return ImGuiKey_Minus;
247
+ case GLFW_KEY_PERIOD: return ImGuiKey_Period;
248
+ case GLFW_KEY_SLASH: return ImGuiKey_Slash;
249
+ case GLFW_KEY_SEMICOLON: return ImGuiKey_Semicolon;
250
+ case GLFW_KEY_EQUAL: return ImGuiKey_Equal;
251
+ case GLFW_KEY_LEFT_BRACKET: return ImGuiKey_LeftBracket;
252
+ case GLFW_KEY_BACKSLASH: return ImGuiKey_Backslash;
253
+ case GLFW_KEY_RIGHT_BRACKET: return ImGuiKey_RightBracket;
254
+ case GLFW_KEY_GRAVE_ACCENT: return ImGuiKey_GraveAccent;
255
+ case GLFW_KEY_CAPS_LOCK: return ImGuiKey_CapsLock;
256
+ case GLFW_KEY_SCROLL_LOCK: return ImGuiKey_ScrollLock;
257
+ case GLFW_KEY_NUM_LOCK: return ImGuiKey_NumLock;
258
+ case GLFW_KEY_PRINT_SCREEN: return ImGuiKey_PrintScreen;
259
+ case GLFW_KEY_PAUSE: return ImGuiKey_Pause;
260
+ case GLFW_KEY_KP_0: return ImGuiKey_Keypad0;
261
+ case GLFW_KEY_KP_1: return ImGuiKey_Keypad1;
262
+ case GLFW_KEY_KP_2: return ImGuiKey_Keypad2;
263
+ case GLFW_KEY_KP_3: return ImGuiKey_Keypad3;
264
+ case GLFW_KEY_KP_4: return ImGuiKey_Keypad4;
265
+ case GLFW_KEY_KP_5: return ImGuiKey_Keypad5;
266
+ case GLFW_KEY_KP_6: return ImGuiKey_Keypad6;
267
+ case GLFW_KEY_KP_7: return ImGuiKey_Keypad7;
268
+ case GLFW_KEY_KP_8: return ImGuiKey_Keypad8;
269
+ case GLFW_KEY_KP_9: return ImGuiKey_Keypad9;
270
+ case GLFW_KEY_KP_DECIMAL: return ImGuiKey_KeypadDecimal;
271
+ case GLFW_KEY_KP_DIVIDE: return ImGuiKey_KeypadDivide;
272
+ case GLFW_KEY_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
273
+ case GLFW_KEY_KP_SUBTRACT: return ImGuiKey_KeypadSubtract;
274
+ case GLFW_KEY_KP_ADD: return ImGuiKey_KeypadAdd;
275
+ case GLFW_KEY_KP_ENTER: return ImGuiKey_KeypadEnter;
276
+ case GLFW_KEY_KP_EQUAL: return ImGuiKey_KeypadEqual;
277
+ case GLFW_KEY_LEFT_SHIFT: return ImGuiKey_LeftShift;
278
+ case GLFW_KEY_LEFT_CONTROL: return ImGuiKey_LeftCtrl;
279
+ case GLFW_KEY_LEFT_ALT: return ImGuiKey_LeftAlt;
280
+ case GLFW_KEY_LEFT_SUPER: return ImGuiKey_LeftSuper;
281
+ case GLFW_KEY_RIGHT_SHIFT: return ImGuiKey_RightShift;
282
+ case GLFW_KEY_RIGHT_CONTROL: return ImGuiKey_RightCtrl;
283
+ case GLFW_KEY_RIGHT_ALT: return ImGuiKey_RightAlt;
284
+ case GLFW_KEY_RIGHT_SUPER: return ImGuiKey_RightSuper;
285
+ case GLFW_KEY_MENU: return ImGuiKey_Menu;
286
+ case GLFW_KEY_0: return ImGuiKey_0;
287
+ case GLFW_KEY_1: return ImGuiKey_1;
288
+ case GLFW_KEY_2: return ImGuiKey_2;
289
+ case GLFW_KEY_3: return ImGuiKey_3;
290
+ case GLFW_KEY_4: return ImGuiKey_4;
291
+ case GLFW_KEY_5: return ImGuiKey_5;
292
+ case GLFW_KEY_6: return ImGuiKey_6;
293
+ case GLFW_KEY_7: return ImGuiKey_7;
294
+ case GLFW_KEY_8: return ImGuiKey_8;
295
+ case GLFW_KEY_9: return ImGuiKey_9;
296
+ case GLFW_KEY_A: return ImGuiKey_A;
297
+ case GLFW_KEY_B: return ImGuiKey_B;
298
+ case GLFW_KEY_C: return ImGuiKey_C;
299
+ case GLFW_KEY_D: return ImGuiKey_D;
300
+ case GLFW_KEY_E: return ImGuiKey_E;
301
+ case GLFW_KEY_F: return ImGuiKey_F;
302
+ case GLFW_KEY_G: return ImGuiKey_G;
303
+ case GLFW_KEY_H: return ImGuiKey_H;
304
+ case GLFW_KEY_I: return ImGuiKey_I;
305
+ case GLFW_KEY_J: return ImGuiKey_J;
306
+ case GLFW_KEY_K: return ImGuiKey_K;
307
+ case GLFW_KEY_L: return ImGuiKey_L;
308
+ case GLFW_KEY_M: return ImGuiKey_M;
309
+ case GLFW_KEY_N: return ImGuiKey_N;
310
+ case GLFW_KEY_O: return ImGuiKey_O;
311
+ case GLFW_KEY_P: return ImGuiKey_P;
312
+ case GLFW_KEY_Q: return ImGuiKey_Q;
313
+ case GLFW_KEY_R: return ImGuiKey_R;
314
+ case GLFW_KEY_S: return ImGuiKey_S;
315
+ case GLFW_KEY_T: return ImGuiKey_T;
316
+ case GLFW_KEY_U: return ImGuiKey_U;
317
+ case GLFW_KEY_V: return ImGuiKey_V;
318
+ case GLFW_KEY_W: return ImGuiKey_W;
319
+ case GLFW_KEY_X: return ImGuiKey_X;
320
+ case GLFW_KEY_Y: return ImGuiKey_Y;
321
+ case GLFW_KEY_Z: return ImGuiKey_Z;
322
+ case GLFW_KEY_F1: return ImGuiKey_F1;
323
+ case GLFW_KEY_F2: return ImGuiKey_F2;
324
+ case GLFW_KEY_F3: return ImGuiKey_F3;
325
+ case GLFW_KEY_F4: return ImGuiKey_F4;
326
+ case GLFW_KEY_F5: return ImGuiKey_F5;
327
+ case GLFW_KEY_F6: return ImGuiKey_F6;
328
+ case GLFW_KEY_F7: return ImGuiKey_F7;
329
+ case GLFW_KEY_F8: return ImGuiKey_F8;
330
+ case GLFW_KEY_F9: return ImGuiKey_F9;
331
+ case GLFW_KEY_F10: return ImGuiKey_F10;
332
+ case GLFW_KEY_F11: return ImGuiKey_F11;
333
+ case GLFW_KEY_F12: return ImGuiKey_F12;
334
+ case GLFW_KEY_F13: return ImGuiKey_F13;
335
+ case GLFW_KEY_F14: return ImGuiKey_F14;
336
+ case GLFW_KEY_F15: return ImGuiKey_F15;
337
+ case GLFW_KEY_F16: return ImGuiKey_F16;
338
+ case GLFW_KEY_F17: return ImGuiKey_F17;
339
+ case GLFW_KEY_F18: return ImGuiKey_F18;
340
+ case GLFW_KEY_F19: return ImGuiKey_F19;
341
+ case GLFW_KEY_F20: return ImGuiKey_F20;
342
+ case GLFW_KEY_F21: return ImGuiKey_F21;
343
+ case GLFW_KEY_F22: return ImGuiKey_F22;
344
+ case GLFW_KEY_F23: return ImGuiKey_F23;
345
+ case GLFW_KEY_F24: return ImGuiKey_F24;
346
+ default: return ImGuiKey_None;
347
+ }
348
+ }
349
+
350
+ // X11 does not include current pressed/released modifier key in 'mods' flags submitted by GLFW
351
+ // See https://github.com/ocornut/imgui/issues/6034 and https://github.com/glfw/glfw/issues/1630
352
+ static void ImGui_ImplGlfw_UpdateKeyModifiers(GLFWwindow* window)
353
+ {
354
+ ImGuiIO& io = ImGui::GetIO();
355
+ io.AddKeyEvent(ImGuiMod_Ctrl, (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS));
356
+ io.AddKeyEvent(ImGuiMod_Shift, (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS));
357
+ io.AddKeyEvent(ImGuiMod_Alt, (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS));
358
+ io.AddKeyEvent(ImGuiMod_Super, (glfwGetKey(window, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS));
359
+ }
360
+
361
+ static bool ImGui_ImplGlfw_ShouldChainCallback(GLFWwindow* window)
362
+ {
363
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
364
+ return bd->CallbacksChainForAllWindows ? true : (window == bd->Window);
365
+ }
366
+
367
+ void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods)
368
+ {
369
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
370
+ if (bd->PrevUserCallbackMousebutton != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
371
+ bd->PrevUserCallbackMousebutton(window, button, action, mods);
372
+
373
+ // Workaround for Linux: ignore mouse up events which are following an focus loss following a viewport creation
374
+ if (bd->MouseIgnoreButtonUp && action == GLFW_RELEASE)
375
+ return;
376
+
377
+ ImGui_ImplGlfw_UpdateKeyModifiers(window);
378
+
379
+ ImGuiIO& io = ImGui::GetIO();
380
+ if (button >= 0 && button < ImGuiMouseButton_COUNT)
381
+ io.AddMouseButtonEvent(button, action == GLFW_PRESS);
382
+ }
383
+
384
+ void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset)
385
+ {
386
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
387
+ if (bd->PrevUserCallbackScroll != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
388
+ bd->PrevUserCallbackScroll(window, xoffset, yoffset);
389
+
390
+ #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
391
+ // Ignore GLFW events: will be processed in ImGui_ImplEmscripten_WheelCallback().
392
+ return;
393
+ #endif
394
+
395
+ ImGuiIO& io = ImGui::GetIO();
396
+ io.AddMouseWheelEvent((float)xoffset, (float)yoffset);
397
+ }
398
+
399
+ // FIXME: should this be baked into ImGui_ImplGlfw_KeyToImGuiKey()? then what about the values passed to io.SetKeyEventNativeData()?
400
+ static int ImGui_ImplGlfw_TranslateUntranslatedKey(int key, int scancode)
401
+ {
402
+ #if GLFW_HAS_GETKEYNAME && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3)
403
+ // GLFW 3.1+ attempts to "untranslate" keys, which goes the opposite of what every other framework does, making using lettered shortcuts difficult.
404
+ // (It had reasons to do so: namely GLFW is/was more likely to be used for WASD-type game controls rather than lettered shortcuts, but IHMO the 3.1 change could have been done differently)
405
+ // See https://github.com/glfw/glfw/issues/1502 for details.
406
+ // Adding a workaround to undo this (so our keys are translated->untranslated->translated, likely a lossy process).
407
+ // This won't cover edge cases but this is at least going to cover common cases.
408
+ if (key >= GLFW_KEY_KP_0 && key <= GLFW_KEY_KP_EQUAL)
409
+ return key;
410
+ GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr);
411
+ const char* key_name = glfwGetKeyName(key, scancode);
412
+ glfwSetErrorCallback(prev_error_callback);
413
+ #if GLFW_HAS_GETERROR && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3) // Eat errors (see #5908)
414
+ (void)glfwGetError(nullptr);
415
+ #endif
416
+ if (key_name && key_name[0] != 0 && key_name[1] == 0)
417
+ {
418
+ const char char_names[] = "`-=[]\\,;\'./";
419
+ const int char_keys[] = { GLFW_KEY_GRAVE_ACCENT, GLFW_KEY_MINUS, GLFW_KEY_EQUAL, GLFW_KEY_LEFT_BRACKET, GLFW_KEY_RIGHT_BRACKET, GLFW_KEY_BACKSLASH, GLFW_KEY_COMMA, GLFW_KEY_SEMICOLON, GLFW_KEY_APOSTROPHE, GLFW_KEY_PERIOD, GLFW_KEY_SLASH, 0 };
420
+ IM_ASSERT(IM_ARRAYSIZE(char_names) == IM_ARRAYSIZE(char_keys));
421
+ if (key_name[0] >= '0' && key_name[0] <= '9') { key = GLFW_KEY_0 + (key_name[0] - '0'); }
422
+ else if (key_name[0] >= 'A' && key_name[0] <= 'Z') { key = GLFW_KEY_A + (key_name[0] - 'A'); }
423
+ else if (key_name[0] >= 'a' && key_name[0] <= 'z') { key = GLFW_KEY_A + (key_name[0] - 'a'); }
424
+ else if (const char* p = strchr(char_names, key_name[0])) { key = char_keys[p - char_names]; }
425
+ }
426
+ // if (action == GLFW_PRESS) printf("key %d scancode %d name '%s'\n", key, scancode, key_name);
427
+ #else
428
+ IM_UNUSED(scancode);
429
+ #endif
430
+ return key;
431
+ }
432
+
433
+ void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int keycode, int scancode, int action, int mods)
434
+ {
435
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
436
+ if (bd->PrevUserCallbackKey != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
437
+ bd->PrevUserCallbackKey(window, keycode, scancode, action, mods);
438
+
439
+ if (action != GLFW_PRESS && action != GLFW_RELEASE)
440
+ return;
441
+
442
+ ImGui_ImplGlfw_UpdateKeyModifiers(window);
443
+
444
+ if (keycode >= 0 && keycode < IM_ARRAYSIZE(bd->KeyOwnerWindows))
445
+ bd->KeyOwnerWindows[keycode] = (action == GLFW_PRESS) ? window : nullptr;
446
+
447
+ keycode = ImGui_ImplGlfw_TranslateUntranslatedKey(keycode, scancode);
448
+
449
+ ImGuiIO& io = ImGui::GetIO();
450
+ ImGuiKey imgui_key = ImGui_ImplGlfw_KeyToImGuiKey(keycode, scancode);
451
+ io.AddKeyEvent(imgui_key, (action == GLFW_PRESS));
452
+ io.SetKeyEventNativeData(imgui_key, keycode, scancode); // To support legacy indexing (<1.87 user code)
453
+ }
454
+
455
+ void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused)
456
+ {
457
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
458
+ if (bd->PrevUserCallbackWindowFocus != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
459
+ bd->PrevUserCallbackWindowFocus(window, focused);
460
+
461
+ // Workaround for Linux: when losing focus with MouseIgnoreButtonUpWaitForFocusLoss set, we will temporarily ignore subsequent Mouse Up events
462
+ bd->MouseIgnoreButtonUp = (bd->MouseIgnoreButtonUpWaitForFocusLoss && focused == 0);
463
+ bd->MouseIgnoreButtonUpWaitForFocusLoss = false;
464
+
465
+ ImGuiIO& io = ImGui::GetIO();
466
+ io.AddFocusEvent(focused != 0);
467
+ }
468
+
469
+ void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y)
470
+ {
471
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
472
+ if (bd->PrevUserCallbackCursorPos != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
473
+ bd->PrevUserCallbackCursorPos(window, x, y);
474
+
475
+ ImGuiIO& io = ImGui::GetIO();
476
+ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
477
+ {
478
+ int window_x, window_y;
479
+ glfwGetWindowPos(window, &window_x, &window_y);
480
+ x += window_x;
481
+ y += window_y;
482
+ }
483
+ io.AddMousePosEvent((float)x, (float)y);
484
+ bd->LastValidMousePos = ImVec2((float)x, (float)y);
485
+ }
486
+
487
+ // Workaround: X11 seems to send spurious Leave/Enter events which would make us lose our position,
488
+ // so we back it up and restore on Leave/Enter (see https://github.com/ocornut/imgui/issues/4984)
489
+ void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered)
490
+ {
491
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
492
+ if (bd->PrevUserCallbackCursorEnter != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
493
+ bd->PrevUserCallbackCursorEnter(window, entered);
494
+
495
+ ImGuiIO& io = ImGui::GetIO();
496
+ if (entered)
497
+ {
498
+ bd->MouseWindow = window;
499
+ io.AddMousePosEvent(bd->LastValidMousePos.x, bd->LastValidMousePos.y);
500
+ }
501
+ else if (!entered && bd->MouseWindow == window)
502
+ {
503
+ bd->LastValidMousePos = io.MousePos;
504
+ bd->MouseWindow = nullptr;
505
+ io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
506
+ }
507
+ }
508
+
509
+ void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c)
510
+ {
511
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
512
+ if (bd->PrevUserCallbackChar != nullptr && ImGui_ImplGlfw_ShouldChainCallback(window))
513
+ bd->PrevUserCallbackChar(window, c);
514
+
515
+ ImGuiIO& io = ImGui::GetIO();
516
+ io.AddInputCharacter(c);
517
+ }
518
+
519
+ void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor*, int)
520
+ {
521
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
522
+ bd->WantUpdateMonitors = true;
523
+ }
524
+
525
+ #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
526
+ static EM_BOOL ImGui_ImplEmscripten_WheelCallback(int, const EmscriptenWheelEvent* ev, void*)
527
+ {
528
+ // Mimic Emscripten_HandleWheel() in SDL.
529
+ // Corresponding equivalent in GLFW JS emulation layer has incorrect quantizing preventing small values. See #6096
530
+ float multiplier = 0.0f;
531
+ if (ev->deltaMode == DOM_DELTA_PIXEL) { multiplier = 1.0f / 100.0f; } // 100 pixels make up a step.
532
+ else if (ev->deltaMode == DOM_DELTA_LINE) { multiplier = 1.0f / 3.0f; } // 3 lines make up a step.
533
+ else if (ev->deltaMode == DOM_DELTA_PAGE) { multiplier = 80.0f; } // A page makes up 80 steps.
534
+ float wheel_x = ev->deltaX * -multiplier;
535
+ float wheel_y = ev->deltaY * -multiplier;
536
+ ImGuiIO& io = ImGui::GetIO();
537
+ io.AddMouseWheelEvent(wheel_x, wheel_y);
538
+ //IMGUI_DEBUG_LOG("[Emsc] mode %d dx: %.2f, dy: %.2f, dz: %.2f --> feed %.2f %.2f\n", (int)ev->deltaMode, ev->deltaX, ev->deltaY, ev->deltaZ, wheel_x, wheel_y);
539
+ return EM_TRUE;
540
+ }
541
+ #endif
542
+
543
+ #ifdef _WIN32
544
+ static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
545
+ #endif
546
+
547
+ void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window)
548
+ {
549
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
550
+ IM_ASSERT(bd->InstalledCallbacks == false && "Callbacks already installed!");
551
+ IM_ASSERT(bd->Window == window);
552
+
553
+ bd->PrevUserCallbackWindowFocus = glfwSetWindowFocusCallback(window, ImGui_ImplGlfw_WindowFocusCallback);
554
+ bd->PrevUserCallbackCursorEnter = glfwSetCursorEnterCallback(window, ImGui_ImplGlfw_CursorEnterCallback);
555
+ bd->PrevUserCallbackCursorPos = glfwSetCursorPosCallback(window, ImGui_ImplGlfw_CursorPosCallback);
556
+ bd->PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);
557
+ bd->PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);
558
+ bd->PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);
559
+ bd->PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);
560
+ bd->PrevUserCallbackMonitor = glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback);
561
+ bd->InstalledCallbacks = true;
562
+ }
563
+
564
+ void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window)
565
+ {
566
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
567
+ IM_ASSERT(bd->InstalledCallbacks == true && "Callbacks not installed!");
568
+ IM_ASSERT(bd->Window == window);
569
+
570
+ glfwSetWindowFocusCallback(window, bd->PrevUserCallbackWindowFocus);
571
+ glfwSetCursorEnterCallback(window, bd->PrevUserCallbackCursorEnter);
572
+ glfwSetCursorPosCallback(window, bd->PrevUserCallbackCursorPos);
573
+ glfwSetMouseButtonCallback(window, bd->PrevUserCallbackMousebutton);
574
+ glfwSetScrollCallback(window, bd->PrevUserCallbackScroll);
575
+ glfwSetKeyCallback(window, bd->PrevUserCallbackKey);
576
+ glfwSetCharCallback(window, bd->PrevUserCallbackChar);
577
+ glfwSetMonitorCallback(bd->PrevUserCallbackMonitor);
578
+ bd->InstalledCallbacks = false;
579
+ bd->PrevUserCallbackWindowFocus = nullptr;
580
+ bd->PrevUserCallbackCursorEnter = nullptr;
581
+ bd->PrevUserCallbackCursorPos = nullptr;
582
+ bd->PrevUserCallbackMousebutton = nullptr;
583
+ bd->PrevUserCallbackScroll = nullptr;
584
+ bd->PrevUserCallbackKey = nullptr;
585
+ bd->PrevUserCallbackChar = nullptr;
586
+ bd->PrevUserCallbackMonitor = nullptr;
587
+ }
588
+
589
+ // Set to 'true' to enable chaining installed callbacks for all windows (including secondary viewports created by backends or by user.
590
+ // This is 'false' by default meaning we only chain callbacks for the main viewport.
591
+ // We cannot set this to 'true' by default because user callbacks code may be not testing the 'window' parameter of their callback.
592
+ // If you set this to 'true' your user callback code will need to make sure you are testing the 'window' parameter.
593
+ void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows)
594
+ {
595
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
596
+ bd->CallbacksChainForAllWindows = chain_for_all_windows;
597
+ }
598
+
599
+ #ifdef __EMSCRIPTEN__
600
+ #if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 34020240817
601
+ void ImGui_ImplGlfw_EmscriptenOpenURL(const char* url) { if (url) emscripten::glfw3::OpenURL(url); }
602
+ #else
603
+ EM_JS(void, ImGui_ImplGlfw_EmscriptenOpenURL, (const char* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); });
604
+ #endif
605
+ #endif
606
+
607
+ static bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks, GlfwClientApi client_api)
608
+ {
609
+ ImGuiIO& io = ImGui::GetIO();
610
+ IMGUI_CHECKVERSION();
611
+ IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
612
+ //printf("GLFW_VERSION: %d.%d.%d (%d)", GLFW_VERSION_MAJOR, GLFW_VERSION_MINOR, GLFW_VERSION_REVISION, GLFW_VERSION_COMBINED);
613
+
614
+ // Setup backend capabilities flags
615
+ ImGui_ImplGlfw_Data* bd = IM_NEW(ImGui_ImplGlfw_Data)();
616
+ io.BackendPlatformUserData = (void*)bd;
617
+ io.BackendPlatformName = "imgui_impl_glfw";
618
+ io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
619
+ io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
620
+ #ifndef __EMSCRIPTEN__
621
+ io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
622
+ #endif
623
+ #if GLFW_HAS_MOUSE_PASSTHROUGH || GLFW_HAS_WINDOW_HOVERED
624
+ io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can call io.AddMouseViewportEvent() with correct data (optional)
625
+ #endif
626
+
627
+ bd->Window = window;
628
+ bd->Time = 0.0;
629
+ bd->WantUpdateMonitors = true;
630
+
631
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
632
+ platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* text) { glfwSetClipboardString(nullptr, text); };
633
+ platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) { return glfwGetClipboardString(nullptr); };
634
+ #ifdef __EMSCRIPTEN__
635
+ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplGlfw_EmscriptenOpenURL(url); return true; };
636
+ #endif
637
+
638
+ // Create mouse cursors
639
+ // (By design, on X11 cursors are user configurable and some cursors may be missing. When a cursor doesn't exist,
640
+ // GLFW will emit an error which will often be printed by the app, so we temporarily disable error reporting.
641
+ // Missing cursors will return nullptr and our _UpdateMouseCursor() function will use the Arrow cursor instead.)
642
+ GLFWerrorfun prev_error_callback = glfwSetErrorCallback(nullptr);
643
+ bd->MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
644
+ bd->MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);
645
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);
646
+ bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);
647
+ bd->MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);
648
+ #if GLFW_HAS_NEW_CURSORS
649
+ bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);
650
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);
651
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);
652
+ bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);
653
+ #else
654
+ bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
655
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
656
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
657
+ bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);
658
+ #endif
659
+ glfwSetErrorCallback(prev_error_callback);
660
+ #if GLFW_HAS_GETERROR && !defined(__EMSCRIPTEN__) // Eat errors (see #5908)
661
+ (void)glfwGetError(nullptr);
662
+ #endif
663
+
664
+ // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.
665
+ if (install_callbacks)
666
+ ImGui_ImplGlfw_InstallCallbacks(window);
667
+
668
+ // Update monitor a first time during init
669
+ // (note: monitor callback are broken in GLFW 3.2 and earlier, see github.com/glfw/glfw/issues/784)
670
+ ImGui_ImplGlfw_UpdateMonitors();
671
+ glfwSetMonitorCallback(ImGui_ImplGlfw_MonitorCallback);
672
+
673
+ // Set platform dependent data in viewport
674
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
675
+ main_viewport->PlatformHandle = (void*)bd->Window;
676
+ #ifdef _WIN32
677
+ main_viewport->PlatformHandleRaw = glfwGetWin32Window(bd->Window);
678
+ #elif defined(__APPLE__)
679
+ main_viewport->PlatformHandleRaw = (void*)glfwGetCocoaWindow(bd->Window);
680
+ #else
681
+ IM_UNUSED(main_viewport);
682
+ #endif
683
+ ImGui_ImplGlfw_InitMultiViewportSupport();
684
+
685
+ // Windows: register a WndProc hook so we can intercept some messages.
686
+ #ifdef _WIN32
687
+ bd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC);
688
+ IM_ASSERT(bd->PrevWndProc != nullptr);
689
+ ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc);
690
+ #endif
691
+
692
+ // Emscripten: the same application can run on various platforms, so we detect the Apple platform at runtime
693
+ // to override io.ConfigMacOSXBehaviors from its default (which is always false in Emscripten).
694
+ #ifdef __EMSCRIPTEN__
695
+ #if EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3 >= 34020240817
696
+ if (emscripten::glfw3::IsRuntimePlatformApple())
697
+ {
698
+ ImGui::GetIO().ConfigMacOSXBehaviors = true;
699
+
700
+ // Due to how the browser (poorly) handles the Meta Key, this line essentially disables repeats when used.
701
+ // This means that Meta + V only registers a single key-press, even if the keys are held.
702
+ // This is a compromise for dealing with this issue in ImGui since ImGui implements key repeat itself.
703
+ // See https://github.com/pongasoft/emscripten-glfw/blob/v3.4.0.20240817/docs/Usage.md#the-problem-of-the-super-key
704
+ emscripten::glfw3::SetSuperPlusKeyTimeouts(10, 10);
705
+ }
706
+ #endif
707
+ #endif
708
+
709
+ bd->ClientApi = client_api;
710
+ return true;
711
+ }
712
+
713
+ bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)
714
+ {
715
+ return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);
716
+ }
717
+
718
+ bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks)
719
+ {
720
+ return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Vulkan);
721
+ }
722
+
723
+ bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks)
724
+ {
725
+ return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_Unknown);
726
+ }
727
+
728
+ void ImGui_ImplGlfw_Shutdown()
729
+ {
730
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
731
+ IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
732
+ ImGuiIO& io = ImGui::GetIO();
733
+
734
+ ImGui_ImplGlfw_ShutdownMultiViewportSupport();
735
+
736
+ if (bd->InstalledCallbacks)
737
+ ImGui_ImplGlfw_RestoreCallbacks(bd->Window);
738
+ #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
739
+ if (bd->CanvasSelector)
740
+ emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, nullptr);
741
+ #endif
742
+
743
+ for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
744
+ glfwDestroyCursor(bd->MouseCursors[cursor_n]);
745
+
746
+ // Windows: restore our WndProc hook
747
+ #ifdef _WIN32
748
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
749
+ ::SetWindowLongPtrW((HWND)main_viewport->PlatformHandleRaw, GWLP_WNDPROC, (LONG_PTR)bd->PrevWndProc);
750
+ bd->PrevWndProc = nullptr;
751
+ #endif
752
+
753
+ io.BackendPlatformName = nullptr;
754
+ io.BackendPlatformUserData = nullptr;
755
+ io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_PlatformHasViewports | ImGuiBackendFlags_HasMouseHoveredViewport);
756
+ IM_DELETE(bd);
757
+ }
758
+
759
+ static void ImGui_ImplGlfw_UpdateMouseData()
760
+ {
761
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
762
+ ImGuiIO& io = ImGui::GetIO();
763
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
764
+
765
+ ImGuiID mouse_viewport_id = 0;
766
+ const ImVec2 mouse_pos_prev = io.MousePos;
767
+ for (int n = 0; n < platform_io.Viewports.Size; n++)
768
+ {
769
+ ImGuiViewport* viewport = platform_io.Viewports[n];
770
+ GLFWwindow* window = (GLFWwindow*)viewport->PlatformHandle;
771
+
772
+ #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
773
+ const bool is_window_focused = true;
774
+ #else
775
+ const bool is_window_focused = glfwGetWindowAttrib(window, GLFW_FOCUSED) != 0;
776
+ #endif
777
+ if (is_window_focused)
778
+ {
779
+ // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
780
+ // When multi-viewports are enabled, all Dear ImGui positions are same as OS positions.
781
+ if (io.WantSetMousePos)
782
+ glfwSetCursorPos(window, (double)(mouse_pos_prev.x - viewport->Pos.x), (double)(mouse_pos_prev.y - viewport->Pos.y));
783
+
784
+ // (Optional) Fallback to provide mouse position when focused (ImGui_ImplGlfw_CursorPosCallback already provides this when hovered or captured)
785
+ if (bd->MouseWindow == nullptr)
786
+ {
787
+ double mouse_x, mouse_y;
788
+ glfwGetCursorPos(window, &mouse_x, &mouse_y);
789
+ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
790
+ {
791
+ // Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
792
+ // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
793
+ int window_x, window_y;
794
+ glfwGetWindowPos(window, &window_x, &window_y);
795
+ mouse_x += window_x;
796
+ mouse_y += window_y;
797
+ }
798
+ bd->LastValidMousePos = ImVec2((float)mouse_x, (float)mouse_y);
799
+ io.AddMousePosEvent((float)mouse_x, (float)mouse_y);
800
+ }
801
+ }
802
+
803
+ // (Optional) When using multiple viewports: call io.AddMouseViewportEvent() with the viewport the OS mouse cursor is hovering.
804
+ // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, Dear imGui will ignore this field and infer the information using its flawed heuristic.
805
+ // - [X] GLFW >= 3.3 backend ON WINDOWS ONLY does correctly ignore viewports with the _NoInputs flag (since we implement hit via our WndProc hook)
806
+ // On other platforms we rely on the library fallbacking to its own search when reporting a viewport with _NoInputs flag.
807
+ // - [!] GLFW <= 3.2 backend CANNOT correctly ignore viewports with the _NoInputs flag, and CANNOT reported Hovered Viewport because of mouse capture.
808
+ // Some backend are not able to handle that correctly. If a backend report an hovered viewport that has the _NoInputs flag (e.g. when dragging a window
809
+ // for docking, the viewport has the _NoInputs flag in order to allow us to find the viewport under), then Dear ImGui is forced to ignore the value reported
810
+ // by the backend, and use its flawed heuristic to guess the viewport behind.
811
+ // - [X] GLFW backend correctly reports this regardless of another viewport behind focused and dragged from (we need this to find a useful drag and drop target).
812
+ // FIXME: This is currently only correct on Win32. See what we do below with the WM_NCHITTEST, missing an equivalent for other systems.
813
+ // See https://github.com/glfw/glfw/issues/1236 if you want to help in making this a GLFW feature.
814
+ #if GLFW_HAS_MOUSE_PASSTHROUGH
815
+ const bool window_no_input = (viewport->Flags & ImGuiViewportFlags_NoInputs) != 0;
816
+ glfwSetWindowAttrib(window, GLFW_MOUSE_PASSTHROUGH, window_no_input);
817
+ #endif
818
+ #if GLFW_HAS_MOUSE_PASSTHROUGH || GLFW_HAS_WINDOW_HOVERED
819
+ if (glfwGetWindowAttrib(window, GLFW_HOVERED))
820
+ mouse_viewport_id = viewport->ID;
821
+ #else
822
+ // We cannot use bd->MouseWindow maintained from CursorEnter/Leave callbacks, because it is locked to the window capturing mouse.
823
+ #endif
824
+ }
825
+
826
+ if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
827
+ io.AddMouseViewportEvent(mouse_viewport_id);
828
+ }
829
+
830
+ static void ImGui_ImplGlfw_UpdateMouseCursor()
831
+ {
832
+ ImGuiIO& io = ImGui::GetIO();
833
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
834
+ if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) || glfwGetInputMode(bd->Window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED)
835
+ return;
836
+
837
+ ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
838
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
839
+ for (int n = 0; n < platform_io.Viewports.Size; n++)
840
+ {
841
+ GLFWwindow* window = (GLFWwindow*)platform_io.Viewports[n]->PlatformHandle;
842
+ if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
843
+ {
844
+ // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
845
+ glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
846
+ }
847
+ else
848
+ {
849
+ // Show OS mouse cursor
850
+ // FIXME-PLATFORM: Unfocused windows seems to fail changing the mouse cursor with GLFW 3.2, but 3.3 works here.
851
+ glfwSetCursor(window, bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow]);
852
+ glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
853
+ }
854
+ }
855
+ }
856
+
857
+ // Update gamepad inputs
858
+ static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
859
+ static void ImGui_ImplGlfw_UpdateGamepads()
860
+ {
861
+ ImGuiIO& io = ImGui::GetIO();
862
+ if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
863
+ return;
864
+
865
+ io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
866
+ #if GLFW_HAS_GAMEPAD_API && !defined(EMSCRIPTEN_USE_EMBEDDED_GLFW3)
867
+ GLFWgamepadstate gamepad;
868
+ if (!glfwGetGamepadState(GLFW_JOYSTICK_1, &gamepad))
869
+ return;
870
+ #define MAP_BUTTON(KEY_NO, BUTTON_NO, _UNUSED) do { io.AddKeyEvent(KEY_NO, gamepad.buttons[BUTTON_NO] != 0); } while (0)
871
+ #define MAP_ANALOG(KEY_NO, AXIS_NO, _UNUSED, V0, V1) do { float v = gamepad.axes[AXIS_NO]; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0)
872
+ #else
873
+ int axes_count = 0, buttons_count = 0;
874
+ const float* axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &axes_count);
875
+ const unsigned char* buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &buttons_count);
876
+ if (axes_count == 0 || buttons_count == 0)
877
+ return;
878
+ #define MAP_BUTTON(KEY_NO, _UNUSED, BUTTON_NO) do { io.AddKeyEvent(KEY_NO, (buttons_count > BUTTON_NO && buttons[BUTTON_NO] == GLFW_PRESS)); } while (0)
879
+ #define MAP_ANALOG(KEY_NO, _UNUSED, AXIS_NO, V0, V1) do { float v = (axes_count > AXIS_NO) ? axes[AXIS_NO] : V0; v = (v - V0) / (V1 - V0); io.AddKeyAnalogEvent(KEY_NO, v > 0.10f, Saturate(v)); } while (0)
880
+ #endif
881
+ io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
882
+ MAP_BUTTON(ImGuiKey_GamepadStart, GLFW_GAMEPAD_BUTTON_START, 7);
883
+ MAP_BUTTON(ImGuiKey_GamepadBack, GLFW_GAMEPAD_BUTTON_BACK, 6);
884
+ MAP_BUTTON(ImGuiKey_GamepadFaceLeft, GLFW_GAMEPAD_BUTTON_X, 2); // Xbox X, PS Square
885
+ MAP_BUTTON(ImGuiKey_GamepadFaceRight, GLFW_GAMEPAD_BUTTON_B, 1); // Xbox B, PS Circle
886
+ MAP_BUTTON(ImGuiKey_GamepadFaceUp, GLFW_GAMEPAD_BUTTON_Y, 3); // Xbox Y, PS Triangle
887
+ MAP_BUTTON(ImGuiKey_GamepadFaceDown, GLFW_GAMEPAD_BUTTON_A, 0); // Xbox A, PS Cross
888
+ MAP_BUTTON(ImGuiKey_GamepadDpadLeft, GLFW_GAMEPAD_BUTTON_DPAD_LEFT, 13);
889
+ MAP_BUTTON(ImGuiKey_GamepadDpadRight, GLFW_GAMEPAD_BUTTON_DPAD_RIGHT, 11);
890
+ MAP_BUTTON(ImGuiKey_GamepadDpadUp, GLFW_GAMEPAD_BUTTON_DPAD_UP, 10);
891
+ MAP_BUTTON(ImGuiKey_GamepadDpadDown, GLFW_GAMEPAD_BUTTON_DPAD_DOWN, 12);
892
+ MAP_BUTTON(ImGuiKey_GamepadL1, GLFW_GAMEPAD_BUTTON_LEFT_BUMPER, 4);
893
+ MAP_BUTTON(ImGuiKey_GamepadR1, GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER, 5);
894
+ MAP_ANALOG(ImGuiKey_GamepadL2, GLFW_GAMEPAD_AXIS_LEFT_TRIGGER, 4, -0.75f, +1.0f);
895
+ MAP_ANALOG(ImGuiKey_GamepadR2, GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER, 5, -0.75f, +1.0f);
896
+ MAP_BUTTON(ImGuiKey_GamepadL3, GLFW_GAMEPAD_BUTTON_LEFT_THUMB, 8);
897
+ MAP_BUTTON(ImGuiKey_GamepadR3, GLFW_GAMEPAD_BUTTON_RIGHT_THUMB, 9);
898
+ MAP_ANALOG(ImGuiKey_GamepadLStickLeft, GLFW_GAMEPAD_AXIS_LEFT_X, 0, -0.25f, -1.0f);
899
+ MAP_ANALOG(ImGuiKey_GamepadLStickRight, GLFW_GAMEPAD_AXIS_LEFT_X, 0, +0.25f, +1.0f);
900
+ MAP_ANALOG(ImGuiKey_GamepadLStickUp, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, -0.25f, -1.0f);
901
+ MAP_ANALOG(ImGuiKey_GamepadLStickDown, GLFW_GAMEPAD_AXIS_LEFT_Y, 1, +0.25f, +1.0f);
902
+ MAP_ANALOG(ImGuiKey_GamepadRStickLeft, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, -0.25f, -1.0f);
903
+ MAP_ANALOG(ImGuiKey_GamepadRStickRight, GLFW_GAMEPAD_AXIS_RIGHT_X, 2, +0.25f, +1.0f);
904
+ MAP_ANALOG(ImGuiKey_GamepadRStickUp, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, -0.25f, -1.0f);
905
+ MAP_ANALOG(ImGuiKey_GamepadRStickDown, GLFW_GAMEPAD_AXIS_RIGHT_Y, 3, +0.25f, +1.0f);
906
+ #undef MAP_BUTTON
907
+ #undef MAP_ANALOG
908
+ }
909
+
910
+ static void ImGui_ImplGlfw_UpdateMonitors()
911
+ {
912
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
913
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
914
+ bd->WantUpdateMonitors = false;
915
+
916
+ int monitors_count = 0;
917
+ GLFWmonitor** glfw_monitors = glfwGetMonitors(&monitors_count);
918
+ if (monitors_count == 0) // Preserve existing monitor list if there are none. Happens on macOS sleeping (#5683)
919
+ return;
920
+
921
+ platform_io.Monitors.resize(0);
922
+ for (int n = 0; n < monitors_count; n++)
923
+ {
924
+ ImGuiPlatformMonitor monitor;
925
+ int x, y;
926
+ glfwGetMonitorPos(glfw_monitors[n], &x, &y);
927
+ const GLFWvidmode* vid_mode = glfwGetVideoMode(glfw_monitors[n]);
928
+ if (vid_mode == nullptr)
929
+ continue; // Failed to get Video mode (e.g. Emscripten does not support this function)
930
+ monitor.MainPos = monitor.WorkPos = ImVec2((float)x, (float)y);
931
+ monitor.MainSize = monitor.WorkSize = ImVec2((float)vid_mode->width, (float)vid_mode->height);
932
+ #if GLFW_HAS_MONITOR_WORK_AREA
933
+ int w, h;
934
+ glfwGetMonitorWorkarea(glfw_monitors[n], &x, &y, &w, &h);
935
+ if (w > 0 && h > 0) // Workaround a small GLFW issue reporting zero on monitor changes: https://github.com/glfw/glfw/pull/1761
936
+ {
937
+ monitor.WorkPos = ImVec2((float)x, (float)y);
938
+ monitor.WorkSize = ImVec2((float)w, (float)h);
939
+ }
940
+ #endif
941
+ #if GLFW_HAS_PER_MONITOR_DPI
942
+ // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, which generally needs to be set in the manifest or at runtime.
943
+ float x_scale, y_scale;
944
+ glfwGetMonitorContentScale(glfw_monitors[n], &x_scale, &y_scale);
945
+ if (x_scale == 0.0f)
946
+ continue; // Some accessibility applications are declaring virtual monitors with a DPI of 0, see #7902.
947
+ monitor.DpiScale = x_scale;
948
+ #endif
949
+ monitor.PlatformHandle = (void*)glfw_monitors[n]; // [...] GLFW doc states: "guaranteed to be valid only until the monitor configuration changes"
950
+ platform_io.Monitors.push_back(monitor);
951
+ }
952
+ }
953
+
954
+ void ImGui_ImplGlfw_NewFrame()
955
+ {
956
+ ImGuiIO& io = ImGui::GetIO();
957
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
958
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplGlfw_InitForXXX()?");
959
+
960
+ // Setup display size (every frame to accommodate for window resizing)
961
+ int w, h;
962
+ int display_w, display_h;
963
+ glfwGetWindowSize(bd->Window, &w, &h);
964
+ glfwGetFramebufferSize(bd->Window, &display_w, &display_h);
965
+ io.DisplaySize = ImVec2((float)w, (float)h);
966
+ if (w > 0 && h > 0)
967
+ io.DisplayFramebufferScale = ImVec2((float)display_w / (float)w, (float)display_h / (float)h);
968
+ if (bd->WantUpdateMonitors)
969
+ ImGui_ImplGlfw_UpdateMonitors();
970
+
971
+ // Setup time step
972
+ // (Accept glfwGetTime() not returning a monotonically increasing value. Seems to happens on disconnecting peripherals and probably on VMs and Emscripten, see #6491, #6189, #6114, #3644)
973
+ double current_time = glfwGetTime();
974
+ if (current_time <= bd->Time)
975
+ current_time = bd->Time + 0.00001f;
976
+ io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f);
977
+ bd->Time = current_time;
978
+
979
+ bd->MouseIgnoreButtonUp = false;
980
+ ImGui_ImplGlfw_UpdateMouseData();
981
+ ImGui_ImplGlfw_UpdateMouseCursor();
982
+
983
+ // Update game controllers (if enabled and available)
984
+ ImGui_ImplGlfw_UpdateGamepads();
985
+ }
986
+
987
+ // GLFW doesn't provide a portable sleep function
988
+ void ImGui_ImplGlfw_Sleep(int milliseconds)
989
+ {
990
+ #ifdef _WIN32
991
+ ::Sleep(milliseconds);
992
+ #else
993
+ usleep(milliseconds * 1000);
994
+ #endif
995
+ }
996
+
997
+ #ifdef EMSCRIPTEN_USE_EMBEDDED_GLFW3
998
+ static EM_BOOL ImGui_ImplGlfw_OnCanvasSizeChange(int event_type, const EmscriptenUiEvent* event, void* user_data)
999
+ {
1000
+ ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data;
1001
+ double canvas_width, canvas_height;
1002
+ emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height);
1003
+ glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height);
1004
+ return true;
1005
+ }
1006
+
1007
+ static EM_BOOL ImGui_ImplEmscripten_FullscreenChangeCallback(int event_type, const EmscriptenFullscreenChangeEvent* event, void* user_data)
1008
+ {
1009
+ ImGui_ImplGlfw_Data* bd = (ImGui_ImplGlfw_Data*)user_data;
1010
+ double canvas_width, canvas_height;
1011
+ emscripten_get_element_css_size(bd->CanvasSelector, &canvas_width, &canvas_height);
1012
+ glfwSetWindowSize(bd->Window, (int)canvas_width, (int)canvas_height);
1013
+ return true;
1014
+ }
1015
+
1016
+ // 'canvas_selector' is a CSS selector. The event listener is applied to the first element that matches the query.
1017
+ // STRING MUST PERSIST FOR THE APPLICATION DURATION. PLEASE USE A STRING LITERAL OR ENSURE POINTER WILL STAY VALID.
1018
+ void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow*, const char* canvas_selector)
1019
+ {
1020
+ IM_ASSERT(canvas_selector != nullptr);
1021
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
1022
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplGlfw_InitForXXX()?");
1023
+
1024
+ bd->CanvasSelector = canvas_selector;
1025
+ emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, bd, false, ImGui_ImplGlfw_OnCanvasSizeChange);
1026
+ emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, bd, false, ImGui_ImplEmscripten_FullscreenChangeCallback);
1027
+
1028
+ // Change the size of the GLFW window according to the size of the canvas
1029
+ ImGui_ImplGlfw_OnCanvasSizeChange(EMSCRIPTEN_EVENT_RESIZE, {}, bd);
1030
+
1031
+ // Register Emscripten Wheel callback to workaround issue in Emscripten GLFW Emulation (#6096)
1032
+ // We intentionally do not check 'if (install_callbacks)' here, as some users may set it to false and call GLFW callback themselves.
1033
+ // FIXME: May break chaining in case user registered their own Emscripten callback?
1034
+ emscripten_set_wheel_callback(bd->CanvasSelector, nullptr, false, ImGui_ImplEmscripten_WheelCallback);
1035
+ }
1036
+ #elif defined(EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3)
1037
+ // When using --use-port=contrib.glfw3 for the GLFW implementation, you can override the behavior of this call
1038
+ // by invoking emscripten_glfw_make_canvas_resizable afterward.
1039
+ // See https://github.com/pongasoft/emscripten-glfw/blob/master/docs/Usage.md#how-to-make-the-canvas-resizable-by-the-user for an explanation
1040
+ void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow* window, const char* canvas_selector)
1041
+ {
1042
+ GLFWwindow* w = (GLFWwindow*)(EM_ASM_INT({ return Module.glfwGetWindow(UTF8ToString($0)); }, canvas_selector));
1043
+ IM_ASSERT(window == w); // Sanity check
1044
+ IM_UNUSED(w);
1045
+ emscripten_glfw_make_canvas_resizable(window, "window", nullptr);
1046
+ }
1047
+ #endif // #ifdef EMSCRIPTEN_USE_PORT_CONTRIB_GLFW3
1048
+
1049
+
1050
+ //--------------------------------------------------------------------------------------------------------
1051
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
1052
+ // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
1053
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
1054
+ //--------------------------------------------------------------------------------------------------------
1055
+
1056
+ // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
1057
+ struct ImGui_ImplGlfw_ViewportData
1058
+ {
1059
+ GLFWwindow* Window;
1060
+ bool WindowOwned;
1061
+ int IgnoreWindowPosEventFrame;
1062
+ int IgnoreWindowSizeEventFrame;
1063
+ #ifdef _WIN32
1064
+ WNDPROC PrevWndProc;
1065
+ #endif
1066
+
1067
+ ImGui_ImplGlfw_ViewportData() { memset(this, 0, sizeof(*this)); IgnoreWindowSizeEventFrame = IgnoreWindowPosEventFrame = -1; }
1068
+ ~ImGui_ImplGlfw_ViewportData() { IM_ASSERT(Window == nullptr); }
1069
+ };
1070
+
1071
+ static void ImGui_ImplGlfw_WindowCloseCallback(GLFWwindow* window)
1072
+ {
1073
+ if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle(window))
1074
+ viewport->PlatformRequestClose = true;
1075
+ }
1076
+
1077
+ // GLFW may dispatch window pos/size events after calling glfwSetWindowPos()/glfwSetWindowSize().
1078
+ // However: depending on the platform the callback may be invoked at different time:
1079
+ // - on Windows it appears to be called within the glfwSetWindowPos()/glfwSetWindowSize() call
1080
+ // - on Linux it is queued and invoked during glfwPollEvents()
1081
+ // Because the event doesn't always fire on glfwSetWindowXXX() we use a frame counter tag to only
1082
+ // ignore recent glfwSetWindowXXX() calls.
1083
+ static void ImGui_ImplGlfw_WindowPosCallback(GLFWwindow* window, int, int)
1084
+ {
1085
+ if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle(window))
1086
+ {
1087
+ if (ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData)
1088
+ {
1089
+ bool ignore_event = (ImGui::GetFrameCount() <= vd->IgnoreWindowPosEventFrame + 1);
1090
+ //data->IgnoreWindowPosEventFrame = -1;
1091
+ if (ignore_event)
1092
+ return;
1093
+ }
1094
+ viewport->PlatformRequestMove = true;
1095
+ }
1096
+ }
1097
+
1098
+ static void ImGui_ImplGlfw_WindowSizeCallback(GLFWwindow* window, int, int)
1099
+ {
1100
+ if (ImGuiViewport* viewport = ImGui::FindViewportByPlatformHandle(window))
1101
+ {
1102
+ if (ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData)
1103
+ {
1104
+ bool ignore_event = (ImGui::GetFrameCount() <= vd->IgnoreWindowSizeEventFrame + 1);
1105
+ //data->IgnoreWindowSizeEventFrame = -1;
1106
+ if (ignore_event)
1107
+ return;
1108
+ }
1109
+ viewport->PlatformRequestResize = true;
1110
+ }
1111
+ }
1112
+
1113
+ static void ImGui_ImplGlfw_CreateWindow(ImGuiViewport* viewport)
1114
+ {
1115
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
1116
+ ImGui_ImplGlfw_ViewportData* vd = IM_NEW(ImGui_ImplGlfw_ViewportData)();
1117
+ viewport->PlatformUserData = vd;
1118
+
1119
+ // Workaround for Linux: ignore mouse up events corresponding to losing focus of the previously focused window (#7733, #3158, #7922)
1120
+ #ifdef __linux__
1121
+ bd->MouseIgnoreButtonUpWaitForFocusLoss = true;
1122
+ #endif
1123
+
1124
+ // GLFW 3.2 unfortunately always set focus on glfwCreateWindow() if GLFW_VISIBLE is set, regardless of GLFW_FOCUSED
1125
+ // With GLFW 3.3, the hint GLFW_FOCUS_ON_SHOW fixes this problem
1126
+ glfwWindowHint(GLFW_VISIBLE, false);
1127
+ glfwWindowHint(GLFW_FOCUSED, false);
1128
+ #if GLFW_HAS_FOCUS_ON_SHOW
1129
+ glfwWindowHint(GLFW_FOCUS_ON_SHOW, false);
1130
+ #endif
1131
+ glfwWindowHint(GLFW_DECORATED, (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? false : true);
1132
+ #if GLFW_HAS_WINDOW_TOPMOST
1133
+ glfwWindowHint(GLFW_FLOATING, (viewport->Flags & ImGuiViewportFlags_TopMost) ? true : false);
1134
+ #endif
1135
+ GLFWwindow* share_window = (bd->ClientApi == GlfwClientApi_OpenGL) ? bd->Window : nullptr;
1136
+ vd->Window = glfwCreateWindow((int)viewport->Size.x, (int)viewport->Size.y, "No Title Yet", nullptr, share_window);
1137
+ vd->WindowOwned = true;
1138
+ viewport->PlatformHandle = (void*)vd->Window;
1139
+ #ifdef _WIN32
1140
+ viewport->PlatformHandleRaw = glfwGetWin32Window(vd->Window);
1141
+ #elif defined(__APPLE__)
1142
+ viewport->PlatformHandleRaw = (void*)glfwGetCocoaWindow(vd->Window);
1143
+ #endif
1144
+ glfwSetWindowPos(vd->Window, (int)viewport->Pos.x, (int)viewport->Pos.y);
1145
+
1146
+ // Install GLFW callbacks for secondary viewports
1147
+ glfwSetWindowFocusCallback(vd->Window, ImGui_ImplGlfw_WindowFocusCallback);
1148
+ glfwSetCursorEnterCallback(vd->Window, ImGui_ImplGlfw_CursorEnterCallback);
1149
+ glfwSetCursorPosCallback(vd->Window, ImGui_ImplGlfw_CursorPosCallback);
1150
+ glfwSetMouseButtonCallback(vd->Window, ImGui_ImplGlfw_MouseButtonCallback);
1151
+ glfwSetScrollCallback(vd->Window, ImGui_ImplGlfw_ScrollCallback);
1152
+ glfwSetKeyCallback(vd->Window, ImGui_ImplGlfw_KeyCallback);
1153
+ glfwSetCharCallback(vd->Window, ImGui_ImplGlfw_CharCallback);
1154
+ glfwSetWindowCloseCallback(vd->Window, ImGui_ImplGlfw_WindowCloseCallback);
1155
+ glfwSetWindowPosCallback(vd->Window, ImGui_ImplGlfw_WindowPosCallback);
1156
+ glfwSetWindowSizeCallback(vd->Window, ImGui_ImplGlfw_WindowSizeCallback);
1157
+ if (bd->ClientApi == GlfwClientApi_OpenGL)
1158
+ {
1159
+ glfwMakeContextCurrent(vd->Window);
1160
+ glfwSwapInterval(0);
1161
+ }
1162
+ }
1163
+
1164
+ static void ImGui_ImplGlfw_DestroyWindow(ImGuiViewport* viewport)
1165
+ {
1166
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
1167
+ if (ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData)
1168
+ {
1169
+ if (vd->WindowOwned)
1170
+ {
1171
+ #if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)
1172
+ HWND hwnd = (HWND)viewport->PlatformHandleRaw;
1173
+ ::RemovePropA(hwnd, "IMGUI_VIEWPORT");
1174
+ #endif
1175
+
1176
+ // Release any keys that were pressed in the window being destroyed and are still held down,
1177
+ // because we will not receive any release events after window is destroyed.
1178
+ for (int i = 0; i < IM_ARRAYSIZE(bd->KeyOwnerWindows); i++)
1179
+ if (bd->KeyOwnerWindows[i] == vd->Window)
1180
+ ImGui_ImplGlfw_KeyCallback(vd->Window, i, 0, GLFW_RELEASE, 0); // Later params are only used for main viewport, on which this function is never called.
1181
+
1182
+ glfwDestroyWindow(vd->Window);
1183
+ }
1184
+ vd->Window = nullptr;
1185
+ IM_DELETE(vd);
1186
+ }
1187
+ viewport->PlatformUserData = viewport->PlatformHandle = nullptr;
1188
+ }
1189
+
1190
+ static void ImGui_ImplGlfw_ShowWindow(ImGuiViewport* viewport)
1191
+ {
1192
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1193
+
1194
+ #if defined(_WIN32)
1195
+ // GLFW hack: Hide icon from task bar
1196
+ HWND hwnd = (HWND)viewport->PlatformHandleRaw;
1197
+ if (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon)
1198
+ {
1199
+ LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
1200
+ ex_style &= ~WS_EX_APPWINDOW;
1201
+ ex_style |= WS_EX_TOOLWINDOW;
1202
+ ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style);
1203
+ }
1204
+
1205
+ // GLFW hack: install hook for WM_NCHITTEST message handler
1206
+ #if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED && defined(_WIN32)
1207
+ ::SetPropA(hwnd, "IMGUI_VIEWPORT", viewport);
1208
+ vd->PrevWndProc = (WNDPROC)::GetWindowLongPtrW(hwnd, GWLP_WNDPROC);
1209
+ ::SetWindowLongPtrW(hwnd, GWLP_WNDPROC, (LONG_PTR)ImGui_ImplGlfw_WndProc);
1210
+ #endif
1211
+
1212
+ #if !GLFW_HAS_FOCUS_ON_SHOW
1213
+ // GLFW hack: GLFW 3.2 has a bug where glfwShowWindow() also activates/focus the window.
1214
+ // The fix was pushed to GLFW repository on 2018/01/09 and should be included in GLFW 3.3 via a GLFW_FOCUS_ON_SHOW window attribute.
1215
+ // See https://github.com/glfw/glfw/issues/1189
1216
+ // FIXME-VIEWPORT: Implement same work-around for Linux/OSX in the meanwhile.
1217
+ if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
1218
+ {
1219
+ ::ShowWindow(hwnd, SW_SHOWNA);
1220
+ return;
1221
+ }
1222
+ #endif
1223
+ #endif
1224
+
1225
+ glfwShowWindow(vd->Window);
1226
+ }
1227
+
1228
+ static ImVec2 ImGui_ImplGlfw_GetWindowPos(ImGuiViewport* viewport)
1229
+ {
1230
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1231
+ int x = 0, y = 0;
1232
+ glfwGetWindowPos(vd->Window, &x, &y);
1233
+ return ImVec2((float)x, (float)y);
1234
+ }
1235
+
1236
+ static void ImGui_ImplGlfw_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
1237
+ {
1238
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1239
+ vd->IgnoreWindowPosEventFrame = ImGui::GetFrameCount();
1240
+ glfwSetWindowPos(vd->Window, (int)pos.x, (int)pos.y);
1241
+ }
1242
+
1243
+ static ImVec2 ImGui_ImplGlfw_GetWindowSize(ImGuiViewport* viewport)
1244
+ {
1245
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1246
+ int w = 0, h = 0;
1247
+ glfwGetWindowSize(vd->Window, &w, &h);
1248
+ return ImVec2((float)w, (float)h);
1249
+ }
1250
+
1251
+ static void ImGui_ImplGlfw_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
1252
+ {
1253
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1254
+ #if __APPLE__ && !GLFW_HAS_OSX_WINDOW_POS_FIX
1255
+ // Native OS windows are positioned from the bottom-left corner on macOS, whereas on other platforms they are
1256
+ // positioned from the upper-left corner. GLFW makes an effort to convert macOS style coordinates, however it
1257
+ // doesn't handle it when changing size. We are manually moving the window in order for changes of size to be based
1258
+ // on the upper-left corner.
1259
+ int x, y, width, height;
1260
+ glfwGetWindowPos(vd->Window, &x, &y);
1261
+ glfwGetWindowSize(vd->Window, &width, &height);
1262
+ glfwSetWindowPos(vd->Window, x, y - height + size.y);
1263
+ #endif
1264
+ vd->IgnoreWindowSizeEventFrame = ImGui::GetFrameCount();
1265
+ glfwSetWindowSize(vd->Window, (int)size.x, (int)size.y);
1266
+ }
1267
+
1268
+ static void ImGui_ImplGlfw_SetWindowTitle(ImGuiViewport* viewport, const char* title)
1269
+ {
1270
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1271
+ glfwSetWindowTitle(vd->Window, title);
1272
+ }
1273
+
1274
+ static void ImGui_ImplGlfw_SetWindowFocus(ImGuiViewport* viewport)
1275
+ {
1276
+ #if GLFW_HAS_FOCUS_WINDOW
1277
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1278
+ glfwFocusWindow(vd->Window);
1279
+ #else
1280
+ // FIXME: What are the effect of not having this function? At the moment imgui doesn't actually call SetWindowFocus - we set that up ahead, will answer that question later.
1281
+ (void)viewport;
1282
+ #endif
1283
+ }
1284
+
1285
+ static bool ImGui_ImplGlfw_GetWindowFocus(ImGuiViewport* viewport)
1286
+ {
1287
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1288
+ return glfwGetWindowAttrib(vd->Window, GLFW_FOCUSED) != 0;
1289
+ }
1290
+
1291
+ static bool ImGui_ImplGlfw_GetWindowMinimized(ImGuiViewport* viewport)
1292
+ {
1293
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1294
+ return glfwGetWindowAttrib(vd->Window, GLFW_ICONIFIED) != 0;
1295
+ }
1296
+
1297
+ #if GLFW_HAS_WINDOW_ALPHA
1298
+ static void ImGui_ImplGlfw_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
1299
+ {
1300
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1301
+ glfwSetWindowOpacity(vd->Window, alpha);
1302
+ }
1303
+ #endif
1304
+
1305
+ static void ImGui_ImplGlfw_RenderWindow(ImGuiViewport* viewport, void*)
1306
+ {
1307
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
1308
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1309
+ if (bd->ClientApi == GlfwClientApi_OpenGL)
1310
+ glfwMakeContextCurrent(vd->Window);
1311
+ }
1312
+
1313
+ static void ImGui_ImplGlfw_SwapBuffers(ImGuiViewport* viewport, void*)
1314
+ {
1315
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
1316
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1317
+ if (bd->ClientApi == GlfwClientApi_OpenGL)
1318
+ {
1319
+ glfwMakeContextCurrent(vd->Window);
1320
+ glfwSwapBuffers(vd->Window);
1321
+ }
1322
+ }
1323
+
1324
+ //--------------------------------------------------------------------------------------------------------
1325
+ // Vulkan support (the Vulkan renderer needs to call a platform-side support function to create the surface)
1326
+ //--------------------------------------------------------------------------------------------------------
1327
+
1328
+ // Avoid including <vulkan.h> so we can build without it
1329
+ #if GLFW_HAS_VULKAN
1330
+ #ifndef VULKAN_H_
1331
+ #define VK_DEFINE_HANDLE(object) typedef struct object##_T* object;
1332
+ #if defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__)
1333
+ #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object;
1334
+ #else
1335
+ #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object;
1336
+ #endif
1337
+ VK_DEFINE_HANDLE(VkInstance)
1338
+ VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR)
1339
+ struct VkAllocationCallbacks;
1340
+ enum VkResult { VK_RESULT_MAX_ENUM = 0x7FFFFFFF };
1341
+ #endif // VULKAN_H_
1342
+ extern "C" { extern GLFWAPI VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface); }
1343
+ static int ImGui_ImplGlfw_CreateVkSurface(ImGuiViewport* viewport, ImU64 vk_instance, const void* vk_allocator, ImU64* out_vk_surface)
1344
+ {
1345
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
1346
+ ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData;
1347
+ IM_UNUSED(bd);
1348
+ IM_ASSERT(bd->ClientApi == GlfwClientApi_Vulkan);
1349
+ VkResult err = glfwCreateWindowSurface((VkInstance)vk_instance, vd->Window, (const VkAllocationCallbacks*)vk_allocator, (VkSurfaceKHR*)out_vk_surface);
1350
+ return (int)err;
1351
+ }
1352
+ #endif // GLFW_HAS_VULKAN
1353
+
1354
+ static void ImGui_ImplGlfw_InitMultiViewportSupport()
1355
+ {
1356
+ // Register platform interface (will be coupled with a renderer interface)
1357
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
1358
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
1359
+ platform_io.Platform_CreateWindow = ImGui_ImplGlfw_CreateWindow;
1360
+ platform_io.Platform_DestroyWindow = ImGui_ImplGlfw_DestroyWindow;
1361
+ platform_io.Platform_ShowWindow = ImGui_ImplGlfw_ShowWindow;
1362
+ platform_io.Platform_SetWindowPos = ImGui_ImplGlfw_SetWindowPos;
1363
+ platform_io.Platform_GetWindowPos = ImGui_ImplGlfw_GetWindowPos;
1364
+ platform_io.Platform_SetWindowSize = ImGui_ImplGlfw_SetWindowSize;
1365
+ platform_io.Platform_GetWindowSize = ImGui_ImplGlfw_GetWindowSize;
1366
+ platform_io.Platform_SetWindowFocus = ImGui_ImplGlfw_SetWindowFocus;
1367
+ platform_io.Platform_GetWindowFocus = ImGui_ImplGlfw_GetWindowFocus;
1368
+ platform_io.Platform_GetWindowMinimized = ImGui_ImplGlfw_GetWindowMinimized;
1369
+ platform_io.Platform_SetWindowTitle = ImGui_ImplGlfw_SetWindowTitle;
1370
+ platform_io.Platform_RenderWindow = ImGui_ImplGlfw_RenderWindow;
1371
+ platform_io.Platform_SwapBuffers = ImGui_ImplGlfw_SwapBuffers;
1372
+ #if GLFW_HAS_WINDOW_ALPHA
1373
+ platform_io.Platform_SetWindowAlpha = ImGui_ImplGlfw_SetWindowAlpha;
1374
+ #endif
1375
+ #if GLFW_HAS_VULKAN
1376
+ platform_io.Platform_CreateVkSurface = ImGui_ImplGlfw_CreateVkSurface;
1377
+ #endif
1378
+
1379
+ // Register main window handle (which is owned by the main application, not by us)
1380
+ // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports.
1381
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
1382
+ ImGui_ImplGlfw_ViewportData* vd = IM_NEW(ImGui_ImplGlfw_ViewportData)();
1383
+ vd->Window = bd->Window;
1384
+ vd->WindowOwned = false;
1385
+ main_viewport->PlatformUserData = vd;
1386
+ main_viewport->PlatformHandle = (void*)bd->Window;
1387
+ }
1388
+
1389
+ static void ImGui_ImplGlfw_ShutdownMultiViewportSupport()
1390
+ {
1391
+ ImGui::DestroyPlatformWindows();
1392
+ }
1393
+
1394
+ //-----------------------------------------------------------------------------
1395
+
1396
+ // WndProc hook (declared here because we will need access to ImGui_ImplGlfw_ViewportData)
1397
+ #ifdef _WIN32
1398
+ static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo()
1399
+ {
1400
+ LPARAM extra_info = ::GetMessageExtraInfo();
1401
+ if ((extra_info & 0xFFFFFF80) == 0xFF515700)
1402
+ return ImGuiMouseSource_Pen;
1403
+ if ((extra_info & 0xFFFFFF80) == 0xFF515780)
1404
+ return ImGuiMouseSource_TouchScreen;
1405
+ return ImGuiMouseSource_Mouse;
1406
+ }
1407
+ static LRESULT CALLBACK ImGui_ImplGlfw_WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1408
+ {
1409
+ ImGui_ImplGlfw_Data* bd = ImGui_ImplGlfw_GetBackendData();
1410
+ WNDPROC prev_wndproc = bd->PrevWndProc;
1411
+ ImGuiViewport* viewport = (ImGuiViewport*)::GetPropA(hWnd, "IMGUI_VIEWPORT");
1412
+ if (viewport != NULL)
1413
+ if (ImGui_ImplGlfw_ViewportData* vd = (ImGui_ImplGlfw_ViewportData*)viewport->PlatformUserData)
1414
+ prev_wndproc = vd->PrevWndProc;
1415
+
1416
+ switch (msg)
1417
+ {
1418
+ // GLFW doesn't allow to distinguish Mouse vs TouchScreen vs Pen.
1419
+ // Add support for Win32 (based on imgui_impl_win32), because we rely on _TouchScreen info to trickle inputs differently.
1420
+ case WM_MOUSEMOVE: case WM_NCMOUSEMOVE:
1421
+ case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_LBUTTONUP:
1422
+ case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_RBUTTONUP:
1423
+ case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_MBUTTONUP:
1424
+ case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: case WM_XBUTTONUP:
1425
+ ImGui::GetIO().AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo());
1426
+ break;
1427
+
1428
+ // We have submitted https://github.com/glfw/glfw/pull/1568 to allow GLFW to support "transparent inputs".
1429
+ // In the meanwhile we implement custom per-platform workarounds here (FIXME-VIEWPORT: Implement same work-around for Linux/OSX!)
1430
+ #if !GLFW_HAS_MOUSE_PASSTHROUGH && GLFW_HAS_WINDOW_HOVERED
1431
+ case WM_NCHITTEST:
1432
+ {
1433
+ // Let mouse pass-through the window. This will allow the backend to call io.AddMouseViewportEvent() properly (which is OPTIONAL).
1434
+ // The ImGuiViewportFlags_NoInputs flag is set while dragging a viewport, as want to detect the window behind the one we are dragging.
1435
+ // If you cannot easily access those viewport flags from your windowing/event code: you may manually synchronize its state e.g. in
1436
+ // your main loop after calling UpdatePlatformWindows(). Iterate all viewports/platform windows and pass the flag to your windowing system.
1437
+ if (viewport && (viewport->Flags & ImGuiViewportFlags_NoInputs))
1438
+ return HTTRANSPARENT;
1439
+ break;
1440
+ }
1441
+ #endif
1442
+ }
1443
+ return ::CallWindowProcW(prev_wndproc, hWnd, msg, wParam, lParam);
1444
+ }
1445
+ #endif // #ifdef _WIN32
1446
+
1447
+ //-----------------------------------------------------------------------------
1448
+
1449
+ #if defined(__clang__)
1450
+ #pragma clang diagnostic pop
1451
+ #endif
1452
+
1453
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_glfw.h ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for GLFW
2
+ // This needs to be used along with a Renderer (e.g. OpenGL3, Vulkan, WebGPU..)
3
+ // (Info: GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan graphics context creation, etc.)
4
+ // (Requires: GLFW 3.1+. Prefer GLFW 3.3+ for full feature support.)
5
+
6
+ // Implemented features:
7
+ // [X] Platform: Clipboard support.
8
+ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen (Windows only).
9
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLFW_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
10
+ // [X] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
11
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Resizing cursors requires GLFW 3.4+! Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
12
+ // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
13
+ // Missing features or Issues:
14
+ // [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor).
15
+
16
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
17
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
18
+ // Learn about Dear ImGui:
19
+ // - FAQ https://dearimgui.com/faq
20
+ // - Getting Started https://dearimgui.com/getting-started
21
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
22
+ // - Introduction, links and more at the top of imgui.cpp
23
+
24
+ #pragma once
25
+ #include "../imgui.h" // IMGUI_IMPL_API
26
+ #ifndef IMGUI_DISABLE
27
+
28
+ struct GLFWwindow;
29
+ struct GLFWmonitor;
30
+
31
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
32
+ IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks);
33
+ IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForVulkan(GLFWwindow* window, bool install_callbacks);
34
+ IMGUI_IMPL_API bool ImGui_ImplGlfw_InitForOther(GLFWwindow* window, bool install_callbacks);
35
+ IMGUI_IMPL_API void ImGui_ImplGlfw_Shutdown();
36
+ IMGUI_IMPL_API void ImGui_ImplGlfw_NewFrame();
37
+
38
+ // Emscripten related initialization phase methods (call after ImGui_ImplGlfw_InitForOpenGL)
39
+ #ifdef __EMSCRIPTEN__
40
+ IMGUI_IMPL_API void ImGui_ImplGlfw_InstallEmscriptenCallbacks(GLFWwindow* window, const char* canvas_selector);
41
+ //static inline void ImGui_ImplGlfw_InstallEmscriptenCanvasResizeCallback(const char* canvas_selector) { ImGui_ImplGlfw_InstallEmscriptenCallbacks(nullptr, canvas_selector); } } // Renamed in 1.91.0
42
+ #endif
43
+
44
+ // GLFW callbacks install
45
+ // - When calling Init with 'install_callbacks=true': ImGui_ImplGlfw_InstallCallbacks() is called. GLFW callbacks will be installed for you. They will chain-call user's previously installed callbacks, if any.
46
+ // - When calling Init with 'install_callbacks=false': GLFW callbacks won't be installed. You will need to call individual function yourself from your own GLFW callbacks.
47
+ IMGUI_IMPL_API void ImGui_ImplGlfw_InstallCallbacks(GLFWwindow* window);
48
+ IMGUI_IMPL_API void ImGui_ImplGlfw_RestoreCallbacks(GLFWwindow* window);
49
+
50
+ // GFLW callbacks options:
51
+ // - Set 'chain_for_all_windows=true' to enable chaining callbacks for all windows (including secondary viewports created by backends or by user)
52
+ IMGUI_IMPL_API void ImGui_ImplGlfw_SetCallbacksChainForAllWindows(bool chain_for_all_windows);
53
+
54
+ // GLFW callbacks (individual callbacks to call yourself if you didn't install callbacks)
55
+ IMGUI_IMPL_API void ImGui_ImplGlfw_WindowFocusCallback(GLFWwindow* window, int focused); // Since 1.84
56
+ IMGUI_IMPL_API void ImGui_ImplGlfw_CursorEnterCallback(GLFWwindow* window, int entered); // Since 1.84
57
+ IMGUI_IMPL_API void ImGui_ImplGlfw_CursorPosCallback(GLFWwindow* window, double x, double y); // Since 1.87
58
+ IMGUI_IMPL_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods);
59
+ IMGUI_IMPL_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset);
60
+ IMGUI_IMPL_API void ImGui_ImplGlfw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
61
+ IMGUI_IMPL_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c);
62
+ IMGUI_IMPL_API void ImGui_ImplGlfw_MonitorCallback(GLFWmonitor* monitor, int event);
63
+
64
+ // GLFW helpers
65
+ IMGUI_IMPL_API void ImGui_ImplGlfw_Sleep(int milliseconds);
66
+
67
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_glut.cpp ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for GLUT/FreeGLUT
2
+ // This needs to be used along with a Renderer (e.g. OpenGL2)
3
+
4
+ // !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!!
5
+ // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!!
6
+ // !!! Nowadays, prefer using GLFW or SDL instead!
7
+
8
+ // Implemented features:
9
+ // [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values are obsolete since 1.87 and not supported since 1.91.5]
10
+ // Missing features or Issues:
11
+ // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I
12
+ // [ ] Platform: Missing horizontal mouse wheel support.
13
+ // [ ] Platform: Missing mouse cursor shape/visibility support.
14
+ // [ ] Platform: Missing clipboard support (not supported by Glut).
15
+ // [ ] Platform: Missing gamepad support.
16
+ // [ ] Platform: Missing multi-viewport support (multiple windows).
17
+
18
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
19
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
20
+ // Learn about Dear ImGui:
21
+ // - FAQ https://dearimgui.com/faq
22
+ // - Getting Started https://dearimgui.com/getting-started
23
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
24
+ // - Introduction, links and more at the top of imgui.cpp
25
+
26
+ // CHANGELOG
27
+ // (minor and older changes stripped away, please see git history for details)
28
+ // 2023-04-17: BREAKING: Removed call to ImGui::NewFrame() from ImGui_ImplGLUT_NewFrame(). Needs to be called from the main application loop, like with every other backends.
29
+ // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
30
+ // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
31
+ // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
32
+ // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
33
+ // 2019-04-03: Misc: Renamed imgui_impl_freeglut.cpp/.h to imgui_impl_glut.cpp/.h.
34
+ // 2019-03-25: Misc: Made io.DeltaTime always above zero.
35
+ // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
36
+ // 2018-03-22: Added GLUT Platform binding.
37
+
38
+ #include "imgui.h"
39
+ #ifndef IMGUI_DISABLE
40
+ #include "imgui_impl_glut.h"
41
+ #define GL_SILENCE_DEPRECATION
42
+ #ifdef __APPLE__
43
+ #include <GLUT/glut.h>
44
+ #else
45
+ #include <GL/freeglut.h>
46
+ #endif
47
+
48
+ #ifdef _MSC_VER
49
+ #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
50
+ #endif
51
+
52
+ static int g_Time = 0; // Current time, in milliseconds
53
+
54
+ // Glut has 1 function for characters and one for "special keys". We map the characters in the 0..255 range and the keys above.
55
+ static ImGuiKey ImGui_ImplGLUT_KeyToImGuiKey(int key)
56
+ {
57
+ switch (key)
58
+ {
59
+ case '\t': return ImGuiKey_Tab;
60
+ case 256 + GLUT_KEY_LEFT: return ImGuiKey_LeftArrow;
61
+ case 256 + GLUT_KEY_RIGHT: return ImGuiKey_RightArrow;
62
+ case 256 + GLUT_KEY_UP: return ImGuiKey_UpArrow;
63
+ case 256 + GLUT_KEY_DOWN: return ImGuiKey_DownArrow;
64
+ case 256 + GLUT_KEY_PAGE_UP: return ImGuiKey_PageUp;
65
+ case 256 + GLUT_KEY_PAGE_DOWN: return ImGuiKey_PageDown;
66
+ case 256 + GLUT_KEY_HOME: return ImGuiKey_Home;
67
+ case 256 + GLUT_KEY_END: return ImGuiKey_End;
68
+ case 256 + GLUT_KEY_INSERT: return ImGuiKey_Insert;
69
+ case 127: return ImGuiKey_Delete;
70
+ case 8: return ImGuiKey_Backspace;
71
+ case ' ': return ImGuiKey_Space;
72
+ case 13: return ImGuiKey_Enter;
73
+ case 27: return ImGuiKey_Escape;
74
+ case 39: return ImGuiKey_Apostrophe;
75
+ case 44: return ImGuiKey_Comma;
76
+ case 45: return ImGuiKey_Minus;
77
+ case 46: return ImGuiKey_Period;
78
+ case 47: return ImGuiKey_Slash;
79
+ case 59: return ImGuiKey_Semicolon;
80
+ case 61: return ImGuiKey_Equal;
81
+ case 91: return ImGuiKey_LeftBracket;
82
+ case 92: return ImGuiKey_Backslash;
83
+ case 93: return ImGuiKey_RightBracket;
84
+ case 96: return ImGuiKey_GraveAccent;
85
+ //case 0: return ImGuiKey_CapsLock;
86
+ //case 0: return ImGuiKey_ScrollLock;
87
+ case 256 + 0x006D: return ImGuiKey_NumLock;
88
+ //case 0: return ImGuiKey_PrintScreen;
89
+ //case 0: return ImGuiKey_Pause;
90
+ //case '0': return ImGuiKey_Keypad0;
91
+ //case '1': return ImGuiKey_Keypad1;
92
+ //case '2': return ImGuiKey_Keypad2;
93
+ //case '3': return ImGuiKey_Keypad3;
94
+ //case '4': return ImGuiKey_Keypad4;
95
+ //case '5': return ImGuiKey_Keypad5;
96
+ //case '6': return ImGuiKey_Keypad6;
97
+ //case '7': return ImGuiKey_Keypad7;
98
+ //case '8': return ImGuiKey_Keypad8;
99
+ //case '9': return ImGuiKey_Keypad9;
100
+ //case 46: return ImGuiKey_KeypadDecimal;
101
+ //case 47: return ImGuiKey_KeypadDivide;
102
+ case 42: return ImGuiKey_KeypadMultiply;
103
+ //case 45: return ImGuiKey_KeypadSubtract;
104
+ case 43: return ImGuiKey_KeypadAdd;
105
+ //case 13: return ImGuiKey_KeypadEnter;
106
+ //case 0: return ImGuiKey_KeypadEqual;
107
+ case 256 + 0x0072: return ImGuiKey_LeftCtrl;
108
+ case 256 + 0x0070: return ImGuiKey_LeftShift;
109
+ case 256 + 0x0074: return ImGuiKey_LeftAlt;
110
+ //case 0: return ImGuiKey_LeftSuper;
111
+ case 256 + 0x0073: return ImGuiKey_RightCtrl;
112
+ case 256 + 0x0071: return ImGuiKey_RightShift;
113
+ case 256 + 0x0075: return ImGuiKey_RightAlt;
114
+ //case 0: return ImGuiKey_RightSuper;
115
+ //case 0: return ImGuiKey_Menu;
116
+ case '0': return ImGuiKey_0;
117
+ case '1': return ImGuiKey_1;
118
+ case '2': return ImGuiKey_2;
119
+ case '3': return ImGuiKey_3;
120
+ case '4': return ImGuiKey_4;
121
+ case '5': return ImGuiKey_5;
122
+ case '6': return ImGuiKey_6;
123
+ case '7': return ImGuiKey_7;
124
+ case '8': return ImGuiKey_8;
125
+ case '9': return ImGuiKey_9;
126
+ case 'A': case 'a': return ImGuiKey_A;
127
+ case 'B': case 'b': return ImGuiKey_B;
128
+ case 'C': case 'c': return ImGuiKey_C;
129
+ case 'D': case 'd': return ImGuiKey_D;
130
+ case 'E': case 'e': return ImGuiKey_E;
131
+ case 'F': case 'f': return ImGuiKey_F;
132
+ case 'G': case 'g': return ImGuiKey_G;
133
+ case 'H': case 'h': return ImGuiKey_H;
134
+ case 'I': case 'i': return ImGuiKey_I;
135
+ case 'J': case 'j': return ImGuiKey_J;
136
+ case 'K': case 'k': return ImGuiKey_K;
137
+ case 'L': case 'l': return ImGuiKey_L;
138
+ case 'M': case 'm': return ImGuiKey_M;
139
+ case 'N': case 'n': return ImGuiKey_N;
140
+ case 'O': case 'o': return ImGuiKey_O;
141
+ case 'P': case 'p': return ImGuiKey_P;
142
+ case 'Q': case 'q': return ImGuiKey_Q;
143
+ case 'R': case 'r': return ImGuiKey_R;
144
+ case 'S': case 's': return ImGuiKey_S;
145
+ case 'T': case 't': return ImGuiKey_T;
146
+ case 'U': case 'u': return ImGuiKey_U;
147
+ case 'V': case 'v': return ImGuiKey_V;
148
+ case 'W': case 'w': return ImGuiKey_W;
149
+ case 'X': case 'x': return ImGuiKey_X;
150
+ case 'Y': case 'y': return ImGuiKey_Y;
151
+ case 'Z': case 'z': return ImGuiKey_Z;
152
+ case 256 + GLUT_KEY_F1: return ImGuiKey_F1;
153
+ case 256 + GLUT_KEY_F2: return ImGuiKey_F2;
154
+ case 256 + GLUT_KEY_F3: return ImGuiKey_F3;
155
+ case 256 + GLUT_KEY_F4: return ImGuiKey_F4;
156
+ case 256 + GLUT_KEY_F5: return ImGuiKey_F5;
157
+ case 256 + GLUT_KEY_F6: return ImGuiKey_F6;
158
+ case 256 + GLUT_KEY_F7: return ImGuiKey_F7;
159
+ case 256 + GLUT_KEY_F8: return ImGuiKey_F8;
160
+ case 256 + GLUT_KEY_F9: return ImGuiKey_F9;
161
+ case 256 + GLUT_KEY_F10: return ImGuiKey_F10;
162
+ case 256 + GLUT_KEY_F11: return ImGuiKey_F11;
163
+ case 256 + GLUT_KEY_F12: return ImGuiKey_F12;
164
+ default: return ImGuiKey_None;
165
+ }
166
+ }
167
+
168
+ bool ImGui_ImplGLUT_Init()
169
+ {
170
+ ImGuiIO& io = ImGui::GetIO();
171
+ IMGUI_CHECKVERSION();
172
+
173
+ #ifdef FREEGLUT
174
+ io.BackendPlatformName = "imgui_impl_glut (freeglut)";
175
+ #else
176
+ io.BackendPlatformName = "imgui_impl_glut";
177
+ #endif
178
+ g_Time = 0;
179
+
180
+ return true;
181
+ }
182
+
183
+ void ImGui_ImplGLUT_InstallFuncs()
184
+ {
185
+ glutReshapeFunc(ImGui_ImplGLUT_ReshapeFunc);
186
+ glutMotionFunc(ImGui_ImplGLUT_MotionFunc);
187
+ glutPassiveMotionFunc(ImGui_ImplGLUT_MotionFunc);
188
+ glutMouseFunc(ImGui_ImplGLUT_MouseFunc);
189
+ #ifdef __FREEGLUT_EXT_H__
190
+ glutMouseWheelFunc(ImGui_ImplGLUT_MouseWheelFunc);
191
+ #endif
192
+ glutKeyboardFunc(ImGui_ImplGLUT_KeyboardFunc);
193
+ glutKeyboardUpFunc(ImGui_ImplGLUT_KeyboardUpFunc);
194
+ glutSpecialFunc(ImGui_ImplGLUT_SpecialFunc);
195
+ glutSpecialUpFunc(ImGui_ImplGLUT_SpecialUpFunc);
196
+ }
197
+
198
+ void ImGui_ImplGLUT_Shutdown()
199
+ {
200
+ ImGuiIO& io = ImGui::GetIO();
201
+ io.BackendPlatformName = nullptr;
202
+ }
203
+
204
+ void ImGui_ImplGLUT_NewFrame()
205
+ {
206
+ // Setup time step
207
+ ImGuiIO& io = ImGui::GetIO();
208
+ int current_time = glutGet(GLUT_ELAPSED_TIME);
209
+ int delta_time_ms = (current_time - g_Time);
210
+ if (delta_time_ms <= 0)
211
+ delta_time_ms = 1;
212
+ io.DeltaTime = delta_time_ms / 1000.0f;
213
+ g_Time = current_time;
214
+ }
215
+
216
+ static void ImGui_ImplGLUT_UpdateKeyModifiers()
217
+ {
218
+ ImGuiIO& io = ImGui::GetIO();
219
+ int glut_key_mods = glutGetModifiers();
220
+ io.AddKeyEvent(ImGuiMod_Ctrl, (glut_key_mods & GLUT_ACTIVE_CTRL) != 0);
221
+ io.AddKeyEvent(ImGuiMod_Shift, (glut_key_mods & GLUT_ACTIVE_SHIFT) != 0);
222
+ io.AddKeyEvent(ImGuiMod_Alt, (glut_key_mods & GLUT_ACTIVE_ALT) != 0);
223
+ }
224
+
225
+ static void ImGui_ImplGLUT_AddKeyEvent(ImGuiKey key, bool down, int native_keycode)
226
+ {
227
+ ImGuiIO& io = ImGui::GetIO();
228
+ io.AddKeyEvent(key, down);
229
+ io.SetKeyEventNativeData(key, native_keycode, -1); // To support legacy indexing (<1.87 user code)
230
+ }
231
+
232
+ void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y)
233
+ {
234
+ // Send character to imgui
235
+ //printf("char_down_func %d '%c'\n", c, c);
236
+ ImGuiIO& io = ImGui::GetIO();
237
+ if (c >= 32)
238
+ io.AddInputCharacter((unsigned int)c);
239
+
240
+ ImGuiKey key = ImGui_ImplGLUT_KeyToImGuiKey(c);
241
+ ImGui_ImplGLUT_AddKeyEvent(key, true, c);
242
+ ImGui_ImplGLUT_UpdateKeyModifiers();
243
+ (void)x; (void)y; // Unused
244
+ }
245
+
246
+ void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y)
247
+ {
248
+ //printf("char_up_func %d '%c'\n", c, c);
249
+ ImGuiKey key = ImGui_ImplGLUT_KeyToImGuiKey(c);
250
+ ImGui_ImplGLUT_AddKeyEvent(key, false, c);
251
+ ImGui_ImplGLUT_UpdateKeyModifiers();
252
+ (void)x; (void)y; // Unused
253
+ }
254
+
255
+ void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y)
256
+ {
257
+ //printf("key_down_func %d\n", key);
258
+ ImGuiKey imgui_key = ImGui_ImplGLUT_KeyToImGuiKey(key + 256);
259
+ ImGui_ImplGLUT_AddKeyEvent(imgui_key, true, key + 256);
260
+ ImGui_ImplGLUT_UpdateKeyModifiers();
261
+ (void)x; (void)y; // Unused
262
+ }
263
+
264
+ void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y)
265
+ {
266
+ //printf("key_up_func %d\n", key);
267
+ ImGuiKey imgui_key = ImGui_ImplGLUT_KeyToImGuiKey(key + 256);
268
+ ImGui_ImplGLUT_AddKeyEvent(imgui_key, false, key + 256);
269
+ ImGui_ImplGLUT_UpdateKeyModifiers();
270
+ (void)x; (void)y; // Unused
271
+ }
272
+
273
+ void ImGui_ImplGLUT_MouseFunc(int glut_button, int state, int x, int y)
274
+ {
275
+ ImGuiIO& io = ImGui::GetIO();
276
+ io.AddMousePosEvent((float)x, (float)y);
277
+ int button = -1;
278
+ if (glut_button == GLUT_LEFT_BUTTON) button = 0;
279
+ if (glut_button == GLUT_RIGHT_BUTTON) button = 1;
280
+ if (glut_button == GLUT_MIDDLE_BUTTON) button = 2;
281
+ if (button != -1 && (state == GLUT_DOWN || state == GLUT_UP))
282
+ io.AddMouseButtonEvent(button, state == GLUT_DOWN);
283
+ }
284
+
285
+ #ifdef __FREEGLUT_EXT_H__
286
+ void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y)
287
+ {
288
+ ImGuiIO& io = ImGui::GetIO();
289
+ io.AddMousePosEvent((float)x, (float)y);
290
+ if (dir != 0)
291
+ io.AddMouseWheelEvent(0.0f, dir > 0 ? 1.0f : -1.0f);
292
+ (void)button; // Unused
293
+ }
294
+ #endif
295
+
296
+ void ImGui_ImplGLUT_ReshapeFunc(int w, int h)
297
+ {
298
+ ImGuiIO& io = ImGui::GetIO();
299
+ io.DisplaySize = ImVec2((float)w, (float)h);
300
+ }
301
+
302
+ void ImGui_ImplGLUT_MotionFunc(int x, int y)
303
+ {
304
+ ImGuiIO& io = ImGui::GetIO();
305
+ io.AddMousePosEvent((float)x, (float)y);
306
+ }
307
+
308
+ //-----------------------------------------------------------------------------
309
+
310
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_glut.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for GLUT/FreeGLUT
2
+ // This needs to be used along with a Renderer (e.g. OpenGL2)
3
+
4
+ // !!! GLUT/FreeGLUT IS OBSOLETE PREHISTORIC SOFTWARE. Using GLUT is not recommended unless you really miss the 90's. !!!
5
+ // !!! If someone or something is teaching you GLUT today, you are being abused. Please show some resistance. !!!
6
+ // !!! Nowadays, prefer using GLFW or SDL instead!
7
+
8
+ // Implemented features:
9
+ // [X] Platform: Partial keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy GLUT values are obsolete since 1.87 and not supported since 1.91.5]
10
+ // Missing features or Issues:
11
+ // [ ] Platform: GLUT is unable to distinguish e.g. Backspace from CTRL+H or TAB from CTRL+I
12
+ // [ ] Platform: Missing horizontal mouse wheel support.
13
+ // [ ] Platform: Missing mouse cursor shape/visibility support.
14
+ // [ ] Platform: Missing clipboard support (not supported by Glut).
15
+ // [ ] Platform: Missing gamepad support.
16
+ // [ ] Platform: Missing multi-viewport support (multiple windows).
17
+
18
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
19
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
20
+ // Learn about Dear ImGui:
21
+ // - FAQ https://dearimgui.com/faq
22
+ // - Getting Started https://dearimgui.com/getting-started
23
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
24
+ // - Introduction, links and more at the top of imgui.cpp
25
+
26
+ #pragma once
27
+ #ifndef IMGUI_DISABLE
28
+ #include "imgui.h" // IMGUI_IMPL_API
29
+
30
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
31
+ IMGUI_IMPL_API bool ImGui_ImplGLUT_Init();
32
+ IMGUI_IMPL_API void ImGui_ImplGLUT_InstallFuncs();
33
+ IMGUI_IMPL_API void ImGui_ImplGLUT_Shutdown();
34
+ IMGUI_IMPL_API void ImGui_ImplGLUT_NewFrame();
35
+
36
+ // You can call ImGui_ImplGLUT_InstallFuncs() to get all those functions installed automatically,
37
+ // or call them yourself from your own GLUT handlers. We are using the same weird names as GLUT for consistency..
38
+ //------------------------------------ GLUT name ---------------------------------------------- Decent Name ---------
39
+ IMGUI_IMPL_API void ImGui_ImplGLUT_ReshapeFunc(int w, int h); // ~ ResizeFunc
40
+ IMGUI_IMPL_API void ImGui_ImplGLUT_MotionFunc(int x, int y); // ~ MouseMoveFunc
41
+ IMGUI_IMPL_API void ImGui_ImplGLUT_MouseFunc(int button, int state, int x, int y); // ~ MouseButtonFunc
42
+ IMGUI_IMPL_API void ImGui_ImplGLUT_MouseWheelFunc(int button, int dir, int x, int y); // ~ MouseWheelFunc
43
+ IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardFunc(unsigned char c, int x, int y); // ~ CharPressedFunc
44
+ IMGUI_IMPL_API void ImGui_ImplGLUT_KeyboardUpFunc(unsigned char c, int x, int y); // ~ CharReleasedFunc
45
+ IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialFunc(int key, int x, int y); // ~ KeyPressedFunc
46
+ IMGUI_IMPL_API void ImGui_ImplGLUT_SpecialUpFunc(int key, int x, int y); // ~ KeyReleasedFunc
47
+
48
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_metal.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for Metal
2
+ // This needs to be used along with a Platform Backend (e.g. OSX)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
8
+
9
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
10
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
11
+ // Learn about Dear ImGui:
12
+ // - FAQ https://dearimgui.com/faq
13
+ // - Getting Started https://dearimgui.com/getting-started
14
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
15
+ // - Introduction, links and more at the top of imgui.cpp
16
+
17
+ #include "imgui.h" // IMGUI_IMPL_API
18
+ #ifndef IMGUI_DISABLE
19
+
20
+ //-----------------------------------------------------------------------------
21
+ // ObjC API
22
+ //-----------------------------------------------------------------------------
23
+
24
+ #ifdef __OBJC__
25
+
26
+ @class MTLRenderPassDescriptor;
27
+ @protocol MTLDevice, MTLCommandBuffer, MTLRenderCommandEncoder;
28
+
29
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
30
+ IMGUI_IMPL_API bool ImGui_ImplMetal_Init(id<MTLDevice> device);
31
+ IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown();
32
+ IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor);
33
+ IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData,
34
+ id<MTLCommandBuffer> commandBuffer,
35
+ id<MTLRenderCommandEncoder> commandEncoder);
36
+
37
+ // Called by Init/NewFrame/Shutdown
38
+ IMGUI_IMPL_API bool ImGui_ImplMetal_CreateFontsTexture(id<MTLDevice> device);
39
+ IMGUI_IMPL_API void ImGui_ImplMetal_DestroyFontsTexture();
40
+ IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(id<MTLDevice> device);
41
+ IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects();
42
+
43
+ #endif
44
+
45
+ //-----------------------------------------------------------------------------
46
+ // C++ API
47
+ //-----------------------------------------------------------------------------
48
+
49
+ // Enable Metal C++ binding support with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file
50
+ // More info about using Metal from C++: https://developer.apple.com/metal/cpp/
51
+
52
+ #ifdef IMGUI_IMPL_METAL_CPP
53
+ #include <Metal/Metal.hpp>
54
+ #ifndef __OBJC__
55
+
56
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
57
+ IMGUI_IMPL_API bool ImGui_ImplMetal_Init(MTL::Device* device);
58
+ IMGUI_IMPL_API void ImGui_ImplMetal_Shutdown();
59
+ IMGUI_IMPL_API void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor);
60
+ IMGUI_IMPL_API void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data,
61
+ MTL::CommandBuffer* commandBuffer,
62
+ MTL::RenderCommandEncoder* commandEncoder);
63
+
64
+ // Called by Init/NewFrame/Shutdown
65
+ IMGUI_IMPL_API bool ImGui_ImplMetal_CreateFontsTexture(MTL::Device* device);
66
+ IMGUI_IMPL_API void ImGui_ImplMetal_DestroyFontsTexture();
67
+ IMGUI_IMPL_API bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device);
68
+ IMGUI_IMPL_API void ImGui_ImplMetal_DestroyDeviceObjects();
69
+
70
+ #endif
71
+ #endif
72
+
73
+ //-----------------------------------------------------------------------------
74
+
75
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_metal.mm ADDED
@@ -0,0 +1,751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for Metal
2
+ // This needs to be used along with a Platform Backend (e.g. OSX)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'MTLTexture' as ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
8
+
9
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
10
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
11
+ // Learn about Dear ImGui:
12
+ // - FAQ https://dearimgui.com/faq
13
+ // - Getting Started https://dearimgui.com/getting-started
14
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
15
+ // - Introduction, links and more at the top of imgui.cpp
16
+
17
+ // CHANGELOG
18
+ // (minor and older changes stripped away, please see git history for details)
19
+ // 2024-XX-XX: Metal: Added support for multiple windows via the ImGuiPlatformIO interface.
20
+ // 2022-08-23: Metal: Update deprecated property 'sampleCount'->'rasterSampleCount'.
21
+ // 2022-07-05: Metal: Add dispatch synchronization.
22
+ // 2022-06-30: Metal: Use __bridge for ARC based systems.
23
+ // 2022-06-01: Metal: Fixed null dereference on exit inside command buffer completion handler.
24
+ // 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts.
25
+ // 2022-01-03: Metal: Ignore ImDrawCmd where ElemCount == 0 (very rare but can technically be manufactured by user code).
26
+ // 2021-12-30: Metal: Added Metal C++ support. Enable with '#define IMGUI_IMPL_METAL_CPP' in your imconfig.h file.
27
+ // 2021-08-24: Metal: Fixed a crash when clipping rect larger than framebuffer is submitted. (#4464)
28
+ // 2021-05-19: Metal: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
29
+ // 2021-02-18: Metal: Change blending equation to preserve alpha in output buffer.
30
+ // 2021-01-25: Metal: Fixed texture storage mode when building on Mac Catalyst.
31
+ // 2019-05-29: Metal: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
32
+ // 2019-04-30: Metal: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
33
+ // 2019-02-11: Metal: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
34
+ // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
35
+ // 2018-07-05: Metal: Added new Metal backend implementation.
36
+
37
+ #include "imgui.h"
38
+ #ifndef IMGUI_DISABLE
39
+ #include "imgui_impl_metal.h"
40
+ #import <time.h>
41
+ #import <Metal/Metal.h>
42
+
43
+ // Forward Declarations
44
+ static void ImGui_ImplMetal_InitMultiViewportSupport();
45
+ static void ImGui_ImplMetal_ShutdownMultiViewportSupport();
46
+ static void ImGui_ImplMetal_CreateDeviceObjectsForPlatformWindows();
47
+ static void ImGui_ImplMetal_InvalidateDeviceObjectsForPlatformWindows();
48
+
49
+ #pragma mark - Support classes
50
+
51
+ // A wrapper around a MTLBuffer object that knows the last time it was reused
52
+ @interface MetalBuffer : NSObject
53
+ @property (nonatomic, strong) id<MTLBuffer> buffer;
54
+ @property (nonatomic, assign) double lastReuseTime;
55
+ - (instancetype)initWithBuffer:(id<MTLBuffer>)buffer;
56
+ @end
57
+
58
+ // An object that encapsulates the data necessary to uniquely identify a
59
+ // render pipeline state. These are used as cache keys.
60
+ @interface FramebufferDescriptor : NSObject<NSCopying>
61
+ @property (nonatomic, assign) unsigned long sampleCount;
62
+ @property (nonatomic, assign) MTLPixelFormat colorPixelFormat;
63
+ @property (nonatomic, assign) MTLPixelFormat depthPixelFormat;
64
+ @property (nonatomic, assign) MTLPixelFormat stencilPixelFormat;
65
+ - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor;
66
+ @end
67
+
68
+ // A singleton that stores long-lived objects that are needed by the Metal
69
+ // renderer backend. Stores the render pipeline state cache and the default
70
+ // font texture, and manages the reusable buffer cache.
71
+ @interface MetalContext : NSObject
72
+ @property (nonatomic, strong) id<MTLDevice> device;
73
+ @property (nonatomic, strong) id<MTLDepthStencilState> depthStencilState;
74
+ @property (nonatomic, strong) FramebufferDescriptor* framebufferDescriptor; // framebuffer descriptor for current frame; transient
75
+ @property (nonatomic, strong) NSMutableDictionary* renderPipelineStateCache; // pipeline cache; keyed on framebuffer descriptors
76
+ @property (nonatomic, strong, nullable) id<MTLTexture> fontTexture;
77
+ @property (nonatomic, strong) NSMutableArray<MetalBuffer*>* bufferCache;
78
+ @property (nonatomic, assign) double lastBufferCachePurge;
79
+ - (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device;
80
+ - (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device;
81
+ @end
82
+
83
+ struct ImGui_ImplMetal_Data
84
+ {
85
+ MetalContext* SharedMetalContext;
86
+
87
+ ImGui_ImplMetal_Data() { memset((void*)this, 0, sizeof(*this)); }
88
+ };
89
+
90
+ static ImGui_ImplMetal_Data* ImGui_ImplMetal_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplMetal_Data*)ImGui::GetIO().BackendRendererUserData : nullptr; }
91
+ static void ImGui_ImplMetal_DestroyBackendData(){ IM_DELETE(ImGui_ImplMetal_GetBackendData()); }
92
+
93
+ static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); }
94
+
95
+ #ifdef IMGUI_IMPL_METAL_CPP
96
+
97
+ #pragma mark - Dear ImGui Metal C++ Backend API
98
+
99
+ bool ImGui_ImplMetal_Init(MTL::Device* device)
100
+ {
101
+ return ImGui_ImplMetal_Init((__bridge id<MTLDevice>)(device));
102
+ }
103
+
104
+ void ImGui_ImplMetal_NewFrame(MTL::RenderPassDescriptor* renderPassDescriptor)
105
+ {
106
+ ImGui_ImplMetal_NewFrame((__bridge MTLRenderPassDescriptor*)(renderPassDescriptor));
107
+ }
108
+
109
+ void ImGui_ImplMetal_RenderDrawData(ImDrawData* draw_data,
110
+ MTL::CommandBuffer* commandBuffer,
111
+ MTL::RenderCommandEncoder* commandEncoder)
112
+ {
113
+ ImGui_ImplMetal_RenderDrawData(draw_data,
114
+ (__bridge id<MTLCommandBuffer>)(commandBuffer),
115
+ (__bridge id<MTLRenderCommandEncoder>)(commandEncoder));
116
+
117
+ }
118
+
119
+ bool ImGui_ImplMetal_CreateFontsTexture(MTL::Device* device)
120
+ {
121
+ return ImGui_ImplMetal_CreateFontsTexture((__bridge id<MTLDevice>)(device));
122
+ }
123
+
124
+ bool ImGui_ImplMetal_CreateDeviceObjects(MTL::Device* device)
125
+ {
126
+ return ImGui_ImplMetal_CreateDeviceObjects((__bridge id<MTLDevice>)(device));
127
+ }
128
+
129
+ #endif // #ifdef IMGUI_IMPL_METAL_CPP
130
+
131
+ #pragma mark - Dear ImGui Metal Backend API
132
+
133
+ bool ImGui_ImplMetal_Init(id<MTLDevice> device)
134
+ {
135
+ ImGuiIO& io = ImGui::GetIO();
136
+ IMGUI_CHECKVERSION();
137
+ IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
138
+
139
+ ImGui_ImplMetal_Data* bd = IM_NEW(ImGui_ImplMetal_Data)();
140
+ io.BackendRendererUserData = (void*)bd;
141
+ io.BackendRendererName = "imgui_impl_metal";
142
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
143
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
144
+
145
+ bd->SharedMetalContext = [[MetalContext alloc] init];
146
+ bd->SharedMetalContext.device = device;
147
+
148
+ ImGui_ImplMetal_InitMultiViewportSupport();
149
+
150
+ return true;
151
+ }
152
+
153
+ void ImGui_ImplMetal_Shutdown()
154
+ {
155
+ ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
156
+ IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
157
+ ImGui_ImplMetal_ShutdownMultiViewportSupport();
158
+ ImGui_ImplMetal_DestroyDeviceObjects();
159
+ ImGui_ImplMetal_DestroyBackendData();
160
+
161
+ ImGuiIO& io = ImGui::GetIO();
162
+ io.BackendRendererName = nullptr;
163
+ io.BackendRendererUserData = nullptr;
164
+ io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
165
+ }
166
+
167
+ void ImGui_ImplMetal_NewFrame(MTLRenderPassDescriptor* renderPassDescriptor)
168
+ {
169
+ ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
170
+ IM_ASSERT(bd != nil && "Context or backend not initialized! Did you call ImGui_ImplMetal_Init()?");
171
+ bd->SharedMetalContext.framebufferDescriptor = [[FramebufferDescriptor alloc] initWithRenderPassDescriptor:renderPassDescriptor];
172
+
173
+ if (bd->SharedMetalContext.depthStencilState == nil)
174
+ ImGui_ImplMetal_CreateDeviceObjects(bd->SharedMetalContext.device);
175
+ }
176
+
177
+ static void ImGui_ImplMetal_SetupRenderState(ImDrawData* drawData, id<MTLCommandBuffer> commandBuffer,
178
+ id<MTLRenderCommandEncoder> commandEncoder, id<MTLRenderPipelineState> renderPipelineState,
179
+ MetalBuffer* vertexBuffer, size_t vertexBufferOffset)
180
+ {
181
+ IM_UNUSED(commandBuffer);
182
+ ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
183
+ [commandEncoder setCullMode:MTLCullModeNone];
184
+ [commandEncoder setDepthStencilState:bd->SharedMetalContext.depthStencilState];
185
+
186
+ // Setup viewport, orthographic projection matrix
187
+ // Our visible imgui space lies from draw_data->DisplayPos (top left) to
188
+ // draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin is typically (0,0) for single viewport apps.
189
+ MTLViewport viewport =
190
+ {
191
+ .originX = 0.0,
192
+ .originY = 0.0,
193
+ .width = (double)(drawData->DisplaySize.x * drawData->FramebufferScale.x),
194
+ .height = (double)(drawData->DisplaySize.y * drawData->FramebufferScale.y),
195
+ .znear = 0.0,
196
+ .zfar = 1.0
197
+ };
198
+ [commandEncoder setViewport:viewport];
199
+
200
+ float L = drawData->DisplayPos.x;
201
+ float R = drawData->DisplayPos.x + drawData->DisplaySize.x;
202
+ float T = drawData->DisplayPos.y;
203
+ float B = drawData->DisplayPos.y + drawData->DisplaySize.y;
204
+ float N = (float)viewport.znear;
205
+ float F = (float)viewport.zfar;
206
+ const float ortho_projection[4][4] =
207
+ {
208
+ { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
209
+ { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
210
+ { 0.0f, 0.0f, 1/(F-N), 0.0f },
211
+ { (R+L)/(L-R), (T+B)/(B-T), N/(F-N), 1.0f },
212
+ };
213
+ [commandEncoder setVertexBytes:&ortho_projection length:sizeof(ortho_projection) atIndex:1];
214
+
215
+ [commandEncoder setRenderPipelineState:renderPipelineState];
216
+
217
+ [commandEncoder setVertexBuffer:vertexBuffer.buffer offset:0 atIndex:0];
218
+ [commandEncoder setVertexBufferOffset:vertexBufferOffset atIndex:0];
219
+ }
220
+
221
+ // Metal Render function.
222
+ void ImGui_ImplMetal_RenderDrawData(ImDrawData* drawData, id<MTLCommandBuffer> commandBuffer, id<MTLRenderCommandEncoder> commandEncoder)
223
+ {
224
+ ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
225
+ MetalContext* ctx = bd->SharedMetalContext;
226
+
227
+ // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
228
+ int fb_width = (int)(drawData->DisplaySize.x * drawData->FramebufferScale.x);
229
+ int fb_height = (int)(drawData->DisplaySize.y * drawData->FramebufferScale.y);
230
+ if (fb_width <= 0 || fb_height <= 0 || drawData->CmdListsCount == 0)
231
+ return;
232
+
233
+ // Try to retrieve a render pipeline state that is compatible with the framebuffer config for this frame
234
+ // The hit rate for this cache should be very near 100%.
235
+ id<MTLRenderPipelineState> renderPipelineState = ctx.renderPipelineStateCache[ctx.framebufferDescriptor];
236
+ if (renderPipelineState == nil)
237
+ {
238
+ // No luck; make a new render pipeline state
239
+ renderPipelineState = [ctx renderPipelineStateForFramebufferDescriptor:ctx.framebufferDescriptor device:commandBuffer.device];
240
+
241
+ // Cache render pipeline state for later reuse
242
+ ctx.renderPipelineStateCache[ctx.framebufferDescriptor] = renderPipelineState;
243
+ }
244
+
245
+ size_t vertexBufferLength = (size_t)drawData->TotalVtxCount * sizeof(ImDrawVert);
246
+ size_t indexBufferLength = (size_t)drawData->TotalIdxCount * sizeof(ImDrawIdx);
247
+ MetalBuffer* vertexBuffer = [ctx dequeueReusableBufferOfLength:vertexBufferLength device:commandBuffer.device];
248
+ MetalBuffer* indexBuffer = [ctx dequeueReusableBufferOfLength:indexBufferLength device:commandBuffer.device];
249
+
250
+ ImGui_ImplMetal_SetupRenderState(drawData, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, 0);
251
+
252
+ // Will project scissor/clipping rectangles into framebuffer space
253
+ ImVec2 clip_off = drawData->DisplayPos; // (0,0) unless using multi-viewports
254
+ ImVec2 clip_scale = drawData->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
255
+
256
+ // Render command lists
257
+ size_t vertexBufferOffset = 0;
258
+ size_t indexBufferOffset = 0;
259
+ for (int n = 0; n < drawData->CmdListsCount; n++)
260
+ {
261
+ const ImDrawList* draw_list = drawData->CmdLists[n];
262
+
263
+ memcpy((char*)vertexBuffer.buffer.contents + vertexBufferOffset, draw_list->VtxBuffer.Data, (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
264
+ memcpy((char*)indexBuffer.buffer.contents + indexBufferOffset, draw_list->IdxBuffer.Data, (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
265
+
266
+ for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
267
+ {
268
+ const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
269
+ if (pcmd->UserCallback)
270
+ {
271
+ // User callback, registered via ImDrawList::AddCallback()
272
+ // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
273
+ if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
274
+ ImGui_ImplMetal_SetupRenderState(drawData, commandBuffer, commandEncoder, renderPipelineState, vertexBuffer, vertexBufferOffset);
275
+ else
276
+ pcmd->UserCallback(draw_list, pcmd);
277
+ }
278
+ else
279
+ {
280
+ // Project scissor/clipping rectangles into framebuffer space
281
+ ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
282
+ ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
283
+
284
+ // Clamp to viewport as setScissorRect() won't accept values that are off bounds
285
+ if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
286
+ if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
287
+ if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
288
+ if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
289
+ if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
290
+ continue;
291
+ if (pcmd->ElemCount == 0) // drawIndexedPrimitives() validation doesn't accept this
292
+ continue;
293
+
294
+ // Apply scissor/clipping rectangle
295
+ MTLScissorRect scissorRect =
296
+ {
297
+ .x = NSUInteger(clip_min.x),
298
+ .y = NSUInteger(clip_min.y),
299
+ .width = NSUInteger(clip_max.x - clip_min.x),
300
+ .height = NSUInteger(clip_max.y - clip_min.y)
301
+ };
302
+ [commandEncoder setScissorRect:scissorRect];
303
+
304
+ // Bind texture, Draw
305
+ if (ImTextureID tex_id = pcmd->GetTexID())
306
+ [commandEncoder setFragmentTexture:(__bridge id<MTLTexture>)(void*)(intptr_t)(tex_id) atIndex:0];
307
+
308
+ [commandEncoder setVertexBufferOffset:(vertexBufferOffset + pcmd->VtxOffset * sizeof(ImDrawVert)) atIndex:0];
309
+ [commandEncoder drawIndexedPrimitives:MTLPrimitiveTypeTriangle
310
+ indexCount:pcmd->ElemCount
311
+ indexType:sizeof(ImDrawIdx) == 2 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32
312
+ indexBuffer:indexBuffer.buffer
313
+ indexBufferOffset:indexBufferOffset + pcmd->IdxOffset * sizeof(ImDrawIdx)];
314
+ }
315
+ }
316
+
317
+ vertexBufferOffset += (size_t)draw_list->VtxBuffer.Size * sizeof(ImDrawVert);
318
+ indexBufferOffset += (size_t)draw_list->IdxBuffer.Size * sizeof(ImDrawIdx);
319
+ }
320
+
321
+ [commandBuffer addCompletedHandler:^(id<MTLCommandBuffer>)
322
+ {
323
+ dispatch_async(dispatch_get_main_queue(), ^{
324
+ ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
325
+ if (bd != nullptr)
326
+ {
327
+ @synchronized(bd->SharedMetalContext.bufferCache)
328
+ {
329
+ [bd->SharedMetalContext.bufferCache addObject:vertexBuffer];
330
+ [bd->SharedMetalContext.bufferCache addObject:indexBuffer];
331
+ }
332
+ }
333
+ });
334
+ }];
335
+ }
336
+
337
+ bool ImGui_ImplMetal_CreateFontsTexture(id<MTLDevice> device)
338
+ {
339
+ ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
340
+ ImGuiIO& io = ImGui::GetIO();
341
+
342
+ // We are retrieving and uploading the font atlas as a 4-channels RGBA texture here.
343
+ // In theory we could call GetTexDataAsAlpha8() and upload a 1-channel texture to save on memory access bandwidth.
344
+ // However, using a shader designed for 1-channel texture would make it less obvious to use the ImTextureID facility to render users own textures.
345
+ // You can make that change in your implementation.
346
+ unsigned char* pixels;
347
+ int width, height;
348
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
349
+ MTLTextureDescriptor* textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
350
+ width:(NSUInteger)width
351
+ height:(NSUInteger)height
352
+ mipmapped:NO];
353
+ textureDescriptor.usage = MTLTextureUsageShaderRead;
354
+ #if TARGET_OS_OSX || TARGET_OS_MACCATALYST
355
+ textureDescriptor.storageMode = MTLStorageModeManaged;
356
+ #else
357
+ textureDescriptor.storageMode = MTLStorageModeShared;
358
+ #endif
359
+ id <MTLTexture> texture = [device newTextureWithDescriptor:textureDescriptor];
360
+ [texture replaceRegion:MTLRegionMake2D(0, 0, (NSUInteger)width, (NSUInteger)height) mipmapLevel:0 withBytes:pixels bytesPerRow:(NSUInteger)width * 4];
361
+ bd->SharedMetalContext.fontTexture = texture;
362
+ io.Fonts->SetTexID((ImTextureID)(intptr_t)(__bridge void*)bd->SharedMetalContext.fontTexture); // ImTextureID == ImU64
363
+
364
+ return (bd->SharedMetalContext.fontTexture != nil);
365
+ }
366
+
367
+ void ImGui_ImplMetal_DestroyFontsTexture()
368
+ {
369
+ ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
370
+ ImGuiIO& io = ImGui::GetIO();
371
+ bd->SharedMetalContext.fontTexture = nil;
372
+ io.Fonts->SetTexID(0);
373
+ }
374
+
375
+ bool ImGui_ImplMetal_CreateDeviceObjects(id<MTLDevice> device)
376
+ {
377
+ ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
378
+ MTLDepthStencilDescriptor* depthStencilDescriptor = [[MTLDepthStencilDescriptor alloc] init];
379
+ depthStencilDescriptor.depthWriteEnabled = NO;
380
+ depthStencilDescriptor.depthCompareFunction = MTLCompareFunctionAlways;
381
+ bd->SharedMetalContext.depthStencilState = [device newDepthStencilStateWithDescriptor:depthStencilDescriptor];
382
+ ImGui_ImplMetal_CreateDeviceObjectsForPlatformWindows();
383
+ ImGui_ImplMetal_CreateFontsTexture(device);
384
+
385
+ return true;
386
+ }
387
+
388
+ void ImGui_ImplMetal_DestroyDeviceObjects()
389
+ {
390
+ ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
391
+ ImGui_ImplMetal_DestroyFontsTexture();
392
+ ImGui_ImplMetal_InvalidateDeviceObjectsForPlatformWindows();
393
+ [bd->SharedMetalContext.renderPipelineStateCache removeAllObjects];
394
+ }
395
+
396
+ #pragma mark - Multi-viewport support
397
+
398
+ #import <QuartzCore/CAMetalLayer.h>
399
+
400
+ #if TARGET_OS_OSX
401
+ #import <Cocoa/Cocoa.h>
402
+ #endif
403
+
404
+ //--------------------------------------------------------------------------------------------------------
405
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
406
+ // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
407
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
408
+ //--------------------------------------------------------------------------------------------------------
409
+
410
+ struct ImGuiViewportDataMetal
411
+ {
412
+ CAMetalLayer* MetalLayer;
413
+ id<MTLCommandQueue> CommandQueue;
414
+ MTLRenderPassDescriptor* RenderPassDescriptor;
415
+ void* Handle = nullptr;
416
+ bool FirstFrame = true;
417
+ };
418
+
419
+ static void ImGui_ImplMetal_CreateWindow(ImGuiViewport* viewport)
420
+ {
421
+ ImGui_ImplMetal_Data* bd = ImGui_ImplMetal_GetBackendData();
422
+ ImGuiViewportDataMetal* data = IM_NEW(ImGuiViewportDataMetal)();
423
+ viewport->RendererUserData = data;
424
+
425
+ // PlatformHandleRaw should always be a NSWindow*, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
426
+ // Some back-ends will leave PlatformHandleRaw == 0, in which case we assume PlatformHandle will contain the NSWindow*.
427
+ void* handle = viewport->PlatformHandleRaw ? viewport->PlatformHandleRaw : viewport->PlatformHandle;
428
+ IM_ASSERT(handle != nullptr);
429
+
430
+ id<MTLDevice> device = bd->SharedMetalContext.device;
431
+ CAMetalLayer* layer = [CAMetalLayer layer];
432
+ layer.device = device;
433
+ layer.framebufferOnly = YES;
434
+ layer.pixelFormat = bd->SharedMetalContext.framebufferDescriptor.colorPixelFormat;
435
+ #if TARGET_OS_OSX
436
+ NSWindow* window = (__bridge NSWindow*)handle;
437
+ NSView* view = window.contentView;
438
+ view.layer = layer;
439
+ view.wantsLayer = YES;
440
+ #endif
441
+ data->MetalLayer = layer;
442
+ data->CommandQueue = [device newCommandQueue];
443
+ data->RenderPassDescriptor = [[MTLRenderPassDescriptor alloc] init];
444
+ data->Handle = handle;
445
+ }
446
+
447
+ static void ImGui_ImplMetal_DestroyWindow(ImGuiViewport* viewport)
448
+ {
449
+ // The main viewport (owned by the application) will always have RendererUserData == 0 since we didn't create the data for it.
450
+ if (ImGuiViewportDataMetal* data = (ImGuiViewportDataMetal*)viewport->RendererUserData)
451
+ IM_DELETE(data);
452
+ viewport->RendererUserData = nullptr;
453
+ }
454
+
455
+ inline static CGSize MakeScaledSize(CGSize size, CGFloat scale)
456
+ {
457
+ return CGSizeMake(size.width * scale, size.height * scale);
458
+ }
459
+
460
+ static void ImGui_ImplMetal_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
461
+ {
462
+ ImGuiViewportDataMetal* data = (ImGuiViewportDataMetal*)viewport->RendererUserData;
463
+ data->MetalLayer.drawableSize = MakeScaledSize(CGSizeMake(size.x, size.y), viewport->DpiScale);
464
+ }
465
+
466
+ static void ImGui_ImplMetal_RenderWindow(ImGuiViewport* viewport, void*)
467
+ {
468
+ ImGuiViewportDataMetal* data = (ImGuiViewportDataMetal*)viewport->RendererUserData;
469
+
470
+ #if TARGET_OS_OSX
471
+ void* handle = viewport->PlatformHandleRaw ? viewport->PlatformHandleRaw : viewport->PlatformHandle;
472
+ NSWindow* window = (__bridge NSWindow*)handle;
473
+
474
+ // Always render the first frame, regardless of occlusionState, to avoid an initial flicker
475
+ if ((window.occlusionState & NSWindowOcclusionStateVisible) == 0 && !data->FirstFrame)
476
+ {
477
+ // Do not render windows which are completely occluded. Calling -[CAMetalLayer nextDrawable] will hang for
478
+ // approximately 1 second if the Metal layer is completely occluded.
479
+ return;
480
+ }
481
+ data->FirstFrame = false;
482
+
483
+ viewport->DpiScale = (float)window.backingScaleFactor;
484
+ if (data->MetalLayer.contentsScale != viewport->DpiScale)
485
+ {
486
+ data->MetalLayer.contentsScale = viewport->DpiScale;
487
+ data->MetalLayer.drawableSize = MakeScaledSize(window.frame.size, viewport->DpiScale);
488
+ }
489
+ viewport->DrawData->FramebufferScale = ImVec2(viewport->DpiScale, viewport->DpiScale);
490
+ #endif
491
+
492
+ id <CAMetalDrawable> drawable = [data->MetalLayer nextDrawable];
493
+ if (drawable == nil)
494
+ return;
495
+
496
+ MTLRenderPassDescriptor* renderPassDescriptor = data->RenderPassDescriptor;
497
+ renderPassDescriptor.colorAttachments[0].texture = drawable.texture;
498
+ renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 0);
499
+ if ((viewport->Flags & ImGuiViewportFlags_NoRendererClear) == 0)
500
+ renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear;
501
+
502
+ id <MTLCommandBuffer> commandBuffer = [data->CommandQueue commandBuffer];
503
+ id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
504
+ ImGui_ImplMetal_RenderDrawData(viewport->DrawData, commandBuffer, renderEncoder);
505
+ [renderEncoder endEncoding];
506
+
507
+ [commandBuffer presentDrawable:drawable];
508
+ [commandBuffer commit];
509
+ }
510
+
511
+ static void ImGui_ImplMetal_InitMultiViewportSupport()
512
+ {
513
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
514
+ platform_io.Renderer_CreateWindow = ImGui_ImplMetal_CreateWindow;
515
+ platform_io.Renderer_DestroyWindow = ImGui_ImplMetal_DestroyWindow;
516
+ platform_io.Renderer_SetWindowSize = ImGui_ImplMetal_SetWindowSize;
517
+ platform_io.Renderer_RenderWindow = ImGui_ImplMetal_RenderWindow;
518
+ }
519
+
520
+ static void ImGui_ImplMetal_ShutdownMultiViewportSupport()
521
+ {
522
+ ImGui::DestroyPlatformWindows();
523
+ }
524
+
525
+ static void ImGui_ImplMetal_CreateDeviceObjectsForPlatformWindows()
526
+ {
527
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
528
+ for (int i = 1; i < platform_io.Viewports.Size; i++)
529
+ if (!platform_io.Viewports[i]->RendererUserData)
530
+ ImGui_ImplMetal_CreateWindow(platform_io.Viewports[i]);
531
+ }
532
+
533
+ static void ImGui_ImplMetal_InvalidateDeviceObjectsForPlatformWindows()
534
+ {
535
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
536
+ for (int i = 1; i < platform_io.Viewports.Size; i++)
537
+ if (platform_io.Viewports[i]->RendererUserData)
538
+ ImGui_ImplMetal_DestroyWindow(platform_io.Viewports[i]);
539
+ }
540
+
541
+ #pragma mark - MetalBuffer implementation
542
+
543
+ @implementation MetalBuffer
544
+ - (instancetype)initWithBuffer:(id<MTLBuffer>)buffer
545
+ {
546
+ if ((self = [super init]))
547
+ {
548
+ _buffer = buffer;
549
+ _lastReuseTime = GetMachAbsoluteTimeInSeconds();
550
+ }
551
+ return self;
552
+ }
553
+ @end
554
+
555
+ #pragma mark - FramebufferDescriptor implementation
556
+
557
+ @implementation FramebufferDescriptor
558
+ - (instancetype)initWithRenderPassDescriptor:(MTLRenderPassDescriptor*)renderPassDescriptor
559
+ {
560
+ if ((self = [super init]))
561
+ {
562
+ _sampleCount = renderPassDescriptor.colorAttachments[0].texture.sampleCount;
563
+ _colorPixelFormat = renderPassDescriptor.colorAttachments[0].texture.pixelFormat;
564
+ _depthPixelFormat = renderPassDescriptor.depthAttachment.texture.pixelFormat;
565
+ _stencilPixelFormat = renderPassDescriptor.stencilAttachment.texture.pixelFormat;
566
+ }
567
+ return self;
568
+ }
569
+
570
+ - (nonnull id)copyWithZone:(nullable NSZone*)zone
571
+ {
572
+ FramebufferDescriptor* copy = [[FramebufferDescriptor allocWithZone:zone] init];
573
+ copy.sampleCount = self.sampleCount;
574
+ copy.colorPixelFormat = self.colorPixelFormat;
575
+ copy.depthPixelFormat = self.depthPixelFormat;
576
+ copy.stencilPixelFormat = self.stencilPixelFormat;
577
+ return copy;
578
+ }
579
+
580
+ - (NSUInteger)hash
581
+ {
582
+ NSUInteger sc = _sampleCount & 0x3;
583
+ NSUInteger cf = _colorPixelFormat & 0x3FF;
584
+ NSUInteger df = _depthPixelFormat & 0x3FF;
585
+ NSUInteger sf = _stencilPixelFormat & 0x3FF;
586
+ NSUInteger hash = (sf << 22) | (df << 12) | (cf << 2) | sc;
587
+ return hash;
588
+ }
589
+
590
+ - (BOOL)isEqual:(id)object
591
+ {
592
+ FramebufferDescriptor* other = object;
593
+ if (![other isKindOfClass:[FramebufferDescriptor class]])
594
+ return NO;
595
+ return other.sampleCount == self.sampleCount &&
596
+ other.colorPixelFormat == self.colorPixelFormat &&
597
+ other.depthPixelFormat == self.depthPixelFormat &&
598
+ other.stencilPixelFormat == self.stencilPixelFormat;
599
+ }
600
+
601
+ @end
602
+
603
+ #pragma mark - MetalContext implementation
604
+
605
+ @implementation MetalContext
606
+ - (instancetype)init
607
+ {
608
+ if ((self = [super init]))
609
+ {
610
+ self.renderPipelineStateCache = [NSMutableDictionary dictionary];
611
+ self.bufferCache = [NSMutableArray array];
612
+ _lastBufferCachePurge = GetMachAbsoluteTimeInSeconds();
613
+ }
614
+ return self;
615
+ }
616
+
617
+ - (MetalBuffer*)dequeueReusableBufferOfLength:(NSUInteger)length device:(id<MTLDevice>)device
618
+ {
619
+ uint64_t now = GetMachAbsoluteTimeInSeconds();
620
+
621
+ @synchronized(self.bufferCache)
622
+ {
623
+ // Purge old buffers that haven't been useful for a while
624
+ if (now - self.lastBufferCachePurge > 1.0)
625
+ {
626
+ NSMutableArray* survivors = [NSMutableArray array];
627
+ for (MetalBuffer* candidate in self.bufferCache)
628
+ if (candidate.lastReuseTime > self.lastBufferCachePurge)
629
+ [survivors addObject:candidate];
630
+ self.bufferCache = [survivors mutableCopy];
631
+ self.lastBufferCachePurge = now;
632
+ }
633
+
634
+ // See if we have a buffer we can reuse
635
+ MetalBuffer* bestCandidate = nil;
636
+ for (MetalBuffer* candidate in self.bufferCache)
637
+ if (candidate.buffer.length >= length && (bestCandidate == nil || bestCandidate.lastReuseTime > candidate.lastReuseTime))
638
+ bestCandidate = candidate;
639
+
640
+ if (bestCandidate != nil)
641
+ {
642
+ [self.bufferCache removeObject:bestCandidate];
643
+ bestCandidate.lastReuseTime = now;
644
+ return bestCandidate;
645
+ }
646
+ }
647
+
648
+ // No luck; make a new buffer
649
+ id<MTLBuffer> backing = [device newBufferWithLength:length options:MTLResourceStorageModeShared];
650
+ return [[MetalBuffer alloc] initWithBuffer:backing];
651
+ }
652
+
653
+ // Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling.
654
+ - (id<MTLRenderPipelineState>)renderPipelineStateForFramebufferDescriptor:(FramebufferDescriptor*)descriptor device:(id<MTLDevice>)device
655
+ {
656
+ NSError* error = nil;
657
+
658
+ NSString* shaderSource = @""
659
+ "#include <metal_stdlib>\n"
660
+ "using namespace metal;\n"
661
+ "\n"
662
+ "struct Uniforms {\n"
663
+ " float4x4 projectionMatrix;\n"
664
+ "};\n"
665
+ "\n"
666
+ "struct VertexIn {\n"
667
+ " float2 position [[attribute(0)]];\n"
668
+ " float2 texCoords [[attribute(1)]];\n"
669
+ " uchar4 color [[attribute(2)]];\n"
670
+ "};\n"
671
+ "\n"
672
+ "struct VertexOut {\n"
673
+ " float4 position [[position]];\n"
674
+ " float2 texCoords;\n"
675
+ " float4 color;\n"
676
+ "};\n"
677
+ "\n"
678
+ "vertex VertexOut vertex_main(VertexIn in [[stage_in]],\n"
679
+ " constant Uniforms &uniforms [[buffer(1)]]) {\n"
680
+ " VertexOut out;\n"
681
+ " out.position = uniforms.projectionMatrix * float4(in.position, 0, 1);\n"
682
+ " out.texCoords = in.texCoords;\n"
683
+ " out.color = float4(in.color) / float4(255.0);\n"
684
+ " return out;\n"
685
+ "}\n"
686
+ "\n"
687
+ "fragment half4 fragment_main(VertexOut in [[stage_in]],\n"
688
+ " texture2d<half, access::sample> texture [[texture(0)]]) {\n"
689
+ " constexpr sampler linearSampler(coord::normalized, min_filter::linear, mag_filter::linear, mip_filter::linear);\n"
690
+ " half4 texColor = texture.sample(linearSampler, in.texCoords);\n"
691
+ " return half4(in.color) * texColor;\n"
692
+ "}\n";
693
+
694
+ id<MTLLibrary> library = [device newLibraryWithSource:shaderSource options:nil error:&error];
695
+ if (library == nil)
696
+ {
697
+ NSLog(@"Error: failed to create Metal library: %@", error);
698
+ return nil;
699
+ }
700
+
701
+ id<MTLFunction> vertexFunction = [library newFunctionWithName:@"vertex_main"];
702
+ id<MTLFunction> fragmentFunction = [library newFunctionWithName:@"fragment_main"];
703
+
704
+ if (vertexFunction == nil || fragmentFunction == nil)
705
+ {
706
+ NSLog(@"Error: failed to find Metal shader functions in library: %@", error);
707
+ return nil;
708
+ }
709
+
710
+ MTLVertexDescriptor* vertexDescriptor = [MTLVertexDescriptor vertexDescriptor];
711
+ vertexDescriptor.attributes[0].offset = offsetof(ImDrawVert, pos);
712
+ vertexDescriptor.attributes[0].format = MTLVertexFormatFloat2; // position
713
+ vertexDescriptor.attributes[0].bufferIndex = 0;
714
+ vertexDescriptor.attributes[1].offset = offsetof(ImDrawVert, uv);
715
+ vertexDescriptor.attributes[1].format = MTLVertexFormatFloat2; // texCoords
716
+ vertexDescriptor.attributes[1].bufferIndex = 0;
717
+ vertexDescriptor.attributes[2].offset = offsetof(ImDrawVert, col);
718
+ vertexDescriptor.attributes[2].format = MTLVertexFormatUChar4; // color
719
+ vertexDescriptor.attributes[2].bufferIndex = 0;
720
+ vertexDescriptor.layouts[0].stepRate = 1;
721
+ vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex;
722
+ vertexDescriptor.layouts[0].stride = sizeof(ImDrawVert);
723
+
724
+ MTLRenderPipelineDescriptor* pipelineDescriptor = [[MTLRenderPipelineDescriptor alloc] init];
725
+ pipelineDescriptor.vertexFunction = vertexFunction;
726
+ pipelineDescriptor.fragmentFunction = fragmentFunction;
727
+ pipelineDescriptor.vertexDescriptor = vertexDescriptor;
728
+ pipelineDescriptor.rasterSampleCount = self.framebufferDescriptor.sampleCount;
729
+ pipelineDescriptor.colorAttachments[0].pixelFormat = self.framebufferDescriptor.colorPixelFormat;
730
+ pipelineDescriptor.colorAttachments[0].blendingEnabled = YES;
731
+ pipelineDescriptor.colorAttachments[0].rgbBlendOperation = MTLBlendOperationAdd;
732
+ pipelineDescriptor.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
733
+ pipelineDescriptor.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
734
+ pipelineDescriptor.colorAttachments[0].alphaBlendOperation = MTLBlendOperationAdd;
735
+ pipelineDescriptor.colorAttachments[0].sourceAlphaBlendFactor = MTLBlendFactorOne;
736
+ pipelineDescriptor.colorAttachments[0].destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
737
+ pipelineDescriptor.depthAttachmentPixelFormat = self.framebufferDescriptor.depthPixelFormat;
738
+ pipelineDescriptor.stencilAttachmentPixelFormat = self.framebufferDescriptor.stencilPixelFormat;
739
+
740
+ id<MTLRenderPipelineState> renderPipelineState = [device newRenderPipelineStateWithDescriptor:pipelineDescriptor error:&error];
741
+ if (error != nil)
742
+ NSLog(@"Error: failed to create Metal pipeline state: %@", error);
743
+
744
+ return renderPipelineState;
745
+ }
746
+
747
+ @end
748
+
749
+ //-----------------------------------------------------------------------------
750
+
751
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_opengl2.cpp ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline)
2
+ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
7
+ // Missing features or Issues:
8
+ // [ ] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
9
+
10
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
11
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
12
+ // Learn about Dear ImGui:
13
+ // - FAQ https://dearimgui.com/faq
14
+ // - Getting Started https://dearimgui.com/getting-started
15
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
16
+ // - Introduction, links and more at the top of imgui.cpp
17
+
18
+ // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
19
+ // **Prefer using the code in imgui_impl_opengl3.cpp**
20
+ // This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
21
+ // If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
22
+ // complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
23
+ // confuse your GPU driver.
24
+ // The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API.
25
+
26
+ // CHANGELOG
27
+ // (minor and older changes stripped away, please see git history for details)
28
+ // 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
29
+ // 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap.
30
+ // 2024-06-28: OpenGL: ImGui_ImplOpenGL2_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL2_DestroyFontsTexture(). (#7748)
31
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
32
+ // 2021-12-08: OpenGL: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86.
33
+ // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
34
+ // 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
35
+ // 2021-01-03: OpenGL: Backup, setup and restore GL_SHADE_MODEL state, disable GL_STENCIL_TEST and disable GL_NORMAL_ARRAY client state to increase compatibility with legacy OpenGL applications.
36
+ // 2020-01-23: OpenGL: Backup, setup and restore GL_TEXTURE_ENV to increase compatibility with legacy OpenGL applications.
37
+ // 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
38
+ // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
39
+ // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
40
+ // 2018-08-03: OpenGL: Disabling/restoring GL_LIGHTING and GL_COLOR_MATERIAL to increase compatibility with legacy OpenGL applications.
41
+ // 2018-06-08: Misc: Extracted imgui_impl_opengl2.cpp/.h away from the old combined GLFW/SDL+OpenGL2 examples.
42
+ // 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
43
+ // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplOpenGL2_RenderDrawData() in the .h file so you can call it yourself.
44
+ // 2017-09-01: OpenGL: Save and restore current polygon mode.
45
+ // 2016-09-10: OpenGL: Uploading font texture as RGBA32 to increase compatibility with users shaders (not ideal).
46
+ // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
47
+
48
+ #include "imgui.h"
49
+ #ifndef IMGUI_DISABLE
50
+ #include "imgui_impl_opengl2.h"
51
+ #include <stdint.h> // intptr_t
52
+
53
+ // Clang/GCC warnings with -Weverything
54
+ #if defined(__clang__)
55
+ #pragma clang diagnostic push
56
+ #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used
57
+ #pragma clang diagnostic ignored "-Wnonportable-system-include-path"
58
+ #endif
59
+
60
+ // Include OpenGL header (without an OpenGL loader) requires a bit of fiddling
61
+ #if defined(_WIN32) && !defined(APIENTRY)
62
+ #define APIENTRY __stdcall // It is customary to use APIENTRY for OpenGL function pointer declarations on all platforms. Additionally, the Windows OpenGL header needs APIENTRY.
63
+ #endif
64
+ #if defined(_WIN32) && !defined(WINGDIAPI)
65
+ #define WINGDIAPI __declspec(dllimport) // Some Windows OpenGL headers need this
66
+ #endif
67
+ #if defined(__APPLE__)
68
+ #define GL_SILENCE_DEPRECATION
69
+ #include <OpenGL/gl.h>
70
+ #else
71
+ #include <GL/gl.h>
72
+ #endif
73
+
74
+ struct ImGui_ImplOpenGL2_Data
75
+ {
76
+ GLuint FontTexture;
77
+
78
+ ImGui_ImplOpenGL2_Data() { memset((void*)this, 0, sizeof(*this)); }
79
+ };
80
+
81
+ // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
82
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
83
+ static ImGui_ImplOpenGL2_Data* ImGui_ImplOpenGL2_GetBackendData()
84
+ {
85
+ return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL2_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
86
+ }
87
+
88
+ // Forward Declarations
89
+ static void ImGui_ImplOpenGL2_InitMultiViewportSupport();
90
+ static void ImGui_ImplOpenGL2_ShutdownMultiViewportSupport();
91
+
92
+ // Functions
93
+ bool ImGui_ImplOpenGL2_Init()
94
+ {
95
+ ImGuiIO& io = ImGui::GetIO();
96
+ IMGUI_CHECKVERSION();
97
+ IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
98
+
99
+ // Setup backend capabilities flags
100
+ ImGui_ImplOpenGL2_Data* bd = IM_NEW(ImGui_ImplOpenGL2_Data)();
101
+ io.BackendRendererUserData = (void*)bd;
102
+ io.BackendRendererName = "imgui_impl_opengl2";
103
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
104
+
105
+ ImGui_ImplOpenGL2_InitMultiViewportSupport();
106
+
107
+ return true;
108
+ }
109
+
110
+ void ImGui_ImplOpenGL2_Shutdown()
111
+ {
112
+ ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData();
113
+ IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
114
+ ImGuiIO& io = ImGui::GetIO();
115
+
116
+ ImGui_ImplOpenGL2_ShutdownMultiViewportSupport();
117
+ ImGui_ImplOpenGL2_DestroyDeviceObjects();
118
+ io.BackendRendererName = nullptr;
119
+ io.BackendRendererUserData = nullptr;
120
+ io.BackendFlags &= ~ImGuiBackendFlags_RendererHasViewports;
121
+ IM_DELETE(bd);
122
+ }
123
+
124
+ void ImGui_ImplOpenGL2_NewFrame()
125
+ {
126
+ ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData();
127
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL2_Init()?");
128
+
129
+ if (!bd->FontTexture)
130
+ ImGui_ImplOpenGL2_CreateDeviceObjects();
131
+ if (!bd->FontTexture)
132
+ ImGui_ImplOpenGL2_CreateFontsTexture();
133
+ }
134
+
135
+ static void ImGui_ImplOpenGL2_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height)
136
+ {
137
+ // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers, polygon fill.
138
+ glEnable(GL_BLEND);
139
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
140
+ //glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // In order to composite our output buffer we need to preserve alpha
141
+ glDisable(GL_CULL_FACE);
142
+ glDisable(GL_DEPTH_TEST);
143
+ glDisable(GL_STENCIL_TEST);
144
+ glDisable(GL_LIGHTING);
145
+ glDisable(GL_COLOR_MATERIAL);
146
+ glEnable(GL_SCISSOR_TEST);
147
+ glEnableClientState(GL_VERTEX_ARRAY);
148
+ glEnableClientState(GL_TEXTURE_COORD_ARRAY);
149
+ glEnableClientState(GL_COLOR_ARRAY);
150
+ glDisableClientState(GL_NORMAL_ARRAY);
151
+ glEnable(GL_TEXTURE_2D);
152
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
153
+ glShadeModel(GL_SMOOTH);
154
+ glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
155
+
156
+ // If you are using this code with non-legacy OpenGL header/contexts (which you should not, prefer using imgui_impl_opengl3.cpp!!),
157
+ // you may need to backup/reset/restore other state, e.g. for current shader using the commented lines below.
158
+ // (DO NOT MODIFY THIS FILE! Add the code in your calling function)
159
+ // GLint last_program;
160
+ // glGetIntegerv(GL_CURRENT_PROGRAM, &last_program);
161
+ // glUseProgram(0);
162
+ // ImGui_ImplOpenGL2_RenderDrawData(...);
163
+ // glUseProgram(last_program)
164
+ // There are potentially many more states you could need to clear/setup that we can't access from default headers.
165
+ // e.g. glBindBuffer(GL_ARRAY_BUFFER, 0), glDisable(GL_TEXTURE_CUBE_MAP).
166
+
167
+ // Setup viewport, orthographic projection matrix
168
+ // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
169
+ glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
170
+ glMatrixMode(GL_PROJECTION);
171
+ glPushMatrix();
172
+ glLoadIdentity();
173
+ glOrtho(draw_data->DisplayPos.x, draw_data->DisplayPos.x + draw_data->DisplaySize.x, draw_data->DisplayPos.y + draw_data->DisplaySize.y, draw_data->DisplayPos.y, -1.0f, +1.0f);
174
+ glMatrixMode(GL_MODELVIEW);
175
+ glPushMatrix();
176
+ glLoadIdentity();
177
+ }
178
+
179
+ // OpenGL2 Render function.
180
+ // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly.
181
+ // This is in order to be able to run within an OpenGL engine that doesn't do so.
182
+ void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data)
183
+ {
184
+ // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
185
+ int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
186
+ int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
187
+ if (fb_width == 0 || fb_height == 0)
188
+ return;
189
+
190
+ // Backup GL state
191
+ GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
192
+ GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
193
+ GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
194
+ GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
195
+ GLint last_shade_model; glGetIntegerv(GL_SHADE_MODEL, &last_shade_model);
196
+ GLint last_tex_env_mode; glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &last_tex_env_mode);
197
+ glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
198
+
199
+ // Setup desired GL state
200
+ ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height);
201
+
202
+ // Will project scissor/clipping rectangles into framebuffer space
203
+ ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
204
+ ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
205
+
206
+ // Render command lists
207
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
208
+ {
209
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
210
+ const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data;
211
+ const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data;
212
+ glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, pos)));
213
+ glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, uv)));
214
+ glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (const GLvoid*)((const char*)vtx_buffer + offsetof(ImDrawVert, col)));
215
+
216
+ for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
217
+ {
218
+ const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
219
+ if (pcmd->UserCallback)
220
+ {
221
+ // User callback, registered via ImDrawList::AddCallback()
222
+ // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
223
+ if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
224
+ ImGui_ImplOpenGL2_SetupRenderState(draw_data, fb_width, fb_height);
225
+ else
226
+ pcmd->UserCallback(draw_list, pcmd);
227
+ }
228
+ else
229
+ {
230
+ // Project scissor/clipping rectangles into framebuffer space
231
+ ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
232
+ ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
233
+ if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
234
+ continue;
235
+
236
+ // Apply scissor/clipping rectangle (Y is inverted in OpenGL)
237
+ glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y));
238
+
239
+ // Bind texture, Draw
240
+ glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID());
241
+ glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset);
242
+ }
243
+ }
244
+ }
245
+
246
+ // Restore modified GL state
247
+ glDisableClientState(GL_COLOR_ARRAY);
248
+ glDisableClientState(GL_TEXTURE_COORD_ARRAY);
249
+ glDisableClientState(GL_VERTEX_ARRAY);
250
+ glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture);
251
+ glMatrixMode(GL_MODELVIEW);
252
+ glPopMatrix();
253
+ glMatrixMode(GL_PROJECTION);
254
+ glPopMatrix();
255
+ glPopAttrib();
256
+ glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]);
257
+ glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
258
+ glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
259
+ glShadeModel(last_shade_model);
260
+ glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, last_tex_env_mode);
261
+ }
262
+
263
+ bool ImGui_ImplOpenGL2_CreateFontsTexture()
264
+ {
265
+ // Build texture atlas
266
+ ImGuiIO& io = ImGui::GetIO();
267
+ ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData();
268
+ unsigned char* pixels;
269
+ int width, height;
270
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
271
+
272
+ // Upload texture to graphics system
273
+ // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
274
+ GLint last_texture;
275
+ glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
276
+ glGenTextures(1, &bd->FontTexture);
277
+ glBindTexture(GL_TEXTURE_2D, bd->FontTexture);
278
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
279
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
280
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
281
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
282
+ glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
283
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
284
+
285
+ // Store our identifier
286
+ io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
287
+
288
+ // Restore state
289
+ glBindTexture(GL_TEXTURE_2D, last_texture);
290
+
291
+ return true;
292
+ }
293
+
294
+ void ImGui_ImplOpenGL2_DestroyFontsTexture()
295
+ {
296
+ ImGuiIO& io = ImGui::GetIO();
297
+ ImGui_ImplOpenGL2_Data* bd = ImGui_ImplOpenGL2_GetBackendData();
298
+ if (bd->FontTexture)
299
+ {
300
+ glDeleteTextures(1, &bd->FontTexture);
301
+ io.Fonts->SetTexID(0);
302
+ bd->FontTexture = 0;
303
+ }
304
+ }
305
+
306
+ bool ImGui_ImplOpenGL2_CreateDeviceObjects()
307
+ {
308
+ return ImGui_ImplOpenGL2_CreateFontsTexture();
309
+ }
310
+
311
+ void ImGui_ImplOpenGL2_DestroyDeviceObjects()
312
+ {
313
+ ImGui_ImplOpenGL2_DestroyFontsTexture();
314
+ }
315
+
316
+
317
+ //--------------------------------------------------------------------------------------------------------
318
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
319
+ // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
320
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
321
+ //--------------------------------------------------------------------------------------------------------
322
+
323
+ static void ImGui_ImplOpenGL2_RenderWindow(ImGuiViewport* viewport, void*)
324
+ {
325
+ if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
326
+ {
327
+ ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
328
+ glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
329
+ glClear(GL_COLOR_BUFFER_BIT);
330
+ }
331
+ ImGui_ImplOpenGL2_RenderDrawData(viewport->DrawData);
332
+ }
333
+
334
+ static void ImGui_ImplOpenGL2_InitMultiViewportSupport()
335
+ {
336
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
337
+ platform_io.Renderer_RenderWindow = ImGui_ImplOpenGL2_RenderWindow;
338
+ }
339
+
340
+ static void ImGui_ImplOpenGL2_ShutdownMultiViewportSupport()
341
+ {
342
+ ImGui::DestroyPlatformWindows();
343
+ }
344
+
345
+ //-----------------------------------------------------------------------------
346
+
347
+ #if defined(__clang__)
348
+ #pragma clang diagnostic pop
349
+ #endif
350
+
351
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_opengl2.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline)
2
+ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
3
+
4
+ // Implemented features:
5
+ // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
6
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
7
+ // Missing features or Issues:
8
+ // [ ] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
9
+
10
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
11
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
12
+ // Learn about Dear ImGui:
13
+ // - FAQ https://dearimgui.com/faq
14
+ // - Getting Started https://dearimgui.com/getting-started
15
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
16
+ // - Introduction, links and more at the top of imgui.cpp
17
+
18
+ // **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
19
+ // **Prefer using the code in imgui_impl_opengl3.cpp**
20
+ // This code is mostly provided as a reference to learn how ImGui integration works, because it is shorter to read.
21
+ // If your code is using GL3+ context or any semi modern OpenGL calls, using this is likely to make everything more
22
+ // complicated, will require your code to reset every single OpenGL attributes to their initial state, and might
23
+ // confuse your GPU driver.
24
+ // The GL2 code is unable to reset attributes or even call e.g. "glUseProgram(0)" because they don't exist in that API.
25
+
26
+ #pragma once
27
+ #include "imgui.h" // IMGUI_IMPL_API
28
+ #ifndef IMGUI_DISABLE
29
+
30
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
31
+ IMGUI_IMPL_API bool ImGui_ImplOpenGL2_Init();
32
+ IMGUI_IMPL_API void ImGui_ImplOpenGL2_Shutdown();
33
+ IMGUI_IMPL_API void ImGui_ImplOpenGL2_NewFrame();
34
+ IMGUI_IMPL_API void ImGui_ImplOpenGL2_RenderDrawData(ImDrawData* draw_data);
35
+
36
+ // Called by Init/NewFrame/Shutdown
37
+ IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateFontsTexture();
38
+ IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyFontsTexture();
39
+ IMGUI_IMPL_API bool ImGui_ImplOpenGL2_CreateDeviceObjects();
40
+ IMGUI_IMPL_API void ImGui_ImplOpenGL2_DestroyDeviceObjects();
41
+
42
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_opengl3.cpp ADDED
@@ -0,0 +1,1005 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
2
+ // - Desktop GL: 2.x 3.x 4.x
3
+ // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
4
+ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
5
+
6
+ // Implemented features:
7
+ // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
8
+ // [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!]
9
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
10
+
11
+ // About WebGL/ES:
12
+ // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES.
13
+ // - This is done automatically on iOS, Android and Emscripten targets.
14
+ // - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h.
15
+
16
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
17
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
18
+ // Learn about Dear ImGui:
19
+ // - FAQ https://dearimgui.com/faq
20
+ // - Getting Started https://dearimgui.com/getting-started
21
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
22
+ // - Introduction, links and more at the top of imgui.cpp
23
+
24
+ // CHANGELOG
25
+ // (minor and older changes stripped away, please see git history for details)
26
+ // 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
27
+ // 2024-10-07: OpenGL: Changed default texture sampler to Clamp instead of Repeat/Wrap.
28
+ // 2024-06-28: OpenGL: ImGui_ImplOpenGL3_NewFrame() recreates font texture if it has been destroyed by ImGui_ImplOpenGL3_DestroyFontsTexture(). (#7748)
29
+ // 2024-05-07: OpenGL: Update loader for Linux to support EGL/GLVND. (#7562)
30
+ // 2024-04-16: OpenGL: Detect ES3 contexts on desktop based on version string, to e.g. avoid calling glPolygonMode() on them. (#7447)
31
+ // 2024-01-09: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" and variants, fixing regression on distros missing a symlink.
32
+ // 2023-11-08: OpenGL: Update GL3W based imgui_impl_opengl3_loader.h to load "libGL.so" instead of "libGL.so.1", accommodating for NetBSD systems having only "libGL.so.3" available. (#6983)
33
+ // 2023-10-05: OpenGL: Rename symbols in our internal loader so that LTO compilation with another copy of gl3w is possible. (#6875, #6668, #4445)
34
+ // 2023-06-20: OpenGL: Fixed erroneous use glGetIntegerv(GL_CONTEXT_PROFILE_MASK) on contexts lower than 3.2. (#6539, #6333)
35
+ // 2023-05-09: OpenGL: Support for glBindSampler() backup/restore on ES3. (#6375)
36
+ // 2023-04-18: OpenGL: Restore front and back polygon mode separately when supported by context. (#6333)
37
+ // 2023-03-23: OpenGL: Properly restoring "no shader program bound" if it was the case prior to running the rendering function. (#6267, #6220, #6224)
38
+ // 2023-03-15: OpenGL: Fixed GL loader crash when GL_VERSION returns NULL. (#6154, #4445, #3530)
39
+ // 2023-03-06: OpenGL: Fixed restoration of a potentially deleted OpenGL program, by calling glIsProgram(). (#6220, #6224)
40
+ // 2022-11-09: OpenGL: Reverted use of glBufferSubData(), too many corruptions issues + old issues seemingly can't be reproed with Intel drivers nowadays (revert 2021-12-15 and 2022-05-23 changes).
41
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
42
+ // 2022-09-27: OpenGL: Added ability to '#define IMGUI_IMPL_OPENGL_DEBUG'.
43
+ // 2022-05-23: OpenGL: Reworking 2021-12-15 "Using buffer orphaning" so it only happens on Intel GPU, seems to cause problems otherwise. (#4468, #4825, #4832, #5127).
44
+ // 2022-05-13: OpenGL: Fixed state corruption on OpenGL ES 2.0 due to not preserving GL_ELEMENT_ARRAY_BUFFER_BINDING and vertex attribute states.
45
+ // 2021-12-15: OpenGL: Using buffer orphaning + glBufferSubData(), seems to fix leaks with multi-viewports with some Intel HD drivers.
46
+ // 2021-08-23: OpenGL: Fixed ES 3.0 shader ("#version 300 es") use normal precision floats to avoid wobbly rendering at HD resolutions.
47
+ // 2021-08-19: OpenGL: Embed and use our own minimal GL loader (imgui_impl_opengl3_loader.h), removing requirement and support for third-party loader.
48
+ // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
49
+ // 2021-06-25: OpenGL: Use OES_vertex_array extension on Emscripten + backup/restore current state.
50
+ // 2021-06-21: OpenGL: Destroy individual vertex/fragment shader objects right after they are linked into the main shader.
51
+ // 2021-05-24: OpenGL: Access GL_CLIP_ORIGIN when "GL_ARB_clip_control" extension is detected, inside of just OpenGL 4.5 version.
52
+ // 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
53
+ // 2021-04-06: OpenGL: Don't try to read GL_CLIP_ORIGIN unless we're OpenGL 4.5 or greater.
54
+ // 2021-02-18: OpenGL: Change blending equation to preserve alpha in output buffer.
55
+ // 2021-01-03: OpenGL: Backup, setup and restore GL_STENCIL_TEST state.
56
+ // 2020-10-23: OpenGL: Backup, setup and restore GL_PRIMITIVE_RESTART state.
57
+ // 2020-10-15: OpenGL: Use glGetString(GL_VERSION) instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x)
58
+ // 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 context which have the defines set by a loader.
59
+ // 2020-07-10: OpenGL: Added support for glad2 OpenGL loader.
60
+ // 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX.
61
+ // 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix.
62
+ // 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset.
63
+ // 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader.
64
+ // 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader.
65
+ // 2019-10-25: OpenGL: Using a combination of GL define and runtime GL version to decide whether to use glDrawElementsBaseVertex(). Fix building with pre-3.2 GL loaders.
66
+ // 2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility.
67
+ // 2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call.
68
+ // 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
69
+ // 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
70
+ // 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop.
71
+ // 2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early.
72
+ // 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0).
73
+ // 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader.
74
+ // 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
75
+ // 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450).
76
+ // 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
77
+ // 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN.
78
+ // 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used.
79
+ // 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES".
80
+ // 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation.
81
+ // 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link.
82
+ // 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples.
83
+ // 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
84
+ // 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state.
85
+ // 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a nullptr pointer.
86
+ // 2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150".
87
+ // 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context.
88
+ // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
89
+ // 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
90
+ // 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode.
91
+ // 2017-05-01: OpenGL: Fixed save and restore of current blend func state.
92
+ // 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
93
+ // 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
94
+ // 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
95
+
96
+ //----------------------------------------
97
+ // OpenGL GLSL GLSL
98
+ // version version string
99
+ //----------------------------------------
100
+ // 2.0 110 "#version 110"
101
+ // 2.1 120 "#version 120"
102
+ // 3.0 130 "#version 130"
103
+ // 3.1 140 "#version 140"
104
+ // 3.2 150 "#version 150"
105
+ // 3.3 330 "#version 330 core"
106
+ // 4.0 400 "#version 400 core"
107
+ // 4.1 410 "#version 410 core"
108
+ // 4.2 420 "#version 410 core"
109
+ // 4.3 430 "#version 430 core"
110
+ // ES 2.0 100 "#version 100" = WebGL 1.0
111
+ // ES 3.0 300 "#version 300 es" = WebGL 2.0
112
+ //----------------------------------------
113
+
114
+ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
115
+ #define _CRT_SECURE_NO_WARNINGS
116
+ #endif
117
+
118
+ #include "../imgui.h"
119
+ #ifndef IMGUI_DISABLE
120
+ #include "imgui_impl_opengl3.h"
121
+ #include <stdio.h>
122
+ #include <stdint.h> // intptr_t
123
+ #if defined(__APPLE__)
124
+ #include <TargetConditionals.h>
125
+ #endif
126
+
127
+ // Clang/GCC warnings with -Weverything
128
+ #if defined(__clang__)
129
+ #pragma clang diagnostic push
130
+ #pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: ignore unknown flags
131
+ #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
132
+ #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
133
+ #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used
134
+ #pragma clang diagnostic ignored "-Wnonportable-system-include-path"
135
+ #pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
136
+ #endif
137
+ #if defined(__GNUC__)
138
+ #pragma GCC diagnostic push
139
+ #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
140
+ #pragma GCC diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx'
141
+ #pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
142
+ #endif
143
+
144
+ // GL includes
145
+ #if defined(IMGUI_IMPL_OPENGL_ES2)
146
+ #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
147
+ #include <OpenGLES/ES2/gl.h> // Use GL ES 2
148
+ #else
149
+ #include <GLES2/gl2.h> // Use GL ES 2
150
+ #endif
151
+ #if defined(__EMSCRIPTEN__)
152
+ #ifndef GL_GLEXT_PROTOTYPES
153
+ #define GL_GLEXT_PROTOTYPES
154
+ #endif
155
+ #include <GLES2/gl2ext.h>
156
+ #endif
157
+ #elif defined(IMGUI_IMPL_OPENGL_ES3)
158
+ #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
159
+ #include <OpenGLES/ES3/gl.h> // Use GL ES 3
160
+ #else
161
+ #include <GLES3/gl3.h> // Use GL ES 3
162
+ #endif
163
+ #elif !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
164
+ // Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
165
+ // Helper libraries are often used for this purpose! Here we are using our own minimal custom loader based on gl3w.
166
+ // In the rest of your app/engine, you can use another loader of your choice (gl3w, glew, glad, glbinding, glext, glLoadGen, etc.).
167
+ // If you happen to be developing a new feature for this backend (imgui_impl_opengl3.cpp):
168
+ // - You may need to regenerate imgui_impl_opengl3_loader.h to add new symbols. See https://github.com/dearimgui/gl3w_stripped
169
+ // Typically you would run: python3 ./gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt
170
+ // - You can temporarily use an unstripped version. See https://github.com/dearimgui/gl3w_stripped/releases
171
+ // Changes to this backend using new APIs should be accompanied by a regenerated stripped loader version.
172
+ #define IMGL3W_IMPL
173
+ #include "imgui_impl_opengl3_loader.h"
174
+ #endif
175
+
176
+ // Vertex arrays are not supported on ES2/WebGL1 unless Emscripten which uses an extension
177
+ #ifndef IMGUI_IMPL_OPENGL_ES2
178
+ #define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
179
+ #elif defined(__EMSCRIPTEN__)
180
+ #define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
181
+ #define glBindVertexArray glBindVertexArrayOES
182
+ #define glGenVertexArrays glGenVertexArraysOES
183
+ #define glDeleteVertexArrays glDeleteVertexArraysOES
184
+ #define GL_VERTEX_ARRAY_BINDING GL_VERTEX_ARRAY_BINDING_OES
185
+ #endif
186
+
187
+ // Desktop GL 2.0+ has extension and glPolygonMode() which GL ES and WebGL don't have..
188
+ // A desktop ES context can technically compile fine with our loader, so we also perform a runtime checks
189
+ #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)
190
+ #define IMGUI_IMPL_OPENGL_HAS_EXTENSIONS // has glGetIntegerv(GL_NUM_EXTENSIONS)
191
+ #define IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE // may have glPolygonMode()
192
+ #endif
193
+
194
+ // Desktop GL 2.1+ and GL ES 3.0+ have glBindBuffer() with GL_PIXEL_UNPACK_BUFFER target.
195
+ #if !defined(IMGUI_IMPL_OPENGL_ES2)
196
+ #define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK
197
+ #endif
198
+
199
+ // Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state
200
+ #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1)
201
+ #define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
202
+ #endif
203
+
204
+ // Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have.
205
+ #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_2)
206
+ #define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
207
+ #endif
208
+
209
+ // Desktop GL 3.3+ and GL ES 3.0+ have glBindSampler()
210
+ #if !defined(IMGUI_IMPL_OPENGL_ES2) && (defined(IMGUI_IMPL_OPENGL_ES3) || defined(GL_VERSION_3_3))
211
+ #define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
212
+ #endif
213
+
214
+ // [Debugging]
215
+ //#define IMGUI_IMPL_OPENGL_DEBUG
216
+ #ifdef IMGUI_IMPL_OPENGL_DEBUG
217
+ #include <stdio.h>
218
+ #define GL_CALL(_CALL) do { _CALL; GLenum gl_err = glGetError(); if (gl_err != 0) fprintf(stderr, "GL error 0x%x returned from '%s'.\n", gl_err, #_CALL); } while (0) // Call with error check
219
+ #else
220
+ #define GL_CALL(_CALL) _CALL // Call without error check
221
+ #endif
222
+
223
+ // OpenGL Data
224
+ struct ImGui_ImplOpenGL3_Data
225
+ {
226
+ GLuint GlVersion; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2)
227
+ char GlslVersionString[32]; // Specified by user or detected based on compile time GL settings.
228
+ bool GlProfileIsES2;
229
+ bool GlProfileIsES3;
230
+ bool GlProfileIsCompat;
231
+ GLint GlProfileMask;
232
+ GLuint FontTexture;
233
+ GLuint ShaderHandle;
234
+ GLint AttribLocationTex; // Uniforms location
235
+ GLint AttribLocationProjMtx;
236
+ GLuint AttribLocationVtxPos; // Vertex attributes location
237
+ GLuint AttribLocationVtxUV;
238
+ GLuint AttribLocationVtxColor;
239
+ unsigned int VboHandle, ElementsHandle;
240
+ GLsizeiptr VertexBufferSize;
241
+ GLsizeiptr IndexBufferSize;
242
+ bool HasPolygonMode;
243
+ bool HasClipOrigin;
244
+ bool UseBufferSubData;
245
+
246
+ ImGui_ImplOpenGL3_Data() { memset((void*)this, 0, sizeof(*this)); }
247
+ };
248
+
249
+ // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
250
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
251
+ static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData()
252
+ {
253
+ return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
254
+ }
255
+
256
+ // Forward Declarations
257
+ static void ImGui_ImplOpenGL3_InitMultiViewportSupport();
258
+ static void ImGui_ImplOpenGL3_ShutdownMultiViewportSupport();
259
+
260
+ // OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only)
261
+ #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
262
+ struct ImGui_ImplOpenGL3_VtxAttribState
263
+ {
264
+ GLint Enabled, Size, Type, Normalized, Stride;
265
+ GLvoid* Ptr;
266
+
267
+ void GetState(GLint index)
268
+ {
269
+ glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &Enabled);
270
+ glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_SIZE, &Size);
271
+ glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_TYPE, &Type);
272
+ glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &Normalized);
273
+ glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &Stride);
274
+ glGetVertexAttribPointerv(index, GL_VERTEX_ATTRIB_ARRAY_POINTER, &Ptr);
275
+ }
276
+ void SetState(GLint index)
277
+ {
278
+ glVertexAttribPointer(index, Size, Type, (GLboolean)Normalized, Stride, Ptr);
279
+ if (Enabled) glEnableVertexAttribArray(index); else glDisableVertexAttribArray(index);
280
+ }
281
+ };
282
+ #endif
283
+
284
+ // Functions
285
+ bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
286
+ {
287
+ ImGuiIO& io = ImGui::GetIO();
288
+ IMGUI_CHECKVERSION();
289
+ IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
290
+
291
+ // Initialize our loader
292
+ #if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
293
+ if (imgl3wInit() != 0)
294
+ {
295
+ fprintf(stderr, "Failed to initialize OpenGL loader!\n");
296
+ return false;
297
+ }
298
+ #endif
299
+
300
+ // Setup backend capabilities flags
301
+ ImGui_ImplOpenGL3_Data* bd = IM_NEW(ImGui_ImplOpenGL3_Data)();
302
+ io.BackendRendererUserData = (void*)bd;
303
+ io.BackendRendererName = "imgui_impl_opengl3";
304
+
305
+ // Query for GL version (e.g. 320 for GL 3.2)
306
+ const char* gl_version_str = (const char*)glGetString(GL_VERSION);
307
+ #if defined(IMGUI_IMPL_OPENGL_ES2)
308
+ // GLES 2
309
+ bd->GlVersion = 200;
310
+ bd->GlProfileIsES2 = true;
311
+ #else
312
+ // Desktop or GLES 3
313
+ GLint major = 0;
314
+ GLint minor = 0;
315
+ glGetIntegerv(GL_MAJOR_VERSION, &major);
316
+ glGetIntegerv(GL_MINOR_VERSION, &minor);
317
+ if (major == 0 && minor == 0)
318
+ sscanf(gl_version_str, "%d.%d", &major, &minor); // Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
319
+ bd->GlVersion = (GLuint)(major * 100 + minor * 10);
320
+ #if defined(GL_CONTEXT_PROFILE_MASK)
321
+ if (bd->GlVersion >= 320)
322
+ glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &bd->GlProfileMask);
323
+ bd->GlProfileIsCompat = (bd->GlProfileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0;
324
+ #endif
325
+
326
+ #if defined(IMGUI_IMPL_OPENGL_ES3)
327
+ bd->GlProfileIsES3 = true;
328
+ #else
329
+ if (strncmp(gl_version_str, "OpenGL ES 3", 11) == 0)
330
+ bd->GlProfileIsES3 = true;
331
+ #endif
332
+
333
+ bd->UseBufferSubData = false;
334
+ /*
335
+ // Query vendor to enable glBufferSubData kludge
336
+ #ifdef _WIN32
337
+ if (const char* vendor = (const char*)glGetString(GL_VENDOR))
338
+ if (strncmp(vendor, "Intel", 5) == 0)
339
+ bd->UseBufferSubData = true;
340
+ #endif
341
+ */
342
+ #endif
343
+
344
+ #ifdef IMGUI_IMPL_OPENGL_DEBUG
345
+ printf("GlVersion = %d, \"%s\"\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2/IsEs3 = %d/%d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, gl_version_str, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG]
346
+ #endif
347
+
348
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
349
+ if (bd->GlVersion >= 320)
350
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
351
+ #endif
352
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
353
+
354
+ // Store GLSL version string so we can refer to it later in case we recreate shaders.
355
+ // Note: GLSL version is NOT the same as GL version. Leave this to nullptr if unsure.
356
+ if (glsl_version == nullptr)
357
+ {
358
+ #if defined(IMGUI_IMPL_OPENGL_ES2)
359
+ glsl_version = "#version 100";
360
+ #elif defined(IMGUI_IMPL_OPENGL_ES3)
361
+ glsl_version = "#version 300 es";
362
+ #elif defined(__APPLE__)
363
+ glsl_version = "#version 150";
364
+ #else
365
+ glsl_version = "#version 130";
366
+ #endif
367
+ }
368
+ IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(bd->GlslVersionString));
369
+ strcpy(bd->GlslVersionString, glsl_version);
370
+ strcat(bd->GlslVersionString, "\n");
371
+
372
+ // Make an arbitrary GL call (we don't actually need the result)
373
+ // IF YOU GET A CRASH HERE: it probably means the OpenGL function loader didn't do its job. Let us know!
374
+ GLint current_texture;
375
+ glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture);
376
+
377
+ // Detect extensions we support
378
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
379
+ bd->HasPolygonMode = (!bd->GlProfileIsES2 && !bd->GlProfileIsES3);
380
+ #endif
381
+ bd->HasClipOrigin = (bd->GlVersion >= 450);
382
+ #ifdef IMGUI_IMPL_OPENGL_HAS_EXTENSIONS
383
+ GLint num_extensions = 0;
384
+ glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions);
385
+ for (GLint i = 0; i < num_extensions; i++)
386
+ {
387
+ const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, i);
388
+ if (extension != nullptr && strcmp(extension, "GL_ARB_clip_control") == 0)
389
+ bd->HasClipOrigin = true;
390
+ }
391
+ #endif
392
+
393
+ ImGui_ImplOpenGL3_InitMultiViewportSupport();
394
+
395
+ return true;
396
+ }
397
+
398
+ void ImGui_ImplOpenGL3_Shutdown()
399
+ {
400
+ ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
401
+ IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
402
+ ImGuiIO& io = ImGui::GetIO();
403
+
404
+ ImGui_ImplOpenGL3_ShutdownMultiViewportSupport();
405
+ ImGui_ImplOpenGL3_DestroyDeviceObjects();
406
+ io.BackendRendererName = nullptr;
407
+ io.BackendRendererUserData = nullptr;
408
+ io.BackendFlags &= ~(ImGuiBackendFlags_RendererHasVtxOffset | ImGuiBackendFlags_RendererHasViewports);
409
+ IM_DELETE(bd);
410
+ }
411
+
412
+ void ImGui_ImplOpenGL3_NewFrame()
413
+ {
414
+ ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
415
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOpenGL3_Init()?");
416
+
417
+ if (!bd->ShaderHandle)
418
+ ImGui_ImplOpenGL3_CreateDeviceObjects();
419
+ if (!bd->FontTexture)
420
+ ImGui_ImplOpenGL3_CreateFontsTexture();
421
+ }
422
+
423
+ static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object)
424
+ {
425
+ ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
426
+
427
+ // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
428
+ glEnable(GL_BLEND);
429
+ glBlendEquation(GL_FUNC_ADD);
430
+ glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
431
+ glDisable(GL_CULL_FACE);
432
+ glDisable(GL_DEPTH_TEST);
433
+ glDisable(GL_STENCIL_TEST);
434
+ glEnable(GL_SCISSOR_TEST);
435
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
436
+ if (bd->GlVersion >= 310)
437
+ glDisable(GL_PRIMITIVE_RESTART);
438
+ #endif
439
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
440
+ if (bd->HasPolygonMode)
441
+ glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
442
+ #endif
443
+
444
+ // Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
445
+ #if defined(GL_CLIP_ORIGIN)
446
+ bool clip_origin_lower_left = true;
447
+ if (bd->HasClipOrigin)
448
+ {
449
+ GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&current_clip_origin);
450
+ if (current_clip_origin == GL_UPPER_LEFT)
451
+ clip_origin_lower_left = false;
452
+ }
453
+ #endif
454
+
455
+ // Setup viewport, orthographic projection matrix
456
+ // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
457
+ GL_CALL(glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height));
458
+ float L = draw_data->DisplayPos.x;
459
+ float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
460
+ float T = draw_data->DisplayPos.y;
461
+ float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
462
+ #if defined(GL_CLIP_ORIGIN)
463
+ if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left
464
+ #endif
465
+ const float ortho_projection[4][4] =
466
+ {
467
+ { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
468
+ { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
469
+ { 0.0f, 0.0f, -1.0f, 0.0f },
470
+ { (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f },
471
+ };
472
+ glUseProgram(bd->ShaderHandle);
473
+ glUniform1i(bd->AttribLocationTex, 0);
474
+ glUniformMatrix4fv(bd->AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
475
+
476
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
477
+ if (bd->GlVersion >= 330 || bd->GlProfileIsES3)
478
+ glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 and GL ES 3.0 may set that otherwise.
479
+ #endif
480
+
481
+ (void)vertex_array_object;
482
+ #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
483
+ glBindVertexArray(vertex_array_object);
484
+ #endif
485
+
486
+ // Bind vertex/index buffers and setup attributes for ImDrawVert
487
+ GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, bd->VboHandle));
488
+ GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bd->ElementsHandle));
489
+ GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxPos));
490
+ GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxUV));
491
+ GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxColor));
492
+ GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, pos)));
493
+ GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, uv)));
494
+ GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)offsetof(ImDrawVert, col)));
495
+ }
496
+
497
+ // OpenGL3 Render function.
498
+ // Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly.
499
+ // This is in order to be able to run within an OpenGL engine that doesn't do so.
500
+ void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
501
+ {
502
+ // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
503
+ int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
504
+ int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
505
+ if (fb_width <= 0 || fb_height <= 0)
506
+ return;
507
+
508
+ ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
509
+
510
+ // Backup GL state
511
+ GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
512
+ glActiveTexture(GL_TEXTURE0);
513
+ GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program);
514
+ GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture);
515
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
516
+ GLuint last_sampler; if (bd->GlVersion >= 330 || bd->GlProfileIsES3) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; }
517
+ #endif
518
+ GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer);
519
+ #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
520
+ // This is part of VAO on OpenGL 3.0+ and OpenGL ES 3.0+.
521
+ GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
522
+ ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_pos; last_vtx_attrib_state_pos.GetState(bd->AttribLocationVtxPos);
523
+ ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_uv; last_vtx_attrib_state_uv.GetState(bd->AttribLocationVtxUV);
524
+ ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_color; last_vtx_attrib_state_color.GetState(bd->AttribLocationVtxColor);
525
+ #endif
526
+ #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
527
+ GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object);
528
+ #endif
529
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
530
+ GLint last_polygon_mode[2]; if (bd->HasPolygonMode) { glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode); }
531
+ #endif
532
+ GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
533
+ GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
534
+ GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
535
+ GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
536
+ GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
537
+ GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
538
+ GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
539
+ GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
540
+ GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
541
+ GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
542
+ GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
543
+ GLboolean last_enable_stencil_test = glIsEnabled(GL_STENCIL_TEST);
544
+ GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
545
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
546
+ GLboolean last_enable_primitive_restart = (bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE;
547
+ #endif
548
+
549
+ // Setup desired GL state
550
+ // Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
551
+ // The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
552
+ GLuint vertex_array_object = 0;
553
+ #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
554
+ GL_CALL(glGenVertexArrays(1, &vertex_array_object));
555
+ #endif
556
+ ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
557
+
558
+ // Will project scissor/clipping rectangles into framebuffer space
559
+ ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
560
+ ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
561
+
562
+ // Render command lists
563
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
564
+ {
565
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
566
+
567
+ // Upload vertex/index buffers
568
+ // - OpenGL drivers are in a very sorry state nowadays....
569
+ // During 2021 we attempted to switch from glBufferData() to orphaning+glBufferSubData() following reports
570
+ // of leaks on Intel GPU when using multi-viewports on Windows.
571
+ // - After this we kept hearing of various display corruptions issues. We started disabling on non-Intel GPU, but issues still got reported on Intel.
572
+ // - We are now back to using exclusively glBufferData(). So bd->UseBufferSubData IS ALWAYS FALSE in this code.
573
+ // We are keeping the old code path for a while in case people finding new issues may want to test the bd->UseBufferSubData path.
574
+ // - See https://github.com/ocornut/imgui/issues/4468 and please report any corruption issues.
575
+ const GLsizeiptr vtx_buffer_size = (GLsizeiptr)draw_list->VtxBuffer.Size * (int)sizeof(ImDrawVert);
576
+ const GLsizeiptr idx_buffer_size = (GLsizeiptr)draw_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx);
577
+ if (bd->UseBufferSubData)
578
+ {
579
+ if (bd->VertexBufferSize < vtx_buffer_size)
580
+ {
581
+ bd->VertexBufferSize = vtx_buffer_size;
582
+ GL_CALL(glBufferData(GL_ARRAY_BUFFER, bd->VertexBufferSize, nullptr, GL_STREAM_DRAW));
583
+ }
584
+ if (bd->IndexBufferSize < idx_buffer_size)
585
+ {
586
+ bd->IndexBufferSize = idx_buffer_size;
587
+ GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, bd->IndexBufferSize, nullptr, GL_STREAM_DRAW));
588
+ }
589
+ GL_CALL(glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)draw_list->VtxBuffer.Data));
590
+ GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)draw_list->IdxBuffer.Data));
591
+ }
592
+ else
593
+ {
594
+ GL_CALL(glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)draw_list->VtxBuffer.Data, GL_STREAM_DRAW));
595
+ GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)draw_list->IdxBuffer.Data, GL_STREAM_DRAW));
596
+ }
597
+
598
+ for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
599
+ {
600
+ const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
601
+ if (pcmd->UserCallback != nullptr)
602
+ {
603
+ // User callback, registered via ImDrawList::AddCallback()
604
+ // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
605
+ if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
606
+ ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
607
+ else
608
+ pcmd->UserCallback(draw_list, pcmd);
609
+ }
610
+ else
611
+ {
612
+ // Project scissor/clipping rectangles into framebuffer space
613
+ ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
614
+ ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
615
+ if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
616
+ continue;
617
+
618
+ // Apply scissor/clipping rectangle (Y is inverted in OpenGL)
619
+ GL_CALL(glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y)));
620
+
621
+ // Bind texture, Draw
622
+ GL_CALL(glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID()));
623
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
624
+ if (bd->GlVersion >= 320)
625
+ GL_CALL(glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset));
626
+ else
627
+ #endif
628
+ GL_CALL(glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx))));
629
+ }
630
+ }
631
+ }
632
+
633
+ // Destroy the temporary VAO
634
+ #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
635
+ GL_CALL(glDeleteVertexArrays(1, &vertex_array_object));
636
+ #endif
637
+
638
+ // Restore modified GL state
639
+ // This "glIsProgram()" check is required because if the program is "pending deletion" at the time of binding backup, it will have been deleted by now and will cause an OpenGL error. See #6220.
640
+ if (last_program == 0 || glIsProgram(last_program)) glUseProgram(last_program);
641
+ glBindTexture(GL_TEXTURE_2D, last_texture);
642
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
643
+ if (bd->GlVersion >= 330 || bd->GlProfileIsES3)
644
+ glBindSampler(0, last_sampler);
645
+ #endif
646
+ glActiveTexture(last_active_texture);
647
+ #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
648
+ glBindVertexArray(last_vertex_array_object);
649
+ #endif
650
+ glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
651
+ #ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
652
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
653
+ last_vtx_attrib_state_pos.SetState(bd->AttribLocationVtxPos);
654
+ last_vtx_attrib_state_uv.SetState(bd->AttribLocationVtxUV);
655
+ last_vtx_attrib_state_color.SetState(bd->AttribLocationVtxColor);
656
+ #endif
657
+ glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
658
+ glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
659
+ if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
660
+ if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
661
+ if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
662
+ if (last_enable_stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST);
663
+ if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
664
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
665
+ if (bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); }
666
+ #endif
667
+
668
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
669
+ // Desktop OpenGL 3.0 and OpenGL 3.1 had separate polygon draw modes for front-facing and back-facing faces of polygons
670
+ if (bd->HasPolygonMode) { if (bd->GlVersion <= 310 || bd->GlProfileIsCompat) { glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]); glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]); } else { glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]); } }
671
+ #endif // IMGUI_IMPL_OPENGL_MAY_HAVE_POLYGON_MODE
672
+
673
+ glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
674
+ glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
675
+ (void)bd; // Not all compilation paths use this
676
+ }
677
+
678
+ bool ImGui_ImplOpenGL3_CreateFontsTexture()
679
+ {
680
+ ImGuiIO& io = ImGui::GetIO();
681
+ ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
682
+
683
+ // Build texture atlas
684
+ unsigned char* pixels;
685
+ int width, height;
686
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
687
+
688
+ // Upload texture to graphics system
689
+ // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
690
+ GLint last_texture;
691
+ GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture));
692
+ GL_CALL(glGenTextures(1, &bd->FontTexture));
693
+ GL_CALL(glBindTexture(GL_TEXTURE_2D, bd->FontTexture));
694
+ GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
695
+ GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
696
+ GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
697
+ GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
698
+ #ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES
699
+ GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0));
700
+ #endif
701
+ GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels));
702
+
703
+ // Store identifier
704
+ io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
705
+
706
+ // Restore state
707
+ GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture));
708
+
709
+ return true;
710
+ }
711
+
712
+ void ImGui_ImplOpenGL3_DestroyFontsTexture()
713
+ {
714
+ ImGuiIO& io = ImGui::GetIO();
715
+ ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
716
+ if (bd->FontTexture)
717
+ {
718
+ glDeleteTextures(1, &bd->FontTexture);
719
+ io.Fonts->SetTexID(0);
720
+ bd->FontTexture = 0;
721
+ }
722
+ }
723
+
724
+ // If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file.
725
+ static bool CheckShader(GLuint handle, const char* desc)
726
+ {
727
+ ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
728
+ GLint status = 0, log_length = 0;
729
+ glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
730
+ glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
731
+ if ((GLboolean)status == GL_FALSE)
732
+ fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s! With GLSL: %s\n", desc, bd->GlslVersionString);
733
+ if (log_length > 1)
734
+ {
735
+ ImVector<char> buf;
736
+ buf.resize((int)(log_length + 1));
737
+ glGetShaderInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin());
738
+ fprintf(stderr, "%s\n", buf.begin());
739
+ }
740
+ return (GLboolean)status == GL_TRUE;
741
+ }
742
+
743
+ // If you get an error please report on GitHub. You may try different GL context version or GLSL version.
744
+ static bool CheckProgram(GLuint handle, const char* desc)
745
+ {
746
+ ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
747
+ GLint status = 0, log_length = 0;
748
+ glGetProgramiv(handle, GL_LINK_STATUS, &status);
749
+ glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
750
+ if ((GLboolean)status == GL_FALSE)
751
+ fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! With GLSL %s\n", desc, bd->GlslVersionString);
752
+ if (log_length > 1)
753
+ {
754
+ ImVector<char> buf;
755
+ buf.resize((int)(log_length + 1));
756
+ glGetProgramInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin());
757
+ fprintf(stderr, "%s\n", buf.begin());
758
+ }
759
+ return (GLboolean)status == GL_TRUE;
760
+ }
761
+
762
+ bool ImGui_ImplOpenGL3_CreateDeviceObjects()
763
+ {
764
+ ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
765
+
766
+ // Backup GL state
767
+ GLint last_texture, last_array_buffer;
768
+ glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
769
+ glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
770
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK
771
+ GLint last_pixel_unpack_buffer = 0;
772
+ if (bd->GlVersion >= 210) { glGetIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &last_pixel_unpack_buffer); glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); }
773
+ #endif
774
+ #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
775
+ GLint last_vertex_array;
776
+ glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
777
+ #endif
778
+
779
+ // Parse GLSL version string
780
+ int glsl_version = 130;
781
+ sscanf(bd->GlslVersionString, "#version %d", &glsl_version);
782
+
783
+ const GLchar* vertex_shader_glsl_120 =
784
+ "uniform mat4 ProjMtx;\n"
785
+ "attribute vec2 Position;\n"
786
+ "attribute vec2 UV;\n"
787
+ "attribute vec4 Color;\n"
788
+ "varying vec2 Frag_UV;\n"
789
+ "varying vec4 Frag_Color;\n"
790
+ "void main()\n"
791
+ "{\n"
792
+ " Frag_UV = UV;\n"
793
+ " Frag_Color = Color;\n"
794
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
795
+ "}\n";
796
+
797
+ const GLchar* vertex_shader_glsl_130 =
798
+ "uniform mat4 ProjMtx;\n"
799
+ "in vec2 Position;\n"
800
+ "in vec2 UV;\n"
801
+ "in vec4 Color;\n"
802
+ "out vec2 Frag_UV;\n"
803
+ "out vec4 Frag_Color;\n"
804
+ "void main()\n"
805
+ "{\n"
806
+ " Frag_UV = UV;\n"
807
+ " Frag_Color = Color;\n"
808
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
809
+ "}\n";
810
+
811
+ const GLchar* vertex_shader_glsl_300_es =
812
+ "precision highp float;\n"
813
+ "layout (location = 0) in vec2 Position;\n"
814
+ "layout (location = 1) in vec2 UV;\n"
815
+ "layout (location = 2) in vec4 Color;\n"
816
+ "uniform mat4 ProjMtx;\n"
817
+ "out vec2 Frag_UV;\n"
818
+ "out vec4 Frag_Color;\n"
819
+ "void main()\n"
820
+ "{\n"
821
+ " Frag_UV = UV;\n"
822
+ " Frag_Color = Color;\n"
823
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
824
+ "}\n";
825
+
826
+ const GLchar* vertex_shader_glsl_410_core =
827
+ "layout (location = 0) in vec2 Position;\n"
828
+ "layout (location = 1) in vec2 UV;\n"
829
+ "layout (location = 2) in vec4 Color;\n"
830
+ "uniform mat4 ProjMtx;\n"
831
+ "out vec2 Frag_UV;\n"
832
+ "out vec4 Frag_Color;\n"
833
+ "void main()\n"
834
+ "{\n"
835
+ " Frag_UV = UV;\n"
836
+ " Frag_Color = Color;\n"
837
+ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
838
+ "}\n";
839
+
840
+ const GLchar* fragment_shader_glsl_120 =
841
+ "#ifdef GL_ES\n"
842
+ " precision mediump float;\n"
843
+ "#endif\n"
844
+ "uniform sampler2D Texture;\n"
845
+ "varying vec2 Frag_UV;\n"
846
+ "varying vec4 Frag_Color;\n"
847
+ "void main()\n"
848
+ "{\n"
849
+ " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
850
+ "}\n";
851
+
852
+ const GLchar* fragment_shader_glsl_130 =
853
+ "uniform sampler2D Texture;\n"
854
+ "in vec2 Frag_UV;\n"
855
+ "in vec4 Frag_Color;\n"
856
+ "out vec4 Out_Color;\n"
857
+ "void main()\n"
858
+ "{\n"
859
+ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
860
+ "}\n";
861
+
862
+ const GLchar* fragment_shader_glsl_300_es =
863
+ "precision mediump float;\n"
864
+ "uniform sampler2D Texture;\n"
865
+ "in vec2 Frag_UV;\n"
866
+ "in vec4 Frag_Color;\n"
867
+ "layout (location = 0) out vec4 Out_Color;\n"
868
+ "void main()\n"
869
+ "{\n"
870
+ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
871
+ "}\n";
872
+
873
+ const GLchar* fragment_shader_glsl_410_core =
874
+ "in vec2 Frag_UV;\n"
875
+ "in vec4 Frag_Color;\n"
876
+ "uniform sampler2D Texture;\n"
877
+ "layout (location = 0) out vec4 Out_Color;\n"
878
+ "void main()\n"
879
+ "{\n"
880
+ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
881
+ "}\n";
882
+
883
+ // Select shaders matching our GLSL versions
884
+ const GLchar* vertex_shader = nullptr;
885
+ const GLchar* fragment_shader = nullptr;
886
+ if (glsl_version < 130)
887
+ {
888
+ vertex_shader = vertex_shader_glsl_120;
889
+ fragment_shader = fragment_shader_glsl_120;
890
+ }
891
+ else if (glsl_version >= 410)
892
+ {
893
+ vertex_shader = vertex_shader_glsl_410_core;
894
+ fragment_shader = fragment_shader_glsl_410_core;
895
+ }
896
+ else if (glsl_version == 300)
897
+ {
898
+ vertex_shader = vertex_shader_glsl_300_es;
899
+ fragment_shader = fragment_shader_glsl_300_es;
900
+ }
901
+ else
902
+ {
903
+ vertex_shader = vertex_shader_glsl_130;
904
+ fragment_shader = fragment_shader_glsl_130;
905
+ }
906
+
907
+ // Create shaders
908
+ const GLchar* vertex_shader_with_version[2] = { bd->GlslVersionString, vertex_shader };
909
+ GLuint vert_handle;
910
+ GL_CALL(vert_handle = glCreateShader(GL_VERTEX_SHADER));
911
+ glShaderSource(vert_handle, 2, vertex_shader_with_version, nullptr);
912
+ glCompileShader(vert_handle);
913
+ CheckShader(vert_handle, "vertex shader");
914
+
915
+ const GLchar* fragment_shader_with_version[2] = { bd->GlslVersionString, fragment_shader };
916
+ GLuint frag_handle;
917
+ GL_CALL(frag_handle = glCreateShader(GL_FRAGMENT_SHADER));
918
+ glShaderSource(frag_handle, 2, fragment_shader_with_version, nullptr);
919
+ glCompileShader(frag_handle);
920
+ CheckShader(frag_handle, "fragment shader");
921
+
922
+ // Link
923
+ bd->ShaderHandle = glCreateProgram();
924
+ glAttachShader(bd->ShaderHandle, vert_handle);
925
+ glAttachShader(bd->ShaderHandle, frag_handle);
926
+ glLinkProgram(bd->ShaderHandle);
927
+ CheckProgram(bd->ShaderHandle, "shader program");
928
+
929
+ glDetachShader(bd->ShaderHandle, vert_handle);
930
+ glDetachShader(bd->ShaderHandle, frag_handle);
931
+ glDeleteShader(vert_handle);
932
+ glDeleteShader(frag_handle);
933
+
934
+ bd->AttribLocationTex = glGetUniformLocation(bd->ShaderHandle, "Texture");
935
+ bd->AttribLocationProjMtx = glGetUniformLocation(bd->ShaderHandle, "ProjMtx");
936
+ bd->AttribLocationVtxPos = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Position");
937
+ bd->AttribLocationVtxUV = (GLuint)glGetAttribLocation(bd->ShaderHandle, "UV");
938
+ bd->AttribLocationVtxColor = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Color");
939
+
940
+ // Create buffers
941
+ glGenBuffers(1, &bd->VboHandle);
942
+ glGenBuffers(1, &bd->ElementsHandle);
943
+
944
+ ImGui_ImplOpenGL3_CreateFontsTexture();
945
+
946
+ // Restore modified GL state
947
+ glBindTexture(GL_TEXTURE_2D, last_texture);
948
+ glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
949
+ #ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_BUFFER_PIXEL_UNPACK
950
+ if (bd->GlVersion >= 210) { glBindBuffer(GL_PIXEL_UNPACK_BUFFER, last_pixel_unpack_buffer); }
951
+ #endif
952
+ #ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
953
+ glBindVertexArray(last_vertex_array);
954
+ #endif
955
+
956
+ return true;
957
+ }
958
+
959
+ void ImGui_ImplOpenGL3_DestroyDeviceObjects()
960
+ {
961
+ ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
962
+ if (bd->VboHandle) { glDeleteBuffers(1, &bd->VboHandle); bd->VboHandle = 0; }
963
+ if (bd->ElementsHandle) { glDeleteBuffers(1, &bd->ElementsHandle); bd->ElementsHandle = 0; }
964
+ if (bd->ShaderHandle) { glDeleteProgram(bd->ShaderHandle); bd->ShaderHandle = 0; }
965
+ ImGui_ImplOpenGL3_DestroyFontsTexture();
966
+ }
967
+
968
+ //--------------------------------------------------------------------------------------------------------
969
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
970
+ // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
971
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
972
+ //--------------------------------------------------------------------------------------------------------
973
+
974
+ static void ImGui_ImplOpenGL3_RenderWindow(ImGuiViewport* viewport, void*)
975
+ {
976
+ if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
977
+ {
978
+ ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
979
+ glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
980
+ glClear(GL_COLOR_BUFFER_BIT);
981
+ }
982
+ ImGui_ImplOpenGL3_RenderDrawData(viewport->DrawData);
983
+ }
984
+
985
+ static void ImGui_ImplOpenGL3_InitMultiViewportSupport()
986
+ {
987
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
988
+ platform_io.Renderer_RenderWindow = ImGui_ImplOpenGL3_RenderWindow;
989
+ }
990
+
991
+ static void ImGui_ImplOpenGL3_ShutdownMultiViewportSupport()
992
+ {
993
+ ImGui::DestroyPlatformWindows();
994
+ }
995
+
996
+ //-----------------------------------------------------------------------------
997
+
998
+ #if defined(__GNUC__)
999
+ #pragma GCC diagnostic pop
1000
+ #endif
1001
+ #if defined(__clang__)
1002
+ #pragma clang diagnostic pop
1003
+ #endif
1004
+
1005
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_opengl3.h ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
2
+ // - Desktop GL: 2.x 3.x 4.x
3
+ // - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
4
+ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
5
+
6
+ // Implemented features:
7
+ // [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
8
+ // [x] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset) [Desktop OpenGL only!]
9
+ // [X] Renderer: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
10
+
11
+ // About WebGL/ES:
12
+ // - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES.
13
+ // - This is done automatically on iOS, Android and Emscripten targets.
14
+ // - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h.
15
+
16
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
17
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
18
+ // Learn about Dear ImGui:
19
+ // - FAQ https://dearimgui.com/faq
20
+ // - Getting Started https://dearimgui.com/getting-started
21
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
22
+ // - Introduction, links and more at the top of imgui.cpp
23
+
24
+ // About GLSL version:
25
+ // The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string.
26
+ // On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es"
27
+ // Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp.
28
+
29
+ #pragma once
30
+ #include "../imgui.h" // IMGUI_IMPL_API
31
+ #ifndef IMGUI_DISABLE
32
+
33
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
34
+ IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr);
35
+ IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown();
36
+ IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame();
37
+ IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data);
38
+
39
+ // (Optional) Called by Init/NewFrame/Shutdown
40
+ IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture();
41
+ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture();
42
+ IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects();
43
+ IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();
44
+
45
+ // Configuration flags to add in your imconfig file:
46
+ //#define IMGUI_IMPL_OPENGL_ES2 // Enable ES 2 (Auto-detected on Emscripten)
47
+ //#define IMGUI_IMPL_OPENGL_ES3 // Enable ES 3 (Auto-detected on iOS/Android)
48
+
49
+ // You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
50
+ #if !defined(IMGUI_IMPL_OPENGL_ES2) \
51
+ && !defined(IMGUI_IMPL_OPENGL_ES3)
52
+
53
+ // Try to detect GLES on matching platforms
54
+ #if defined(__APPLE__)
55
+ #include <TargetConditionals.h>
56
+ #endif
57
+ #if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__))
58
+ #define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es"
59
+ #elif defined(__EMSCRIPTEN__) || defined(__amigaos4__)
60
+ #define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100"
61
+ #else
62
+ // Otherwise imgui_impl_opengl3_loader.h will be used.
63
+ #endif
64
+
65
+ #endif
66
+
67
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_opengl3_loader.h ADDED
@@ -0,0 +1,916 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //-----------------------------------------------------------------------------
2
+ // About imgui_impl_opengl3_loader.h:
3
+ //
4
+ // We embed our own OpenGL loader to not require user to provide their own or to have to use ours,
5
+ // which proved to be endless problems for users.
6
+ // Our loader is custom-generated, based on gl3w but automatically filtered to only include
7
+ // enums/functions that we use in our imgui_impl_opengl3.cpp source file in order to be small.
8
+ //
9
+ // YOU SHOULD NOT NEED TO INCLUDE/USE THIS DIRECTLY. THIS IS USED BY imgui_impl_opengl3.cpp ONLY.
10
+ // THE REST OF YOUR APP SHOULD USE A DIFFERENT GL LOADER: ANY GL LOADER OF YOUR CHOICE.
11
+ //
12
+ // IF YOU GET BUILD ERRORS IN THIS FILE (commonly macro redefinitions or function redefinitions):
13
+ // IT LIKELY MEANS THAT YOU ARE BUILDING 'imgui_impl_opengl3.cpp' OR INCLUDING 'imgui_impl_opengl3_loader.h'
14
+ // IN THE SAME COMPILATION UNIT AS ONE OF YOUR FILE WHICH IS USING A THIRD-PARTY OPENGL LOADER.
15
+ // (e.g. COULD HAPPEN IF YOU ARE DOING A UNITY/JUMBO BUILD, OR INCLUDING .CPP FILES FROM OTHERS)
16
+ // YOU SHOULD NOT BUILD BOTH IN THE SAME COMPILATION UNIT.
17
+ // BUT IF YOU REALLY WANT TO, you can '#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM' and imgui_impl_opengl3.cpp
18
+ // WILL NOT BE USING OUR LOADER, AND INSTEAD EXPECT ANOTHER/YOUR LOADER TO BE AVAILABLE IN THE COMPILATION UNIT.
19
+ //
20
+ // Regenerate with:
21
+ // python3 gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt
22
+ //
23
+ // More info:
24
+ // https://github.com/dearimgui/gl3w_stripped
25
+ // https://github.com/ocornut/imgui/issues/4445
26
+ //-----------------------------------------------------------------------------
27
+
28
+ /*
29
+ * This file was generated with gl3w_gen.py, part of imgl3w
30
+ * (hosted at https://github.com/dearimgui/gl3w_stripped)
31
+ *
32
+ * This is free and unencumbered software released into the public domain.
33
+ *
34
+ * Anyone is free to copy, modify, publish, use, compile, sell, or
35
+ * distribute this software, either in source code form or as a compiled
36
+ * binary, for any purpose, commercial or non-commercial, and by any
37
+ * means.
38
+ *
39
+ * In jurisdictions that recognize copyright laws, the author or authors
40
+ * of this software dedicate any and all copyright interest in the
41
+ * software to the public domain. We make this dedication for the benefit
42
+ * of the public at large and to the detriment of our heirs and
43
+ * successors. We intend this dedication to be an overt act of
44
+ * relinquishment in perpetuity of all present and future rights to this
45
+ * software under copyright law.
46
+ *
47
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
48
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
49
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
50
+ * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
51
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
52
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
53
+ * OTHER DEALINGS IN THE SOFTWARE.
54
+ */
55
+
56
+ #ifndef __gl3w_h_
57
+ #define __gl3w_h_
58
+
59
+ // Adapted from KHR/khrplatform.h to avoid including entire file.
60
+ #ifndef __khrplatform_h_
61
+ typedef float khronos_float_t;
62
+ typedef signed char khronos_int8_t;
63
+ typedef unsigned char khronos_uint8_t;
64
+ typedef signed short int khronos_int16_t;
65
+ typedef unsigned short int khronos_uint16_t;
66
+ #ifdef _WIN64
67
+ typedef signed long long int khronos_intptr_t;
68
+ typedef signed long long int khronos_ssize_t;
69
+ #else
70
+ typedef signed long int khronos_intptr_t;
71
+ typedef signed long int khronos_ssize_t;
72
+ #endif
73
+
74
+ #if defined(_MSC_VER) && !defined(__clang__)
75
+ typedef signed __int64 khronos_int64_t;
76
+ typedef unsigned __int64 khronos_uint64_t;
77
+ #elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100)
78
+ #include <stdint.h>
79
+ typedef int64_t khronos_int64_t;
80
+ typedef uint64_t khronos_uint64_t;
81
+ #else
82
+ typedef signed long long khronos_int64_t;
83
+ typedef unsigned long long khronos_uint64_t;
84
+ #endif
85
+ #endif // __khrplatform_h_
86
+
87
+ #ifndef __gl_glcorearb_h_
88
+ #define __gl_glcorearb_h_ 1
89
+ #ifdef __cplusplus
90
+ extern "C" {
91
+ #endif
92
+ /*
93
+ ** Copyright 2013-2020 The Khronos Group Inc.
94
+ ** SPDX-License-Identifier: MIT
95
+ **
96
+ ** This header is generated from the Khronos OpenGL / OpenGL ES XML
97
+ ** API Registry. The current version of the Registry, generator scripts
98
+ ** used to make the header, and the header can be found at
99
+ ** https://github.com/KhronosGroup/OpenGL-Registry
100
+ */
101
+ #if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
102
+ #ifndef WIN32_LEAN_AND_MEAN
103
+ #define WIN32_LEAN_AND_MEAN 1
104
+ #endif
105
+ #include <windows.h>
106
+ #endif
107
+ #ifndef APIENTRY
108
+ #define APIENTRY
109
+ #endif
110
+ #ifndef APIENTRYP
111
+ #define APIENTRYP APIENTRY *
112
+ #endif
113
+ #ifndef GLAPI
114
+ #define GLAPI extern
115
+ #endif
116
+ /* glcorearb.h is for use with OpenGL core profile implementations.
117
+ ** It should should be placed in the same directory as gl.h and
118
+ ** included as <GL/glcorearb.h>.
119
+ **
120
+ ** glcorearb.h includes only APIs in the latest OpenGL core profile
121
+ ** implementation together with APIs in newer ARB extensions which
122
+ ** can be supported by the core profile. It does not, and never will
123
+ ** include functionality removed from the core profile, such as
124
+ ** fixed-function vertex and fragment processing.
125
+ **
126
+ ** Do not #include both <GL/glcorearb.h> and either of <GL/gl.h> or
127
+ ** <GL/glext.h> in the same source file.
128
+ */
129
+ /* Generated C header for:
130
+ * API: gl
131
+ * Profile: core
132
+ * Versions considered: .*
133
+ * Versions emitted: .*
134
+ * Default extensions included: glcore
135
+ * Additional extensions included: _nomatch_^
136
+ * Extensions removed: _nomatch_^
137
+ */
138
+ #ifndef GL_VERSION_1_0
139
+ typedef void GLvoid;
140
+ typedef unsigned int GLenum;
141
+
142
+ typedef khronos_float_t GLfloat;
143
+ typedef int GLint;
144
+ typedef int GLsizei;
145
+ typedef unsigned int GLbitfield;
146
+ typedef double GLdouble;
147
+ typedef unsigned int GLuint;
148
+ typedef unsigned char GLboolean;
149
+ typedef khronos_uint8_t GLubyte;
150
+ #define GL_COLOR_BUFFER_BIT 0x00004000
151
+ #define GL_FALSE 0
152
+ #define GL_TRUE 1
153
+ #define GL_TRIANGLES 0x0004
154
+ #define GL_ONE 1
155
+ #define GL_SRC_ALPHA 0x0302
156
+ #define GL_ONE_MINUS_SRC_ALPHA 0x0303
157
+ #define GL_FRONT 0x0404
158
+ #define GL_BACK 0x0405
159
+ #define GL_FRONT_AND_BACK 0x0408
160
+ #define GL_POLYGON_MODE 0x0B40
161
+ #define GL_CULL_FACE 0x0B44
162
+ #define GL_DEPTH_TEST 0x0B71
163
+ #define GL_STENCIL_TEST 0x0B90
164
+ #define GL_VIEWPORT 0x0BA2
165
+ #define GL_BLEND 0x0BE2
166
+ #define GL_SCISSOR_BOX 0x0C10
167
+ #define GL_SCISSOR_TEST 0x0C11
168
+ #define GL_UNPACK_ROW_LENGTH 0x0CF2
169
+ #define GL_PACK_ALIGNMENT 0x0D05
170
+ #define GL_TEXTURE_2D 0x0DE1
171
+ #define GL_UNSIGNED_BYTE 0x1401
172
+ #define GL_UNSIGNED_SHORT 0x1403
173
+ #define GL_UNSIGNED_INT 0x1405
174
+ #define GL_FLOAT 0x1406
175
+ #define GL_RGBA 0x1908
176
+ #define GL_FILL 0x1B02
177
+ #define GL_VENDOR 0x1F00
178
+ #define GL_RENDERER 0x1F01
179
+ #define GL_VERSION 0x1F02
180
+ #define GL_EXTENSIONS 0x1F03
181
+ #define GL_LINEAR 0x2601
182
+ #define GL_TEXTURE_MAG_FILTER 0x2800
183
+ #define GL_TEXTURE_MIN_FILTER 0x2801
184
+ #define GL_TEXTURE_WRAP_S 0x2802
185
+ #define GL_TEXTURE_WRAP_T 0x2803
186
+ #define GL_REPEAT 0x2901
187
+ typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode);
188
+ typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
189
+ typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param);
190
+ typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
191
+ typedef void (APIENTRYP PFNGLCLEARPROC) (GLbitfield mask);
192
+ typedef void (APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
193
+ typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap);
194
+ typedef void (APIENTRYP PFNGLENABLEPROC) (GLenum cap);
195
+ typedef void (APIENTRYP PFNGLFLUSHPROC) (void);
196
+ typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param);
197
+ typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
198
+ typedef GLenum (APIENTRYP PFNGLGETERRORPROC) (void);
199
+ typedef void (APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data);
200
+ typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGPROC) (GLenum name);
201
+ typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC) (GLenum cap);
202
+ typedef void (APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
203
+ #ifdef GL_GLEXT_PROTOTYPES
204
+ GLAPI void APIENTRY glPolygonMode (GLenum face, GLenum mode);
205
+ GLAPI void APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
206
+ GLAPI void APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
207
+ GLAPI void APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
208
+ GLAPI void APIENTRY glClear (GLbitfield mask);
209
+ GLAPI void APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
210
+ GLAPI void APIENTRY glDisable (GLenum cap);
211
+ GLAPI void APIENTRY glEnable (GLenum cap);
212
+ GLAPI void APIENTRY glFlush (void);
213
+ GLAPI void APIENTRY glPixelStorei (GLenum pname, GLint param);
214
+ GLAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
215
+ GLAPI GLenum APIENTRY glGetError (void);
216
+ GLAPI void APIENTRY glGetIntegerv (GLenum pname, GLint *data);
217
+ GLAPI const GLubyte *APIENTRY glGetString (GLenum name);
218
+ GLAPI GLboolean APIENTRY glIsEnabled (GLenum cap);
219
+ GLAPI void APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
220
+ #endif
221
+ #endif /* GL_VERSION_1_0 */
222
+ #ifndef GL_VERSION_1_1
223
+ typedef khronos_float_t GLclampf;
224
+ typedef double GLclampd;
225
+ #define GL_TEXTURE_BINDING_2D 0x8069
226
+ typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices);
227
+ typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture);
228
+ typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures);
229
+ typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures);
230
+ #ifdef GL_GLEXT_PROTOTYPES
231
+ GLAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices);
232
+ GLAPI void APIENTRY glBindTexture (GLenum target, GLuint texture);
233
+ GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures);
234
+ GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures);
235
+ #endif
236
+ #endif /* GL_VERSION_1_1 */
237
+ #ifndef GL_VERSION_1_2
238
+ #define GL_CLAMP_TO_EDGE 0x812F
239
+ #endif /* GL_VERSION_1_2 */
240
+ #ifndef GL_VERSION_1_3
241
+ #define GL_TEXTURE0 0x84C0
242
+ #define GL_ACTIVE_TEXTURE 0x84E0
243
+ typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
244
+ #ifdef GL_GLEXT_PROTOTYPES
245
+ GLAPI void APIENTRY glActiveTexture (GLenum texture);
246
+ #endif
247
+ #endif /* GL_VERSION_1_3 */
248
+ #ifndef GL_VERSION_1_4
249
+ #define GL_BLEND_DST_RGB 0x80C8
250
+ #define GL_BLEND_SRC_RGB 0x80C9
251
+ #define GL_BLEND_DST_ALPHA 0x80CA
252
+ #define GL_BLEND_SRC_ALPHA 0x80CB
253
+ #define GL_FUNC_ADD 0x8006
254
+ typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
255
+ typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
256
+ #ifdef GL_GLEXT_PROTOTYPES
257
+ GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
258
+ GLAPI void APIENTRY glBlendEquation (GLenum mode);
259
+ #endif
260
+ #endif /* GL_VERSION_1_4 */
261
+ #ifndef GL_VERSION_1_5
262
+ typedef khronos_ssize_t GLsizeiptr;
263
+ typedef khronos_intptr_t GLintptr;
264
+ #define GL_ARRAY_BUFFER 0x8892
265
+ #define GL_ELEMENT_ARRAY_BUFFER 0x8893
266
+ #define GL_ARRAY_BUFFER_BINDING 0x8894
267
+ #define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
268
+ #define GL_STREAM_DRAW 0x88E0
269
+ typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
270
+ typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
271
+ typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
272
+ typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
273
+ typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
274
+ #ifdef GL_GLEXT_PROTOTYPES
275
+ GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer);
276
+ GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers);
277
+ GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers);
278
+ GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
279
+ GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
280
+ #endif
281
+ #endif /* GL_VERSION_1_5 */
282
+ #ifndef GL_VERSION_2_0
283
+ typedef char GLchar;
284
+ typedef khronos_int16_t GLshort;
285
+ typedef khronos_int8_t GLbyte;
286
+ typedef khronos_uint16_t GLushort;
287
+ #define GL_BLEND_EQUATION_RGB 0x8009
288
+ #define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
289
+ #define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
290
+ #define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
291
+ #define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
292
+ #define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
293
+ #define GL_BLEND_EQUATION_ALPHA 0x883D
294
+ #define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
295
+ #define GL_FRAGMENT_SHADER 0x8B30
296
+ #define GL_VERTEX_SHADER 0x8B31
297
+ #define GL_COMPILE_STATUS 0x8B81
298
+ #define GL_LINK_STATUS 0x8B82
299
+ #define GL_INFO_LOG_LENGTH 0x8B84
300
+ #define GL_CURRENT_PROGRAM 0x8B8D
301
+ #define GL_UPPER_LEFT 0x8CA2
302
+ typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
303
+ typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
304
+ typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
305
+ typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
306
+ typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
307
+ typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
308
+ typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
309
+ typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
310
+ typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
311
+ typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
312
+ typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
313
+ typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
314
+ typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
315
+ typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
316
+ typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
317
+ typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
318
+ typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
319
+ typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer);
320
+ typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);
321
+ typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
322
+ typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
323
+ typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
324
+ typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
325
+ typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
326
+ typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
327
+ #ifdef GL_GLEXT_PROTOTYPES
328
+ GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
329
+ GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader);
330
+ GLAPI void APIENTRY glCompileShader (GLuint shader);
331
+ GLAPI GLuint APIENTRY glCreateProgram (void);
332
+ GLAPI GLuint APIENTRY glCreateShader (GLenum type);
333
+ GLAPI void APIENTRY glDeleteProgram (GLuint program);
334
+ GLAPI void APIENTRY glDeleteShader (GLuint shader);
335
+ GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader);
336
+ GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index);
337
+ GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index);
338
+ GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name);
339
+ GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params);
340
+ GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
341
+ GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params);
342
+ GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
343
+ GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name);
344
+ GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params);
345
+ GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer);
346
+ GLAPI GLboolean APIENTRY glIsProgram (GLuint program);
347
+ GLAPI void APIENTRY glLinkProgram (GLuint program);
348
+ GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
349
+ GLAPI void APIENTRY glUseProgram (GLuint program);
350
+ GLAPI void APIENTRY glUniform1i (GLint location, GLint v0);
351
+ GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
352
+ GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
353
+ #endif
354
+ #endif /* GL_VERSION_2_0 */
355
+ #ifndef GL_VERSION_2_1
356
+ #define GL_PIXEL_UNPACK_BUFFER 0x88EC
357
+ #define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF
358
+ #endif /* GL_VERSION_2_1 */
359
+ #ifndef GL_VERSION_3_0
360
+ typedef khronos_uint16_t GLhalf;
361
+ #define GL_MAJOR_VERSION 0x821B
362
+ #define GL_MINOR_VERSION 0x821C
363
+ #define GL_NUM_EXTENSIONS 0x821D
364
+ #define GL_FRAMEBUFFER_SRGB 0x8DB9
365
+ #define GL_VERTEX_ARRAY_BINDING 0x85B5
366
+ typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data);
367
+ typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data);
368
+ typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index);
369
+ typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array);
370
+ typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays);
371
+ typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays);
372
+ #ifdef GL_GLEXT_PROTOTYPES
373
+ GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index);
374
+ GLAPI void APIENTRY glBindVertexArray (GLuint array);
375
+ GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays);
376
+ GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays);
377
+ #endif
378
+ #endif /* GL_VERSION_3_0 */
379
+ #ifndef GL_VERSION_3_1
380
+ #define GL_VERSION_3_1 1
381
+ #define GL_PRIMITIVE_RESTART 0x8F9D
382
+ #endif /* GL_VERSION_3_1 */
383
+ #ifndef GL_VERSION_3_2
384
+ #define GL_VERSION_3_2 1
385
+ typedef struct __GLsync *GLsync;
386
+ typedef khronos_uint64_t GLuint64;
387
+ typedef khronos_int64_t GLint64;
388
+ #define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002
389
+ #define GL_CONTEXT_PROFILE_MASK 0x9126
390
+ typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
391
+ typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data);
392
+ #ifdef GL_GLEXT_PROTOTYPES
393
+ GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
394
+ #endif
395
+ #endif /* GL_VERSION_3_2 */
396
+ #ifndef GL_VERSION_3_3
397
+ #define GL_VERSION_3_3 1
398
+ #define GL_SAMPLER_BINDING 0x8919
399
+ typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler);
400
+ #ifdef GL_GLEXT_PROTOTYPES
401
+ GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler);
402
+ #endif
403
+ #endif /* GL_VERSION_3_3 */
404
+ #ifndef GL_VERSION_4_1
405
+ typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data);
406
+ typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data);
407
+ #endif /* GL_VERSION_4_1 */
408
+ #ifndef GL_VERSION_4_3
409
+ typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
410
+ #endif /* GL_VERSION_4_3 */
411
+ #ifndef GL_VERSION_4_5
412
+ #define GL_CLIP_ORIGIN 0x935C
413
+ typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param);
414
+ typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param);
415
+ #endif /* GL_VERSION_4_5 */
416
+ #ifndef GL_ARB_bindless_texture
417
+ typedef khronos_uint64_t GLuint64EXT;
418
+ #endif /* GL_ARB_bindless_texture */
419
+ #ifndef GL_ARB_cl_event
420
+ struct _cl_context;
421
+ struct _cl_event;
422
+ #endif /* GL_ARB_cl_event */
423
+ #ifndef GL_ARB_clip_control
424
+ #define GL_ARB_clip_control 1
425
+ #endif /* GL_ARB_clip_control */
426
+ #ifndef GL_ARB_debug_output
427
+ typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
428
+ #endif /* GL_ARB_debug_output */
429
+ #ifndef GL_EXT_EGL_image_storage
430
+ typedef void *GLeglImageOES;
431
+ #endif /* GL_EXT_EGL_image_storage */
432
+ #ifndef GL_EXT_direct_state_access
433
+ typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params);
434
+ typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params);
435
+ typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params);
436
+ typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param);
437
+ typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param);
438
+ #endif /* GL_EXT_direct_state_access */
439
+ #ifndef GL_NV_draw_vulkan_image
440
+ typedef void (APIENTRY *GLVULKANPROCNV)(void);
441
+ #endif /* GL_NV_draw_vulkan_image */
442
+ #ifndef GL_NV_gpu_shader5
443
+ typedef khronos_int64_t GLint64EXT;
444
+ #endif /* GL_NV_gpu_shader5 */
445
+ #ifndef GL_NV_vertex_buffer_unified_memory
446
+ typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result);
447
+ #endif /* GL_NV_vertex_buffer_unified_memory */
448
+ #ifdef __cplusplus
449
+ }
450
+ #endif
451
+ #endif
452
+
453
+ #ifndef GL3W_API
454
+ #define GL3W_API
455
+ #endif
456
+
457
+ #ifndef __gl_h_
458
+ #define __gl_h_
459
+ #endif
460
+
461
+ #ifdef __cplusplus
462
+ extern "C" {
463
+ #endif
464
+
465
+ #define GL3W_OK 0
466
+ #define GL3W_ERROR_INIT -1
467
+ #define GL3W_ERROR_LIBRARY_OPEN -2
468
+ #define GL3W_ERROR_OPENGL_VERSION -3
469
+
470
+ typedef void (*GL3WglProc)(void);
471
+ typedef GL3WglProc (*GL3WGetProcAddressProc)(const char *proc);
472
+
473
+ /* gl3w api */
474
+ GL3W_API int imgl3wInit(void);
475
+ GL3W_API int imgl3wInit2(GL3WGetProcAddressProc proc);
476
+ GL3W_API int imgl3wIsSupported(int major, int minor);
477
+ GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc);
478
+
479
+ /* gl3w internal state */
480
+ union ImGL3WProcs {
481
+ GL3WglProc ptr[59];
482
+ struct {
483
+ PFNGLACTIVETEXTUREPROC ActiveTexture;
484
+ PFNGLATTACHSHADERPROC AttachShader;
485
+ PFNGLBINDBUFFERPROC BindBuffer;
486
+ PFNGLBINDSAMPLERPROC BindSampler;
487
+ PFNGLBINDTEXTUREPROC BindTexture;
488
+ PFNGLBINDVERTEXARRAYPROC BindVertexArray;
489
+ PFNGLBLENDEQUATIONPROC BlendEquation;
490
+ PFNGLBLENDEQUATIONSEPARATEPROC BlendEquationSeparate;
491
+ PFNGLBLENDFUNCSEPARATEPROC BlendFuncSeparate;
492
+ PFNGLBUFFERDATAPROC BufferData;
493
+ PFNGLBUFFERSUBDATAPROC BufferSubData;
494
+ PFNGLCLEARPROC Clear;
495
+ PFNGLCLEARCOLORPROC ClearColor;
496
+ PFNGLCOMPILESHADERPROC CompileShader;
497
+ PFNGLCREATEPROGRAMPROC CreateProgram;
498
+ PFNGLCREATESHADERPROC CreateShader;
499
+ PFNGLDELETEBUFFERSPROC DeleteBuffers;
500
+ PFNGLDELETEPROGRAMPROC DeleteProgram;
501
+ PFNGLDELETESHADERPROC DeleteShader;
502
+ PFNGLDELETETEXTURESPROC DeleteTextures;
503
+ PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays;
504
+ PFNGLDETACHSHADERPROC DetachShader;
505
+ PFNGLDISABLEPROC Disable;
506
+ PFNGLDISABLEVERTEXATTRIBARRAYPROC DisableVertexAttribArray;
507
+ PFNGLDRAWELEMENTSPROC DrawElements;
508
+ PFNGLDRAWELEMENTSBASEVERTEXPROC DrawElementsBaseVertex;
509
+ PFNGLENABLEPROC Enable;
510
+ PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray;
511
+ PFNGLFLUSHPROC Flush;
512
+ PFNGLGENBUFFERSPROC GenBuffers;
513
+ PFNGLGENTEXTURESPROC GenTextures;
514
+ PFNGLGENVERTEXARRAYSPROC GenVertexArrays;
515
+ PFNGLGETATTRIBLOCATIONPROC GetAttribLocation;
516
+ PFNGLGETERRORPROC GetError;
517
+ PFNGLGETINTEGERVPROC GetIntegerv;
518
+ PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog;
519
+ PFNGLGETPROGRAMIVPROC GetProgramiv;
520
+ PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog;
521
+ PFNGLGETSHADERIVPROC GetShaderiv;
522
+ PFNGLGETSTRINGPROC GetString;
523
+ PFNGLGETSTRINGIPROC GetStringi;
524
+ PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation;
525
+ PFNGLGETVERTEXATTRIBPOINTERVPROC GetVertexAttribPointerv;
526
+ PFNGLGETVERTEXATTRIBIVPROC GetVertexAttribiv;
527
+ PFNGLISENABLEDPROC IsEnabled;
528
+ PFNGLISPROGRAMPROC IsProgram;
529
+ PFNGLLINKPROGRAMPROC LinkProgram;
530
+ PFNGLPIXELSTOREIPROC PixelStorei;
531
+ PFNGLPOLYGONMODEPROC PolygonMode;
532
+ PFNGLREADPIXELSPROC ReadPixels;
533
+ PFNGLSCISSORPROC Scissor;
534
+ PFNGLSHADERSOURCEPROC ShaderSource;
535
+ PFNGLTEXIMAGE2DPROC TexImage2D;
536
+ PFNGLTEXPARAMETERIPROC TexParameteri;
537
+ PFNGLUNIFORM1IPROC Uniform1i;
538
+ PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv;
539
+ PFNGLUSEPROGRAMPROC UseProgram;
540
+ PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer;
541
+ PFNGLVIEWPORTPROC Viewport;
542
+ } gl;
543
+ };
544
+
545
+ GL3W_API extern union ImGL3WProcs imgl3wProcs;
546
+
547
+ /* OpenGL functions */
548
+ #define glActiveTexture imgl3wProcs.gl.ActiveTexture
549
+ #define glAttachShader imgl3wProcs.gl.AttachShader
550
+ #define glBindBuffer imgl3wProcs.gl.BindBuffer
551
+ #define glBindSampler imgl3wProcs.gl.BindSampler
552
+ #define glBindTexture imgl3wProcs.gl.BindTexture
553
+ #define glBindVertexArray imgl3wProcs.gl.BindVertexArray
554
+ #define glBlendEquation imgl3wProcs.gl.BlendEquation
555
+ #define glBlendEquationSeparate imgl3wProcs.gl.BlendEquationSeparate
556
+ #define glBlendFuncSeparate imgl3wProcs.gl.BlendFuncSeparate
557
+ #define glBufferData imgl3wProcs.gl.BufferData
558
+ #define glBufferSubData imgl3wProcs.gl.BufferSubData
559
+ #define glClear imgl3wProcs.gl.Clear
560
+ #define glClearColor imgl3wProcs.gl.ClearColor
561
+ #define glCompileShader imgl3wProcs.gl.CompileShader
562
+ #define glCreateProgram imgl3wProcs.gl.CreateProgram
563
+ #define glCreateShader imgl3wProcs.gl.CreateShader
564
+ #define glDeleteBuffers imgl3wProcs.gl.DeleteBuffers
565
+ #define glDeleteProgram imgl3wProcs.gl.DeleteProgram
566
+ #define glDeleteShader imgl3wProcs.gl.DeleteShader
567
+ #define glDeleteTextures imgl3wProcs.gl.DeleteTextures
568
+ #define glDeleteVertexArrays imgl3wProcs.gl.DeleteVertexArrays
569
+ #define glDetachShader imgl3wProcs.gl.DetachShader
570
+ #define glDisable imgl3wProcs.gl.Disable
571
+ #define glDisableVertexAttribArray imgl3wProcs.gl.DisableVertexAttribArray
572
+ #define glDrawElements imgl3wProcs.gl.DrawElements
573
+ #define glDrawElementsBaseVertex imgl3wProcs.gl.DrawElementsBaseVertex
574
+ #define glEnable imgl3wProcs.gl.Enable
575
+ #define glEnableVertexAttribArray imgl3wProcs.gl.EnableVertexAttribArray
576
+ #define glFlush imgl3wProcs.gl.Flush
577
+ #define glGenBuffers imgl3wProcs.gl.GenBuffers
578
+ #define glGenTextures imgl3wProcs.gl.GenTextures
579
+ #define glGenVertexArrays imgl3wProcs.gl.GenVertexArrays
580
+ #define glGetAttribLocation imgl3wProcs.gl.GetAttribLocation
581
+ #define glGetError imgl3wProcs.gl.GetError
582
+ #define glGetIntegerv imgl3wProcs.gl.GetIntegerv
583
+ #define glGetProgramInfoLog imgl3wProcs.gl.GetProgramInfoLog
584
+ #define glGetProgramiv imgl3wProcs.gl.GetProgramiv
585
+ #define glGetShaderInfoLog imgl3wProcs.gl.GetShaderInfoLog
586
+ #define glGetShaderiv imgl3wProcs.gl.GetShaderiv
587
+ #define glGetString imgl3wProcs.gl.GetString
588
+ #define glGetStringi imgl3wProcs.gl.GetStringi
589
+ #define glGetUniformLocation imgl3wProcs.gl.GetUniformLocation
590
+ #define glGetVertexAttribPointerv imgl3wProcs.gl.GetVertexAttribPointerv
591
+ #define glGetVertexAttribiv imgl3wProcs.gl.GetVertexAttribiv
592
+ #define glIsEnabled imgl3wProcs.gl.IsEnabled
593
+ #define glIsProgram imgl3wProcs.gl.IsProgram
594
+ #define glLinkProgram imgl3wProcs.gl.LinkProgram
595
+ #define glPixelStorei imgl3wProcs.gl.PixelStorei
596
+ #define glPolygonMode imgl3wProcs.gl.PolygonMode
597
+ #define glReadPixels imgl3wProcs.gl.ReadPixels
598
+ #define glScissor imgl3wProcs.gl.Scissor
599
+ #define glShaderSource imgl3wProcs.gl.ShaderSource
600
+ #define glTexImage2D imgl3wProcs.gl.TexImage2D
601
+ #define glTexParameteri imgl3wProcs.gl.TexParameteri
602
+ #define glUniform1i imgl3wProcs.gl.Uniform1i
603
+ #define glUniformMatrix4fv imgl3wProcs.gl.UniformMatrix4fv
604
+ #define glUseProgram imgl3wProcs.gl.UseProgram
605
+ #define glVertexAttribPointer imgl3wProcs.gl.VertexAttribPointer
606
+ #define glViewport imgl3wProcs.gl.Viewport
607
+
608
+ #ifdef __cplusplus
609
+ }
610
+ #endif
611
+
612
+ #endif
613
+
614
+ #ifdef IMGL3W_IMPL
615
+ #ifdef __cplusplus
616
+ extern "C" {
617
+ #endif
618
+
619
+ #include <stdlib.h>
620
+
621
+ #define GL3W_ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
622
+
623
+ #if defined(_WIN32)
624
+ #ifndef WIN32_LEAN_AND_MEAN
625
+ #define WIN32_LEAN_AND_MEAN 1
626
+ #endif
627
+ #include <windows.h>
628
+
629
+ static HMODULE libgl;
630
+ typedef PROC(__stdcall* GL3WglGetProcAddr)(LPCSTR);
631
+ static GL3WglGetProcAddr wgl_get_proc_address;
632
+
633
+ static int open_libgl(void)
634
+ {
635
+ libgl = LoadLibraryA("opengl32.dll");
636
+ if (!libgl)
637
+ return GL3W_ERROR_LIBRARY_OPEN;
638
+ wgl_get_proc_address = (GL3WglGetProcAddr)GetProcAddress(libgl, "wglGetProcAddress");
639
+ return GL3W_OK;
640
+ }
641
+
642
+ static void close_libgl(void) { FreeLibrary(libgl); }
643
+ static GL3WglProc get_proc(const char *proc)
644
+ {
645
+ GL3WglProc res;
646
+ res = (GL3WglProc)wgl_get_proc_address(proc);
647
+ if (!res)
648
+ res = (GL3WglProc)GetProcAddress(libgl, proc);
649
+ return res;
650
+ }
651
+ #elif defined(__APPLE__)
652
+ #include <dlfcn.h>
653
+
654
+ static void *libgl;
655
+ static int open_libgl(void)
656
+ {
657
+ libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL);
658
+ if (!libgl)
659
+ return GL3W_ERROR_LIBRARY_OPEN;
660
+ return GL3W_OK;
661
+ }
662
+
663
+ static void close_libgl(void) { dlclose(libgl); }
664
+
665
+ static GL3WglProc get_proc(const char *proc)
666
+ {
667
+ GL3WglProc res;
668
+ *(void **)(&res) = dlsym(libgl, proc);
669
+ return res;
670
+ }
671
+ #else
672
+ #include <dlfcn.h>
673
+
674
+ static void* libgl; // OpenGL library
675
+ static void* libglx; // GLX library
676
+ static void* libegl; // EGL library
677
+ static GL3WGetProcAddressProc gl_get_proc_address;
678
+
679
+ static void close_libgl(void)
680
+ {
681
+ if (libgl) {
682
+ dlclose(libgl);
683
+ libgl = NULL;
684
+ }
685
+ if (libegl) {
686
+ dlclose(libegl);
687
+ libegl = NULL;
688
+ }
689
+ if (libglx) {
690
+ dlclose(libglx);
691
+ libglx = NULL;
692
+ }
693
+ }
694
+
695
+ static int is_library_loaded(const char* name, void** lib)
696
+ {
697
+ *lib = dlopen(name, RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
698
+ return *lib != NULL;
699
+ }
700
+
701
+ static int open_libs(void)
702
+ {
703
+ // On Linux we have two APIs to get process addresses: EGL and GLX.
704
+ // EGL is supported under both X11 and Wayland, whereas GLX is X11-specific.
705
+
706
+ libgl = NULL;
707
+ libegl = NULL;
708
+ libglx = NULL;
709
+
710
+ // First check what's already loaded, the windowing library might have
711
+ // already loaded either EGL or GLX and we want to use the same one.
712
+
713
+ if (is_library_loaded("libEGL.so.1", &libegl) ||
714
+ is_library_loaded("libGLX.so.0", &libglx)) {
715
+ libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL);
716
+ if (libgl)
717
+ return GL3W_OK;
718
+ else
719
+ close_libgl();
720
+ }
721
+
722
+ if (is_library_loaded("libGL.so", &libgl))
723
+ return GL3W_OK;
724
+ if (is_library_loaded("libGL.so.1", &libgl))
725
+ return GL3W_OK;
726
+ if (is_library_loaded("libGL.so.3", &libgl))
727
+ return GL3W_OK;
728
+
729
+ // Neither is already loaded, so we have to load one. Try EGL first
730
+ // because it is supported under both X11 and Wayland.
731
+
732
+ // Load OpenGL + EGL
733
+ libgl = dlopen("libOpenGL.so.0", RTLD_LAZY | RTLD_LOCAL);
734
+ libegl = dlopen("libEGL.so.1", RTLD_LAZY | RTLD_LOCAL);
735
+ if (libgl && libegl)
736
+ return GL3W_OK;
737
+ else
738
+ close_libgl();
739
+
740
+ // Fall back to legacy libGL, which includes GLX
741
+ // While most systems use libGL.so.1, NetBSD seems to use that libGL.so.3. See https://github.com/ocornut/imgui/issues/6983
742
+ libgl = dlopen("libGL.so", RTLD_LAZY | RTLD_LOCAL);
743
+ if (!libgl)
744
+ libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL);
745
+ if (!libgl)
746
+ libgl = dlopen("libGL.so.3", RTLD_LAZY | RTLD_LOCAL);
747
+
748
+ if (libgl)
749
+ return GL3W_OK;
750
+
751
+ return GL3W_ERROR_LIBRARY_OPEN;
752
+ }
753
+
754
+ static int open_libgl(void)
755
+ {
756
+ int res = open_libs();
757
+ if (res)
758
+ return res;
759
+
760
+ if (libegl)
761
+ *(void**)(&gl_get_proc_address) = dlsym(libegl, "eglGetProcAddress");
762
+ else if (libglx)
763
+ *(void**)(&gl_get_proc_address) = dlsym(libglx, "glXGetProcAddressARB");
764
+ else
765
+ *(void**)(&gl_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB");
766
+
767
+ if (!gl_get_proc_address) {
768
+ close_libgl();
769
+ return GL3W_ERROR_LIBRARY_OPEN;
770
+ }
771
+
772
+ return GL3W_OK;
773
+ }
774
+
775
+ static GL3WglProc get_proc(const char* proc)
776
+ {
777
+ GL3WglProc res = NULL;
778
+
779
+ // Before EGL version 1.5, eglGetProcAddress doesn't support querying core
780
+ // functions and may return a dummy function if we try, so try to load the
781
+ // function from the GL library directly first.
782
+ if (libegl)
783
+ *(void**)(&res) = dlsym(libgl, proc);
784
+
785
+ if (!res)
786
+ res = gl_get_proc_address(proc);
787
+
788
+ if (!libegl && !res)
789
+ *(void**)(&res) = dlsym(libgl, proc);
790
+
791
+ return res;
792
+ }
793
+ #endif
794
+
795
+ static struct { int major, minor; } version;
796
+
797
+ static int parse_version(void)
798
+ {
799
+ if (!glGetIntegerv)
800
+ return GL3W_ERROR_INIT;
801
+ glGetIntegerv(GL_MAJOR_VERSION, &version.major);
802
+ glGetIntegerv(GL_MINOR_VERSION, &version.minor);
803
+ if (version.major == 0 && version.minor == 0)
804
+ {
805
+ // Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
806
+ if (const char* gl_version = (const char*)glGetString(GL_VERSION))
807
+ sscanf(gl_version, "%d.%d", &version.major, &version.minor);
808
+ }
809
+ if (version.major < 2)
810
+ return GL3W_ERROR_OPENGL_VERSION;
811
+ return GL3W_OK;
812
+ }
813
+
814
+ static void load_procs(GL3WGetProcAddressProc proc);
815
+
816
+ int imgl3wInit(void)
817
+ {
818
+ int res = open_libgl();
819
+ if (res)
820
+ return res;
821
+ atexit(close_libgl);
822
+ return imgl3wInit2(get_proc);
823
+ }
824
+
825
+ int imgl3wInit2(GL3WGetProcAddressProc proc)
826
+ {
827
+ load_procs(proc);
828
+ return parse_version();
829
+ }
830
+
831
+ int imgl3wIsSupported(int major, int minor)
832
+ {
833
+ if (major < 2)
834
+ return 0;
835
+ if (version.major == major)
836
+ return version.minor >= minor;
837
+ return version.major >= major;
838
+ }
839
+
840
+ GL3WglProc imgl3wGetProcAddress(const char *proc) { return get_proc(proc); }
841
+
842
+ static const char *proc_names[] = {
843
+ "glActiveTexture",
844
+ "glAttachShader",
845
+ "glBindBuffer",
846
+ "glBindSampler",
847
+ "glBindTexture",
848
+ "glBindVertexArray",
849
+ "glBlendEquation",
850
+ "glBlendEquationSeparate",
851
+ "glBlendFuncSeparate",
852
+ "glBufferData",
853
+ "glBufferSubData",
854
+ "glClear",
855
+ "glClearColor",
856
+ "glCompileShader",
857
+ "glCreateProgram",
858
+ "glCreateShader",
859
+ "glDeleteBuffers",
860
+ "glDeleteProgram",
861
+ "glDeleteShader",
862
+ "glDeleteTextures",
863
+ "glDeleteVertexArrays",
864
+ "glDetachShader",
865
+ "glDisable",
866
+ "glDisableVertexAttribArray",
867
+ "glDrawElements",
868
+ "glDrawElementsBaseVertex",
869
+ "glEnable",
870
+ "glEnableVertexAttribArray",
871
+ "glFlush",
872
+ "glGenBuffers",
873
+ "glGenTextures",
874
+ "glGenVertexArrays",
875
+ "glGetAttribLocation",
876
+ "glGetError",
877
+ "glGetIntegerv",
878
+ "glGetProgramInfoLog",
879
+ "glGetProgramiv",
880
+ "glGetShaderInfoLog",
881
+ "glGetShaderiv",
882
+ "glGetString",
883
+ "glGetStringi",
884
+ "glGetUniformLocation",
885
+ "glGetVertexAttribPointerv",
886
+ "glGetVertexAttribiv",
887
+ "glIsEnabled",
888
+ "glIsProgram",
889
+ "glLinkProgram",
890
+ "glPixelStorei",
891
+ "glPolygonMode",
892
+ "glReadPixels",
893
+ "glScissor",
894
+ "glShaderSource",
895
+ "glTexImage2D",
896
+ "glTexParameteri",
897
+ "glUniform1i",
898
+ "glUniformMatrix4fv",
899
+ "glUseProgram",
900
+ "glVertexAttribPointer",
901
+ "glViewport",
902
+ };
903
+
904
+ GL3W_API union ImGL3WProcs imgl3wProcs;
905
+
906
+ static void load_procs(GL3WGetProcAddressProc proc)
907
+ {
908
+ size_t i;
909
+ for (i = 0; i < GL3W_ARRAY_SIZE(proc_names); i++)
910
+ imgl3wProcs.ptr[i] = proc(proc_names[i]);
911
+ }
912
+
913
+ #ifdef __cplusplus
914
+ }
915
+ #endif
916
+ #endif
3rdparty/imgui/backends/imgui_impl_osx.h ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for OSX / Cocoa
2
+ // This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..)
3
+ // - Not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac.
4
+ // - Requires linking with the GameController framework ("-framework GameController").
5
+
6
+ // Implemented features:
7
+ // [X] Platform: Clipboard support is part of core Dear ImGui (no specific code in this backend).
8
+ // [X] Platform: Mouse support. Can discriminate Mouse/Pen.
9
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values are obsolete since 1.87 and not supported since 1.91.5]
10
+ // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
11
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
12
+ // [X] Platform: IME support.
13
+ // [x] Platform: Multi-viewport / platform windows.
14
+ // Issues:
15
+ // [ ] Platform: Multi-viewport: Window size not correctly reported when enabling io.ConfigViewportsNoDecoration
16
+ // [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor).
17
+
18
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
19
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
20
+ // Learn about Dear ImGui:
21
+ // - FAQ https://dearimgui.com/faq
22
+ // - Getting Started https://dearimgui.com/getting-started
23
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
24
+ // - Introduction, links and more at the top of imgui.cpp
25
+
26
+ #include "imgui.h" // IMGUI_IMPL_API
27
+ #ifndef IMGUI_DISABLE
28
+
29
+ #ifdef __OBJC__
30
+
31
+ @class NSEvent;
32
+ @class NSView;
33
+
34
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
35
+ IMGUI_IMPL_API bool ImGui_ImplOSX_Init(NSView* _Nonnull view);
36
+ IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown();
37
+ IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView* _Nullable view);
38
+
39
+ #endif
40
+
41
+ //-----------------------------------------------------------------------------
42
+ // C++ API
43
+ //-----------------------------------------------------------------------------
44
+
45
+ #ifdef IMGUI_IMPL_METAL_CPP_EXTENSIONS
46
+ // #include <AppKit/AppKit.hpp>
47
+ #ifndef __OBJC__
48
+
49
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
50
+ IMGUI_IMPL_API bool ImGui_ImplOSX_Init(void* _Nonnull view);
51
+ IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown();
52
+ IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view);
53
+
54
+ #endif
55
+ #endif
56
+
57
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_osx.mm ADDED
@@ -0,0 +1,1157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for OSX / Cocoa
2
+ // This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..)
3
+ // - Not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac.
4
+ // - Requires linking with the GameController framework ("-framework GameController").
5
+
6
+ // Implemented features:
7
+ // [X] Platform: Clipboard support is part of core Dear ImGui (no specific code in this backend).
8
+ // [X] Platform: Mouse support. Can discriminate Mouse/Pen.
9
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy kVK_* values are obsolete since 1.87 and not supported since 1.91.5]
10
+ // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
11
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
12
+ // [X] Platform: IME support.
13
+ // [x] Platform: Multi-viewport / platform windows.
14
+ // Issues:
15
+ // [ ] Platform: Multi-viewport: Window size not correctly reported when enabling io.ConfigViewportsNoDecoration
16
+ // [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor).
17
+
18
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
19
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
20
+ // Learn about Dear ImGui:
21
+ // - FAQ https://dearimgui.com/faq
22
+ // - Getting Started https://dearimgui.com/getting-started
23
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
24
+ // - Introduction, links and more at the top of imgui.cpp
25
+
26
+ #import "imgui.h"
27
+ #ifndef IMGUI_DISABLE
28
+ #import "imgui_impl_osx.h"
29
+ #import <Cocoa/Cocoa.h>
30
+ #import <Carbon/Carbon.h>
31
+ #import <GameController/GameController.h>
32
+ #import <time.h>
33
+
34
+ // CHANGELOG
35
+ // (minor and older changes stripped away, please see git history for details)
36
+ // 2024-XX-XX: Added support for multiple windows via the ImGuiPlatformIO interface.
37
+ // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
38
+ // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
39
+ // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
40
+ // - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
41
+ // 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library.
42
+ // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F20 function keys. Stopped mapping F13 into PrintScreen.
43
+ // 2023-04-09: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_Pen.
44
+ // 2023-02-01: Fixed scroll wheel scaling for devices emitting events with hasPreciseScrollingDeltas==false (e.g. non-Apple mices).
45
+ // 2022-11-02: Fixed mouse coordinates before clicking the host window.
46
+ // 2022-10-06: Fixed mouse inputs on flipped views.
47
+ // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
48
+ // 2022-05-03: Inputs: Removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture.
49
+ // 2022-04-27: Misc: Store backend data in a per-context struct, allowing to use this backend with multiple contexts.
50
+ // 2022-03-22: Inputs: Monitor NSKeyUp events to catch missing keyUp for key when user press Cmd + key
51
+ // 2022-02-07: Inputs: Forward keyDown/keyUp events to OS when unused by dear imgui.
52
+ // 2022-01-31: Fixed building with old Xcode versions that are missing gamepad features.
53
+ // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
54
+ // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
55
+ // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
56
+ // 2022-01-12: Inputs: Added basic Platform IME support, hooking the io.SetPlatformImeDataFn() function.
57
+ // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
58
+ // 2021-12-13: *BREAKING CHANGE* Add NSView parameter to ImGui_ImplOSX_Init(). Generally fix keyboard support. Using kVK_* codes for keyboard keys.
59
+ // 2021-12-13: Add game controller support.
60
+ // 2021-09-21: Use mach_absolute_time as CFAbsoluteTimeGetCurrent can jump backwards.
61
+ // 2021-08-17: Calling io.AddFocusEvent() on NSApplicationDidBecomeActiveNotification/NSApplicationDidResignActiveNotification events.
62
+ // 2021-06-23: Inputs: Added a fix for shortcuts using CTRL key instead of CMD key.
63
+ // 2021-04-19: Inputs: Added a fix for keys remaining stuck in pressed state when CMD-tabbing into different application.
64
+ // 2021-01-27: Inputs: Added a fix for mouse position not being reported when mouse buttons other than left one are down.
65
+ // 2020-10-28: Inputs: Added a fix for handling keypad-enter key.
66
+ // 2020-05-25: Inputs: Added a fix for missing trackpad clicks when done with "soft tap".
67
+ // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
68
+ // 2019-10-11: Inputs: Fix using Backspace key.
69
+ // 2019-07-21: Re-added clipboard handlers as they are not enabled by default in core imgui.cpp (reverted 2019-05-18 change).
70
+ // 2019-05-28: Inputs: Added mouse cursor shape and visibility support.
71
+ // 2019-05-18: Misc: Removed clipboard handlers as they are now supported by core imgui.cpp.
72
+ // 2019-05-11: Inputs: Don't filter character values before calling AddInputCharacter() apart from 0xF700..0xFFFF range.
73
+ // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
74
+ // 2018-07-07: Initial version.
75
+
76
+ #define APPLE_HAS_BUTTON_OPTIONS (__IPHONE_OS_VERSION_MIN_REQUIRED >= 130000 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500 || __TV_OS_VERSION_MIN_REQUIRED >= 130000)
77
+ #define APPLE_HAS_CONTROLLER (__IPHONE_OS_VERSION_MIN_REQUIRED >= 140000 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 110000 || __TV_OS_VERSION_MIN_REQUIRED >= 140000)
78
+ #define APPLE_HAS_THUMBSTICKS (__IPHONE_OS_VERSION_MIN_REQUIRED >= 120100 || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101401 || __TV_OS_VERSION_MIN_REQUIRED >= 120100)
79
+
80
+ @class ImGuiObserver;
81
+ @class KeyEventResponder;
82
+
83
+ // Data
84
+ struct ImGui_ImplOSX_Data
85
+ {
86
+ CFTimeInterval Time;
87
+ NSCursor* MouseCursors[ImGuiMouseCursor_COUNT];
88
+ bool MouseCursorHidden;
89
+ ImGuiObserver* Observer;
90
+ KeyEventResponder* KeyEventResponder;
91
+ NSTextInputContext* InputContext;
92
+ id Monitor;
93
+ NSWindow* Window;
94
+
95
+ ImGui_ImplOSX_Data() { memset((void*)this, 0, sizeof(*this)); }
96
+ };
97
+
98
+ static ImGui_ImplOSX_Data* ImGui_ImplOSX_GetBackendData() { return (ImGui_ImplOSX_Data*)ImGui::GetIO().BackendPlatformUserData; }
99
+ static void ImGui_ImplOSX_DestroyBackendData() { IM_DELETE(ImGui_ImplOSX_GetBackendData()); }
100
+
101
+ static inline CFTimeInterval GetMachAbsoluteTimeInSeconds() { return (CFTimeInterval)(double)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1e9); }
102
+
103
+ // Forward Declarations
104
+ static void ImGui_ImplOSX_InitMultiViewportSupport();
105
+ static void ImGui_ImplOSX_ShutdownMultiViewportSupport();
106
+ static void ImGui_ImplOSX_UpdateMonitors();
107
+ static void ImGui_ImplOSX_AddTrackingArea(NSView* _Nonnull view);
108
+ static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view);
109
+
110
+ // Undocumented methods for creating cursors.
111
+ @interface NSCursor()
112
+ + (id)_windowResizeNorthWestSouthEastCursor;
113
+ + (id)_windowResizeNorthEastSouthWestCursor;
114
+ + (id)_windowResizeNorthSouthCursor;
115
+ + (id)_windowResizeEastWestCursor;
116
+ @end
117
+
118
+ /**
119
+ KeyEventResponder implements the NSTextInputClient protocol as is required by the macOS text input manager.
120
+
121
+ The macOS text input manager is invoked by calling the interpretKeyEvents method from the keyDown method.
122
+ Keyboard events are then evaluated by the macOS input manager and valid text input is passed back via the
123
+ insertText:replacementRange method.
124
+
125
+ This is the same approach employed by other cross-platform libraries such as SDL2:
126
+ https://github.com/spurious/SDL-mirror/blob/e17aacbd09e65a4fd1e166621e011e581fb017a8/src/video/cocoa/SDL_cocoakeyboard.m#L53
127
+ and GLFW:
128
+ https://github.com/glfw/glfw/blob/b55a517ae0c7b5127dffa79a64f5406021bf9076/src/cocoa_window.m#L722-L723
129
+ */
130
+ @interface KeyEventResponder: NSView<NSTextInputClient>
131
+ @end
132
+
133
+ @implementation KeyEventResponder
134
+ {
135
+ float _posX;
136
+ float _posY;
137
+ NSRect _imeRect;
138
+ }
139
+
140
+ #pragma mark - Public
141
+
142
+ - (void)setImePosX:(float)posX imePosY:(float)posY
143
+ {
144
+ _posX = posX;
145
+ _posY = posY;
146
+ }
147
+
148
+ - (void)updateImePosWithView:(NSView *)view
149
+ {
150
+ NSWindow* window = view.window;
151
+ if (!window)
152
+ return;
153
+
154
+ ImGuiIO& io = ImGui::GetIO();
155
+ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
156
+ {
157
+ NSRect frame = window.frame;
158
+ NSRect contentRect = window.contentLayoutRect;
159
+ if (window.styleMask & NSWindowStyleMaskFullSizeContentView) // No title bar windows should be considered.
160
+ contentRect = frame;
161
+
162
+ NSRect firstScreenFrame = NSScreen.screens[0].frame;
163
+ _imeRect = NSMakeRect(_posX, _posY, 0, 0);
164
+ _imeRect.origin.y = firstScreenFrame.size.height - _imeRect.size.height - _imeRect.origin.y; // Opposite of ConvertNSRect()
165
+ }
166
+ else
167
+ {
168
+ NSRect contentRect = [window contentRectForFrameRect:window.frame];
169
+ NSRect rect = NSMakeRect(_posX, contentRect.size.height - _posY, 0, 0);
170
+ _imeRect = [window convertRectToScreen:rect];
171
+ }
172
+ }
173
+
174
+ - (void)viewDidMoveToWindow
175
+ {
176
+ // Ensure self is a first responder to receive the input events.
177
+ [self.window makeFirstResponder:self];
178
+ }
179
+
180
+ - (void)keyDown:(NSEvent*)event
181
+ {
182
+ if (!ImGui_ImplOSX_HandleEvent(event, self))
183
+ [super keyDown:event];
184
+
185
+ // Call to the macOS input manager system.
186
+ [self interpretKeyEvents:@[event]];
187
+ }
188
+
189
+ - (void)keyUp:(NSEvent*)event
190
+ {
191
+ if (!ImGui_ImplOSX_HandleEvent(event, self))
192
+ [super keyUp:event];
193
+ }
194
+
195
+ - (void)insertText:(id)aString replacementRange:(NSRange)replacementRange
196
+ {
197
+ ImGuiIO& io = ImGui::GetIO();
198
+
199
+ NSString* characters;
200
+ if ([aString isKindOfClass:[NSAttributedString class]])
201
+ characters = [aString string];
202
+ else
203
+ characters = (NSString*)aString;
204
+
205
+ io.AddInputCharactersUTF8(characters.UTF8String);
206
+ }
207
+
208
+ - (BOOL)acceptsFirstResponder
209
+ {
210
+ return YES;
211
+ }
212
+
213
+ - (void)doCommandBySelector:(SEL)myselector
214
+ {
215
+ }
216
+
217
+ - (nullable NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range actualRange:(nullable NSRangePointer)actualRange
218
+ {
219
+ return nil;
220
+ }
221
+
222
+ - (NSUInteger)characterIndexForPoint:(NSPoint)point
223
+ {
224
+ return 0;
225
+ }
226
+
227
+ - (NSRect)firstRectForCharacterRange:(NSRange)range actualRange:(nullable NSRangePointer)actualRange
228
+ {
229
+ return _imeRect;
230
+ }
231
+
232
+ - (BOOL)hasMarkedText
233
+ {
234
+ return NO;
235
+ }
236
+
237
+ - (NSRange)markedRange
238
+ {
239
+ return NSMakeRange(NSNotFound, 0);
240
+ }
241
+
242
+ - (NSRange)selectedRange
243
+ {
244
+ return NSMakeRange(NSNotFound, 0);
245
+ }
246
+
247
+ - (void)setMarkedText:(nonnull id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
248
+ {
249
+ }
250
+
251
+ - (void)unmarkText
252
+ {
253
+ }
254
+
255
+ - (nonnull NSArray<NSAttributedStringKey>*)validAttributesForMarkedText
256
+ {
257
+ return @[];
258
+ }
259
+
260
+ @end
261
+
262
+ @interface ImGuiObserver : NSObject
263
+
264
+ - (void)onApplicationBecomeActive:(NSNotification*)aNotification;
265
+ - (void)onApplicationBecomeInactive:(NSNotification*)aNotification;
266
+ - (void)displaysDidChange:(NSNotification*)aNotification;
267
+
268
+ @end
269
+
270
+ @implementation ImGuiObserver
271
+
272
+ - (void)onApplicationBecomeActive:(NSNotification*)aNotification
273
+ {
274
+ ImGuiIO& io = ImGui::GetIO();
275
+ io.AddFocusEvent(true);
276
+ }
277
+
278
+ - (void)onApplicationBecomeInactive:(NSNotification*)aNotification
279
+ {
280
+ ImGuiIO& io = ImGui::GetIO();
281
+ io.AddFocusEvent(false);
282
+ }
283
+
284
+ - (void)displaysDidChange:(NSNotification*)aNotification
285
+ {
286
+ ImGui_ImplOSX_UpdateMonitors();
287
+ }
288
+
289
+ @end
290
+
291
+ // Functions
292
+
293
+ // Not static to allow third-party code to use that if they want to (but undocumented)
294
+ ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code);
295
+ ImGuiKey ImGui_ImplOSX_KeyCodeToImGuiKey(int key_code)
296
+ {
297
+ switch (key_code)
298
+ {
299
+ case kVK_ANSI_A: return ImGuiKey_A;
300
+ case kVK_ANSI_S: return ImGuiKey_S;
301
+ case kVK_ANSI_D: return ImGuiKey_D;
302
+ case kVK_ANSI_F: return ImGuiKey_F;
303
+ case kVK_ANSI_H: return ImGuiKey_H;
304
+ case kVK_ANSI_G: return ImGuiKey_G;
305
+ case kVK_ANSI_Z: return ImGuiKey_Z;
306
+ case kVK_ANSI_X: return ImGuiKey_X;
307
+ case kVK_ANSI_C: return ImGuiKey_C;
308
+ case kVK_ANSI_V: return ImGuiKey_V;
309
+ case kVK_ANSI_B: return ImGuiKey_B;
310
+ case kVK_ANSI_Q: return ImGuiKey_Q;
311
+ case kVK_ANSI_W: return ImGuiKey_W;
312
+ case kVK_ANSI_E: return ImGuiKey_E;
313
+ case kVK_ANSI_R: return ImGuiKey_R;
314
+ case kVK_ANSI_Y: return ImGuiKey_Y;
315
+ case kVK_ANSI_T: return ImGuiKey_T;
316
+ case kVK_ANSI_1: return ImGuiKey_1;
317
+ case kVK_ANSI_2: return ImGuiKey_2;
318
+ case kVK_ANSI_3: return ImGuiKey_3;
319
+ case kVK_ANSI_4: return ImGuiKey_4;
320
+ case kVK_ANSI_6: return ImGuiKey_6;
321
+ case kVK_ANSI_5: return ImGuiKey_5;
322
+ case kVK_ANSI_Equal: return ImGuiKey_Equal;
323
+ case kVK_ANSI_9: return ImGuiKey_9;
324
+ case kVK_ANSI_7: return ImGuiKey_7;
325
+ case kVK_ANSI_Minus: return ImGuiKey_Minus;
326
+ case kVK_ANSI_8: return ImGuiKey_8;
327
+ case kVK_ANSI_0: return ImGuiKey_0;
328
+ case kVK_ANSI_RightBracket: return ImGuiKey_RightBracket;
329
+ case kVK_ANSI_O: return ImGuiKey_O;
330
+ case kVK_ANSI_U: return ImGuiKey_U;
331
+ case kVK_ANSI_LeftBracket: return ImGuiKey_LeftBracket;
332
+ case kVK_ANSI_I: return ImGuiKey_I;
333
+ case kVK_ANSI_P: return ImGuiKey_P;
334
+ case kVK_ANSI_L: return ImGuiKey_L;
335
+ case kVK_ANSI_J: return ImGuiKey_J;
336
+ case kVK_ANSI_Quote: return ImGuiKey_Apostrophe;
337
+ case kVK_ANSI_K: return ImGuiKey_K;
338
+ case kVK_ANSI_Semicolon: return ImGuiKey_Semicolon;
339
+ case kVK_ANSI_Backslash: return ImGuiKey_Backslash;
340
+ case kVK_ANSI_Comma: return ImGuiKey_Comma;
341
+ case kVK_ANSI_Slash: return ImGuiKey_Slash;
342
+ case kVK_ANSI_N: return ImGuiKey_N;
343
+ case kVK_ANSI_M: return ImGuiKey_M;
344
+ case kVK_ANSI_Period: return ImGuiKey_Period;
345
+ case kVK_ANSI_Grave: return ImGuiKey_GraveAccent;
346
+ case kVK_ANSI_KeypadDecimal: return ImGuiKey_KeypadDecimal;
347
+ case kVK_ANSI_KeypadMultiply: return ImGuiKey_KeypadMultiply;
348
+ case kVK_ANSI_KeypadPlus: return ImGuiKey_KeypadAdd;
349
+ case kVK_ANSI_KeypadClear: return ImGuiKey_NumLock;
350
+ case kVK_ANSI_KeypadDivide: return ImGuiKey_KeypadDivide;
351
+ case kVK_ANSI_KeypadEnter: return ImGuiKey_KeypadEnter;
352
+ case kVK_ANSI_KeypadMinus: return ImGuiKey_KeypadSubtract;
353
+ case kVK_ANSI_KeypadEquals: return ImGuiKey_KeypadEqual;
354
+ case kVK_ANSI_Keypad0: return ImGuiKey_Keypad0;
355
+ case kVK_ANSI_Keypad1: return ImGuiKey_Keypad1;
356
+ case kVK_ANSI_Keypad2: return ImGuiKey_Keypad2;
357
+ case kVK_ANSI_Keypad3: return ImGuiKey_Keypad3;
358
+ case kVK_ANSI_Keypad4: return ImGuiKey_Keypad4;
359
+ case kVK_ANSI_Keypad5: return ImGuiKey_Keypad5;
360
+ case kVK_ANSI_Keypad6: return ImGuiKey_Keypad6;
361
+ case kVK_ANSI_Keypad7: return ImGuiKey_Keypad7;
362
+ case kVK_ANSI_Keypad8: return ImGuiKey_Keypad8;
363
+ case kVK_ANSI_Keypad9: return ImGuiKey_Keypad9;
364
+ case kVK_Return: return ImGuiKey_Enter;
365
+ case kVK_Tab: return ImGuiKey_Tab;
366
+ case kVK_Space: return ImGuiKey_Space;
367
+ case kVK_Delete: return ImGuiKey_Backspace;
368
+ case kVK_Escape: return ImGuiKey_Escape;
369
+ case kVK_CapsLock: return ImGuiKey_CapsLock;
370
+ case kVK_Control: return ImGuiKey_LeftCtrl;
371
+ case kVK_Shift: return ImGuiKey_LeftShift;
372
+ case kVK_Option: return ImGuiKey_LeftAlt;
373
+ case kVK_Command: return ImGuiKey_LeftSuper;
374
+ case kVK_RightControl: return ImGuiKey_RightCtrl;
375
+ case kVK_RightShift: return ImGuiKey_RightShift;
376
+ case kVK_RightOption: return ImGuiKey_RightAlt;
377
+ case kVK_RightCommand: return ImGuiKey_RightSuper;
378
+ // case kVK_Function: return ImGuiKey_;
379
+ // case kVK_VolumeUp: return ImGuiKey_;
380
+ // case kVK_VolumeDown: return ImGuiKey_;
381
+ // case kVK_Mute: return ImGuiKey_;
382
+ case kVK_F1: return ImGuiKey_F1;
383
+ case kVK_F2: return ImGuiKey_F2;
384
+ case kVK_F3: return ImGuiKey_F3;
385
+ case kVK_F4: return ImGuiKey_F4;
386
+ case kVK_F5: return ImGuiKey_F5;
387
+ case kVK_F6: return ImGuiKey_F6;
388
+ case kVK_F7: return ImGuiKey_F7;
389
+ case kVK_F8: return ImGuiKey_F8;
390
+ case kVK_F9: return ImGuiKey_F9;
391
+ case kVK_F10: return ImGuiKey_F10;
392
+ case kVK_F11: return ImGuiKey_F11;
393
+ case kVK_F12: return ImGuiKey_F12;
394
+ case kVK_F13: return ImGuiKey_F13;
395
+ case kVK_F14: return ImGuiKey_F14;
396
+ case kVK_F15: return ImGuiKey_F15;
397
+ case kVK_F16: return ImGuiKey_F16;
398
+ case kVK_F17: return ImGuiKey_F17;
399
+ case kVK_F18: return ImGuiKey_F18;
400
+ case kVK_F19: return ImGuiKey_F19;
401
+ case kVK_F20: return ImGuiKey_F20;
402
+ case 0x6E: return ImGuiKey_Menu;
403
+ case kVK_Help: return ImGuiKey_Insert;
404
+ case kVK_Home: return ImGuiKey_Home;
405
+ case kVK_PageUp: return ImGuiKey_PageUp;
406
+ case kVK_ForwardDelete: return ImGuiKey_Delete;
407
+ case kVK_End: return ImGuiKey_End;
408
+ case kVK_PageDown: return ImGuiKey_PageDown;
409
+ case kVK_LeftArrow: return ImGuiKey_LeftArrow;
410
+ case kVK_RightArrow: return ImGuiKey_RightArrow;
411
+ case kVK_DownArrow: return ImGuiKey_DownArrow;
412
+ case kVK_UpArrow: return ImGuiKey_UpArrow;
413
+ default: return ImGuiKey_None;
414
+ }
415
+ }
416
+
417
+ #ifdef IMGUI_IMPL_METAL_CPP_EXTENSIONS
418
+
419
+ IMGUI_IMPL_API bool ImGui_ImplOSX_Init(void* _Nonnull view) {
420
+ return ImGui_ImplOSX_Init((__bridge NSView*)(view));
421
+ }
422
+
423
+ IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(void* _Nullable view) {
424
+ return ImGui_ImplOSX_NewFrame((__bridge NSView*)(view));
425
+ }
426
+
427
+ #endif
428
+
429
+
430
+ bool ImGui_ImplOSX_Init(NSView* view)
431
+ {
432
+ ImGuiIO& io = ImGui::GetIO();
433
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
434
+ IMGUI_CHECKVERSION();
435
+ IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
436
+
437
+ // Setup backend capabilities flags
438
+ ImGui_ImplOSX_Data* bd = IM_NEW(ImGui_ImplOSX_Data)();
439
+ io.BackendPlatformUserData = (void*)bd;
440
+ io.BackendPlatformName = "imgui_impl_osx";
441
+ io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
442
+ //io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
443
+ io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
444
+ //io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can call io.AddMouseViewportEvent() with correct data (optional)
445
+
446
+ bd->Observer = [ImGuiObserver new];
447
+ bd->Window = view.window ?: NSApp.orderedWindows.firstObject;
448
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
449
+ main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (__bridge_retained void*)bd->Window;
450
+ ImGui_ImplOSX_UpdateMonitors();
451
+ ImGui_ImplOSX_InitMultiViewportSupport();
452
+
453
+ // Load cursors. Some of them are undocumented.
454
+ bd->MouseCursorHidden = false;
455
+ bd->MouseCursors[ImGuiMouseCursor_Arrow] = [NSCursor arrowCursor];
456
+ bd->MouseCursors[ImGuiMouseCursor_TextInput] = [NSCursor IBeamCursor];
457
+ bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = [NSCursor closedHandCursor];
458
+ bd->MouseCursors[ImGuiMouseCursor_Hand] = [NSCursor pointingHandCursor];
459
+ bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = [NSCursor operationNotAllowedCursor];
460
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] ? [NSCursor _windowResizeNorthSouthCursor] : [NSCursor resizeUpDownCursor];
461
+ bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] ? [NSCursor _windowResizeEastWestCursor] : [NSCursor resizeLeftRightCursor];
462
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor];
463
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor];
464
+
465
+ // Note that imgui.cpp also include default OSX clipboard handlers which can be enabled
466
+ // by adding '#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS' in imconfig.h and adding '-framework ApplicationServices' to your linker command-line.
467
+ // Since we are already in ObjC land here, it is easy for us to add a clipboard handler using the NSPasteboard api.
468
+ platform_io.Platform_SetClipboardTextFn = [](ImGuiContext*, const char* str) -> void
469
+ {
470
+ NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
471
+ [pasteboard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:nil];
472
+ [pasteboard setString:[NSString stringWithUTF8String:str] forType:NSPasteboardTypeString];
473
+ };
474
+
475
+ platform_io.Platform_GetClipboardTextFn = [](ImGuiContext*) -> const char*
476
+ {
477
+ NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
478
+ NSString* available = [pasteboard availableTypeFromArray: [NSArray arrayWithObject:NSPasteboardTypeString]];
479
+ if (![available isEqualToString:NSPasteboardTypeString])
480
+ return nullptr;
481
+
482
+ NSString* string = [pasteboard stringForType:NSPasteboardTypeString];
483
+ if (string == nil)
484
+ return nullptr;
485
+
486
+ const char* string_c = (const char*)[string UTF8String];
487
+ size_t string_len = strlen(string_c);
488
+ static ImVector<char> s_clipboard;
489
+ s_clipboard.resize((int)string_len + 1);
490
+ strcpy(s_clipboard.Data, string_c);
491
+ return s_clipboard.Data;
492
+ };
493
+
494
+ [[NSNotificationCenter defaultCenter] addObserver:bd->Observer
495
+ selector:@selector(onApplicationBecomeActive:)
496
+ name:NSApplicationDidBecomeActiveNotification
497
+ object:nil];
498
+ [[NSNotificationCenter defaultCenter] addObserver:bd->Observer
499
+ selector:@selector(onApplicationBecomeInactive:)
500
+ name:NSApplicationDidResignActiveNotification
501
+ object:nil];
502
+
503
+ // Add the NSTextInputClient to the view hierarchy,
504
+ // to receive keyboard events and translate them to input text.
505
+ bd->KeyEventResponder = [[KeyEventResponder alloc] initWithFrame:NSZeroRect];
506
+ bd->InputContext = [[NSTextInputContext alloc] initWithClient:bd->KeyEventResponder];
507
+ [view addSubview:bd->KeyEventResponder];
508
+ ImGui_ImplOSX_AddTrackingArea(view);
509
+
510
+ platform_io.Platform_SetImeDataFn = [](ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data) -> void
511
+ {
512
+ ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
513
+ if (data->WantVisible)
514
+ {
515
+ [bd->InputContext activate];
516
+ }
517
+ else
518
+ {
519
+ [bd->InputContext discardMarkedText];
520
+ [bd->InputContext invalidateCharacterCoordinates];
521
+ [bd->InputContext deactivate];
522
+ }
523
+ [bd->KeyEventResponder setImePosX:data->InputPos.x imePosY:data->InputPos.y + data->InputLineHeight];
524
+ };
525
+
526
+ return true;
527
+ }
528
+
529
+ void ImGui_ImplOSX_Shutdown()
530
+ {
531
+ ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
532
+ IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
533
+
534
+ bd->Observer = nullptr;
535
+ if (bd->Monitor != nullptr)
536
+ {
537
+ [NSEvent removeMonitor:bd->Monitor];
538
+ bd->Monitor = nullptr;
539
+ }
540
+
541
+ ImGui_ImplOSX_ShutdownMultiViewportSupport();
542
+ ImGui_ImplOSX_DestroyBackendData();
543
+ ImGuiIO& io = ImGui::GetIO();
544
+ io.BackendPlatformName = nullptr;
545
+ io.BackendPlatformUserData = nullptr;
546
+ io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_PlatformHasViewports);
547
+ }
548
+
549
+ static void ImGui_ImplOSX_UpdateMouseCursor()
550
+ {
551
+ ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
552
+ ImGuiIO& io = ImGui::GetIO();
553
+ if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
554
+ return;
555
+
556
+ ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
557
+ if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
558
+ {
559
+ // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
560
+ if (!bd->MouseCursorHidden)
561
+ {
562
+ bd->MouseCursorHidden = true;
563
+ [NSCursor hide];
564
+ }
565
+ }
566
+ else
567
+ {
568
+ NSCursor* desired = bd->MouseCursors[imgui_cursor] ?: bd->MouseCursors[ImGuiMouseCursor_Arrow];
569
+ // -[NSCursor set] generates measureable overhead if called unconditionally.
570
+ if (desired != NSCursor.currentCursor)
571
+ {
572
+ [desired set];
573
+ }
574
+ if (bd->MouseCursorHidden)
575
+ {
576
+ bd->MouseCursorHidden = false;
577
+ [NSCursor unhide];
578
+ }
579
+ }
580
+ }
581
+
582
+ static void ImGui_ImplOSX_UpdateGamepads()
583
+ {
584
+ ImGuiIO& io = ImGui::GetIO();
585
+ if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
586
+ return;
587
+
588
+ #if APPLE_HAS_CONTROLLER
589
+ GCController* controller = GCController.current;
590
+ #else
591
+ GCController* controller = GCController.controllers.firstObject;
592
+ #endif
593
+ if (controller == nil || controller.extendedGamepad == nil)
594
+ {
595
+ io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
596
+ return;
597
+ }
598
+
599
+ GCExtendedGamepad* gp = controller.extendedGamepad;
600
+
601
+ // Update gamepad inputs
602
+ #define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V)
603
+ #define MAP_BUTTON(KEY_NO, BUTTON_NAME) { io.AddKeyEvent(KEY_NO, gp.BUTTON_NAME.isPressed); }
604
+ #define MAP_ANALOG(KEY_NO, AXIS_NAME, V0, V1) { float vn = (float)(gp.AXIS_NAME.value - V0) / (float)(V1 - V0); vn = IM_SATURATE(vn); io.AddKeyAnalogEvent(KEY_NO, vn > 0.1f, vn); }
605
+ const float thumb_dead_zone = 0.0f;
606
+
607
+ #if APPLE_HAS_BUTTON_OPTIONS
608
+ MAP_BUTTON(ImGuiKey_GamepadBack, buttonOptions);
609
+ #endif
610
+ MAP_BUTTON(ImGuiKey_GamepadFaceLeft, buttonX); // Xbox X, PS Square
611
+ MAP_BUTTON(ImGuiKey_GamepadFaceRight, buttonB); // Xbox B, PS Circle
612
+ MAP_BUTTON(ImGuiKey_GamepadFaceUp, buttonY); // Xbox Y, PS Triangle
613
+ MAP_BUTTON(ImGuiKey_GamepadFaceDown, buttonA); // Xbox A, PS Cross
614
+ MAP_BUTTON(ImGuiKey_GamepadDpadLeft, dpad.left);
615
+ MAP_BUTTON(ImGuiKey_GamepadDpadRight, dpad.right);
616
+ MAP_BUTTON(ImGuiKey_GamepadDpadUp, dpad.up);
617
+ MAP_BUTTON(ImGuiKey_GamepadDpadDown, dpad.down);
618
+ MAP_ANALOG(ImGuiKey_GamepadL1, leftShoulder, 0.0f, 1.0f);
619
+ MAP_ANALOG(ImGuiKey_GamepadR1, rightShoulder, 0.0f, 1.0f);
620
+ MAP_ANALOG(ImGuiKey_GamepadL2, leftTrigger, 0.0f, 1.0f);
621
+ MAP_ANALOG(ImGuiKey_GamepadR2, rightTrigger, 0.0f, 1.0f);
622
+ #if APPLE_HAS_THUMBSTICKS
623
+ MAP_BUTTON(ImGuiKey_GamepadL3, leftThumbstickButton);
624
+ MAP_BUTTON(ImGuiKey_GamepadR3, rightThumbstickButton);
625
+ #endif
626
+ MAP_ANALOG(ImGuiKey_GamepadLStickLeft, leftThumbstick.xAxis, -thumb_dead_zone, -1.0f);
627
+ MAP_ANALOG(ImGuiKey_GamepadLStickRight, leftThumbstick.xAxis, +thumb_dead_zone, +1.0f);
628
+ MAP_ANALOG(ImGuiKey_GamepadLStickUp, leftThumbstick.yAxis, +thumb_dead_zone, +1.0f);
629
+ MAP_ANALOG(ImGuiKey_GamepadLStickDown, leftThumbstick.yAxis, -thumb_dead_zone, -1.0f);
630
+ MAP_ANALOG(ImGuiKey_GamepadRStickLeft, rightThumbstick.xAxis, -thumb_dead_zone, -1.0f);
631
+ MAP_ANALOG(ImGuiKey_GamepadRStickRight, rightThumbstick.xAxis, +thumb_dead_zone, +1.0f);
632
+ MAP_ANALOG(ImGuiKey_GamepadRStickUp, rightThumbstick.yAxis, +thumb_dead_zone, +1.0f);
633
+ MAP_ANALOG(ImGuiKey_GamepadRStickDown, rightThumbstick.yAxis, -thumb_dead_zone, -1.0f);
634
+ #undef MAP_BUTTON
635
+ #undef MAP_ANALOG
636
+
637
+ io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
638
+ }
639
+
640
+ static void ImGui_ImplOSX_UpdateImePosWithView(NSView* view)
641
+ {
642
+ ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
643
+ ImGuiIO& io = ImGui::GetIO();
644
+ if (io.WantTextInput)
645
+ [bd->KeyEventResponder updateImePosWithView:view];
646
+ }
647
+
648
+ void ImGui_ImplOSX_NewFrame(NSView* view)
649
+ {
650
+ ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
651
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplOSX_Init()?");
652
+ ImGuiIO& io = ImGui::GetIO();
653
+
654
+ // Setup display size
655
+ if (view)
656
+ {
657
+ const float dpi = (float)[view.window backingScaleFactor];
658
+ io.DisplaySize = ImVec2((float)view.bounds.size.width, (float)view.bounds.size.height);
659
+ io.DisplayFramebufferScale = ImVec2(dpi, dpi);
660
+ }
661
+
662
+ // Setup time step
663
+ if (bd->Time == 0.0)
664
+ bd->Time = GetMachAbsoluteTimeInSeconds();
665
+
666
+ double current_time = GetMachAbsoluteTimeInSeconds();
667
+ io.DeltaTime = (float)(current_time - bd->Time);
668
+ bd->Time = current_time;
669
+
670
+ ImGui_ImplOSX_UpdateMouseCursor();
671
+ ImGui_ImplOSX_UpdateGamepads();
672
+ ImGui_ImplOSX_UpdateImePosWithView(view);
673
+ }
674
+
675
+ // Must only be called for a mouse event, otherwise an exception occurs
676
+ // (Note that NSEventTypeScrollWheel is considered "other input". Oddly enough an exception does not occur with it, but the value will sometimes be wrong!)
677
+ static ImGuiMouseSource GetMouseSource(NSEvent* event)
678
+ {
679
+ switch (event.subtype)
680
+ {
681
+ case NSEventSubtypeTabletPoint:
682
+ return ImGuiMouseSource_Pen;
683
+ // macOS considers input from relative touch devices (like the trackpad or Apple Magic Mouse) to be touch input.
684
+ // This doesn't really make sense for Dear ImGui, which expects absolute touch devices only.
685
+ // There does not seem to be a simple way to disambiguate things here so we consider NSEventSubtypeTouch events to always come from mice.
686
+ // See https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/HandlingTouchEvents/HandlingTouchEvents.html#//apple_ref/doc/uid/10000060i-CH13-SW24
687
+ //case NSEventSubtypeTouch:
688
+ // return ImGuiMouseSource_TouchScreen;
689
+ case NSEventSubtypeMouseEvent:
690
+ default:
691
+ return ImGuiMouseSource_Mouse;
692
+ }
693
+ }
694
+
695
+ static bool ImGui_ImplOSX_HandleEvent(NSEvent* event, NSView* view)
696
+ {
697
+ ImGuiIO& io = ImGui::GetIO();
698
+
699
+ if (event.type == NSEventTypeLeftMouseDown || event.type == NSEventTypeRightMouseDown || event.type == NSEventTypeOtherMouseDown)
700
+ {
701
+ int button = (int)[event buttonNumber];
702
+ if (button >= 0 && button < ImGuiMouseButton_COUNT)
703
+ {
704
+ io.AddMouseSourceEvent(GetMouseSource(event));
705
+ io.AddMouseButtonEvent(button, true);
706
+ }
707
+ return io.WantCaptureMouse;
708
+ }
709
+
710
+ if (event.type == NSEventTypeLeftMouseUp || event.type == NSEventTypeRightMouseUp || event.type == NSEventTypeOtherMouseUp)
711
+ {
712
+ int button = (int)[event buttonNumber];
713
+ if (button >= 0 && button < ImGuiMouseButton_COUNT)
714
+ {
715
+ io.AddMouseSourceEvent(GetMouseSource(event));
716
+ io.AddMouseButtonEvent(button, false);
717
+ }
718
+ return io.WantCaptureMouse;
719
+ }
720
+
721
+ if (event.type == NSEventTypeMouseMoved || event.type == NSEventTypeLeftMouseDragged || event.type == NSEventTypeRightMouseDragged || event.type == NSEventTypeOtherMouseDragged)
722
+ {
723
+ NSPoint mousePoint;
724
+ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
725
+ {
726
+ mousePoint = NSEvent.mouseLocation;
727
+ mousePoint.y = CGDisplayPixelsHigh(kCGDirectMainDisplay) - mousePoint.y; // Normalize y coordinate to top-left of main display.
728
+ }
729
+ else
730
+ {
731
+ mousePoint = event.locationInWindow;
732
+ if (event.window == nil)
733
+ mousePoint = [[view window] convertPointFromScreen:mousePoint];
734
+ mousePoint = [view convertPoint:mousePoint fromView:nil]; // Convert to local coordinates of view
735
+ if ([view isFlipped])
736
+ mousePoint = NSMakePoint(mousePoint.x, mousePoint.y);
737
+ else
738
+ mousePoint = NSMakePoint(mousePoint.x, view.bounds.size.height - mousePoint.y);
739
+ }
740
+ io.AddMouseSourceEvent(GetMouseSource(event));
741
+ io.AddMousePosEvent((float)mousePoint.x, (float)mousePoint.y);
742
+ return io.WantCaptureMouse;
743
+ }
744
+
745
+ if (event.type == NSEventTypeScrollWheel)
746
+ {
747
+ // Ignore canceled events.
748
+ //
749
+ // From macOS 12.1, scrolling with two fingers and then decelerating
750
+ // by tapping two fingers results in two events appearing:
751
+ //
752
+ // 1. A scroll wheel NSEvent, with a phase == NSEventPhaseMayBegin, when the user taps
753
+ // two fingers to decelerate or stop the scroll events.
754
+ //
755
+ // 2. A scroll wheel NSEvent, with a phase == NSEventPhaseCancelled, when the user releases the
756
+ // two-finger tap. It is this event that sometimes contains large values for scrollingDeltaX and
757
+ // scrollingDeltaY. When these are added to the current x and y positions of the scrolling view,
758
+ // it appears to jump up or down. It can be observed in Preview, various JetBrains IDEs and here.
759
+ if (event.phase == NSEventPhaseCancelled)
760
+ return false;
761
+
762
+ double wheel_dx = 0.0;
763
+ double wheel_dy = 0.0;
764
+
765
+ #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
766
+ if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6)
767
+ {
768
+ wheel_dx = [event scrollingDeltaX];
769
+ wheel_dy = [event scrollingDeltaY];
770
+ if ([event hasPreciseScrollingDeltas])
771
+ {
772
+ wheel_dx *= 0.01;
773
+ wheel_dy *= 0.01;
774
+ }
775
+ }
776
+ else
777
+ #endif // MAC_OS_X_VERSION_MAX_ALLOWED
778
+ {
779
+ wheel_dx = [event deltaX] * 0.1;
780
+ wheel_dy = [event deltaY] * 0.1;
781
+ }
782
+ if (wheel_dx != 0.0 || wheel_dy != 0.0)
783
+ io.AddMouseWheelEvent((float)wheel_dx, (float)wheel_dy);
784
+
785
+ return io.WantCaptureMouse;
786
+ }
787
+
788
+ if (event.type == NSEventTypeKeyDown || event.type == NSEventTypeKeyUp)
789
+ {
790
+ if ([event isARepeat])
791
+ return io.WantCaptureKeyboard;
792
+
793
+ int key_code = (int)[event keyCode];
794
+ ImGuiKey key = ImGui_ImplOSX_KeyCodeToImGuiKey(key_code);
795
+ io.AddKeyEvent(key, event.type == NSEventTypeKeyDown);
796
+ io.SetKeyEventNativeData(key, key_code, -1); // To support legacy indexing (<1.87 user code)
797
+
798
+ return io.WantCaptureKeyboard;
799
+ }
800
+
801
+ if (event.type == NSEventTypeFlagsChanged)
802
+ {
803
+ unsigned short key_code = [event keyCode];
804
+ NSEventModifierFlags modifier_flags = [event modifierFlags];
805
+
806
+ io.AddKeyEvent(ImGuiMod_Shift, (modifier_flags & NSEventModifierFlagShift) != 0);
807
+ io.AddKeyEvent(ImGuiMod_Ctrl, (modifier_flags & NSEventModifierFlagControl) != 0);
808
+ io.AddKeyEvent(ImGuiMod_Alt, (modifier_flags & NSEventModifierFlagOption) != 0);
809
+ io.AddKeyEvent(ImGuiMod_Super, (modifier_flags & NSEventModifierFlagCommand) != 0);
810
+
811
+ ImGuiKey key = ImGui_ImplOSX_KeyCodeToImGuiKey(key_code);
812
+ if (key != ImGuiKey_None)
813
+ {
814
+ // macOS does not generate down/up event for modifiers. We're trying
815
+ // to use hardware dependent masks to extract that information.
816
+ // 'imgui_mask' is left as a fallback.
817
+ NSEventModifierFlags mask = 0;
818
+ switch (key)
819
+ {
820
+ case ImGuiKey_LeftCtrl: mask = 0x0001; break;
821
+ case ImGuiKey_RightCtrl: mask = 0x2000; break;
822
+ case ImGuiKey_LeftShift: mask = 0x0002; break;
823
+ case ImGuiKey_RightShift: mask = 0x0004; break;
824
+ case ImGuiKey_LeftSuper: mask = 0x0008; break;
825
+ case ImGuiKey_RightSuper: mask = 0x0010; break;
826
+ case ImGuiKey_LeftAlt: mask = 0x0020; break;
827
+ case ImGuiKey_RightAlt: mask = 0x0040; break;
828
+ default:
829
+ return io.WantCaptureKeyboard;
830
+ }
831
+
832
+ NSEventModifierFlags modifier_flags = [event modifierFlags];
833
+ io.AddKeyEvent(key, (modifier_flags & mask) != 0);
834
+ io.SetKeyEventNativeData(key, key_code, -1); // To support legacy indexing (<1.87 user code)
835
+ }
836
+
837
+ return io.WantCaptureKeyboard;
838
+ }
839
+
840
+ return false;
841
+ }
842
+
843
+ static void ImGui_ImplOSX_AddTrackingArea(NSView* _Nonnull view)
844
+ {
845
+ // If we want to receive key events, we either need to be in the responder chain of the key view,
846
+ // or else we can install a local monitor. The consequence of this heavy-handed approach is that
847
+ // we receive events for all controls, not just Dear ImGui widgets. If we had native controls in our
848
+ // window, we'd want to be much more careful than just ingesting the complete event stream.
849
+ // To match the behavior of other backends, we pass every event down to the OS.
850
+ ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
851
+ if (bd->Monitor)
852
+ return;
853
+ NSEventMask eventMask = 0;
854
+ eventMask |= NSEventMaskMouseMoved | NSEventMaskScrollWheel;
855
+ eventMask |= NSEventMaskLeftMouseDown | NSEventMaskLeftMouseUp | NSEventMaskLeftMouseDragged;
856
+ eventMask |= NSEventMaskRightMouseDown | NSEventMaskRightMouseUp | NSEventMaskRightMouseDragged;
857
+ eventMask |= NSEventMaskOtherMouseDown | NSEventMaskOtherMouseUp | NSEventMaskOtherMouseDragged;
858
+ eventMask |= NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged;
859
+ bd->Monitor = [NSEvent addLocalMonitorForEventsMatchingMask:eventMask
860
+ handler:^NSEvent* _Nullable(NSEvent* event)
861
+ {
862
+ ImGui_ImplOSX_HandleEvent(event, view);
863
+ return event;
864
+ }];
865
+ }
866
+
867
+ //--------------------------------------------------------------------------------------------------------
868
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
869
+ // This is an _advanced_ and _optional_ feature, allowing the back-end to create and handle multiple viewports simultaneously.
870
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
871
+ //--------------------------------------------------------------------------------------------------------
872
+
873
+ struct ImGuiViewportDataOSX
874
+ {
875
+ NSWindow* Window;
876
+ bool WindowOwned;
877
+
878
+ ImGuiViewportDataOSX() { WindowOwned = false; }
879
+ ~ImGuiViewportDataOSX() { IM_ASSERT(Window == nil); }
880
+ };
881
+
882
+ @interface ImGui_ImplOSX_Window: NSWindow
883
+ @end
884
+
885
+ @implementation ImGui_ImplOSX_Window
886
+
887
+ - (BOOL)canBecomeKeyWindow
888
+ {
889
+ return YES;
890
+ }
891
+
892
+ @end
893
+
894
+ static void ConvertNSRect(NSRect* r)
895
+ {
896
+ NSRect firstScreenFrame = NSScreen.screens[0].frame;
897
+ IM_ASSERT(firstScreenFrame.origin.x == 0 && firstScreenFrame.origin.y == 0);
898
+ r->origin.y = firstScreenFrame.size.height - r->origin.y - r->size.height;
899
+ }
900
+
901
+ static void ImGui_ImplOSX_CreateWindow(ImGuiViewport* viewport)
902
+ {
903
+ ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
904
+ ImGuiViewportDataOSX* data = IM_NEW(ImGuiViewportDataOSX)();
905
+ viewport->PlatformUserData = data;
906
+
907
+ NSScreen* screen = bd->Window.screen;
908
+ NSRect rect = NSMakeRect(viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y);
909
+ ConvertNSRect(&rect);
910
+
911
+ NSWindowStyleMask styleMask = 0;
912
+ if (viewport->Flags & ImGuiViewportFlags_NoDecoration)
913
+ styleMask |= NSWindowStyleMaskBorderless;
914
+ else
915
+ styleMask |= NSWindowStyleMaskTitled | NSWindowStyleMaskResizable | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable;
916
+
917
+ NSWindow* window = [[ImGui_ImplOSX_Window alloc] initWithContentRect:rect
918
+ styleMask:styleMask
919
+ backing:NSBackingStoreBuffered
920
+ defer:YES
921
+ screen:screen];
922
+ if (viewport->Flags & ImGuiViewportFlags_TopMost)
923
+ [window setLevel:NSFloatingWindowLevel];
924
+
925
+ window.title = @"Untitled";
926
+ window.opaque = YES;
927
+
928
+ KeyEventResponder* view = [[KeyEventResponder alloc] initWithFrame:rect];
929
+ if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6 && ceil(NSAppKitVersionNumber) < NSAppKitVersionNumber10_15)
930
+ [view setWantsBestResolutionOpenGLSurface:YES];
931
+
932
+ window.contentView = view;
933
+
934
+ data->Window = window;
935
+ data->WindowOwned = true;
936
+ viewport->PlatformRequestResize = false;
937
+ viewport->PlatformHandle = viewport->PlatformHandleRaw = (__bridge_retained void*)window;
938
+ }
939
+
940
+ static void ImGui_ImplOSX_DestroyWindow(ImGuiViewport* viewport)
941
+ {
942
+ NSWindow* window = (__bridge_transfer NSWindow*)viewport->PlatformHandleRaw;
943
+ window = nil;
944
+
945
+ if (ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData)
946
+ {
947
+ NSWindow* window = data->Window;
948
+ if (window != nil && data->WindowOwned)
949
+ {
950
+ window.contentView = nil;
951
+ window.contentViewController = nil;
952
+ [window orderOut:nil];
953
+ }
954
+ data->Window = nil;
955
+ IM_DELETE(data);
956
+ }
957
+ viewport->PlatformUserData = viewport->PlatformHandle = viewport->PlatformHandleRaw = nullptr;
958
+ }
959
+
960
+ static void ImGui_ImplOSX_ShowWindow(ImGuiViewport* viewport)
961
+ {
962
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData;
963
+ IM_ASSERT(data->Window != 0);
964
+
965
+ if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
966
+ [data->Window orderFront:nil];
967
+ else
968
+ [data->Window makeKeyAndOrderFront:nil];
969
+
970
+ [data->Window setIsVisible:YES];
971
+ }
972
+
973
+ static ImVec2 ImGui_ImplOSX_GetWindowPos(ImGuiViewport* viewport)
974
+ {
975
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData;
976
+ IM_ASSERT(data->Window != 0);
977
+
978
+ NSWindow* window = data->Window;
979
+ NSRect frame = window.frame;
980
+ NSRect contentRect = window.contentLayoutRect;
981
+ if (window.styleMask & NSWindowStyleMaskFullSizeContentView) // No title bar windows should be considered.
982
+ contentRect = frame;
983
+
984
+ NSRect firstScreenFrame = NSScreen.screens[0].frame;
985
+ return ImVec2(frame.origin.x, firstScreenFrame.size.height - frame.origin.y - contentRect.size.height);
986
+ }
987
+
988
+ static void ImGui_ImplOSX_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
989
+ {
990
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData;
991
+ IM_ASSERT(data->Window != 0);
992
+
993
+ NSWindow* window = data->Window;
994
+ NSSize size = window.frame.size;
995
+
996
+ NSRect r = NSMakeRect(pos.x, pos.y, size.width, size.height);
997
+ ConvertNSRect(&r);
998
+ [window setFrameOrigin:r.origin];
999
+ }
1000
+
1001
+ static ImVec2 ImGui_ImplOSX_GetWindowSize(ImGuiViewport* viewport)
1002
+ {
1003
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData;
1004
+ IM_ASSERT(data->Window != 0);
1005
+
1006
+ NSWindow* window = data->Window;
1007
+ NSSize size = window.contentLayoutRect.size;
1008
+ return ImVec2(size.width, size.height);
1009
+ }
1010
+
1011
+ static void ImGui_ImplOSX_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
1012
+ {
1013
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData;
1014
+ IM_ASSERT(data->Window != 0);
1015
+
1016
+ NSWindow* window = data->Window;
1017
+ NSRect rect = window.frame;
1018
+ rect.origin.y -= (size.y - rect.size.height);
1019
+ rect.size.width = size.x;
1020
+ rect.size.height = size.y;
1021
+ [window setFrame:rect display:YES];
1022
+ }
1023
+
1024
+ static void ImGui_ImplOSX_SetWindowFocus(ImGuiViewport* viewport)
1025
+ {
1026
+ ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
1027
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData;
1028
+ IM_ASSERT(data->Window != 0);
1029
+ [data->Window makeKeyAndOrderFront:bd->Window];
1030
+ }
1031
+
1032
+ static bool ImGui_ImplOSX_GetWindowFocus(ImGuiViewport* viewport)
1033
+ {
1034
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData;
1035
+ IM_ASSERT(data->Window != 0);
1036
+
1037
+ return data->Window.isKeyWindow;
1038
+ }
1039
+
1040
+ static bool ImGui_ImplOSX_GetWindowMinimized(ImGuiViewport* viewport)
1041
+ {
1042
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData;
1043
+ IM_ASSERT(data->Window != 0);
1044
+
1045
+ return data->Window.isMiniaturized;
1046
+ }
1047
+
1048
+ static void ImGui_ImplOSX_SetWindowTitle(ImGuiViewport* viewport, const char* title)
1049
+ {
1050
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData;
1051
+ IM_ASSERT(data->Window != 0);
1052
+
1053
+ data->Window.title = [NSString stringWithUTF8String:title];
1054
+ }
1055
+
1056
+ static void ImGui_ImplOSX_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
1057
+ {
1058
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData;
1059
+ IM_ASSERT(data->Window != 0);
1060
+ IM_ASSERT(alpha >= 0.0f && alpha <= 1.0f);
1061
+
1062
+ data->Window.alphaValue = alpha;
1063
+ }
1064
+
1065
+ static float ImGui_ImplOSX_GetWindowDpiScale(ImGuiViewport* viewport)
1066
+ {
1067
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)viewport->PlatformUserData;
1068
+ IM_ASSERT(data->Window != 0);
1069
+
1070
+ return data->Window.backingScaleFactor;
1071
+ }
1072
+
1073
+ static void ImGui_ImplOSX_UpdateMonitors()
1074
+ {
1075
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
1076
+ platform_io.Monitors.resize(0);
1077
+
1078
+ NSRect firstScreenFrame = NSScreen.screens[0].frame;
1079
+ IM_ASSERT(firstScreenFrame.origin.x == 0 && firstScreenFrame.origin.y == 0);
1080
+
1081
+ for (NSScreen* screen in NSScreen.screens)
1082
+ {
1083
+ NSRect frame = screen.frame;
1084
+ NSRect visibleFrame = screen.visibleFrame;
1085
+ ConvertNSRect(&frame);
1086
+ ConvertNSRect(&visibleFrame);
1087
+
1088
+ ImGuiPlatformMonitor imgui_monitor;
1089
+ imgui_monitor.MainPos = ImVec2(frame.origin.x, frame.origin.y);
1090
+ imgui_monitor.MainSize = ImVec2(frame.size.width, frame.size.height);
1091
+ imgui_monitor.WorkPos = ImVec2(visibleFrame.origin.x, visibleFrame.origin.y);
1092
+ imgui_monitor.WorkSize = ImVec2(visibleFrame.size.width, visibleFrame.size.height);
1093
+ imgui_monitor.DpiScale = screen.backingScaleFactor;
1094
+ imgui_monitor.PlatformHandle = (__bridge_retained void*)screen;
1095
+
1096
+ platform_io.Monitors.push_back(imgui_monitor);
1097
+ }
1098
+ }
1099
+
1100
+ static void ImGui_ImplOSX_InitMultiViewportSupport()
1101
+ {
1102
+ ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
1103
+
1104
+ // Register platform interface (will be coupled with a renderer interface)
1105
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
1106
+ platform_io.Platform_CreateWindow = ImGui_ImplOSX_CreateWindow;
1107
+ platform_io.Platform_DestroyWindow = ImGui_ImplOSX_DestroyWindow;
1108
+ platform_io.Platform_ShowWindow = ImGui_ImplOSX_ShowWindow;
1109
+ platform_io.Platform_SetWindowPos = ImGui_ImplOSX_SetWindowPos;
1110
+ platform_io.Platform_GetWindowPos = ImGui_ImplOSX_GetWindowPos;
1111
+ platform_io.Platform_SetWindowSize = ImGui_ImplOSX_SetWindowSize;
1112
+ platform_io.Platform_GetWindowSize = ImGui_ImplOSX_GetWindowSize;
1113
+ platform_io.Platform_SetWindowFocus = ImGui_ImplOSX_SetWindowFocus;
1114
+ platform_io.Platform_GetWindowFocus = ImGui_ImplOSX_GetWindowFocus;
1115
+ platform_io.Platform_GetWindowMinimized = ImGui_ImplOSX_GetWindowMinimized;
1116
+ platform_io.Platform_SetWindowTitle = ImGui_ImplOSX_SetWindowTitle;
1117
+ platform_io.Platform_SetWindowAlpha = ImGui_ImplOSX_SetWindowAlpha;
1118
+ platform_io.Platform_GetWindowDpiScale = ImGui_ImplOSX_GetWindowDpiScale; // FIXME-DPI
1119
+
1120
+ // Register main window handle (which is owned by the main application, not by us)
1121
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
1122
+ ImGuiViewportDataOSX* data = IM_NEW(ImGuiViewportDataOSX)();
1123
+ data->Window = bd->Window;
1124
+ data->WindowOwned = false;
1125
+ main_viewport->PlatformUserData = data;
1126
+ main_viewport->PlatformHandle = (__bridge void*)bd->Window;
1127
+
1128
+ [NSNotificationCenter.defaultCenter addObserver:bd->Observer
1129
+ selector:@selector(displaysDidChange:)
1130
+ name:NSApplicationDidChangeScreenParametersNotification
1131
+ object:nil];
1132
+ }
1133
+
1134
+ static void ImGui_ImplOSX_ShutdownMultiViewportSupport()
1135
+ {
1136
+ ImGui_ImplOSX_Data* bd = ImGui_ImplOSX_GetBackendData();
1137
+ [NSNotificationCenter.defaultCenter removeObserver:bd->Observer
1138
+ name:NSApplicationDidChangeScreenParametersNotification
1139
+ object:nil];
1140
+ bd->Observer = nullptr;
1141
+ bd->Window = nullptr;
1142
+ if (bd->Monitor != nullptr)
1143
+ {
1144
+ [NSEvent removeMonitor:bd->Monitor];
1145
+ bd->Monitor = nullptr;
1146
+ }
1147
+
1148
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
1149
+ ImGuiViewportDataOSX* data = (ImGuiViewportDataOSX*)main_viewport->PlatformUserData;
1150
+ IM_DELETE(data);
1151
+ main_viewport->PlatformUserData = nullptr;
1152
+ ImGui::DestroyPlatformWindows();
1153
+ }
1154
+
1155
+ //-----------------------------------------------------------------------------
1156
+
1157
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_sdl2.cpp ADDED
@@ -0,0 +1,1206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for SDL2
2
+ // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
3
+ // (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
4
+ // (Prefer SDL 2.0.5+ for full feature support.)
5
+
6
+ // Implemented features:
7
+ // [X] Platform: Clipboard support.
8
+ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
9
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
10
+ // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
11
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
12
+ // [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
13
+ // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
14
+ // Missing features or Issues:
15
+ // [ ] Platform: Multi-viewport: Minimized windows seems to break mouse wheel events (at least under Windows).
16
+ // [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor).
17
+
18
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
19
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
20
+ // Learn about Dear ImGui:
21
+ // - FAQ https://dearimgui.com/faq
22
+ // - Getting Started https://dearimgui.com/getting-started
23
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
24
+ // - Introduction, links and more at the top of imgui.cpp
25
+
26
+ // CHANGELOG
27
+ // (minor and older changes stripped away, please see git history for details)
28
+ // 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
29
+ // 2024-10-24: Emscripten: from SDL 2.30.9, SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f.
30
+ // 2024-09-09: use SDL_Vulkan_GetDrawableSize() when available. (#7967, #3190)
31
+ // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
32
+ // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
33
+ // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
34
+ // - io.PlatformOpenInShellFn -> platform_io.Platform_OpenInShellFn
35
+ // - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
36
+ // 2024-08-19: Storing SDL's Uint32 WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*.
37
+ // 2024-08-19: ImGui_ImplSDL2_ProcessEvent() now ignores events intended for other SDL windows. (#7853)
38
+ // 2024-07-02: Emscripten: Added io.PlatformOpenInShellFn() handler for Emscripten versions.
39
+ // 2024-07-02: Update for io.SetPlatformImeDataFn() -> io.PlatformSetImeDataFn() renaming in main library.
40
+ // 2024-02-14: Inputs: Handle gamepad disconnection. Added ImGui_ImplSDL2_SetGamepadMode().
41
+ // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys.
42
+ // 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306)
43
+ // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702)
44
+ // 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644)
45
+ // 2023-02-07: Implement IME handler (io.SetPlatformImeDataFn will call SDL_SetTextInputRect()/SDL_StartTextInput()).
46
+ // 2023-02-07: *BREAKING CHANGE* Renamed this backend file from imgui_impl_sdl.cpp/.h to imgui_impl_sdl2.cpp/.h in prevision for the future release of SDL3.
47
+ // 2023-02-02: Avoid calling SDL_SetCursor() when cursor has not changed, as the function is surprisingly costly on Mac with latest SDL (may be fixed in next SDL version).
48
+ // 2023-02-02: Added support for SDL 2.0.18+ preciseX/preciseY mouse wheel data for smooth scrolling + Scaling X value on Emscripten (bug?). (#4019, #6096)
49
+ // 2023-02-02: Removed SDL_MOUSEWHEEL value clamping, as values seem correct in latest Emscripten. (#4019)
50
+ // 2023-02-01: Flipping SDL_MOUSEWHEEL 'wheel.x' value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463)
51
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
52
+ // 2022-09-26: Inputs: Disable SDL 2.0.22 new "auto capture" (SDL_HINT_MOUSE_AUTO_CAPTURE) which prevents drag and drop across windows for multi-viewport support + don't capture when drag and dropping. (#5710)
53
+ // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
54
+ // 2022-03-22: Inputs: Fix mouse position issues when dragging outside of boundaries. SDL_CaptureMouse() erroneously still gives out LEAVE events when hovering OS decorations.
55
+ // 2022-03-22: Inputs: Added support for extra mouse buttons (SDL_BUTTON_X1/SDL_BUTTON_X2).
56
+ // 2022-02-04: Added SDL_Renderer* parameter to ImGui_ImplSDL2_InitForSDLRenderer(), so we can use SDL_GetRendererOutputSize() instead of SDL_GL_GetDrawableSize() when bound to a SDL_Renderer.
57
+ // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
58
+ // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
59
+ // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
60
+ // 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates.
61
+ // 2022-01-12: Update mouse inputs using SDL_MOUSEMOTION/SDL_WINDOWEVENT_LEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass it to future input queue API.
62
+ // 2022-01-12: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted.
63
+ // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
64
+ // 2021-08-17: Calling io.AddFocusEvent() on SDL_WINDOWEVENT_FOCUS_GAINED/SDL_WINDOWEVENT_FOCUS_LOST.
65
+ // 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using SDL_GetMouseFocus() + SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, requires SDL 2.0.5+)
66
+ // 2021-06:29: *BREAKING CHANGE* Removed 'SDL_Window* window' parameter to ImGui_ImplSDL2_NewFrame() which was unnecessary.
67
+ // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
68
+ // 2021-03-22: Rework global mouse pos availability check listing supported platforms explicitly, effectively fixing mouse access on Raspberry Pi. (#2837, #3950)
69
+ // 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends.
70
+ // 2020-02-20: Inputs: Fixed mapping for ImGuiKey_KeyPadEnter (using SDL_SCANCODE_KP_ENTER instead of SDL_SCANCODE_RETURN2).
71
+ // 2019-12-17: Inputs: On Wayland, use SDL_GetMouseState (because there is no global mouse state).
72
+ // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
73
+ // 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
74
+ // 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application).
75
+ // 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
76
+ // 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls.
77
+ // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
78
+ // 2018-11-14: Changed the signature of ImGui_ImplSDL2_ProcessEvent() to take a 'const SDL_Event*'.
79
+ // 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
80
+ // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
81
+ // 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples.
82
+ // 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter.
83
+ // 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText).
84
+ // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
85
+ // 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value.
86
+ // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
87
+ // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
88
+ // 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS).
89
+ // 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes.
90
+ // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
91
+ // 2018-01-19: Inputs: When available (SDL 2.0.4+) using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging. Otherwise (SDL 2.0.3 and before) testing for SDL_WINDOW_INPUT_FOCUS instead of SDL_WINDOW_MOUSE_FOCUS.
92
+ // 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
93
+ // 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
94
+ // 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
95
+
96
+ #include "imgui.h"
97
+ #ifndef IMGUI_DISABLE
98
+ #include "imgui_impl_sdl2.h"
99
+
100
+ // Clang warnings with -Weverything
101
+ #if defined(__clang__)
102
+ #pragma clang diagnostic push
103
+ #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
104
+ #endif
105
+
106
+ // SDL
107
+ // (the multi-viewports feature requires SDL features supported from SDL 2.0.4+. SDL 2.0.5+ is highly recommended)
108
+ #include <SDL.h>
109
+ #include <SDL_syswm.h>
110
+ #ifdef __APPLE__
111
+ #include <TargetConditionals.h>
112
+ #endif
113
+ #ifdef __EMSCRIPTEN__
114
+ #include <emscripten/em_js.h>
115
+ #endif
116
+
117
+ #if SDL_VERSION_ATLEAST(2,0,4) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__)
118
+ #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1
119
+ #else
120
+ #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0
121
+ #endif
122
+ #define SDL_HAS_WINDOW_ALPHA SDL_VERSION_ATLEAST(2,0,5)
123
+ #define SDL_HAS_ALWAYS_ON_TOP SDL_VERSION_ATLEAST(2,0,5)
124
+ #define SDL_HAS_USABLE_DISPLAY_BOUNDS SDL_VERSION_ATLEAST(2,0,5)
125
+ #define SDL_HAS_PER_MONITOR_DPI SDL_VERSION_ATLEAST(2,0,4)
126
+ #define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6)
127
+ #define SDL_HAS_DISPLAY_EVENT SDL_VERSION_ATLEAST(2,0,9)
128
+ #define SDL_HAS_SHOW_WINDOW_ACTIVATION_HINT SDL_VERSION_ATLEAST(2,0,18)
129
+ #if SDL_HAS_VULKAN
130
+ #include <SDL_vulkan.h>
131
+ #else
132
+ static const Uint32 SDL_WINDOW_VULKAN = 0x10000000;
133
+ #endif
134
+
135
+ // SDL Data
136
+ struct ImGui_ImplSDL2_Data
137
+ {
138
+ SDL_Window* Window;
139
+ Uint32 WindowID;
140
+ SDL_Renderer* Renderer;
141
+ Uint64 Time;
142
+ char* ClipboardTextData;
143
+ bool UseVulkan;
144
+ bool WantUpdateMonitors;
145
+
146
+ // Mouse handling
147
+ Uint32 MouseWindowID;
148
+ int MouseButtonsDown;
149
+ SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT];
150
+ SDL_Cursor* MouseLastCursor;
151
+ int MouseLastLeaveFrame;
152
+ bool MouseCanUseGlobalState;
153
+ bool MouseCanReportHoveredViewport; // This is hard to use/unreliable on SDL so we'll set ImGuiBackendFlags_HasMouseHoveredViewport dynamically based on state.
154
+
155
+ // Gamepad handling
156
+ ImVector<SDL_GameController*> Gamepads;
157
+ ImGui_ImplSDL2_GamepadMode GamepadMode;
158
+ bool WantUpdateGamepadsList;
159
+
160
+ ImGui_ImplSDL2_Data() { memset((void*)this, 0, sizeof(*this)); }
161
+ };
162
+
163
+ // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
164
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
165
+ // FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
166
+ // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
167
+ static ImGui_ImplSDL2_Data* ImGui_ImplSDL2_GetBackendData()
168
+ {
169
+ return ImGui::GetCurrentContext() ? (ImGui_ImplSDL2_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
170
+ }
171
+
172
+ // Forward Declarations
173
+ static void ImGui_ImplSDL2_UpdateMonitors();
174
+ static void ImGui_ImplSDL2_InitMultiViewportSupport(SDL_Window* window, void* sdl_gl_context);
175
+ static void ImGui_ImplSDL2_ShutdownMultiViewportSupport();
176
+
177
+ // Functions
178
+ static const char* ImGui_ImplSDL2_GetClipboardText(ImGuiContext*)
179
+ {
180
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
181
+ if (bd->ClipboardTextData)
182
+ SDL_free(bd->ClipboardTextData);
183
+ bd->ClipboardTextData = SDL_GetClipboardText();
184
+ return bd->ClipboardTextData;
185
+ }
186
+
187
+ static void ImGui_ImplSDL2_SetClipboardText(ImGuiContext*, const char* text)
188
+ {
189
+ SDL_SetClipboardText(text);
190
+ }
191
+
192
+ // Note: native IME will only display if user calls SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1") _before_ SDL_CreateWindow().
193
+ static void ImGui_ImplSDL2_PlatformSetImeData(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
194
+ {
195
+ if (data->WantVisible)
196
+ {
197
+ SDL_Rect r;
198
+ r.x = (int)(data->InputPos.x - viewport->Pos.x);
199
+ r.y = (int)(data->InputPos.y - viewport->Pos.y + data->InputLineHeight);
200
+ r.w = 1;
201
+ r.h = (int)data->InputLineHeight;
202
+ SDL_SetTextInputRect(&r);
203
+ }
204
+ }
205
+
206
+ // Not static to allow third-party code to use that if they want to (but undocumented)
207
+ ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode);
208
+ ImGuiKey ImGui_ImplSDL2_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
209
+ {
210
+ IM_UNUSED(scancode);
211
+ switch (keycode)
212
+ {
213
+ case SDLK_TAB: return ImGuiKey_Tab;
214
+ case SDLK_LEFT: return ImGuiKey_LeftArrow;
215
+ case SDLK_RIGHT: return ImGuiKey_RightArrow;
216
+ case SDLK_UP: return ImGuiKey_UpArrow;
217
+ case SDLK_DOWN: return ImGuiKey_DownArrow;
218
+ case SDLK_PAGEUP: return ImGuiKey_PageUp;
219
+ case SDLK_PAGEDOWN: return ImGuiKey_PageDown;
220
+ case SDLK_HOME: return ImGuiKey_Home;
221
+ case SDLK_END: return ImGuiKey_End;
222
+ case SDLK_INSERT: return ImGuiKey_Insert;
223
+ case SDLK_DELETE: return ImGuiKey_Delete;
224
+ case SDLK_BACKSPACE: return ImGuiKey_Backspace;
225
+ case SDLK_SPACE: return ImGuiKey_Space;
226
+ case SDLK_RETURN: return ImGuiKey_Enter;
227
+ case SDLK_ESCAPE: return ImGuiKey_Escape;
228
+ case SDLK_QUOTE: return ImGuiKey_Apostrophe;
229
+ case SDLK_COMMA: return ImGuiKey_Comma;
230
+ case SDLK_MINUS: return ImGuiKey_Minus;
231
+ case SDLK_PERIOD: return ImGuiKey_Period;
232
+ case SDLK_SLASH: return ImGuiKey_Slash;
233
+ case SDLK_SEMICOLON: return ImGuiKey_Semicolon;
234
+ case SDLK_EQUALS: return ImGuiKey_Equal;
235
+ case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket;
236
+ case SDLK_BACKSLASH: return ImGuiKey_Backslash;
237
+ case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket;
238
+ case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent;
239
+ case SDLK_CAPSLOCK: return ImGuiKey_CapsLock;
240
+ case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock;
241
+ case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock;
242
+ case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen;
243
+ case SDLK_PAUSE: return ImGuiKey_Pause;
244
+ case SDLK_KP_0: return ImGuiKey_Keypad0;
245
+ case SDLK_KP_1: return ImGuiKey_Keypad1;
246
+ case SDLK_KP_2: return ImGuiKey_Keypad2;
247
+ case SDLK_KP_3: return ImGuiKey_Keypad3;
248
+ case SDLK_KP_4: return ImGuiKey_Keypad4;
249
+ case SDLK_KP_5: return ImGuiKey_Keypad5;
250
+ case SDLK_KP_6: return ImGuiKey_Keypad6;
251
+ case SDLK_KP_7: return ImGuiKey_Keypad7;
252
+ case SDLK_KP_8: return ImGuiKey_Keypad8;
253
+ case SDLK_KP_9: return ImGuiKey_Keypad9;
254
+ case SDLK_KP_PERIOD: return ImGuiKey_KeypadDecimal;
255
+ case SDLK_KP_DIVIDE: return ImGuiKey_KeypadDivide;
256
+ case SDLK_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
257
+ case SDLK_KP_MINUS: return ImGuiKey_KeypadSubtract;
258
+ case SDLK_KP_PLUS: return ImGuiKey_KeypadAdd;
259
+ case SDLK_KP_ENTER: return ImGuiKey_KeypadEnter;
260
+ case SDLK_KP_EQUALS: return ImGuiKey_KeypadEqual;
261
+ case SDLK_LCTRL: return ImGuiKey_LeftCtrl;
262
+ case SDLK_LSHIFT: return ImGuiKey_LeftShift;
263
+ case SDLK_LALT: return ImGuiKey_LeftAlt;
264
+ case SDLK_LGUI: return ImGuiKey_LeftSuper;
265
+ case SDLK_RCTRL: return ImGuiKey_RightCtrl;
266
+ case SDLK_RSHIFT: return ImGuiKey_RightShift;
267
+ case SDLK_RALT: return ImGuiKey_RightAlt;
268
+ case SDLK_RGUI: return ImGuiKey_RightSuper;
269
+ case SDLK_APPLICATION: return ImGuiKey_Menu;
270
+ case SDLK_0: return ImGuiKey_0;
271
+ case SDLK_1: return ImGuiKey_1;
272
+ case SDLK_2: return ImGuiKey_2;
273
+ case SDLK_3: return ImGuiKey_3;
274
+ case SDLK_4: return ImGuiKey_4;
275
+ case SDLK_5: return ImGuiKey_5;
276
+ case SDLK_6: return ImGuiKey_6;
277
+ case SDLK_7: return ImGuiKey_7;
278
+ case SDLK_8: return ImGuiKey_8;
279
+ case SDLK_9: return ImGuiKey_9;
280
+ case SDLK_a: return ImGuiKey_A;
281
+ case SDLK_b: return ImGuiKey_B;
282
+ case SDLK_c: return ImGuiKey_C;
283
+ case SDLK_d: return ImGuiKey_D;
284
+ case SDLK_e: return ImGuiKey_E;
285
+ case SDLK_f: return ImGuiKey_F;
286
+ case SDLK_g: return ImGuiKey_G;
287
+ case SDLK_h: return ImGuiKey_H;
288
+ case SDLK_i: return ImGuiKey_I;
289
+ case SDLK_j: return ImGuiKey_J;
290
+ case SDLK_k: return ImGuiKey_K;
291
+ case SDLK_l: return ImGuiKey_L;
292
+ case SDLK_m: return ImGuiKey_M;
293
+ case SDLK_n: return ImGuiKey_N;
294
+ case SDLK_o: return ImGuiKey_O;
295
+ case SDLK_p: return ImGuiKey_P;
296
+ case SDLK_q: return ImGuiKey_Q;
297
+ case SDLK_r: return ImGuiKey_R;
298
+ case SDLK_s: return ImGuiKey_S;
299
+ case SDLK_t: return ImGuiKey_T;
300
+ case SDLK_u: return ImGuiKey_U;
301
+ case SDLK_v: return ImGuiKey_V;
302
+ case SDLK_w: return ImGuiKey_W;
303
+ case SDLK_x: return ImGuiKey_X;
304
+ case SDLK_y: return ImGuiKey_Y;
305
+ case SDLK_z: return ImGuiKey_Z;
306
+ case SDLK_F1: return ImGuiKey_F1;
307
+ case SDLK_F2: return ImGuiKey_F2;
308
+ case SDLK_F3: return ImGuiKey_F3;
309
+ case SDLK_F4: return ImGuiKey_F4;
310
+ case SDLK_F5: return ImGuiKey_F5;
311
+ case SDLK_F6: return ImGuiKey_F6;
312
+ case SDLK_F7: return ImGuiKey_F7;
313
+ case SDLK_F8: return ImGuiKey_F8;
314
+ case SDLK_F9: return ImGuiKey_F9;
315
+ case SDLK_F10: return ImGuiKey_F10;
316
+ case SDLK_F11: return ImGuiKey_F11;
317
+ case SDLK_F12: return ImGuiKey_F12;
318
+ case SDLK_F13: return ImGuiKey_F13;
319
+ case SDLK_F14: return ImGuiKey_F14;
320
+ case SDLK_F15: return ImGuiKey_F15;
321
+ case SDLK_F16: return ImGuiKey_F16;
322
+ case SDLK_F17: return ImGuiKey_F17;
323
+ case SDLK_F18: return ImGuiKey_F18;
324
+ case SDLK_F19: return ImGuiKey_F19;
325
+ case SDLK_F20: return ImGuiKey_F20;
326
+ case SDLK_F21: return ImGuiKey_F21;
327
+ case SDLK_F22: return ImGuiKey_F22;
328
+ case SDLK_F23: return ImGuiKey_F23;
329
+ case SDLK_F24: return ImGuiKey_F24;
330
+ case SDLK_AC_BACK: return ImGuiKey_AppBack;
331
+ case SDLK_AC_FORWARD: return ImGuiKey_AppForward;
332
+ default: break;
333
+ }
334
+ return ImGuiKey_None;
335
+ }
336
+
337
+ static void ImGui_ImplSDL2_UpdateKeyModifiers(SDL_Keymod sdl_key_mods)
338
+ {
339
+ ImGuiIO& io = ImGui::GetIO();
340
+ io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0);
341
+ io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0);
342
+ io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0);
343
+ io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0);
344
+ }
345
+
346
+ static ImGuiViewport* ImGui_ImplSDL2_GetViewportForWindowID(Uint32 window_id)
347
+ {
348
+ return ImGui::FindViewportByPlatformHandle((void*)(intptr_t)window_id);
349
+ }
350
+
351
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
352
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
353
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
354
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
355
+ bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
356
+ {
357
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
358
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?");
359
+ ImGuiIO& io = ImGui::GetIO();
360
+
361
+ switch (event->type)
362
+ {
363
+ case SDL_MOUSEMOTION:
364
+ {
365
+ if (ImGui_ImplSDL2_GetViewportForWindowID(event->motion.windowID) == nullptr)
366
+ return false;
367
+ ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);
368
+ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
369
+ {
370
+ int window_x, window_y;
371
+ SDL_GetWindowPosition(SDL_GetWindowFromID(event->motion.windowID), &window_x, &window_y);
372
+ mouse_pos.x += window_x;
373
+ mouse_pos.y += window_y;
374
+ }
375
+ io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
376
+ io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);
377
+ return true;
378
+ }
379
+ case SDL_MOUSEWHEEL:
380
+ {
381
+ if (ImGui_ImplSDL2_GetViewportForWindowID(event->wheel.windowID) == nullptr)
382
+ return false;
383
+ //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);
384
+ #if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!
385
+ float wheel_x = -event->wheel.preciseX;
386
+ float wheel_y = event->wheel.preciseY;
387
+ #else
388
+ float wheel_x = -(float)event->wheel.x;
389
+ float wheel_y = (float)event->wheel.y;
390
+ #endif
391
+ #if defined(__EMSCRIPTEN__) && !SDL_VERSION_ATLEAST(2,31,0)
392
+ wheel_x /= 100.0f;
393
+ #endif
394
+ io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
395
+ io.AddMouseWheelEvent(wheel_x, wheel_y);
396
+ return true;
397
+ }
398
+ case SDL_MOUSEBUTTONDOWN:
399
+ case SDL_MOUSEBUTTONUP:
400
+ {
401
+ if (ImGui_ImplSDL2_GetViewportForWindowID(event->button.windowID) == nullptr)
402
+ return false;
403
+ int mouse_button = -1;
404
+ if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }
405
+ if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }
406
+ if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }
407
+ if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }
408
+ if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }
409
+ if (mouse_button == -1)
410
+ break;
411
+ io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
412
+ io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN));
413
+ bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));
414
+ return true;
415
+ }
416
+ case SDL_TEXTINPUT:
417
+ {
418
+ if (ImGui_ImplSDL2_GetViewportForWindowID(event->text.windowID) == nullptr)
419
+ return false;
420
+ io.AddInputCharactersUTF8(event->text.text);
421
+ return true;
422
+ }
423
+ case SDL_KEYDOWN:
424
+ case SDL_KEYUP:
425
+ {
426
+ if (ImGui_ImplSDL2_GetViewportForWindowID(event->key.windowID) == nullptr)
427
+ return false;
428
+ ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);
429
+ ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);
430
+ io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));
431
+ io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.
432
+ return true;
433
+ }
434
+ #if SDL_HAS_DISPLAY_EVENT
435
+ case SDL_DISPLAYEVENT:
436
+ {
437
+ // 2.0.26 has SDL_DISPLAYEVENT_CONNECTED/SDL_DISPLAYEVENT_DISCONNECTED/SDL_DISPLAYEVENT_ORIENTATION,
438
+ // so change of DPI/Scaling are not reflected in this event. (SDL3 has it)
439
+ bd->WantUpdateMonitors = true;
440
+ return true;
441
+ }
442
+ #endif
443
+ case SDL_WINDOWEVENT:
444
+ {
445
+ ImGuiViewport* viewport = ImGui_ImplSDL2_GetViewportForWindowID(event->window.windowID);
446
+ if (viewport == NULL)
447
+ return false;
448
+
449
+ // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right.
450
+ // - However we won't get a correct LEAVE event for a captured window.
451
+ // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,
452
+ // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why
453
+ // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.
454
+ Uint8 window_event = event->window.event;
455
+ if (window_event == SDL_WINDOWEVENT_ENTER)
456
+ {
457
+ bd->MouseWindowID = event->window.windowID;
458
+ bd->MouseLastLeaveFrame = 0;
459
+ }
460
+ if (window_event == SDL_WINDOWEVENT_LEAVE)
461
+ bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1;
462
+ if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)
463
+ io.AddFocusEvent(true);
464
+ else if (window_event == SDL_WINDOWEVENT_FOCUS_LOST)
465
+ io.AddFocusEvent(false);
466
+ else if (window_event == SDL_WINDOWEVENT_CLOSE)
467
+ viewport->PlatformRequestClose = true;
468
+ else if (window_event == SDL_WINDOWEVENT_MOVED)
469
+ viewport->PlatformRequestMove = true;
470
+ else if (window_event == SDL_WINDOWEVENT_RESIZED)
471
+ viewport->PlatformRequestResize = true;
472
+ return true;
473
+ }
474
+ case SDL_CONTROLLERDEVICEADDED:
475
+ case SDL_CONTROLLERDEVICEREMOVED:
476
+ {
477
+ bd->WantUpdateGamepadsList = true;
478
+ return true;
479
+ }
480
+ }
481
+ return false;
482
+ }
483
+
484
+ #ifdef __EMSCRIPTEN__
485
+ EM_JS(void, ImGui_ImplSDL2_EmscriptenOpenURL, (char const* url), { url = url ? UTF8ToString(url) : null; if (url) window.open(url, '_blank'); });
486
+ #endif
487
+
488
+ static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context)
489
+ {
490
+ ImGuiIO& io = ImGui::GetIO();
491
+ IMGUI_CHECKVERSION();
492
+ IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
493
+
494
+ // Check and store if we are on a SDL backend that supports global mouse position
495
+ // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list)
496
+ bool mouse_can_use_global_state = false;
497
+ #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
498
+ const char* sdl_backend = SDL_GetCurrentVideoDriver();
499
+ const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" };
500
+ for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++)
501
+ if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0)
502
+ mouse_can_use_global_state = true;
503
+ #endif
504
+
505
+ // Setup backend capabilities flags
506
+ ImGui_ImplSDL2_Data* bd = IM_NEW(ImGui_ImplSDL2_Data)();
507
+ io.BackendPlatformUserData = (void*)bd;
508
+ io.BackendPlatformName = "imgui_impl_sdl2";
509
+ io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
510
+ io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
511
+ if (mouse_can_use_global_state)
512
+ io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
513
+
514
+ bd->Window = window;
515
+ bd->WindowID = SDL_GetWindowID(window);
516
+ bd->Renderer = renderer;
517
+
518
+ // SDL on Linux/OSX doesn't report events for unfocused windows (see https://github.com/ocornut/imgui/issues/4960)
519
+ // We will use 'MouseCanReportHoveredViewport' to set 'ImGuiBackendFlags_HasMouseHoveredViewport' dynamically each frame.
520
+ bd->MouseCanUseGlobalState = mouse_can_use_global_state;
521
+ #ifndef __APPLE__
522
+ bd->MouseCanReportHoveredViewport = bd->MouseCanUseGlobalState;
523
+ #else
524
+ bd->MouseCanReportHoveredViewport = false;
525
+ #endif
526
+
527
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
528
+ platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText;
529
+ platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText;
530
+ platform_io.Platform_ClipboardUserData = nullptr;
531
+ platform_io.Platform_SetImeDataFn = ImGui_ImplSDL2_PlatformSetImeData;
532
+ #ifdef __EMSCRIPTEN__
533
+ platform_io.Platform_OpenInShellFn = [](ImGuiContext*, const char* url) { ImGui_ImplSDL2_EmscriptenOpenURL(url); return true; };
534
+ #endif
535
+
536
+ // Update monitor a first time during init
537
+ ImGui_ImplSDL2_UpdateMonitors();
538
+
539
+ // Gamepad handling
540
+ bd->GamepadMode = ImGui_ImplSDL2_GamepadMode_AutoFirst;
541
+ bd->WantUpdateGamepadsList = true;
542
+
543
+ // Load mouse cursors
544
+ bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
545
+ bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
546
+ bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
547
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
548
+ bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
549
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
550
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
551
+ bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
552
+ bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO);
553
+
554
+ // Set platform dependent data in viewport
555
+ // Our mouse update function expect PlatformHandle to be filled for the main viewport
556
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
557
+ main_viewport->PlatformHandle = (void*)(intptr_t)bd->WindowID;
558
+ main_viewport->PlatformHandleRaw = nullptr;
559
+ SDL_SysWMinfo info;
560
+ SDL_VERSION(&info.version);
561
+ if (SDL_GetWindowWMInfo(window, &info))
562
+ {
563
+ #if defined(SDL_VIDEO_DRIVER_WINDOWS)
564
+ main_viewport->PlatformHandleRaw = (void*)info.info.win.window;
565
+ #elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
566
+ main_viewport->PlatformHandleRaw = (void*)info.info.cocoa.window;
567
+ #endif
568
+ }
569
+
570
+ // From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event.
571
+ // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered.
572
+ // (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application.
573
+ // It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click:
574
+ // you can ignore SDL_MOUSEBUTTONDOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED)
575
+ #ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH
576
+ SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
577
+ #endif
578
+
579
+ // From 2.0.18: Enable native IME.
580
+ // IMPORTANT: This is used at the time of SDL_CreateWindow() so this will only affects secondary windows, if any.
581
+ // For the main window to be affected, your application needs to call this manually before calling SDL_CreateWindow().
582
+ #ifdef SDL_HINT_IME_SHOW_UI
583
+ SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");
584
+ #endif
585
+
586
+ // From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710)
587
+ #ifdef SDL_HINT_MOUSE_AUTO_CAPTURE
588
+ SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0");
589
+ #endif
590
+
591
+ // We need SDL_CaptureMouse(), SDL_GetGlobalMouseState() from SDL 2.0.4+ to support multiple viewports.
592
+ // We left the call to ImGui_ImplSDL2_InitMultiViewportSupport() outside of #ifdef to avoid unused-function warnings.
593
+ if (io.BackendFlags & ImGuiBackendFlags_PlatformHasViewports)
594
+ ImGui_ImplSDL2_InitMultiViewportSupport(window, sdl_gl_context);
595
+
596
+ return true;
597
+ }
598
+
599
+ bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
600
+ {
601
+ return ImGui_ImplSDL2_Init(window, nullptr, sdl_gl_context);
602
+ }
603
+
604
+ bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window)
605
+ {
606
+ #if !SDL_HAS_VULKAN
607
+ IM_ASSERT(0 && "Unsupported");
608
+ #endif
609
+ if (!ImGui_ImplSDL2_Init(window, nullptr, nullptr))
610
+ return false;
611
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
612
+ bd->UseVulkan = true;
613
+ return true;
614
+ }
615
+
616
+ bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window)
617
+ {
618
+ #if !defined(_WIN32)
619
+ IM_ASSERT(0 && "Unsupported");
620
+ #endif
621
+ return ImGui_ImplSDL2_Init(window, nullptr, nullptr);
622
+ }
623
+
624
+ bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window)
625
+ {
626
+ return ImGui_ImplSDL2_Init(window, nullptr, nullptr);
627
+ }
628
+
629
+ bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer)
630
+ {
631
+ return ImGui_ImplSDL2_Init(window, renderer, nullptr);
632
+ }
633
+
634
+ bool ImGui_ImplSDL2_InitForOther(SDL_Window* window)
635
+ {
636
+ return ImGui_ImplSDL2_Init(window, nullptr, nullptr);
637
+ }
638
+
639
+ static void ImGui_ImplSDL2_CloseGamepads();
640
+
641
+ void ImGui_ImplSDL2_Shutdown()
642
+ {
643
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
644
+ IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
645
+ ImGuiIO& io = ImGui::GetIO();
646
+
647
+ ImGui_ImplSDL2_ShutdownMultiViewportSupport();
648
+
649
+ if (bd->ClipboardTextData)
650
+ SDL_free(bd->ClipboardTextData);
651
+ for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
652
+ SDL_FreeCursor(bd->MouseCursors[cursor_n]);
653
+ ImGui_ImplSDL2_CloseGamepads();
654
+
655
+ io.BackendPlatformName = nullptr;
656
+ io.BackendPlatformUserData = nullptr;
657
+ io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_PlatformHasViewports | ImGuiBackendFlags_HasMouseHoveredViewport);
658
+ IM_DELETE(bd);
659
+ }
660
+
661
+ // This code is incredibly messy because some of the functions we need for full viewport support are not available in SDL < 2.0.4.
662
+ static void ImGui_ImplSDL2_UpdateMouseData()
663
+ {
664
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
665
+ ImGuiIO& io = ImGui::GetIO();
666
+
667
+ // We forward mouse input when hovered or captured (via SDL_MOUSEMOTION) or when focused (below)
668
+ #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
669
+ // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside
670
+ SDL_CaptureMouse((bd->MouseButtonsDown != 0) ? SDL_TRUE : SDL_FALSE);
671
+ SDL_Window* focused_window = SDL_GetKeyboardFocus();
672
+ const bool is_app_focused = (focused_window && (bd->Window == focused_window || ImGui_ImplSDL2_GetViewportForWindowID(SDL_GetWindowID(focused_window)) != NULL));
673
+ #else
674
+ SDL_Window* focused_window = bd->Window;
675
+ const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only
676
+ #endif
677
+
678
+ if (is_app_focused)
679
+ {
680
+ // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
681
+ if (io.WantSetMousePos)
682
+ {
683
+ #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
684
+ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
685
+ SDL_WarpMouseGlobal((int)io.MousePos.x, (int)io.MousePos.y);
686
+ else
687
+ #endif
688
+ SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y);
689
+ }
690
+
691
+ // (Optional) Fallback to provide mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured)
692
+ if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0)
693
+ {
694
+ // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
695
+ // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
696
+ int mouse_x, mouse_y, window_x, window_y;
697
+ SDL_GetGlobalMouseState(&mouse_x, &mouse_y);
698
+ if (!(io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable))
699
+ {
700
+ SDL_GetWindowPosition(focused_window, &window_x, &window_y);
701
+ mouse_x -= window_x;
702
+ mouse_y -= window_y;
703
+ }
704
+ io.AddMousePosEvent((float)mouse_x, (float)mouse_y);
705
+ }
706
+ }
707
+
708
+ // (Optional) When using multiple viewports: call io.AddMouseViewportEvent() with the viewport the OS mouse cursor is hovering.
709
+ // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, Dear imGui will ignore this field and infer the information using its flawed heuristic.
710
+ // - [!] SDL backend does NOT correctly ignore viewports with the _NoInputs flag.
711
+ // Some backend are not able to handle that correctly. If a backend report an hovered viewport that has the _NoInputs flag (e.g. when dragging a window
712
+ // for docking, the viewport has the _NoInputs flag in order to allow us to find the viewport under), then Dear ImGui is forced to ignore the value reported
713
+ // by the backend, and use its flawed heuristic to guess the viewport behind.
714
+ // - [X] SDL backend correctly reports this regardless of another viewport behind focused and dragged from (we need this to find a useful drag and drop target).
715
+ if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
716
+ {
717
+ ImGuiID mouse_viewport_id = 0;
718
+ if (ImGuiViewport* mouse_viewport = ImGui_ImplSDL2_GetViewportForWindowID(bd->MouseWindowID))
719
+ mouse_viewport_id = mouse_viewport->ID;
720
+ io.AddMouseViewportEvent(mouse_viewport_id);
721
+ }
722
+ }
723
+
724
+ static void ImGui_ImplSDL2_UpdateMouseCursor()
725
+ {
726
+ ImGuiIO& io = ImGui::GetIO();
727
+ if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
728
+ return;
729
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
730
+
731
+ ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
732
+ if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
733
+ {
734
+ // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
735
+ SDL_ShowCursor(SDL_FALSE);
736
+ }
737
+ else
738
+ {
739
+ // Show OS mouse cursor
740
+ SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow];
741
+ if (bd->MouseLastCursor != expected_cursor)
742
+ {
743
+ SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113)
744
+ bd->MouseLastCursor = expected_cursor;
745
+ }
746
+ SDL_ShowCursor(SDL_TRUE);
747
+ }
748
+ }
749
+
750
+ static void ImGui_ImplSDL2_CloseGamepads()
751
+ {
752
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
753
+ if (bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual)
754
+ for (SDL_GameController* gamepad : bd->Gamepads)
755
+ SDL_GameControllerClose(gamepad);
756
+ bd->Gamepads.resize(0);
757
+ }
758
+
759
+ void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array, int manual_gamepads_count)
760
+ {
761
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
762
+ ImGui_ImplSDL2_CloseGamepads();
763
+ if (mode == ImGui_ImplSDL2_GamepadMode_Manual)
764
+ {
765
+ IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0);
766
+ for (int n = 0; n < manual_gamepads_count; n++)
767
+ bd->Gamepads.push_back(manual_gamepads_array[n]);
768
+ }
769
+ else
770
+ {
771
+ IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0);
772
+ bd->WantUpdateGamepadsList = true;
773
+ }
774
+ bd->GamepadMode = mode;
775
+ }
776
+
777
+ static void ImGui_ImplSDL2_UpdateGamepadButton(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerButton button_no)
778
+ {
779
+ bool merged_value = false;
780
+ for (SDL_GameController* gamepad : bd->Gamepads)
781
+ merged_value |= SDL_GameControllerGetButton(gamepad, button_no) != 0;
782
+ io.AddKeyEvent(key, merged_value);
783
+ }
784
+
785
+ static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
786
+ static void ImGui_ImplSDL2_UpdateGamepadAnalog(ImGui_ImplSDL2_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GameControllerAxis axis_no, float v0, float v1)
787
+ {
788
+ float merged_value = 0.0f;
789
+ for (SDL_GameController* gamepad : bd->Gamepads)
790
+ {
791
+ float vn = Saturate((float)(SDL_GameControllerGetAxis(gamepad, axis_no) - v0) / (float)(v1 - v0));
792
+ if (merged_value < vn)
793
+ merged_value = vn;
794
+ }
795
+ io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value);
796
+ }
797
+
798
+ static void ImGui_ImplSDL2_UpdateGamepads()
799
+ {
800
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
801
+ ImGuiIO& io = ImGui::GetIO();
802
+
803
+ // Update list of controller(s) to use
804
+ if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL2_GamepadMode_Manual)
805
+ {
806
+ ImGui_ImplSDL2_CloseGamepads();
807
+ int joystick_count = SDL_NumJoysticks();
808
+ for (int n = 0; n < joystick_count; n++)
809
+ if (SDL_IsGameController(n))
810
+ if (SDL_GameController* gamepad = SDL_GameControllerOpen(n))
811
+ {
812
+ bd->Gamepads.push_back(gamepad);
813
+ if (bd->GamepadMode == ImGui_ImplSDL2_GamepadMode_AutoFirst)
814
+ break;
815
+ }
816
+ bd->WantUpdateGamepadsList = false;
817
+ }
818
+
819
+ // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
820
+ if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
821
+ return;
822
+ io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
823
+ if (bd->Gamepads.Size == 0)
824
+ return;
825
+ io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
826
+
827
+ // Update gamepad inputs
828
+ const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value.
829
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_CONTROLLER_BUTTON_START);
830
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_CONTROLLER_BUTTON_BACK);
831
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_CONTROLLER_BUTTON_X); // Xbox X, PS Square
832
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_CONTROLLER_BUTTON_B); // Xbox B, PS Circle
833
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_CONTROLLER_BUTTON_Y); // Xbox Y, PS Triangle
834
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_CONTROLLER_BUTTON_A); // Xbox A, PS Cross
835
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT);
836
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
837
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP);
838
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN);
839
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_CONTROLLER_BUTTON_LEFTSHOULDER);
840
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);
841
+ ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_CONTROLLER_AXIS_TRIGGERLEFT, 0.0f, 32767);
842
+ ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 0.0f, 32767);
843
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_CONTROLLER_BUTTON_LEFTSTICK);
844
+ ImGui_ImplSDL2_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_CONTROLLER_BUTTON_RIGHTSTICK);
845
+ ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768);
846
+ ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767);
847
+ ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32768);
848
+ ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767);
849
+ ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_CONTROLLER_AXIS_RIGHTX, -thumb_dead_zone, -32768);
850
+ ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_CONTROLLER_AXIS_RIGHTX, +thumb_dead_zone, +32767);
851
+ ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_CONTROLLER_AXIS_RIGHTY, -thumb_dead_zone, -32768);
852
+ ImGui_ImplSDL2_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_CONTROLLER_AXIS_RIGHTY, +thumb_dead_zone, +32767);
853
+ }
854
+
855
+ // FIXME: Note that doesn't update with DPI/Scaling change only as SDL2 doesn't have an event for it (SDL3 has).
856
+ static void ImGui_ImplSDL2_UpdateMonitors()
857
+ {
858
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
859
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
860
+ platform_io.Monitors.resize(0);
861
+ bd->WantUpdateMonitors = false;
862
+ int display_count = SDL_GetNumVideoDisplays();
863
+ for (int n = 0; n < display_count; n++)
864
+ {
865
+ // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, which generally needs to be set in the manifest or at runtime.
866
+ ImGuiPlatformMonitor monitor;
867
+ SDL_Rect r;
868
+ SDL_GetDisplayBounds(n, &r);
869
+ monitor.MainPos = monitor.WorkPos = ImVec2((float)r.x, (float)r.y);
870
+ monitor.MainSize = monitor.WorkSize = ImVec2((float)r.w, (float)r.h);
871
+ #if SDL_HAS_USABLE_DISPLAY_BOUNDS
872
+ SDL_GetDisplayUsableBounds(n, &r);
873
+ monitor.WorkPos = ImVec2((float)r.x, (float)r.y);
874
+ monitor.WorkSize = ImVec2((float)r.w, (float)r.h);
875
+ #endif
876
+ #if SDL_HAS_PER_MONITOR_DPI
877
+ // FIXME-VIEWPORT: On MacOS SDL reports actual monitor DPI scale, ignoring OS configuration. We may want to set
878
+ // DpiScale to cocoa_window.backingScaleFactor here.
879
+ float dpi = 0.0f;
880
+ if (!SDL_GetDisplayDPI(n, &dpi, nullptr, nullptr))
881
+ {
882
+ if (dpi <= 0.0f)
883
+ continue; // Some accessibility applications are declaring virtual monitors with a DPI of 0, see #7902.
884
+ monitor.DpiScale = dpi / 96.0f;
885
+ }
886
+ #endif
887
+ monitor.PlatformHandle = (void*)(intptr_t)n;
888
+ platform_io.Monitors.push_back(monitor);
889
+ }
890
+ }
891
+
892
+ void ImGui_ImplSDL2_NewFrame()
893
+ {
894
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
895
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?");
896
+ ImGuiIO& io = ImGui::GetIO();
897
+
898
+ // Setup display size (every frame to accommodate for window resizing)
899
+ int w, h;
900
+ int display_w, display_h;
901
+ SDL_GetWindowSize(bd->Window, &w, &h);
902
+ if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED)
903
+ w = h = 0;
904
+ if (bd->Renderer != nullptr)
905
+ SDL_GetRendererOutputSize(bd->Renderer, &display_w, &display_h);
906
+ #if SDL_HAS_VULKAN
907
+ else if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_VULKAN)
908
+ SDL_Vulkan_GetDrawableSize(bd->Window, &display_w, &display_h);
909
+ #endif
910
+ else
911
+ SDL_GL_GetDrawableSize(bd->Window, &display_w, &display_h);
912
+ io.DisplaySize = ImVec2((float)w, (float)h);
913
+ if (w > 0 && h > 0)
914
+ io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);
915
+
916
+ // Update monitors
917
+ if (bd->WantUpdateMonitors)
918
+ ImGui_ImplSDL2_UpdateMonitors();
919
+
920
+ // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution)
921
+ // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644)
922
+ static Uint64 frequency = SDL_GetPerformanceFrequency();
923
+ Uint64 current_time = SDL_GetPerformanceCounter();
924
+ if (current_time <= bd->Time)
925
+ current_time = bd->Time + 1;
926
+ io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f);
927
+ bd->Time = current_time;
928
+
929
+ if (bd->MouseLastLeaveFrame && bd->MouseLastLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0)
930
+ {
931
+ bd->MouseWindowID = 0;
932
+ bd->MouseLastLeaveFrame = 0;
933
+ io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
934
+ }
935
+
936
+ // Our io.AddMouseViewportEvent() calls will only be valid when not capturing.
937
+ // Technically speaking testing for 'bd->MouseButtonsDown == 0' would be more rigorous, but testing for payload reduces noise and potential side-effects.
938
+ if (bd->MouseCanReportHoveredViewport && ImGui::GetDragDropPayload() == nullptr)
939
+ io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport;
940
+ else
941
+ io.BackendFlags &= ~ImGuiBackendFlags_HasMouseHoveredViewport;
942
+
943
+ ImGui_ImplSDL2_UpdateMouseData();
944
+ ImGui_ImplSDL2_UpdateMouseCursor();
945
+
946
+ // Update game controllers (if enabled and available)
947
+ ImGui_ImplSDL2_UpdateGamepads();
948
+ }
949
+
950
+ //--------------------------------------------------------------------------------------------------------
951
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
952
+ // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
953
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
954
+ //--------------------------------------------------------------------------------------------------------
955
+
956
+ // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
957
+ struct ImGui_ImplSDL2_ViewportData
958
+ {
959
+ SDL_Window* Window;
960
+ Uint32 WindowID;
961
+ bool WindowOwned;
962
+ SDL_GLContext GLContext;
963
+
964
+ ImGui_ImplSDL2_ViewportData() { Window = nullptr; WindowID = 0; WindowOwned = false; GLContext = nullptr; }
965
+ ~ImGui_ImplSDL2_ViewportData() { IM_ASSERT(Window == nullptr && GLContext == nullptr); }
966
+ };
967
+
968
+ static void ImGui_ImplSDL2_CreateWindow(ImGuiViewport* viewport)
969
+ {
970
+ ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
971
+ ImGui_ImplSDL2_ViewportData* vd = IM_NEW(ImGui_ImplSDL2_ViewportData)();
972
+ viewport->PlatformUserData = vd;
973
+
974
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
975
+ ImGui_ImplSDL2_ViewportData* main_viewport_data = (ImGui_ImplSDL2_ViewportData*)main_viewport->PlatformUserData;
976
+
977
+ // Share GL resources with main context
978
+ bool use_opengl = (main_viewport_data->GLContext != nullptr);
979
+ SDL_GLContext backup_context = nullptr;
980
+ if (use_opengl)
981
+ {
982
+ backup_context = SDL_GL_GetCurrentContext();
983
+ SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
984
+ SDL_GL_MakeCurrent(main_viewport_data->Window, main_viewport_data->GLContext);
985
+ }
986
+
987
+ Uint32 sdl_flags = 0;
988
+ sdl_flags |= use_opengl ? SDL_WINDOW_OPENGL : (bd->UseVulkan ? SDL_WINDOW_VULKAN : 0);
989
+ sdl_flags |= SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_ALLOW_HIGHDPI;
990
+ sdl_flags |= SDL_WINDOW_HIDDEN;
991
+ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? SDL_WINDOW_BORDERLESS : 0;
992
+ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? 0 : SDL_WINDOW_RESIZABLE;
993
+ #if !defined(_WIN32)
994
+ // See SDL hack in ImGui_ImplSDL2_ShowWindow().
995
+ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon) ? SDL_WINDOW_SKIP_TASKBAR : 0;
996
+ #endif
997
+ #if SDL_HAS_ALWAYS_ON_TOP
998
+ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_TopMost) ? SDL_WINDOW_ALWAYS_ON_TOP : 0;
999
+ #endif
1000
+ vd->Window = SDL_CreateWindow("No Title Yet", (int)viewport->Pos.x, (int)viewport->Pos.y, (int)viewport->Size.x, (int)viewport->Size.y, sdl_flags);
1001
+ vd->WindowOwned = true;
1002
+ if (use_opengl)
1003
+ {
1004
+ vd->GLContext = SDL_GL_CreateContext(vd->Window);
1005
+ SDL_GL_SetSwapInterval(0);
1006
+ }
1007
+ if (use_opengl && backup_context)
1008
+ SDL_GL_MakeCurrent(vd->Window, backup_context);
1009
+
1010
+ viewport->PlatformHandle = (void*)(intptr_t)SDL_GetWindowID(vd->Window);
1011
+ viewport->PlatformHandleRaw = nullptr;
1012
+ SDL_SysWMinfo info;
1013
+ SDL_VERSION(&info.version);
1014
+ if (SDL_GetWindowWMInfo(vd->Window, &info))
1015
+ {
1016
+ #if defined(SDL_VIDEO_DRIVER_WINDOWS)
1017
+ viewport->PlatformHandleRaw = info.info.win.window;
1018
+ #elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
1019
+ viewport->PlatformHandleRaw = (void*)info.info.cocoa.window;
1020
+ #endif
1021
+ }
1022
+ }
1023
+
1024
+ static void ImGui_ImplSDL2_DestroyWindow(ImGuiViewport* viewport)
1025
+ {
1026
+ if (ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData)
1027
+ {
1028
+ if (vd->GLContext && vd->WindowOwned)
1029
+ SDL_GL_DeleteContext(vd->GLContext);
1030
+ if (vd->Window && vd->WindowOwned)
1031
+ SDL_DestroyWindow(vd->Window);
1032
+ vd->GLContext = nullptr;
1033
+ vd->Window = nullptr;
1034
+ IM_DELETE(vd);
1035
+ }
1036
+ viewport->PlatformUserData = viewport->PlatformHandle = nullptr;
1037
+ }
1038
+
1039
+ static void ImGui_ImplSDL2_ShowWindow(ImGuiViewport* viewport)
1040
+ {
1041
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1042
+ #if defined(_WIN32) && !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES))
1043
+ HWND hwnd = (HWND)viewport->PlatformHandleRaw;
1044
+
1045
+ // SDL hack: Hide icon from task bar
1046
+ // Note: SDL 2.0.6+ has a SDL_WINDOW_SKIP_TASKBAR flag which is supported under Windows but the way it create the window breaks our seamless transition.
1047
+ if (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon)
1048
+ {
1049
+ LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
1050
+ ex_style &= ~WS_EX_APPWINDOW;
1051
+ ex_style |= WS_EX_TOOLWINDOW;
1052
+ ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style);
1053
+ }
1054
+ #endif
1055
+
1056
+ #if SDL_HAS_SHOW_WINDOW_ACTIVATION_HINT
1057
+ SDL_SetHint(SDL_HINT_WINDOW_NO_ACTIVATION_WHEN_SHOWN, (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) ? "1" : "0");
1058
+ #elif defined(_WIN32)
1059
+ // SDL hack: SDL always activate/focus windows :/
1060
+ if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
1061
+ {
1062
+ ::ShowWindow(hwnd, SW_SHOWNA);
1063
+ return;
1064
+ }
1065
+ #endif
1066
+ SDL_ShowWindow(vd->Window);
1067
+ }
1068
+
1069
+ static ImVec2 ImGui_ImplSDL2_GetWindowPos(ImGuiViewport* viewport)
1070
+ {
1071
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1072
+ int x = 0, y = 0;
1073
+ SDL_GetWindowPosition(vd->Window, &x, &y);
1074
+ return ImVec2((float)x, (float)y);
1075
+ }
1076
+
1077
+ static void ImGui_ImplSDL2_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
1078
+ {
1079
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1080
+ SDL_SetWindowPosition(vd->Window, (int)pos.x, (int)pos.y);
1081
+ }
1082
+
1083
+ static ImVec2 ImGui_ImplSDL2_GetWindowSize(ImGuiViewport* viewport)
1084
+ {
1085
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1086
+ int w = 0, h = 0;
1087
+ SDL_GetWindowSize(vd->Window, &w, &h);
1088
+ return ImVec2((float)w, (float)h);
1089
+ }
1090
+
1091
+ static void ImGui_ImplSDL2_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
1092
+ {
1093
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1094
+ SDL_SetWindowSize(vd->Window, (int)size.x, (int)size.y);
1095
+ }
1096
+
1097
+ static void ImGui_ImplSDL2_SetWindowTitle(ImGuiViewport* viewport, const char* title)
1098
+ {
1099
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1100
+ SDL_SetWindowTitle(vd->Window, title);
1101
+ }
1102
+
1103
+ #if SDL_HAS_WINDOW_ALPHA
1104
+ static void ImGui_ImplSDL2_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
1105
+ {
1106
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1107
+ SDL_SetWindowOpacity(vd->Window, alpha);
1108
+ }
1109
+ #endif
1110
+
1111
+ static void ImGui_ImplSDL2_SetWindowFocus(ImGuiViewport* viewport)
1112
+ {
1113
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1114
+ SDL_RaiseWindow(vd->Window);
1115
+ }
1116
+
1117
+ static bool ImGui_ImplSDL2_GetWindowFocus(ImGuiViewport* viewport)
1118
+ {
1119
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1120
+ return (SDL_GetWindowFlags(vd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0;
1121
+ }
1122
+
1123
+ static bool ImGui_ImplSDL2_GetWindowMinimized(ImGuiViewport* viewport)
1124
+ {
1125
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1126
+ return (SDL_GetWindowFlags(vd->Window) & SDL_WINDOW_MINIMIZED) != 0;
1127
+ }
1128
+
1129
+ static void ImGui_ImplSDL2_RenderWindow(ImGuiViewport* viewport, void*)
1130
+ {
1131
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1132
+ if (vd->GLContext)
1133
+ SDL_GL_MakeCurrent(vd->Window, vd->GLContext);
1134
+ }
1135
+
1136
+ static void ImGui_ImplSDL2_SwapBuffers(ImGuiViewport* viewport, void*)
1137
+ {
1138
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1139
+ if (vd->GLContext)
1140
+ {
1141
+ SDL_GL_MakeCurrent(vd->Window, vd->GLContext);
1142
+ SDL_GL_SwapWindow(vd->Window);
1143
+ }
1144
+ }
1145
+
1146
+ // Vulkan support (the Vulkan renderer needs to call a platform-side support function to create the surface)
1147
+ // SDL is graceful enough to _not_ need <vulkan/vulkan.h> so we can safely include this.
1148
+ #if SDL_HAS_VULKAN
1149
+ #include <SDL_vulkan.h>
1150
+ static int ImGui_ImplSDL2_CreateVkSurface(ImGuiViewport* viewport, ImU64 vk_instance, const void* vk_allocator, ImU64* out_vk_surface)
1151
+ {
1152
+ ImGui_ImplSDL2_ViewportData* vd = (ImGui_ImplSDL2_ViewportData*)viewport->PlatformUserData;
1153
+ (void)vk_allocator;
1154
+ SDL_bool ret = SDL_Vulkan_CreateSurface(vd->Window, (VkInstance)vk_instance, (VkSurfaceKHR*)out_vk_surface);
1155
+ return ret ? 0 : 1; // ret ? VK_SUCCESS : VK_NOT_READY
1156
+ }
1157
+ #endif // SDL_HAS_VULKAN
1158
+
1159
+ static void ImGui_ImplSDL2_InitMultiViewportSupport(SDL_Window* window, void* sdl_gl_context)
1160
+ {
1161
+ // Register platform interface (will be coupled with a renderer interface)
1162
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
1163
+ platform_io.Platform_CreateWindow = ImGui_ImplSDL2_CreateWindow;
1164
+ platform_io.Platform_DestroyWindow = ImGui_ImplSDL2_DestroyWindow;
1165
+ platform_io.Platform_ShowWindow = ImGui_ImplSDL2_ShowWindow;
1166
+ platform_io.Platform_SetWindowPos = ImGui_ImplSDL2_SetWindowPos;
1167
+ platform_io.Platform_GetWindowPos = ImGui_ImplSDL2_GetWindowPos;
1168
+ platform_io.Platform_SetWindowSize = ImGui_ImplSDL2_SetWindowSize;
1169
+ platform_io.Platform_GetWindowSize = ImGui_ImplSDL2_GetWindowSize;
1170
+ platform_io.Platform_SetWindowFocus = ImGui_ImplSDL2_SetWindowFocus;
1171
+ platform_io.Platform_GetWindowFocus = ImGui_ImplSDL2_GetWindowFocus;
1172
+ platform_io.Platform_GetWindowMinimized = ImGui_ImplSDL2_GetWindowMinimized;
1173
+ platform_io.Platform_SetWindowTitle = ImGui_ImplSDL2_SetWindowTitle;
1174
+ platform_io.Platform_RenderWindow = ImGui_ImplSDL2_RenderWindow;
1175
+ platform_io.Platform_SwapBuffers = ImGui_ImplSDL2_SwapBuffers;
1176
+ #if SDL_HAS_WINDOW_ALPHA
1177
+ platform_io.Platform_SetWindowAlpha = ImGui_ImplSDL2_SetWindowAlpha;
1178
+ #endif
1179
+ #if SDL_HAS_VULKAN
1180
+ platform_io.Platform_CreateVkSurface = ImGui_ImplSDL2_CreateVkSurface;
1181
+ #endif
1182
+
1183
+ // Register main window handle (which is owned by the main application, not by us)
1184
+ // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports.
1185
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
1186
+ ImGui_ImplSDL2_ViewportData* vd = IM_NEW(ImGui_ImplSDL2_ViewportData)();
1187
+ vd->Window = window;
1188
+ vd->WindowID = SDL_GetWindowID(window);
1189
+ vd->WindowOwned = false;
1190
+ vd->GLContext = sdl_gl_context;
1191
+ main_viewport->PlatformUserData = vd;
1192
+ main_viewport->PlatformHandle = (void*)(intptr_t)vd->WindowID;
1193
+ }
1194
+
1195
+ static void ImGui_ImplSDL2_ShutdownMultiViewportSupport()
1196
+ {
1197
+ ImGui::DestroyPlatformWindows();
1198
+ }
1199
+
1200
+ //-----------------------------------------------------------------------------
1201
+
1202
+ #if defined(__clang__)
1203
+ #pragma clang diagnostic pop
1204
+ #endif
1205
+
1206
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_sdl2.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for SDL2
2
+ // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
3
+ // (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
4
+
5
+ // Implemented features:
6
+ // [X] Platform: Clipboard support.
7
+ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
8
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
9
+ // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
10
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
11
+ // [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
12
+ // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
13
+ // Missing features or Issues:
14
+ // [ ] Platform: Multi-viewport: Minimized windows seems to break mouse wheel events (at least under Windows).
15
+ // [ ] Platform: Multi-viewport: ParentViewportID not honored, and so io.ConfigViewportsNoDefaultParent has no effect (minor).
16
+
17
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
18
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
19
+ // Learn about Dear ImGui:
20
+ // - FAQ https://dearimgui.com/faq
21
+ // - Getting Started https://dearimgui.com/getting-started
22
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
23
+ // - Introduction, links and more at the top of imgui.cpp
24
+
25
+ #pragma once
26
+ #include "imgui.h" // IMGUI_IMPL_API
27
+ #ifndef IMGUI_DISABLE
28
+
29
+ struct SDL_Window;
30
+ struct SDL_Renderer;
31
+ struct _SDL_GameController;
32
+ typedef union SDL_Event SDL_Event;
33
+
34
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
35
+ IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context);
36
+ IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window);
37
+ IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window);
38
+ IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window);
39
+ IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer);
40
+ IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOther(SDL_Window* window);
41
+ IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown();
42
+ IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame();
43
+ IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event);
44
+
45
+ // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this.
46
+ // When using manual mode, caller is responsible for opening/closing gamepad.
47
+ enum ImGui_ImplSDL2_GamepadMode { ImGui_ImplSDL2_GamepadMode_AutoFirst, ImGui_ImplSDL2_GamepadMode_AutoAll, ImGui_ImplSDL2_GamepadMode_Manual };
48
+ IMGUI_IMPL_API void ImGui_ImplSDL2_SetGamepadMode(ImGui_ImplSDL2_GamepadMode mode, struct _SDL_GameController** manual_gamepads_array = nullptr, int manual_gamepads_count = -1);
49
+
50
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_sdl3.cpp ADDED
@@ -0,0 +1,1155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*)
2
+ // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
3
+ // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
4
+
5
+ // (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**)
6
+
7
+ // Implemented features:
8
+ // [X] Platform: Clipboard support.
9
+ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
10
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
11
+ // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
12
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
13
+ // [x] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable' -> the OS animation effect when window gets created/destroyed is problematic. SDL2 backend doesn't have issue.
14
+ // Missing features or Issues:
15
+ // [ ] Platform: Multi-viewport: Minimized windows seems to break mouse wheel events (at least under Windows).
16
+ // [x] Platform: IME support. Position somehow broken in SDL3 + app needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
17
+
18
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
19
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
20
+ // Learn about Dear ImGui:
21
+ // - FAQ https://dearimgui.com/faq
22
+ // - Getting Started https://dearimgui.com/getting-started
23
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
24
+ // - Introduction, links and more at the top of imgui.cpp
25
+
26
+ // CHANGELOG
27
+ // (minor and older changes stripped away, please see git history for details)
28
+ // 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
29
+ // 2024-09-11: (Docking) Added support for viewport->ParentViewportId field to support parenting at OS level. (#7973)
30
+ // 2024-10-24: Emscripten: SDL_EVENT_MOUSE_WHEEL event doesn't require dividing by 100.0f on Emscripten.
31
+ // 2024-09-03: Update for SDL3 api changes: SDL_GetGamepads() memory ownership revert. (#7918, #7898, #7807)
32
+ // 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
33
+ // - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
34
+ // - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
35
+ // - io.PlatformSetImeDataFn -> platform_io.Platform_SetImeDataFn
36
+ // 2024-08-19: Storing SDL_WindowID inside ImGuiViewport::PlatformHandle instead of SDL_Window*.
37
+ // 2024-08-19: ImGui_ImplSDL3_ProcessEvent() now ignores events intended for other SDL windows. (#7853)
38
+ // 2024-07-22: Update for SDL3 api changes: SDL_GetGamepads() memory ownership change. (#7807)
39
+ // 2024-07-18: Update for SDL3 api changes: SDL_GetClipboardText() memory ownership change. (#7801)
40
+ // 2024-07-15: Update for SDL3 api changes: SDL_GetProperty() change to SDL_GetPointerProperty(). (#7794)
41
+ // 2024-07-02: Update for SDL3 api changes: SDLK_x renames and SDLK_KP_x removals (#7761, #7762).
42
+ // 2024-07-01: Update for SDL3 api changes: SDL_SetTextInputRect() changed to SDL_SetTextInputArea().
43
+ // 2024-06-26: Update for SDL3 api changes: SDL_StartTextInput()/SDL_StopTextInput()/SDL_SetTextInputRect() functions signatures.
44
+ // 2024-06-24: Update for SDL3 api changes: SDL_EVENT_KEY_DOWN/SDL_EVENT_KEY_UP contents.
45
+ // 2024-06-03; Update for SDL3 api changes: SDL_SYSTEM_CURSOR_ renames.
46
+ // 2024-05-15: Update for SDL3 api changes: SDLK_ renames.
47
+ // 2024-04-15: Inputs: Re-enable calling SDL_StartTextInput()/SDL_StopTextInput() as SDL3 no longer enables it by default and should play nicer with IME.
48
+ // 2024-02-13: Inputs: Fixed gamepad support. Handle gamepad disconnection. Added ImGui_ImplSDL3_SetGamepadMode().
49
+ // 2023-11-13: Updated for recent SDL3 API changes.
50
+ // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys.
51
+ // 2023-05-04: Fixed build on Emscripten/iOS/Android. (#6391)
52
+ // 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306)
53
+ // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702)
54
+ // 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644)
55
+ // 2023-02-07: Forked "imgui_impl_sdl2" into "imgui_impl_sdl3". Removed version checks for old feature. Refer to imgui_impl_sdl2.cpp for older changelog.
56
+
57
+ #include "imgui.h"
58
+ #ifndef IMGUI_DISABLE
59
+ #include "imgui_impl_sdl3.h"
60
+
61
+ // Clang warnings with -Weverything
62
+ #if defined(__clang__)
63
+ #pragma clang diagnostic push
64
+ #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
65
+ #endif
66
+
67
+ // SDL
68
+ #include <SDL3/SDL.h>
69
+ #if defined(__APPLE__)
70
+ #include <TargetConditionals.h>
71
+ #endif
72
+ #ifdef _WIN32
73
+ #ifndef WIN32_LEAN_AND_MEAN
74
+ #define WIN32_LEAN_AND_MEAN
75
+ #endif
76
+ #include <windows.h>
77
+ #endif
78
+
79
+ #if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__)
80
+ #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1
81
+ #else
82
+ #define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0
83
+ #endif
84
+
85
+ // FIXME-LEGACY: remove when SDL 3.1.3 preview is released.
86
+ #ifndef SDLK_APOSTROPHE
87
+ #define SDLK_APOSTROPHE SDLK_QUOTE
88
+ #endif
89
+ #ifndef SDLK_GRAVE
90
+ #define SDLK_GRAVE SDLK_BACKQUOTE
91
+ #endif
92
+
93
+ // SDL Data
94
+ struct ImGui_ImplSDL3_Data
95
+ {
96
+ SDL_Window* Window;
97
+ SDL_WindowID WindowID;
98
+ SDL_Renderer* Renderer;
99
+ Uint64 Time;
100
+ char* ClipboardTextData;
101
+ bool UseVulkan;
102
+ bool WantUpdateMonitors;
103
+
104
+ // IME handling
105
+ SDL_Window* ImeWindow;
106
+
107
+ // Mouse handling
108
+ Uint32 MouseWindowID;
109
+ int MouseButtonsDown;
110
+ SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT];
111
+ SDL_Cursor* MouseLastCursor;
112
+ int MousePendingLeaveFrame;
113
+ bool MouseCanUseGlobalState;
114
+ bool MouseCanReportHoveredViewport; // This is hard to use/unreliable on SDL so we'll set ImGuiBackendFlags_HasMouseHoveredViewport dynamically based on state.
115
+
116
+ // Gamepad handling
117
+ ImVector<SDL_Gamepad*> Gamepads;
118
+ ImGui_ImplSDL3_GamepadMode GamepadMode;
119
+ bool WantUpdateGamepadsList;
120
+
121
+ ImGui_ImplSDL3_Data() { memset((void*)this, 0, sizeof(*this)); }
122
+ };
123
+
124
+ // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
125
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
126
+ // FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
127
+ // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
128
+ static ImGui_ImplSDL3_Data* ImGui_ImplSDL3_GetBackendData()
129
+ {
130
+ return ImGui::GetCurrentContext() ? (ImGui_ImplSDL3_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
131
+ }
132
+
133
+ // Forward Declarations
134
+ static void ImGui_ImplSDL3_UpdateMonitors();
135
+ static void ImGui_ImplSDL3_InitMultiViewportSupport(SDL_Window* window, void* sdl_gl_context);
136
+ static void ImGui_ImplSDL3_ShutdownMultiViewportSupport();
137
+
138
+ // Functions
139
+ static const char* ImGui_ImplSDL3_GetClipboardText(ImGuiContext*)
140
+ {
141
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
142
+ if (bd->ClipboardTextData)
143
+ SDL_free(bd->ClipboardTextData);
144
+ const char* sdl_clipboard_text = SDL_GetClipboardText();
145
+ bd->ClipboardTextData = sdl_clipboard_text ? SDL_strdup(sdl_clipboard_text) : nullptr;
146
+ return bd->ClipboardTextData;
147
+ }
148
+
149
+ static void ImGui_ImplSDL3_SetClipboardText(ImGuiContext*, const char* text)
150
+ {
151
+ SDL_SetClipboardText(text);
152
+ }
153
+
154
+ static void ImGui_ImplSDL3_PlatformSetImeData(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
155
+ {
156
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
157
+ SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle;
158
+ SDL_Window* window = SDL_GetWindowFromID(window_id);
159
+ if ((data->WantVisible == false || bd->ImeWindow != window) && bd->ImeWindow != nullptr)
160
+ {
161
+ SDL_StopTextInput(bd->ImeWindow);
162
+ bd->ImeWindow = nullptr;
163
+ }
164
+ if (data->WantVisible)
165
+ {
166
+ SDL_Rect r;
167
+ r.x = (int)(data->InputPos.x - viewport->Pos.x);
168
+ r.y = (int)(data->InputPos.y - viewport->Pos.y + data->InputLineHeight);
169
+ r.w = 1;
170
+ r.h = (int)data->InputLineHeight;
171
+ SDL_SetTextInputArea(window, &r, 0);
172
+ SDL_StartTextInput(window);
173
+ bd->ImeWindow = window;
174
+ }
175
+ }
176
+
177
+ // Not static to allow third-party code to use that if they want to (but undocumented)
178
+ ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode);
179
+ ImGuiKey ImGui_ImplSDL3_KeyEventToImGuiKey(SDL_Keycode keycode, SDL_Scancode scancode)
180
+ {
181
+ // Keypad doesn't have individual key values in SDL3
182
+ switch (scancode)
183
+ {
184
+ case SDL_SCANCODE_KP_0: return ImGuiKey_Keypad0;
185
+ case SDL_SCANCODE_KP_1: return ImGuiKey_Keypad1;
186
+ case SDL_SCANCODE_KP_2: return ImGuiKey_Keypad2;
187
+ case SDL_SCANCODE_KP_3: return ImGuiKey_Keypad3;
188
+ case SDL_SCANCODE_KP_4: return ImGuiKey_Keypad4;
189
+ case SDL_SCANCODE_KP_5: return ImGuiKey_Keypad5;
190
+ case SDL_SCANCODE_KP_6: return ImGuiKey_Keypad6;
191
+ case SDL_SCANCODE_KP_7: return ImGuiKey_Keypad7;
192
+ case SDL_SCANCODE_KP_8: return ImGuiKey_Keypad8;
193
+ case SDL_SCANCODE_KP_9: return ImGuiKey_Keypad9;
194
+ case SDL_SCANCODE_KP_PERIOD: return ImGuiKey_KeypadDecimal;
195
+ case SDL_SCANCODE_KP_DIVIDE: return ImGuiKey_KeypadDivide;
196
+ case SDL_SCANCODE_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
197
+ case SDL_SCANCODE_KP_MINUS: return ImGuiKey_KeypadSubtract;
198
+ case SDL_SCANCODE_KP_PLUS: return ImGuiKey_KeypadAdd;
199
+ case SDL_SCANCODE_KP_ENTER: return ImGuiKey_KeypadEnter;
200
+ case SDL_SCANCODE_KP_EQUALS: return ImGuiKey_KeypadEqual;
201
+ default: break;
202
+ }
203
+ switch (keycode)
204
+ {
205
+ case SDLK_TAB: return ImGuiKey_Tab;
206
+ case SDLK_LEFT: return ImGuiKey_LeftArrow;
207
+ case SDLK_RIGHT: return ImGuiKey_RightArrow;
208
+ case SDLK_UP: return ImGuiKey_UpArrow;
209
+ case SDLK_DOWN: return ImGuiKey_DownArrow;
210
+ case SDLK_PAGEUP: return ImGuiKey_PageUp;
211
+ case SDLK_PAGEDOWN: return ImGuiKey_PageDown;
212
+ case SDLK_HOME: return ImGuiKey_Home;
213
+ case SDLK_END: return ImGuiKey_End;
214
+ case SDLK_INSERT: return ImGuiKey_Insert;
215
+ case SDLK_DELETE: return ImGuiKey_Delete;
216
+ case SDLK_BACKSPACE: return ImGuiKey_Backspace;
217
+ case SDLK_SPACE: return ImGuiKey_Space;
218
+ case SDLK_RETURN: return ImGuiKey_Enter;
219
+ case SDLK_ESCAPE: return ImGuiKey_Escape;
220
+ case SDLK_APOSTROPHE: return ImGuiKey_Apostrophe;
221
+ case SDLK_COMMA: return ImGuiKey_Comma;
222
+ case SDLK_MINUS: return ImGuiKey_Minus;
223
+ case SDLK_PERIOD: return ImGuiKey_Period;
224
+ case SDLK_SLASH: return ImGuiKey_Slash;
225
+ case SDLK_SEMICOLON: return ImGuiKey_Semicolon;
226
+ case SDLK_EQUALS: return ImGuiKey_Equal;
227
+ case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket;
228
+ case SDLK_BACKSLASH: return ImGuiKey_Backslash;
229
+ case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket;
230
+ case SDLK_GRAVE: return ImGuiKey_GraveAccent;
231
+ case SDLK_CAPSLOCK: return ImGuiKey_CapsLock;
232
+ case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock;
233
+ case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock;
234
+ case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen;
235
+ case SDLK_PAUSE: return ImGuiKey_Pause;
236
+ case SDLK_LCTRL: return ImGuiKey_LeftCtrl;
237
+ case SDLK_LSHIFT: return ImGuiKey_LeftShift;
238
+ case SDLK_LALT: return ImGuiKey_LeftAlt;
239
+ case SDLK_LGUI: return ImGuiKey_LeftSuper;
240
+ case SDLK_RCTRL: return ImGuiKey_RightCtrl;
241
+ case SDLK_RSHIFT: return ImGuiKey_RightShift;
242
+ case SDLK_RALT: return ImGuiKey_RightAlt;
243
+ case SDLK_RGUI: return ImGuiKey_RightSuper;
244
+ case SDLK_APPLICATION: return ImGuiKey_Menu;
245
+ case SDLK_0: return ImGuiKey_0;
246
+ case SDLK_1: return ImGuiKey_1;
247
+ case SDLK_2: return ImGuiKey_2;
248
+ case SDLK_3: return ImGuiKey_3;
249
+ case SDLK_4: return ImGuiKey_4;
250
+ case SDLK_5: return ImGuiKey_5;
251
+ case SDLK_6: return ImGuiKey_6;
252
+ case SDLK_7: return ImGuiKey_7;
253
+ case SDLK_8: return ImGuiKey_8;
254
+ case SDLK_9: return ImGuiKey_9;
255
+ case SDLK_A: return ImGuiKey_A;
256
+ case SDLK_B: return ImGuiKey_B;
257
+ case SDLK_C: return ImGuiKey_C;
258
+ case SDLK_D: return ImGuiKey_D;
259
+ case SDLK_E: return ImGuiKey_E;
260
+ case SDLK_F: return ImGuiKey_F;
261
+ case SDLK_G: return ImGuiKey_G;
262
+ case SDLK_H: return ImGuiKey_H;
263
+ case SDLK_I: return ImGuiKey_I;
264
+ case SDLK_J: return ImGuiKey_J;
265
+ case SDLK_K: return ImGuiKey_K;
266
+ case SDLK_L: return ImGuiKey_L;
267
+ case SDLK_M: return ImGuiKey_M;
268
+ case SDLK_N: return ImGuiKey_N;
269
+ case SDLK_O: return ImGuiKey_O;
270
+ case SDLK_P: return ImGuiKey_P;
271
+ case SDLK_Q: return ImGuiKey_Q;
272
+ case SDLK_R: return ImGuiKey_R;
273
+ case SDLK_S: return ImGuiKey_S;
274
+ case SDLK_T: return ImGuiKey_T;
275
+ case SDLK_U: return ImGuiKey_U;
276
+ case SDLK_V: return ImGuiKey_V;
277
+ case SDLK_W: return ImGuiKey_W;
278
+ case SDLK_X: return ImGuiKey_X;
279
+ case SDLK_Y: return ImGuiKey_Y;
280
+ case SDLK_Z: return ImGuiKey_Z;
281
+ case SDLK_F1: return ImGuiKey_F1;
282
+ case SDLK_F2: return ImGuiKey_F2;
283
+ case SDLK_F3: return ImGuiKey_F3;
284
+ case SDLK_F4: return ImGuiKey_F4;
285
+ case SDLK_F5: return ImGuiKey_F5;
286
+ case SDLK_F6: return ImGuiKey_F6;
287
+ case SDLK_F7: return ImGuiKey_F7;
288
+ case SDLK_F8: return ImGuiKey_F8;
289
+ case SDLK_F9: return ImGuiKey_F9;
290
+ case SDLK_F10: return ImGuiKey_F10;
291
+ case SDLK_F11: return ImGuiKey_F11;
292
+ case SDLK_F12: return ImGuiKey_F12;
293
+ case SDLK_F13: return ImGuiKey_F13;
294
+ case SDLK_F14: return ImGuiKey_F14;
295
+ case SDLK_F15: return ImGuiKey_F15;
296
+ case SDLK_F16: return ImGuiKey_F16;
297
+ case SDLK_F17: return ImGuiKey_F17;
298
+ case SDLK_F18: return ImGuiKey_F18;
299
+ case SDLK_F19: return ImGuiKey_F19;
300
+ case SDLK_F20: return ImGuiKey_F20;
301
+ case SDLK_F21: return ImGuiKey_F21;
302
+ case SDLK_F22: return ImGuiKey_F22;
303
+ case SDLK_F23: return ImGuiKey_F23;
304
+ case SDLK_F24: return ImGuiKey_F24;
305
+ case SDLK_AC_BACK: return ImGuiKey_AppBack;
306
+ case SDLK_AC_FORWARD: return ImGuiKey_AppForward;
307
+ default: break;
308
+ }
309
+ return ImGuiKey_None;
310
+ }
311
+
312
+ static void ImGui_ImplSDL3_UpdateKeyModifiers(SDL_Keymod sdl_key_mods)
313
+ {
314
+ ImGuiIO& io = ImGui::GetIO();
315
+ io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & SDL_KMOD_CTRL) != 0);
316
+ io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & SDL_KMOD_SHIFT) != 0);
317
+ io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & SDL_KMOD_ALT) != 0);
318
+ io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & SDL_KMOD_GUI) != 0);
319
+ }
320
+
321
+ static ImGuiViewport* ImGui_ImplSDL3_GetViewportForWindowID(SDL_WindowID window_id)
322
+ {
323
+ return ImGui::FindViewportByPlatformHandle((void*)(intptr_t)window_id);
324
+ }
325
+
326
+ // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
327
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
328
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
329
+ // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
330
+ bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event)
331
+ {
332
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
333
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?");
334
+ ImGuiIO& io = ImGui::GetIO();
335
+
336
+ switch (event->type)
337
+ {
338
+ case SDL_EVENT_MOUSE_MOTION:
339
+ {
340
+ if (ImGui_ImplSDL3_GetViewportForWindowID(event->motion.windowID) == nullptr)
341
+ return false;
342
+ ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);
343
+ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
344
+ {
345
+ int window_x, window_y;
346
+ SDL_GetWindowPosition(SDL_GetWindowFromID(event->motion.windowID), &window_x, &window_y);
347
+ mouse_pos.x += window_x;
348
+ mouse_pos.y += window_y;
349
+ }
350
+ io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
351
+ io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);
352
+ return true;
353
+ }
354
+ case SDL_EVENT_MOUSE_WHEEL:
355
+ {
356
+ if (ImGui_ImplSDL3_GetViewportForWindowID(event->wheel.windowID) == nullptr)
357
+ return false;
358
+ //IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);
359
+ float wheel_x = -event->wheel.x;
360
+ float wheel_y = event->wheel.y;
361
+ io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
362
+ io.AddMouseWheelEvent(wheel_x, wheel_y);
363
+ return true;
364
+ }
365
+ case SDL_EVENT_MOUSE_BUTTON_DOWN:
366
+ case SDL_EVENT_MOUSE_BUTTON_UP:
367
+ {
368
+ if (ImGui_ImplSDL3_GetViewportForWindowID(event->button.windowID) == nullptr)
369
+ return false;
370
+ int mouse_button = -1;
371
+ if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }
372
+ if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }
373
+ if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }
374
+ if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }
375
+ if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }
376
+ if (mouse_button == -1)
377
+ break;
378
+ io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
379
+ io.AddMouseButtonEvent(mouse_button, (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN));
380
+ bd->MouseButtonsDown = (event->type == SDL_EVENT_MOUSE_BUTTON_DOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));
381
+ return true;
382
+ }
383
+ case SDL_EVENT_TEXT_INPUT:
384
+ {
385
+ if (ImGui_ImplSDL3_GetViewportForWindowID(event->text.windowID) == nullptr)
386
+ return false;
387
+ io.AddInputCharactersUTF8(event->text.text);
388
+ return true;
389
+ }
390
+ case SDL_EVENT_KEY_DOWN:
391
+ case SDL_EVENT_KEY_UP:
392
+ {
393
+ if (ImGui_ImplSDL3_GetViewportForWindowID(event->key.windowID) == nullptr)
394
+ return false;
395
+ //IMGUI_DEBUG_LOG("SDL_EVENT_KEY_%d: key=%d, scancode=%d, mod=%X\n", (event->type == SDL_EVENT_KEY_DOWN) ? "DOWN" : "UP", event->key.key, event->key.scancode, event->key.mod);
396
+ ImGui_ImplSDL3_UpdateKeyModifiers((SDL_Keymod)event->key.mod);
397
+ ImGuiKey key = ImGui_ImplSDL3_KeyEventToImGuiKey(event->key.key, event->key.scancode);
398
+ io.AddKeyEvent(key, (event->type == SDL_EVENT_KEY_DOWN));
399
+ io.SetKeyEventNativeData(key, event->key.key, event->key.scancode, event->key.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.
400
+ return true;
401
+ }
402
+ case SDL_EVENT_DISPLAY_ORIENTATION:
403
+ case SDL_EVENT_DISPLAY_ADDED:
404
+ case SDL_EVENT_DISPLAY_REMOVED:
405
+ case SDL_EVENT_DISPLAY_MOVED:
406
+ case SDL_EVENT_DISPLAY_CONTENT_SCALE_CHANGED:
407
+ {
408
+ bd->WantUpdateMonitors = true;
409
+ return true;
410
+ }
411
+ case SDL_EVENT_WINDOW_MOUSE_ENTER:
412
+ {
413
+ if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
414
+ return false;
415
+ bd->MouseWindowID = event->window.windowID;
416
+ bd->MousePendingLeaveFrame = 0;
417
+ return true;
418
+ }
419
+ // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,
420
+ // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why
421
+ // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.
422
+ // FIXME: Unconfirmed whether this is still needed with SDL3.
423
+ case SDL_EVENT_WINDOW_MOUSE_LEAVE:
424
+ {
425
+ if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
426
+ return false;
427
+ bd->MousePendingLeaveFrame = ImGui::GetFrameCount() + 1;
428
+ return true;
429
+ }
430
+ case SDL_EVENT_WINDOW_FOCUS_GAINED:
431
+ case SDL_EVENT_WINDOW_FOCUS_LOST:
432
+ {
433
+ if (ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID) == nullptr)
434
+ return false;
435
+ io.AddFocusEvent(event->type == SDL_EVENT_WINDOW_FOCUS_GAINED);
436
+ return true;
437
+ }
438
+ case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
439
+ case SDL_EVENT_WINDOW_MOVED:
440
+ case SDL_EVENT_WINDOW_RESIZED:
441
+ {
442
+ ImGuiViewport* viewport = ImGui_ImplSDL3_GetViewportForWindowID(event->window.windowID);
443
+ if (viewport == NULL)
444
+ return false;
445
+ if (event->type == SDL_EVENT_WINDOW_CLOSE_REQUESTED)
446
+ viewport->PlatformRequestClose = true;
447
+ if (event->type == SDL_EVENT_WINDOW_MOVED)
448
+ viewport->PlatformRequestMove = true;
449
+ if (event->type == SDL_EVENT_WINDOW_RESIZED)
450
+ viewport->PlatformRequestResize = true;
451
+ return true;
452
+ }
453
+ case SDL_EVENT_GAMEPAD_ADDED:
454
+ case SDL_EVENT_GAMEPAD_REMOVED:
455
+ {
456
+ bd->WantUpdateGamepadsList = true;
457
+ return true;
458
+ }
459
+ }
460
+ return false;
461
+ }
462
+
463
+ static void ImGui_ImplSDL3_SetupPlatformHandles(ImGuiViewport* viewport, SDL_Window* window)
464
+ {
465
+ viewport->PlatformHandle = (void*)(intptr_t)SDL_GetWindowID(window);
466
+ viewport->PlatformHandleRaw = nullptr;
467
+ #if defined(_WIN32) && !defined(__WINRT__)
468
+ viewport->PlatformHandleRaw = (HWND)SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr);
469
+ #elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
470
+ viewport->PlatformHandleRaw = SDL_GetPointerProperty(SDL_GetWindowProperties(window), SDL_PROP_WINDOW_COCOA_WINDOW_POINTER, nullptr);
471
+ #endif
472
+ }
473
+
474
+ static bool ImGui_ImplSDL3_Init(SDL_Window* window, SDL_Renderer* renderer, void* sdl_gl_context)
475
+ {
476
+ ImGuiIO& io = ImGui::GetIO();
477
+ IMGUI_CHECKVERSION();
478
+ IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
479
+ IM_UNUSED(sdl_gl_context); // Unused in this branch
480
+
481
+ // Check and store if we are on a SDL backend that supports global mouse position
482
+ // ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list)
483
+ bool mouse_can_use_global_state = false;
484
+ #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
485
+ const char* sdl_backend = SDL_GetCurrentVideoDriver();
486
+ const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" };
487
+ for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++)
488
+ if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0)
489
+ mouse_can_use_global_state = true;
490
+ #endif
491
+
492
+ // Setup backend capabilities flags
493
+ ImGui_ImplSDL3_Data* bd = IM_NEW(ImGui_ImplSDL3_Data)();
494
+ io.BackendPlatformUserData = (void*)bd;
495
+ io.BackendPlatformName = "imgui_impl_sdl3";
496
+ io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
497
+ io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
498
+ if (mouse_can_use_global_state)
499
+ io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
500
+
501
+ bd->Window = window;
502
+ bd->WindowID = SDL_GetWindowID(window);
503
+ bd->Renderer = renderer;
504
+
505
+ // SDL on Linux/OSX doesn't report events for unfocused windows (see https://github.com/ocornut/imgui/issues/4960)
506
+ // We will use 'MouseCanReportHoveredViewport' to set 'ImGuiBackendFlags_HasMouseHoveredViewport' dynamically each frame.
507
+ bd->MouseCanUseGlobalState = mouse_can_use_global_state;
508
+ #ifndef __APPLE__
509
+ bd->MouseCanReportHoveredViewport = bd->MouseCanUseGlobalState;
510
+ #else
511
+ bd->MouseCanReportHoveredViewport = false;
512
+ #endif
513
+
514
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
515
+ platform_io.Platform_SetClipboardTextFn = ImGui_ImplSDL3_SetClipboardText;
516
+ platform_io.Platform_GetClipboardTextFn = ImGui_ImplSDL3_GetClipboardText;
517
+ platform_io.Platform_SetImeDataFn = ImGui_ImplSDL3_PlatformSetImeData;
518
+
519
+ // Update monitor a first time during init
520
+ ImGui_ImplSDL3_UpdateMonitors();
521
+
522
+ // Gamepad handling
523
+ bd->GamepadMode = ImGui_ImplSDL3_GamepadMode_AutoFirst;
524
+ bd->WantUpdateGamepadsList = true;
525
+
526
+ // Load mouse cursors
527
+ bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_DEFAULT);
528
+ bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_TEXT);
529
+ bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_MOVE);
530
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NS_RESIZE);
531
+ bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_EW_RESIZE);
532
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NESW_RESIZE);
533
+ bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NWSE_RESIZE);
534
+ bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_POINTER);
535
+ bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NOT_ALLOWED);
536
+
537
+ // Set platform dependent data in viewport
538
+ // Our mouse update function expect PlatformHandle to be filled for the main viewport
539
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
540
+ ImGui_ImplSDL3_SetupPlatformHandles(main_viewport, window);
541
+
542
+ // From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event.
543
+ // Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered.
544
+ // (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application.
545
+ // It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click:
546
+ // you can ignore SDL_EVENT_MOUSE_BUTTON_DOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED)
547
+ SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
548
+
549
+ // From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710)
550
+ SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0");
551
+
552
+ // SDL 3.x : see https://github.com/libsdl-org/SDL/issues/6659
553
+ SDL_SetHint("SDL_BORDERLESS_WINDOWED_STYLE", "0");
554
+
555
+ // We need SDL_CaptureMouse(), SDL_GetGlobalMouseState() from SDL 2.0.4+ to support multiple viewports.
556
+ // We left the call to ImGui_ImplSDL3_InitPlatformInterface() outside of #ifdef to avoid unused-function warnings.
557
+ if (io.BackendFlags & ImGuiBackendFlags_PlatformHasViewports)
558
+ ImGui_ImplSDL3_InitMultiViewportSupport(window, sdl_gl_context);
559
+
560
+ return true;
561
+ }
562
+
563
+ // Should technically be a SDL_GLContext but due to typedef it is sane to keep it void* in public interface.
564
+ bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
565
+ {
566
+ return ImGui_ImplSDL3_Init(window, nullptr, sdl_gl_context);
567
+ }
568
+
569
+ bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window)
570
+ {
571
+ if (!ImGui_ImplSDL3_Init(window, nullptr, nullptr))
572
+ return false;
573
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
574
+ bd->UseVulkan = true;
575
+ return true;
576
+ }
577
+
578
+ bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window)
579
+ {
580
+ #if !defined(_WIN32)
581
+ IM_ASSERT(0 && "Unsupported");
582
+ #endif
583
+ return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
584
+ }
585
+
586
+ bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window)
587
+ {
588
+ return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
589
+ }
590
+
591
+ bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer)
592
+ {
593
+ return ImGui_ImplSDL3_Init(window, renderer, nullptr);
594
+ }
595
+
596
+ bool ImGui_ImplSDL3_InitForOther(SDL_Window* window)
597
+ {
598
+ return ImGui_ImplSDL3_Init(window, nullptr, nullptr);
599
+ }
600
+
601
+ static void ImGui_ImplSDL3_CloseGamepads();
602
+
603
+ void ImGui_ImplSDL3_Shutdown()
604
+ {
605
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
606
+ IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
607
+ ImGuiIO& io = ImGui::GetIO();
608
+
609
+ ImGui_ImplSDL3_ShutdownMultiViewportSupport();
610
+
611
+ if (bd->ClipboardTextData)
612
+ SDL_free(bd->ClipboardTextData);
613
+ for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
614
+ SDL_DestroyCursor(bd->MouseCursors[cursor_n]);
615
+ ImGui_ImplSDL3_CloseGamepads();
616
+
617
+ io.BackendPlatformName = nullptr;
618
+ io.BackendPlatformUserData = nullptr;
619
+ io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_PlatformHasViewports | ImGuiBackendFlags_HasMouseHoveredViewport);
620
+ IM_DELETE(bd);
621
+ }
622
+
623
+ // This code is incredibly messy because some of the functions we need for full viewport support are not available in SDL < 2.0.4.
624
+ static void ImGui_ImplSDL3_UpdateMouseData()
625
+ {
626
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
627
+ ImGuiIO& io = ImGui::GetIO();
628
+
629
+ // We forward mouse input when hovered or captured (via SDL_EVENT_MOUSE_MOTION) or when focused (below)
630
+ #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
631
+ // SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside
632
+ SDL_CaptureMouse(bd->MouseButtonsDown != 0);
633
+ SDL_Window* focused_window = SDL_GetKeyboardFocus();
634
+ const bool is_app_focused = (focused_window && (bd->Window == focused_window || ImGui_ImplSDL3_GetViewportForWindowID(SDL_GetWindowID(focused_window)) != NULL));
635
+ #else
636
+ SDL_Window* focused_window = bd->Window;
637
+ const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only
638
+ #endif
639
+ if (is_app_focused)
640
+ {
641
+ // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
642
+ if (io.WantSetMousePos)
643
+ {
644
+ #if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
645
+ if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
646
+ SDL_WarpMouseGlobal(io.MousePos.x, io.MousePos.y);
647
+ else
648
+ #endif
649
+ SDL_WarpMouseInWindow(bd->Window, io.MousePos.x, io.MousePos.y);
650
+ }
651
+
652
+ // (Optional) Fallback to provide mouse position when focused (SDL_EVENT_MOUSE_MOTION already provides this when hovered or captured)
653
+ if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0)
654
+ {
655
+ // Single-viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
656
+ // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
657
+ float mouse_x, mouse_y;
658
+ int window_x, window_y;
659
+ SDL_GetGlobalMouseState(&mouse_x, &mouse_y);
660
+ if (!(io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable))
661
+ {
662
+ SDL_GetWindowPosition(focused_window, &window_x, &window_y);
663
+ mouse_x -= window_x;
664
+ mouse_y -= window_y;
665
+ }
666
+ io.AddMousePosEvent((float)mouse_x, (float)mouse_y);
667
+ }
668
+ }
669
+
670
+ // (Optional) When using multiple viewports: call io.AddMouseViewportEvent() with the viewport the OS mouse cursor is hovering.
671
+ // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, Dear imGui will ignore this field and infer the information using its flawed heuristic.
672
+ // - [!] SDL backend does NOT correctly ignore viewports with the _NoInputs flag.
673
+ // Some backend are not able to handle that correctly. If a backend report an hovered viewport that has the _NoInputs flag (e.g. when dragging a window
674
+ // for docking, the viewport has the _NoInputs flag in order to allow us to find the viewport under), then Dear ImGui is forced to ignore the value reported
675
+ // by the backend, and use its flawed heuristic to guess the viewport behind.
676
+ // - [X] SDL backend correctly reports this regardless of another viewport behind focused and dragged from (we need this to find a useful drag and drop target).
677
+ if (io.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
678
+ {
679
+ ImGuiID mouse_viewport_id = 0;
680
+ if (ImGuiViewport* mouse_viewport = ImGui_ImplSDL3_GetViewportForWindowID(bd->MouseWindowID))
681
+ mouse_viewport_id = mouse_viewport->ID;
682
+ io.AddMouseViewportEvent(mouse_viewport_id);
683
+ }
684
+ }
685
+
686
+ static void ImGui_ImplSDL3_UpdateMouseCursor()
687
+ {
688
+ ImGuiIO& io = ImGui::GetIO();
689
+ if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
690
+ return;
691
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
692
+
693
+ ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
694
+ if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
695
+ {
696
+ // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
697
+ SDL_HideCursor();
698
+ }
699
+ else
700
+ {
701
+ // Show OS mouse cursor
702
+ SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow];
703
+ if (bd->MouseLastCursor != expected_cursor)
704
+ {
705
+ SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113)
706
+ bd->MouseLastCursor = expected_cursor;
707
+ }
708
+ SDL_ShowCursor();
709
+ }
710
+ }
711
+
712
+ static void ImGui_ImplSDL3_CloseGamepads()
713
+ {
714
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
715
+ if (bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual)
716
+ for (SDL_Gamepad* gamepad : bd->Gamepads)
717
+ SDL_CloseGamepad(gamepad);
718
+ bd->Gamepads.resize(0);
719
+ }
720
+
721
+ void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array, int manual_gamepads_count)
722
+ {
723
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
724
+ ImGui_ImplSDL3_CloseGamepads();
725
+ if (mode == ImGui_ImplSDL3_GamepadMode_Manual)
726
+ {
727
+ IM_ASSERT(manual_gamepads_array != nullptr && manual_gamepads_count > 0);
728
+ for (int n = 0; n < manual_gamepads_count; n++)
729
+ bd->Gamepads.push_back(manual_gamepads_array[n]);
730
+ }
731
+ else
732
+ {
733
+ IM_ASSERT(manual_gamepads_array == nullptr && manual_gamepads_count <= 0);
734
+ bd->WantUpdateGamepadsList = true;
735
+ }
736
+ bd->GamepadMode = mode;
737
+ }
738
+
739
+ static void ImGui_ImplSDL3_UpdateGamepadButton(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadButton button_no)
740
+ {
741
+ bool merged_value = false;
742
+ for (SDL_Gamepad* gamepad : bd->Gamepads)
743
+ merged_value |= SDL_GetGamepadButton(gamepad, button_no) != 0;
744
+ io.AddKeyEvent(key, merged_value);
745
+ }
746
+
747
+ static inline float Saturate(float v) { return v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v; }
748
+ static void ImGui_ImplSDL3_UpdateGamepadAnalog(ImGui_ImplSDL3_Data* bd, ImGuiIO& io, ImGuiKey key, SDL_GamepadAxis axis_no, float v0, float v1)
749
+ {
750
+ float merged_value = 0.0f;
751
+ for (SDL_Gamepad* gamepad : bd->Gamepads)
752
+ {
753
+ float vn = Saturate((float)(SDL_GetGamepadAxis(gamepad, axis_no) - v0) / (float)(v1 - v0));
754
+ if (merged_value < vn)
755
+ merged_value = vn;
756
+ }
757
+ io.AddKeyAnalogEvent(key, merged_value > 0.1f, merged_value);
758
+ }
759
+
760
+ static void ImGui_ImplSDL3_UpdateGamepads()
761
+ {
762
+ ImGuiIO& io = ImGui::GetIO();
763
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
764
+
765
+ // Update list of gamepads to use
766
+ if (bd->WantUpdateGamepadsList && bd->GamepadMode != ImGui_ImplSDL3_GamepadMode_Manual)
767
+ {
768
+ ImGui_ImplSDL3_CloseGamepads();
769
+ int sdl_gamepads_count = 0;
770
+ SDL_JoystickID* sdl_gamepads = SDL_GetGamepads(&sdl_gamepads_count);
771
+ for (int n = 0; n < sdl_gamepads_count; n++)
772
+ if (SDL_Gamepad* gamepad = SDL_OpenGamepad(sdl_gamepads[n]))
773
+ {
774
+ bd->Gamepads.push_back(gamepad);
775
+ if (bd->GamepadMode == ImGui_ImplSDL3_GamepadMode_AutoFirst)
776
+ break;
777
+ }
778
+ bd->WantUpdateGamepadsList = false;
779
+ SDL_free(sdl_gamepads);
780
+ }
781
+
782
+ // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
783
+ if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0)
784
+ return;
785
+ io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
786
+ if (bd->Gamepads.Size == 0)
787
+ return;
788
+ io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
789
+
790
+ // Update gamepad inputs
791
+ const int thumb_dead_zone = 8000; // SDL_gamepad.h suggests using this value.
792
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadStart, SDL_GAMEPAD_BUTTON_START);
793
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadBack, SDL_GAMEPAD_BUTTON_BACK);
794
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceLeft, SDL_GAMEPAD_BUTTON_WEST); // Xbox X, PS Square
795
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceRight, SDL_GAMEPAD_BUTTON_EAST); // Xbox B, PS Circle
796
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceUp, SDL_GAMEPAD_BUTTON_NORTH); // Xbox Y, PS Triangle
797
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadFaceDown, SDL_GAMEPAD_BUTTON_SOUTH); // Xbox A, PS Cross
798
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT);
799
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT);
800
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadUp, SDL_GAMEPAD_BUTTON_DPAD_UP);
801
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadDpadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN);
802
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL1, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER);
803
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR1, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER);
804
+ ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadL2, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, 0.0f, 32767);
805
+ ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadR2, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, 0.0f, 32767);
806
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadL3, SDL_GAMEPAD_BUTTON_LEFT_STICK);
807
+ ImGui_ImplSDL3_UpdateGamepadButton(bd, io, ImGuiKey_GamepadR3, SDL_GAMEPAD_BUTTON_RIGHT_STICK);
808
+ ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickLeft, SDL_GAMEPAD_AXIS_LEFTX, -thumb_dead_zone, -32768);
809
+ ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickRight, SDL_GAMEPAD_AXIS_LEFTX, +thumb_dead_zone, +32767);
810
+ ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickUp, SDL_GAMEPAD_AXIS_LEFTY, -thumb_dead_zone, -32768);
811
+ ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadLStickDown, SDL_GAMEPAD_AXIS_LEFTY, +thumb_dead_zone, +32767);
812
+ ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickLeft, SDL_GAMEPAD_AXIS_RIGHTX, -thumb_dead_zone, -32768);
813
+ ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickRight, SDL_GAMEPAD_AXIS_RIGHTX, +thumb_dead_zone, +32767);
814
+ ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickUp, SDL_GAMEPAD_AXIS_RIGHTY, -thumb_dead_zone, -32768);
815
+ ImGui_ImplSDL3_UpdateGamepadAnalog(bd, io, ImGuiKey_GamepadRStickDown, SDL_GAMEPAD_AXIS_RIGHTY, +thumb_dead_zone, +32767);
816
+ }
817
+
818
+ static void ImGui_ImplSDL3_UpdateMonitors()
819
+ {
820
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
821
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
822
+ platform_io.Monitors.resize(0);
823
+ bd->WantUpdateMonitors = false;
824
+
825
+ int display_count;
826
+ SDL_DisplayID* displays = SDL_GetDisplays(&display_count);
827
+ for (int n = 0; n < display_count; n++)
828
+ {
829
+ // Warning: the validity of monitor DPI information on Windows depends on the application DPI awareness settings, which generally needs to be set in the manifest or at runtime.
830
+ SDL_DisplayID display_id = displays[n];
831
+ ImGuiPlatformMonitor monitor;
832
+ SDL_Rect r;
833
+ SDL_GetDisplayBounds(display_id, &r);
834
+ monitor.MainPos = monitor.WorkPos = ImVec2((float)r.x, (float)r.y);
835
+ monitor.MainSize = monitor.WorkSize = ImVec2((float)r.w, (float)r.h);
836
+ SDL_GetDisplayUsableBounds(display_id, &r);
837
+ monitor.WorkPos = ImVec2((float)r.x, (float)r.y);
838
+ monitor.WorkSize = ImVec2((float)r.w, (float)r.h);
839
+ // FIXME-VIEWPORT: On MacOS SDL reports actual monitor DPI scale, ignoring OS configuration. We may want to set
840
+ // DpiScale to cocoa_window.backingScaleFactor here.
841
+ monitor.DpiScale = SDL_GetDisplayContentScale(display_id);
842
+ monitor.PlatformHandle = (void*)(intptr_t)n;
843
+ if (monitor.DpiScale <= 0.0f)
844
+ continue; // Some accessibility applications are declaring virtual monitors with a DPI of 0, see #7902.
845
+ platform_io.Monitors.push_back(monitor);
846
+ }
847
+ SDL_free(displays);
848
+ }
849
+
850
+ void ImGui_ImplSDL3_NewFrame()
851
+ {
852
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
853
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDL3_Init()?");
854
+ ImGuiIO& io = ImGui::GetIO();
855
+
856
+ // Setup display size (every frame to accommodate for window resizing)
857
+ int w, h;
858
+ int display_w, display_h;
859
+ SDL_GetWindowSize(bd->Window, &w, &h);
860
+ if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED)
861
+ w = h = 0;
862
+ SDL_GetWindowSizeInPixels(bd->Window, &display_w, &display_h);
863
+ io.DisplaySize = ImVec2((float)w, (float)h);
864
+ if (w > 0 && h > 0)
865
+ io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);
866
+
867
+ // Update monitors
868
+ if (bd->WantUpdateMonitors)
869
+ ImGui_ImplSDL3_UpdateMonitors();
870
+
871
+ // Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution)
872
+ // (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644)
873
+ static Uint64 frequency = SDL_GetPerformanceFrequency();
874
+ Uint64 current_time = SDL_GetPerformanceCounter();
875
+ if (current_time <= bd->Time)
876
+ current_time = bd->Time + 1;
877
+ io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f);
878
+ bd->Time = current_time;
879
+
880
+ if (bd->MousePendingLeaveFrame && bd->MousePendingLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0)
881
+ {
882
+ bd->MouseWindowID = 0;
883
+ bd->MousePendingLeaveFrame = 0;
884
+ io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
885
+ }
886
+
887
+ // Our io.AddMouseViewportEvent() calls will only be valid when not capturing.
888
+ // Technically speaking testing for 'bd->MouseButtonsDown == 0' would be more rigorous, but testing for payload reduces noise and potential side-effects.
889
+ if (bd->MouseCanReportHoveredViewport && ImGui::GetDragDropPayload() == nullptr)
890
+ io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport;
891
+ else
892
+ io.BackendFlags &= ~ImGuiBackendFlags_HasMouseHoveredViewport;
893
+
894
+ ImGui_ImplSDL3_UpdateMouseData();
895
+ ImGui_ImplSDL3_UpdateMouseCursor();
896
+
897
+ // Update game controllers (if enabled and available)
898
+ ImGui_ImplSDL3_UpdateGamepads();
899
+ }
900
+
901
+ //--------------------------------------------------------------------------------------------------------
902
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
903
+ // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
904
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
905
+ //--------------------------------------------------------------------------------------------------------
906
+
907
+ // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
908
+ struct ImGui_ImplSDL3_ViewportData
909
+ {
910
+ SDL_Window* Window;
911
+ SDL_Window* ParentWindow;
912
+ Uint32 WindowID;
913
+ bool WindowOwned;
914
+ SDL_GLContext GLContext;
915
+
916
+ ImGui_ImplSDL3_ViewportData() { Window = ParentWindow = nullptr; WindowID = 0; WindowOwned = false; GLContext = nullptr; }
917
+ ~ImGui_ImplSDL3_ViewportData() { IM_ASSERT(Window == nullptr && GLContext == nullptr); }
918
+ };
919
+
920
+ static SDL_Window* ImGui_ImplSDL3_GetSDLWindowFromViewportID(ImGuiID viewport_id)
921
+ {
922
+ if (viewport_id != 0)
923
+ if (ImGuiViewport* viewport = ImGui::FindViewportByID(viewport_id))
924
+ {
925
+ SDL_WindowID window_id = (SDL_WindowID)(intptr_t)viewport->PlatformHandle;
926
+ return SDL_GetWindowFromID(window_id);
927
+ }
928
+ return nullptr;
929
+ }
930
+
931
+ static void ImGui_ImplSDL3_CreateWindow(ImGuiViewport* viewport)
932
+ {
933
+ ImGui_ImplSDL3_Data* bd = ImGui_ImplSDL3_GetBackendData();
934
+ ImGui_ImplSDL3_ViewportData* vd = IM_NEW(ImGui_ImplSDL3_ViewportData)();
935
+ viewport->PlatformUserData = vd;
936
+
937
+ vd->ParentWindow = ImGui_ImplSDL3_GetSDLWindowFromViewportID(viewport->ParentViewportId);
938
+
939
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
940
+ ImGui_ImplSDL3_ViewportData* main_viewport_data = (ImGui_ImplSDL3_ViewportData*)main_viewport->PlatformUserData;
941
+
942
+ // Share GL resources with main context
943
+ bool use_opengl = (main_viewport_data->GLContext != nullptr);
944
+ SDL_GLContext backup_context = nullptr;
945
+ if (use_opengl)
946
+ {
947
+ backup_context = SDL_GL_GetCurrentContext();
948
+ SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1);
949
+ SDL_GL_MakeCurrent(main_viewport_data->Window, main_viewport_data->GLContext);
950
+ }
951
+
952
+ SDL_WindowFlags sdl_flags = 0;
953
+ sdl_flags |= use_opengl ? SDL_WINDOW_OPENGL : (bd->UseVulkan ? SDL_WINDOW_VULKAN : 0);
954
+ sdl_flags |= SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_HIGH_PIXEL_DENSITY;
955
+ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? SDL_WINDOW_BORDERLESS : 0;
956
+ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoDecoration) ? 0 : SDL_WINDOW_RESIZABLE;
957
+ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon) ? SDL_WINDOW_UTILITY : 0;
958
+ sdl_flags |= (viewport->Flags & ImGuiViewportFlags_TopMost) ? SDL_WINDOW_ALWAYS_ON_TOP : 0;
959
+ vd->Window = SDL_CreateWindow("No Title Yet", (int)viewport->Size.x, (int)viewport->Size.y, sdl_flags);
960
+ SDL_SetWindowParent(vd->Window, vd->ParentWindow);
961
+ SDL_SetWindowPosition(vd->Window, (int)viewport->Pos.x, (int)viewport->Pos.y);
962
+ vd->WindowOwned = true;
963
+ if (use_opengl)
964
+ {
965
+ vd->GLContext = SDL_GL_CreateContext(vd->Window);
966
+ SDL_GL_SetSwapInterval(0);
967
+ }
968
+ if (use_opengl && backup_context)
969
+ SDL_GL_MakeCurrent(vd->Window, backup_context);
970
+
971
+ ImGui_ImplSDL3_SetupPlatformHandles(viewport, vd->Window);
972
+ }
973
+
974
+ static void ImGui_ImplSDL3_DestroyWindow(ImGuiViewport* viewport)
975
+ {
976
+ if (ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData)
977
+ {
978
+ if (vd->GLContext && vd->WindowOwned)
979
+ SDL_GL_DestroyContext(vd->GLContext);
980
+ if (vd->Window && vd->WindowOwned)
981
+ SDL_DestroyWindow(vd->Window);
982
+ vd->GLContext = nullptr;
983
+ vd->Window = nullptr;
984
+ IM_DELETE(vd);
985
+ }
986
+ viewport->PlatformUserData = viewport->PlatformHandle = nullptr;
987
+ }
988
+
989
+ static void ImGui_ImplSDL3_ShowWindow(ImGuiViewport* viewport)
990
+ {
991
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
992
+ #if defined(_WIN32) && !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES))
993
+ HWND hwnd = (HWND)viewport->PlatformHandleRaw;
994
+
995
+ // SDL hack: Show icon in task bar (#7989)
996
+ // Note: SDL_WINDOW_UTILITY can be used to control task bar visibility, but on Windows, it does not affect child windows.
997
+ if (!(viewport->Flags & ImGuiViewportFlags_NoTaskBarIcon))
998
+ {
999
+ LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE);
1000
+ ex_style |= WS_EX_APPWINDOW;
1001
+ ex_style &= ~WS_EX_TOOLWINDOW;
1002
+ ::ShowWindow(hwnd, SW_HIDE);
1003
+ ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style);
1004
+ }
1005
+ #endif
1006
+
1007
+ SDL_SetHint(SDL_HINT_WINDOW_ACTIVATE_WHEN_SHOWN, (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing) ? "0" : "1");
1008
+ SDL_ShowWindow(vd->Window);
1009
+ }
1010
+
1011
+ static void ImGui_ImplSDL3_UpdateWindow(ImGuiViewport* viewport)
1012
+ {
1013
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1014
+
1015
+ // Update SDL3 parent if it changed _after_ creation.
1016
+ // This is for advanced apps that are manipulating ParentViewportID manually.
1017
+ SDL_Window* new_parent = ImGui_ImplSDL3_GetSDLWindowFromViewportID(viewport->ParentViewportId);
1018
+ if (new_parent != vd->ParentWindow)
1019
+ {
1020
+ vd->ParentWindow = new_parent;
1021
+ SDL_SetWindowParent(vd->Window, vd->ParentWindow);
1022
+ }
1023
+ }
1024
+
1025
+ static ImVec2 ImGui_ImplSDL3_GetWindowPos(ImGuiViewport* viewport)
1026
+ {
1027
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1028
+ int x = 0, y = 0;
1029
+ SDL_GetWindowPosition(vd->Window, &x, &y);
1030
+ return ImVec2((float)x, (float)y);
1031
+ }
1032
+
1033
+ static void ImGui_ImplSDL3_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
1034
+ {
1035
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1036
+ SDL_SetWindowPosition(vd->Window, (int)pos.x, (int)pos.y);
1037
+ }
1038
+
1039
+ static ImVec2 ImGui_ImplSDL3_GetWindowSize(ImGuiViewport* viewport)
1040
+ {
1041
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1042
+ int w = 0, h = 0;
1043
+ SDL_GetWindowSize(vd->Window, &w, &h);
1044
+ return ImVec2((float)w, (float)h);
1045
+ }
1046
+
1047
+ static void ImGui_ImplSDL3_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
1048
+ {
1049
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1050
+ SDL_SetWindowSize(vd->Window, (int)size.x, (int)size.y);
1051
+ }
1052
+
1053
+ static void ImGui_ImplSDL3_SetWindowTitle(ImGuiViewport* viewport, const char* title)
1054
+ {
1055
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1056
+ SDL_SetWindowTitle(vd->Window, title);
1057
+ }
1058
+
1059
+ static void ImGui_ImplSDL3_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
1060
+ {
1061
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1062
+ SDL_SetWindowOpacity(vd->Window, alpha);
1063
+ }
1064
+
1065
+ static void ImGui_ImplSDL3_SetWindowFocus(ImGuiViewport* viewport)
1066
+ {
1067
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1068
+ SDL_RaiseWindow(vd->Window);
1069
+ }
1070
+
1071
+ static bool ImGui_ImplSDL3_GetWindowFocus(ImGuiViewport* viewport)
1072
+ {
1073
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1074
+ return (SDL_GetWindowFlags(vd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0;
1075
+ }
1076
+
1077
+ static bool ImGui_ImplSDL3_GetWindowMinimized(ImGuiViewport* viewport)
1078
+ {
1079
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1080
+ return (SDL_GetWindowFlags(vd->Window) & SDL_WINDOW_MINIMIZED) != 0;
1081
+ }
1082
+
1083
+ static void ImGui_ImplSDL3_RenderWindow(ImGuiViewport* viewport, void*)
1084
+ {
1085
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1086
+ if (vd->GLContext)
1087
+ SDL_GL_MakeCurrent(vd->Window, vd->GLContext);
1088
+ }
1089
+
1090
+ static void ImGui_ImplSDL3_SwapBuffers(ImGuiViewport* viewport, void*)
1091
+ {
1092
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1093
+ if (vd->GLContext)
1094
+ {
1095
+ SDL_GL_MakeCurrent(vd->Window, vd->GLContext);
1096
+ SDL_GL_SwapWindow(vd->Window);
1097
+ }
1098
+ }
1099
+
1100
+ // Vulkan support (the Vulkan renderer needs to call a platform-side support function to create the surface)
1101
+ // SDL is graceful enough to _not_ need <vulkan/vulkan.h> so we can safely include this.
1102
+ #include <SDL3/SDL_vulkan.h>
1103
+ static int ImGui_ImplSDL3_CreateVkSurface(ImGuiViewport* viewport, ImU64 vk_instance, const void* vk_allocator, ImU64* out_vk_surface)
1104
+ {
1105
+ ImGui_ImplSDL3_ViewportData* vd = (ImGui_ImplSDL3_ViewportData*)viewport->PlatformUserData;
1106
+ (void)vk_allocator;
1107
+ bool ret = SDL_Vulkan_CreateSurface(vd->Window, (VkInstance)vk_instance, (VkAllocationCallbacks*)vk_allocator, (VkSurfaceKHR*)out_vk_surface);
1108
+ return ret ? 0 : 1; // ret ? VK_SUCCESS : VK_NOT_READY
1109
+ }
1110
+
1111
+ static void ImGui_ImplSDL3_InitMultiViewportSupport(SDL_Window* window, void* sdl_gl_context)
1112
+ {
1113
+ // Register platform interface (will be coupled with a renderer interface)
1114
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
1115
+ platform_io.Platform_CreateWindow = ImGui_ImplSDL3_CreateWindow;
1116
+ platform_io.Platform_DestroyWindow = ImGui_ImplSDL3_DestroyWindow;
1117
+ platform_io.Platform_ShowWindow = ImGui_ImplSDL3_ShowWindow;
1118
+ platform_io.Platform_UpdateWindow = ImGui_ImplSDL3_UpdateWindow;
1119
+ platform_io.Platform_SetWindowPos = ImGui_ImplSDL3_SetWindowPos;
1120
+ platform_io.Platform_GetWindowPos = ImGui_ImplSDL3_GetWindowPos;
1121
+ platform_io.Platform_SetWindowSize = ImGui_ImplSDL3_SetWindowSize;
1122
+ platform_io.Platform_GetWindowSize = ImGui_ImplSDL3_GetWindowSize;
1123
+ platform_io.Platform_SetWindowFocus = ImGui_ImplSDL3_SetWindowFocus;
1124
+ platform_io.Platform_GetWindowFocus = ImGui_ImplSDL3_GetWindowFocus;
1125
+ platform_io.Platform_GetWindowMinimized = ImGui_ImplSDL3_GetWindowMinimized;
1126
+ platform_io.Platform_SetWindowTitle = ImGui_ImplSDL3_SetWindowTitle;
1127
+ platform_io.Platform_RenderWindow = ImGui_ImplSDL3_RenderWindow;
1128
+ platform_io.Platform_SwapBuffers = ImGui_ImplSDL3_SwapBuffers;
1129
+ platform_io.Platform_SetWindowAlpha = ImGui_ImplSDL3_SetWindowAlpha;
1130
+ platform_io.Platform_CreateVkSurface = ImGui_ImplSDL3_CreateVkSurface;
1131
+
1132
+ // Register main window handle (which is owned by the main application, not by us)
1133
+ // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports.
1134
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
1135
+ ImGui_ImplSDL3_ViewportData* vd = IM_NEW(ImGui_ImplSDL3_ViewportData)();
1136
+ vd->Window = window;
1137
+ vd->WindowID = SDL_GetWindowID(window);
1138
+ vd->WindowOwned = false;
1139
+ vd->GLContext = (SDL_GLContext)sdl_gl_context;
1140
+ main_viewport->PlatformUserData = vd;
1141
+ main_viewport->PlatformHandle = (void*)(intptr_t)vd->WindowID;
1142
+ }
1143
+
1144
+ static void ImGui_ImplSDL3_ShutdownMultiViewportSupport()
1145
+ {
1146
+ ImGui::DestroyPlatformWindows();
1147
+ }
1148
+
1149
+ //-----------------------------------------------------------------------------
1150
+
1151
+ #if defined(__clang__)
1152
+ #pragma clang diagnostic pop
1153
+ #endif
1154
+
1155
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_sdl3.h ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for SDL3 (*EXPERIMENTAL*)
2
+ // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
3
+ // (Info: SDL3 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
4
+
5
+ // (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**)
6
+
7
+ // Implemented features:
8
+ // [X] Platform: Clipboard support.
9
+ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
10
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values are obsolete since 1.87 and not supported since 1.91.5]
11
+ // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
12
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
13
+ // [x] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable' -> the OS animation effect when window gets created/destroyed is problematic. SDL2 backend doesn't have issue.
14
+ // Missing features or Issues:
15
+ // [ ] Platform: Multi-viewport: Minimized windows seems to break mouse wheel events (at least under Windows).
16
+ // [x] Platform: IME support. Position somehow broken in SDL3 + app needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
17
+
18
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
19
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
20
+ // Learn about Dear ImGui:
21
+ // - FAQ https://dearimgui.com/faq
22
+ // - Getting Started https://dearimgui.com/getting-started
23
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
24
+ // - Introduction, links and more at the top of imgui.cpp
25
+
26
+ #pragma once
27
+ #include "imgui.h" // IMGUI_IMPL_API
28
+ #ifndef IMGUI_DISABLE
29
+
30
+ struct SDL_Window;
31
+ struct SDL_Renderer;
32
+ struct SDL_Gamepad;
33
+ typedef union SDL_Event SDL_Event;
34
+
35
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
36
+ IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOpenGL(SDL_Window* window, void* sdl_gl_context);
37
+ IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForVulkan(SDL_Window* window);
38
+ IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForD3D(SDL_Window* window);
39
+ IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForMetal(SDL_Window* window);
40
+ IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer);
41
+ IMGUI_IMPL_API bool ImGui_ImplSDL3_InitForOther(SDL_Window* window);
42
+ IMGUI_IMPL_API void ImGui_ImplSDL3_Shutdown();
43
+ IMGUI_IMPL_API void ImGui_ImplSDL3_NewFrame();
44
+ IMGUI_IMPL_API bool ImGui_ImplSDL3_ProcessEvent(const SDL_Event* event);
45
+
46
+ // Gamepad selection automatically starts in AutoFirst mode, picking first available SDL_Gamepad. You may override this.
47
+ // When using manual mode, caller is responsible for opening/closing gamepad.
48
+ enum ImGui_ImplSDL3_GamepadMode { ImGui_ImplSDL3_GamepadMode_AutoFirst, ImGui_ImplSDL3_GamepadMode_AutoAll, ImGui_ImplSDL3_GamepadMode_Manual };
49
+ IMGUI_IMPL_API void ImGui_ImplSDL3_SetGamepadMode(ImGui_ImplSDL3_GamepadMode mode, SDL_Gamepad** manual_gamepads_array = nullptr, int manual_gamepads_count = -1);
50
+
51
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_sdlrenderer2.cpp ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for SDL_Renderer for SDL2
2
+ // (Requires: SDL 2.0.17+)
3
+
4
+ // Note how SDL_Renderer is an _optional_ component of SDL2.
5
+ // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX.
6
+ // If your application will want to render any non trivial amount of graphics other than UI,
7
+ // please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and
8
+ // it might be difficult to step out of those boundaries.
9
+
10
+ // Implemented features:
11
+ // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
12
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
13
+ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
14
+ // Missing features:
15
+ // [ ] Renderer: Multi-viewport support (multiple windows).
16
+
17
+ // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
18
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
19
+ // Learn about Dear ImGui:
20
+ // - FAQ https://dearimgui.com/faq
21
+ // - Getting Started https://dearimgui.com/getting-started
22
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
23
+ // - Introduction, links and more at the top of imgui.cpp
24
+
25
+ // CHANGELOG
26
+ // 2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer2_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
27
+ // 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter.
28
+ // 2023-05-30: Renamed imgui_impl_sdlrenderer.h/.cpp to imgui_impl_sdlrenderer2.h/.cpp to accommodate for upcoming SDL3.
29
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
30
+ // 2021-12-21: Update SDL_RenderGeometryRaw() format to work with SDL 2.0.19.
31
+ // 2021-12-03: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
32
+ // 2021-10-06: Backup and restore modified ClipRect/Viewport.
33
+ // 2021-09-21: Initial version.
34
+
35
+ #include "imgui.h"
36
+ #ifndef IMGUI_DISABLE
37
+ #include "imgui_impl_sdlrenderer2.h"
38
+ #include <stdint.h> // intptr_t
39
+
40
+ // Clang warnings with -Weverything
41
+ #if defined(__clang__)
42
+ #pragma clang diagnostic push
43
+ #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
44
+ #endif
45
+
46
+ // SDL
47
+ #include <SDL.h>
48
+ #if !SDL_VERSION_ATLEAST(2,0,17)
49
+ #error This backend requires SDL 2.0.17+ because of SDL_RenderGeometry() function
50
+ #endif
51
+
52
+ // SDL_Renderer data
53
+ struct ImGui_ImplSDLRenderer2_Data
54
+ {
55
+ SDL_Renderer* Renderer; // Main viewport's renderer
56
+ SDL_Texture* FontTexture;
57
+ ImGui_ImplSDLRenderer2_Data() { memset((void*)this, 0, sizeof(*this)); }
58
+ };
59
+
60
+ // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
61
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
62
+ static ImGui_ImplSDLRenderer2_Data* ImGui_ImplSDLRenderer2_GetBackendData()
63
+ {
64
+ return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer2_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
65
+ }
66
+
67
+ // Functions
68
+ bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer)
69
+ {
70
+ ImGuiIO& io = ImGui::GetIO();
71
+ IMGUI_CHECKVERSION();
72
+ IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
73
+ IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!");
74
+
75
+ // Setup backend capabilities flags
76
+ ImGui_ImplSDLRenderer2_Data* bd = IM_NEW(ImGui_ImplSDLRenderer2_Data)();
77
+ io.BackendRendererUserData = (void*)bd;
78
+ io.BackendRendererName = "imgui_impl_sdlrenderer2";
79
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
80
+
81
+ bd->Renderer = renderer;
82
+
83
+ return true;
84
+ }
85
+
86
+ void ImGui_ImplSDLRenderer2_Shutdown()
87
+ {
88
+ ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
89
+ IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
90
+ ImGuiIO& io = ImGui::GetIO();
91
+
92
+ ImGui_ImplSDLRenderer2_DestroyDeviceObjects();
93
+
94
+ io.BackendRendererName = nullptr;
95
+ io.BackendRendererUserData = nullptr;
96
+ io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
97
+ IM_DELETE(bd);
98
+ }
99
+
100
+ static void ImGui_ImplSDLRenderer2_SetupRenderState(SDL_Renderer* renderer)
101
+ {
102
+ // Clear out any viewports and cliprect set by the user
103
+ // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process.
104
+ SDL_RenderSetViewport(renderer, nullptr);
105
+ SDL_RenderSetClipRect(renderer, nullptr);
106
+ }
107
+
108
+ void ImGui_ImplSDLRenderer2_NewFrame()
109
+ {
110
+ ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
111
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLRenderer2_Init()?");
112
+
113
+ if (!bd->FontTexture)
114
+ ImGui_ImplSDLRenderer2_CreateDeviceObjects();
115
+ }
116
+
117
+ void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer)
118
+ {
119
+ // If there's a scale factor set by the user, use that instead
120
+ // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass
121
+ // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here.
122
+ float rsx = 1.0f;
123
+ float rsy = 1.0f;
124
+ SDL_RenderGetScale(renderer, &rsx, &rsy);
125
+ ImVec2 render_scale;
126
+ render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f;
127
+ render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f;
128
+
129
+ // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
130
+ int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x);
131
+ int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y);
132
+ if (fb_width == 0 || fb_height == 0)
133
+ return;
134
+
135
+ // Backup SDL_Renderer state that will be modified to restore it afterwards
136
+ struct BackupSDLRendererState
137
+ {
138
+ SDL_Rect Viewport;
139
+ bool ClipEnabled;
140
+ SDL_Rect ClipRect;
141
+ };
142
+ BackupSDLRendererState old = {};
143
+ old.ClipEnabled = SDL_RenderIsClipEnabled(renderer) == SDL_TRUE;
144
+ SDL_RenderGetViewport(renderer, &old.Viewport);
145
+ SDL_RenderGetClipRect(renderer, &old.ClipRect);
146
+
147
+ // Setup desired state
148
+ ImGui_ImplSDLRenderer2_SetupRenderState(renderer);
149
+
150
+ // Setup render state structure (for callbacks and custom texture bindings)
151
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
152
+ ImGui_ImplSDLRenderer2_RenderState render_state;
153
+ render_state.Renderer = renderer;
154
+ platform_io.Renderer_RenderState = &render_state;
155
+
156
+ // Will project scissor/clipping rectangles into framebuffer space
157
+ ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
158
+ ImVec2 clip_scale = render_scale;
159
+
160
+ // Render command lists
161
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
162
+ {
163
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
164
+ const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data;
165
+ const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data;
166
+
167
+ for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
168
+ {
169
+ const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
170
+ if (pcmd->UserCallback)
171
+ {
172
+ // User callback, registered via ImDrawList::AddCallback()
173
+ // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
174
+ if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
175
+ ImGui_ImplSDLRenderer2_SetupRenderState(renderer);
176
+ else
177
+ pcmd->UserCallback(draw_list, pcmd);
178
+ }
179
+ else
180
+ {
181
+ // Project scissor/clipping rectangles into framebuffer space
182
+ ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
183
+ ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
184
+ if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
185
+ if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
186
+ if (clip_max.x > (float)fb_width) { clip_max.x = (float)fb_width; }
187
+ if (clip_max.y > (float)fb_height) { clip_max.y = (float)fb_height; }
188
+ if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
189
+ continue;
190
+
191
+ SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) };
192
+ SDL_RenderSetClipRect(renderer, &r);
193
+
194
+ const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, pos));
195
+ const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, uv));
196
+ #if SDL_VERSION_ATLEAST(2,0,19)
197
+ const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.19+
198
+ #else
199
+ const int* color = (const int*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.17 and 2.0.18
200
+ #endif
201
+
202
+ // Bind texture, Draw
203
+ SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID();
204
+ SDL_RenderGeometryRaw(renderer, tex,
205
+ xy, (int)sizeof(ImDrawVert),
206
+ color, (int)sizeof(ImDrawVert),
207
+ uv, (int)sizeof(ImDrawVert),
208
+ draw_list->VtxBuffer.Size - pcmd->VtxOffset,
209
+ idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx));
210
+ }
211
+ }
212
+ }
213
+ platform_io.Renderer_RenderState = nullptr;
214
+
215
+ // Restore modified SDL_Renderer state
216
+ SDL_RenderSetViewport(renderer, &old.Viewport);
217
+ SDL_RenderSetClipRect(renderer, old.ClipEnabled ? &old.ClipRect : nullptr);
218
+ }
219
+
220
+ // Called by Init/NewFrame/Shutdown
221
+ bool ImGui_ImplSDLRenderer2_CreateFontsTexture()
222
+ {
223
+ ImGuiIO& io = ImGui::GetIO();
224
+ ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
225
+
226
+ // Build texture atlas
227
+ unsigned char* pixels;
228
+ int width, height;
229
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
230
+
231
+ // Upload texture to graphics system
232
+ // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
233
+ bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height);
234
+ if (bd->FontTexture == nullptr)
235
+ {
236
+ SDL_Log("error creating texture");
237
+ return false;
238
+ }
239
+ SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width);
240
+ SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND);
241
+ SDL_SetTextureScaleMode(bd->FontTexture, SDL_ScaleModeLinear);
242
+
243
+ // Store our identifier
244
+ io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
245
+
246
+ return true;
247
+ }
248
+
249
+ void ImGui_ImplSDLRenderer2_DestroyFontsTexture()
250
+ {
251
+ ImGuiIO& io = ImGui::GetIO();
252
+ ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
253
+ if (bd->FontTexture)
254
+ {
255
+ io.Fonts->SetTexID(0);
256
+ SDL_DestroyTexture(bd->FontTexture);
257
+ bd->FontTexture = nullptr;
258
+ }
259
+ }
260
+
261
+ bool ImGui_ImplSDLRenderer2_CreateDeviceObjects()
262
+ {
263
+ return ImGui_ImplSDLRenderer2_CreateFontsTexture();
264
+ }
265
+
266
+ void ImGui_ImplSDLRenderer2_DestroyDeviceObjects()
267
+ {
268
+ ImGui_ImplSDLRenderer2_DestroyFontsTexture();
269
+ }
270
+
271
+ //-----------------------------------------------------------------------------
272
+
273
+ #if defined(__clang__)
274
+ #pragma clang diagnostic pop
275
+ #endif
276
+
277
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_sdlrenderer2.h ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for SDL_Renderer for SDL2
2
+ // (Requires: SDL 2.0.17+)
3
+
4
+ // Note how SDL_Renderer is an _optional_ component of SDL2.
5
+ // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX.
6
+ // If your application will want to render any non trivial amount of graphics other than UI,
7
+ // please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and
8
+ // it might be difficult to step out of those boundaries.
9
+
10
+ // Implemented features:
11
+ // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
12
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
13
+ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
14
+ // Missing features:
15
+ // [ ] Renderer: Multi-viewport support (multiple windows).
16
+
17
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
18
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
19
+ // Learn about Dear ImGui:
20
+ // - FAQ https://dearimgui.com/faq
21
+ // - Getting Started https://dearimgui.com/getting-started
22
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
23
+ // - Introduction, links and more at the top of imgui.cpp
24
+
25
+ #pragma once
26
+ #ifndef IMGUI_DISABLE
27
+ #include "imgui.h" // IMGUI_IMPL_API
28
+
29
+ struct SDL_Renderer;
30
+
31
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
32
+ IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer);
33
+ IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_Shutdown();
34
+ IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_NewFrame();
35
+ IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer);
36
+
37
+ // Called by Init/NewFrame/Shutdown
38
+ IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateFontsTexture();
39
+ IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyFontsTexture();
40
+ IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateDeviceObjects();
41
+ IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyDeviceObjects();
42
+
43
+ // [BETA] Selected render state data shared with callbacks.
44
+ // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplSDLRenderer2_RenderDrawData() call.
45
+ // (Please open an issue if you feel you need access to more data)
46
+ struct ImGui_ImplSDLRenderer2_RenderState
47
+ {
48
+ SDL_Renderer* Renderer;
49
+ };
50
+
51
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_sdlrenderer3.cpp ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for SDL_Renderer for SDL3
2
+ // (Requires: SDL 3.0.0+)
3
+
4
+ // (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**)
5
+
6
+ // Note how SDL_Renderer is an _optional_ component of SDL3.
7
+ // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX.
8
+ // If your application will want to render any non trivial amount of graphics other than UI,
9
+ // please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and
10
+ // it might be difficult to step out of those boundaries.
11
+
12
+ // Implemented features:
13
+ // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
14
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
15
+ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
16
+ // Missing features:
17
+ // [ ] Renderer: Multi-viewport support (multiple windows).
18
+
19
+ // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
20
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
21
+ // Learn about Dear ImGui:
22
+ // - FAQ https://dearimgui.com/faq
23
+ // - Getting Started https://dearimgui.com/getting-started
24
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
25
+ // - Introduction, links and more at the top of imgui.cpp
26
+
27
+ // CHANGELOG
28
+ // 2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer3_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
29
+ // 2024-07-01: Update for SDL3 api changes: SDL_RenderGeometryRaw() uint32 version was removed (SDL#9009).
30
+ // 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter.
31
+ // 2024-02-12: Amend to query SDL_RenderViewportSet() and restore viewport accordingly.
32
+ // 2023-05-30: Initial version.
33
+
34
+ #include "imgui.h"
35
+ #ifndef IMGUI_DISABLE
36
+ #include "imgui_impl_sdlrenderer3.h"
37
+ #include <stdint.h> // intptr_t
38
+
39
+ // Clang warnings with -Weverything
40
+ #if defined(__clang__)
41
+ #pragma clang diagnostic push
42
+ #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
43
+ #endif
44
+
45
+ // SDL
46
+ #include <SDL3/SDL.h>
47
+ #if !SDL_VERSION_ATLEAST(3,0,0)
48
+ #error This backend requires SDL 3.0.0+
49
+ #endif
50
+
51
+ // SDL_Renderer data
52
+ struct ImGui_ImplSDLRenderer3_Data
53
+ {
54
+ SDL_Renderer* Renderer; // Main viewport's renderer
55
+ SDL_Texture* FontTexture;
56
+ ImVector<SDL_FColor> ColorBuffer;
57
+
58
+ ImGui_ImplSDLRenderer3_Data() { memset((void*)this, 0, sizeof(*this)); }
59
+ };
60
+
61
+ // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
62
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
63
+ static ImGui_ImplSDLRenderer3_Data* ImGui_ImplSDLRenderer3_GetBackendData()
64
+ {
65
+ return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
66
+ }
67
+
68
+ // Functions
69
+ bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer)
70
+ {
71
+ ImGuiIO& io = ImGui::GetIO();
72
+ IMGUI_CHECKVERSION();
73
+ IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
74
+ IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!");
75
+
76
+ // Setup backend capabilities flags
77
+ ImGui_ImplSDLRenderer3_Data* bd = IM_NEW(ImGui_ImplSDLRenderer3_Data)();
78
+ io.BackendRendererUserData = (void*)bd;
79
+ io.BackendRendererName = "imgui_impl_sdlrenderer3";
80
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
81
+
82
+ bd->Renderer = renderer;
83
+
84
+ return true;
85
+ }
86
+
87
+ void ImGui_ImplSDLRenderer3_Shutdown()
88
+ {
89
+ ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData();
90
+ IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
91
+ ImGuiIO& io = ImGui::GetIO();
92
+
93
+ ImGui_ImplSDLRenderer3_DestroyDeviceObjects();
94
+
95
+ io.BackendRendererName = nullptr;
96
+ io.BackendRendererUserData = nullptr;
97
+ io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
98
+ IM_DELETE(bd);
99
+ }
100
+
101
+ static void ImGui_ImplSDLRenderer3_SetupRenderState(SDL_Renderer* renderer)
102
+ {
103
+ // Clear out any viewports and cliprect set by the user
104
+ // FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process.
105
+ SDL_SetRenderViewport(renderer, nullptr);
106
+ SDL_SetRenderClipRect(renderer, nullptr);
107
+ }
108
+
109
+ void ImGui_ImplSDLRenderer3_NewFrame()
110
+ {
111
+ ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData();
112
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLRenderer3_Init()?");
113
+
114
+ if (!bd->FontTexture)
115
+ ImGui_ImplSDLRenderer3_CreateDeviceObjects();
116
+ }
117
+
118
+ // https://github.com/libsdl-org/SDL/issues/9009
119
+ static int SDL_RenderGeometryRaw8BitColor(SDL_Renderer* renderer, ImVector<SDL_FColor>& colors_out, SDL_Texture* texture, const float* xy, int xy_stride, const SDL_Color* color, int color_stride, const float* uv, int uv_stride, int num_vertices, const void* indices, int num_indices, int size_indices)
120
+ {
121
+ const Uint8* color2 = (const Uint8*)color;
122
+ colors_out.resize(num_vertices);
123
+ SDL_FColor* color3 = colors_out.Data;
124
+ for (int i = 0; i < num_vertices; i++)
125
+ {
126
+ color3[i].r = color->r / 255.0f;
127
+ color3[i].g = color->g / 255.0f;
128
+ color3[i].b = color->b / 255.0f;
129
+ color3[i].a = color->a / 255.0f;
130
+ color2 += color_stride;
131
+ color = (const SDL_Color*)color2;
132
+ }
133
+ return SDL_RenderGeometryRaw(renderer, texture, xy, xy_stride, color3, sizeof(*color3), uv, uv_stride, num_vertices, indices, num_indices, size_indices);
134
+ }
135
+
136
+ void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer)
137
+ {
138
+ ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData();
139
+
140
+ // If there's a scale factor set by the user, use that instead
141
+ // If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass
142
+ // to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here.
143
+ float rsx = 1.0f;
144
+ float rsy = 1.0f;
145
+ SDL_GetRenderScale(renderer, &rsx, &rsy);
146
+ ImVec2 render_scale;
147
+ render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f;
148
+ render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f;
149
+
150
+ // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
151
+ int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x);
152
+ int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y);
153
+ if (fb_width == 0 || fb_height == 0)
154
+ return;
155
+
156
+ // Backup SDL_Renderer state that will be modified to restore it afterwards
157
+ struct BackupSDLRendererState
158
+ {
159
+ SDL_Rect Viewport;
160
+ bool ViewportEnabled;
161
+ bool ClipEnabled;
162
+ SDL_Rect ClipRect;
163
+ };
164
+ BackupSDLRendererState old = {};
165
+ old.ViewportEnabled = SDL_RenderViewportSet(renderer);
166
+ old.ClipEnabled = SDL_RenderClipEnabled(renderer);
167
+ SDL_GetRenderViewport(renderer, &old.Viewport);
168
+ SDL_GetRenderClipRect(renderer, &old.ClipRect);
169
+
170
+ // Setup desired state
171
+ ImGui_ImplSDLRenderer3_SetupRenderState(renderer);
172
+
173
+ // Setup render state structure (for callbacks and custom texture bindings)
174
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
175
+ ImGui_ImplSDLRenderer3_RenderState render_state;
176
+ render_state.Renderer = renderer;
177
+ platform_io.Renderer_RenderState = &render_state;
178
+
179
+ // Will project scissor/clipping rectangles into framebuffer space
180
+ ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
181
+ ImVec2 clip_scale = render_scale;
182
+
183
+ // Render command lists
184
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
185
+ {
186
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
187
+ const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data;
188
+ const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data;
189
+
190
+ for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
191
+ {
192
+ const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
193
+ if (pcmd->UserCallback)
194
+ {
195
+ // User callback, registered via ImDrawList::AddCallback()
196
+ // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
197
+ if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
198
+ ImGui_ImplSDLRenderer3_SetupRenderState(renderer);
199
+ else
200
+ pcmd->UserCallback(draw_list, pcmd);
201
+ }
202
+ else
203
+ {
204
+ // Project scissor/clipping rectangles into framebuffer space
205
+ ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
206
+ ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
207
+ if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
208
+ if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
209
+ if (clip_max.x > (float)fb_width) { clip_max.x = (float)fb_width; }
210
+ if (clip_max.y > (float)fb_height) { clip_max.y = (float)fb_height; }
211
+ if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
212
+ continue;
213
+
214
+ SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) };
215
+ SDL_SetRenderClipRect(renderer, &r);
216
+
217
+ const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, pos));
218
+ const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, uv));
219
+ const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.19+
220
+
221
+ // Bind texture, Draw
222
+ SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID();
223
+ SDL_RenderGeometryRaw8BitColor(renderer, bd->ColorBuffer, tex,
224
+ xy, (int)sizeof(ImDrawVert),
225
+ color, (int)sizeof(ImDrawVert),
226
+ uv, (int)sizeof(ImDrawVert),
227
+ draw_list->VtxBuffer.Size - pcmd->VtxOffset,
228
+ idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx));
229
+ }
230
+ }
231
+ }
232
+ platform_io.Renderer_RenderState = nullptr;
233
+
234
+ // Restore modified SDL_Renderer state
235
+ SDL_SetRenderViewport(renderer, old.ViewportEnabled ? &old.Viewport : nullptr);
236
+ SDL_SetRenderClipRect(renderer, old.ClipEnabled ? &old.ClipRect : nullptr);
237
+ }
238
+
239
+ // Called by Init/NewFrame/Shutdown
240
+ bool ImGui_ImplSDLRenderer3_CreateFontsTexture()
241
+ {
242
+ ImGuiIO& io = ImGui::GetIO();
243
+ ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData();
244
+
245
+ // Build texture atlas
246
+ unsigned char* pixels;
247
+ int width, height;
248
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
249
+
250
+ // Upload texture to graphics system
251
+ // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
252
+ bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STATIC, width, height);
253
+ if (bd->FontTexture == nullptr)
254
+ {
255
+ SDL_Log("error creating texture");
256
+ return false;
257
+ }
258
+ SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width);
259
+ SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND);
260
+ SDL_SetTextureScaleMode(bd->FontTexture, SDL_SCALEMODE_LINEAR);
261
+
262
+ // Store our identifier
263
+ io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
264
+
265
+ return true;
266
+ }
267
+
268
+ void ImGui_ImplSDLRenderer3_DestroyFontsTexture()
269
+ {
270
+ ImGuiIO& io = ImGui::GetIO();
271
+ ImGui_ImplSDLRenderer3_Data* bd = ImGui_ImplSDLRenderer3_GetBackendData();
272
+ if (bd->FontTexture)
273
+ {
274
+ io.Fonts->SetTexID(0);
275
+ SDL_DestroyTexture(bd->FontTexture);
276
+ bd->FontTexture = nullptr;
277
+ }
278
+ }
279
+
280
+ bool ImGui_ImplSDLRenderer3_CreateDeviceObjects()
281
+ {
282
+ return ImGui_ImplSDLRenderer3_CreateFontsTexture();
283
+ }
284
+
285
+ void ImGui_ImplSDLRenderer3_DestroyDeviceObjects()
286
+ {
287
+ ImGui_ImplSDLRenderer3_DestroyFontsTexture();
288
+ }
289
+
290
+ //-----------------------------------------------------------------------------
291
+
292
+ #if defined(__clang__)
293
+ #pragma clang diagnostic pop
294
+ #endif
295
+
296
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_sdlrenderer3.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for SDL_Renderer for SDL3
2
+ // (Requires: SDL 3.0.0+)
3
+
4
+ // (**IMPORTANT: SDL 3.0.0 is NOT YET RELEASED AND CURRENTLY HAS A FAST CHANGING API. THIS CODE BREAKS OFTEN AS SDL3 CHANGES.**)
5
+
6
+ // Note how SDL_Renderer is an _optional_ component of SDL3.
7
+ // For a multi-platform app consider using e.g. SDL+DirectX on Windows and SDL+OpenGL on Linux/OSX.
8
+ // If your application will want to render any non trivial amount of graphics other than UI,
9
+ // please be aware that SDL_Renderer currently offers a limited graphic API to the end-user and
10
+ // it might be difficult to step out of those boundaries.
11
+
12
+ // Implemented features:
13
+ // [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
14
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
15
+ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
16
+ // Missing features:
17
+ // [ ] Renderer: Multi-viewport support (multiple windows).
18
+
19
+ // You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
20
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
21
+ // Learn about Dear ImGui:
22
+ // - FAQ https://dearimgui.com/faq
23
+ // - Getting Started https://dearimgui.com/getting-started
24
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
25
+ // - Introduction, links and more at the top of imgui.cpp
26
+
27
+ #pragma once
28
+ #include "imgui.h" // IMGUI_IMPL_API
29
+ #ifndef IMGUI_DISABLE
30
+
31
+ struct SDL_Renderer;
32
+
33
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
34
+ IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_Init(SDL_Renderer* renderer);
35
+ IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_Shutdown();
36
+ IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_NewFrame();
37
+ IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer);
38
+
39
+ // Called by Init/NewFrame/Shutdown
40
+ IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateFontsTexture();
41
+ IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyFontsTexture();
42
+ IMGUI_IMPL_API bool ImGui_ImplSDLRenderer3_CreateDeviceObjects();
43
+ IMGUI_IMPL_API void ImGui_ImplSDLRenderer3_DestroyDeviceObjects();
44
+
45
+ // [BETA] Selected render state data shared with callbacks.
46
+ // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplSDLRenderer3_RenderDrawData() call.
47
+ // (Please open an issue if you feel you need access to more data)
48
+ struct ImGui_ImplSDLRenderer3_RenderState
49
+ {
50
+ SDL_Renderer* Renderer;
51
+ };
52
+
53
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_vulkan.cpp ADDED
The diff for this file is too large to render. See raw diff
 
3rdparty/imgui/backends/imgui_impl_vulkan.h ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer Backend for Vulkan
2
+ // This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
3
+
4
+ // Implemented features:
5
+ // [!] Renderer: User texture binding. Use 'VkDescriptorSet' as ImTextureID. Call ImGui_ImplVulkan_AddTexture() to register one. Read the FAQ about ImTextureID! See https://github.com/ocornut/imgui/pull/914 for discussions.
6
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
7
+ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
8
+ // [x] Renderer: Multi-viewport / platform windows. With issues (flickering when creating a new viewport).
9
+
10
+ // The aim of imgui_impl_vulkan.h/.cpp is to be usable in your engine without any modification.
11
+ // IF YOU FEEL YOU NEED TO MAKE ANY CHANGE TO THIS CODE, please share them and your feedback at https://github.com/ocornut/imgui/
12
+
13
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
14
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
15
+ // Learn about Dear ImGui:
16
+ // - FAQ https://dearimgui.com/faq
17
+ // - Getting Started https://dearimgui.com/getting-started
18
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
19
+ // - Introduction, links and more at the top of imgui.cpp
20
+
21
+ // Important note to the reader who wish to integrate imgui_impl_vulkan.cpp/.h in their own engine/app.
22
+ // - Common ImGui_ImplVulkan_XXX functions and structures are used to interface with imgui_impl_vulkan.cpp/.h.
23
+ // You will use those if you want to use this rendering backend in your engine/app.
24
+ // - Helper ImGui_ImplVulkanH_XXX functions and structures are only used by this example (main.cpp) and by
25
+ // the backend itself (imgui_impl_vulkan.cpp), but should PROBABLY NOT be used by your own engine/app code.
26
+ // Read comments in imgui_impl_vulkan.h.
27
+
28
+ #pragma once
29
+ #ifndef IMGUI_DISABLE
30
+ #include "imgui.h" // IMGUI_IMPL_API
31
+
32
+ // [Configuration] in order to use a custom Vulkan function loader:
33
+ // (1) You'll need to disable default Vulkan function prototypes.
34
+ // We provide a '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' convenience configuration flag.
35
+ // In order to make sure this is visible from the imgui_impl_vulkan.cpp compilation unit:
36
+ // - Add '#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES' in your imconfig.h file
37
+ // - Or as a compilation flag in your build system
38
+ // - Or uncomment here (not recommended because you'd be modifying imgui sources!)
39
+ // - Do not simply add it in a .cpp file!
40
+ // (2) Call ImGui_ImplVulkan_LoadFunctions() before ImGui_ImplVulkan_Init() with your custom function.
41
+ // If you have no idea what this is, leave it alone!
42
+ //#define IMGUI_IMPL_VULKAN_NO_PROTOTYPES
43
+
44
+ // Convenience support for Volk
45
+ // (you can also technically use IMGUI_IMPL_VULKAN_NO_PROTOTYPES + wrap Volk via ImGui_ImplVulkan_LoadFunctions().)
46
+ //#define IMGUI_IMPL_VULKAN_USE_VOLK
47
+
48
+ #if defined(IMGUI_IMPL_VULKAN_NO_PROTOTYPES) && !defined(VK_NO_PROTOTYPES)
49
+ #define VK_NO_PROTOTYPES
50
+ #endif
51
+ #if defined(VK_USE_PLATFORM_WIN32_KHR) && !defined(NOMINMAX)
52
+ #define NOMINMAX
53
+ #endif
54
+
55
+ // Vulkan includes
56
+ #ifdef IMGUI_IMPL_VULKAN_USE_VOLK
57
+ #include <volk.h>
58
+ #else
59
+ #include <vulkan/vulkan.h>
60
+ #endif
61
+ #if defined(VK_VERSION_1_3) || defined(VK_KHR_dynamic_rendering)
62
+ #define IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
63
+ #endif
64
+
65
+ // Initialization data, for ImGui_ImplVulkan_Init()
66
+ // [Please zero-clear before use!]
67
+ // - About descriptor pool:
68
+ // - A VkDescriptorPool should be created with VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT,
69
+ // and must contain a pool size large enough to hold a small number of VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER descriptors.
70
+ // - As an convenience, by setting DescriptorPoolSize > 0 the backend will create one for you.
71
+ // - Current version of the backend use 1 descriptor for the font atlas + as many as additional calls done to ImGui_ImplVulkan_AddTexture().
72
+ // - It is expected that as early as Q1 2025 the backend will use a few more descriptors, so aim at 10 + number of desierd calls to ImGui_ImplVulkan_AddTexture().
73
+ // - About dynamic rendering:
74
+ // - When using dynamic rendering, set UseDynamicRendering=true and fill PipelineRenderingCreateInfo structure.
75
+ struct ImGui_ImplVulkan_InitInfo
76
+ {
77
+ VkInstance Instance;
78
+ VkPhysicalDevice PhysicalDevice;
79
+ VkDevice Device;
80
+ uint32_t QueueFamily;
81
+ VkQueue Queue;
82
+ VkDescriptorPool DescriptorPool; // See requirements in note above; ignored if using DescriptorPoolSize > 0
83
+ VkRenderPass RenderPass; // Ignored if using dynamic rendering
84
+ uint32_t MinImageCount; // >= 2
85
+ uint32_t ImageCount; // >= MinImageCount
86
+ VkSampleCountFlagBits MSAASamples; // 0 defaults to VK_SAMPLE_COUNT_1_BIT
87
+
88
+ // (Optional)
89
+ VkPipelineCache PipelineCache;
90
+ uint32_t Subpass;
91
+
92
+ // (Optional) Set to create internal descriptor pool instead of using DescriptorPool
93
+ uint32_t DescriptorPoolSize;
94
+
95
+ // (Optional) Dynamic Rendering
96
+ // Need to explicitly enable VK_KHR_dynamic_rendering extension to use this, even for Vulkan 1.3.
97
+ bool UseDynamicRendering;
98
+ #ifdef IMGUI_IMPL_VULKAN_HAS_DYNAMIC_RENDERING
99
+ VkPipelineRenderingCreateInfoKHR PipelineRenderingCreateInfo;
100
+ #endif
101
+
102
+ // (Optional) Allocation, Debugging
103
+ const VkAllocationCallbacks* Allocator;
104
+ void (*CheckVkResultFn)(VkResult err);
105
+ VkDeviceSize MinAllocationSize; // Minimum allocation size. Set to 1024*1024 to satisfy zealous best practices validation layer and waste a little memory.
106
+ };
107
+
108
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
109
+ IMGUI_IMPL_API bool ImGui_ImplVulkan_Init(ImGui_ImplVulkan_InitInfo* info);
110
+ IMGUI_IMPL_API void ImGui_ImplVulkan_Shutdown();
111
+ IMGUI_IMPL_API void ImGui_ImplVulkan_NewFrame();
112
+ IMGUI_IMPL_API void ImGui_ImplVulkan_RenderDrawData(ImDrawData* draw_data, VkCommandBuffer command_buffer, VkPipeline pipeline = VK_NULL_HANDLE);
113
+ IMGUI_IMPL_API bool ImGui_ImplVulkan_CreateFontsTexture();
114
+ IMGUI_IMPL_API void ImGui_ImplVulkan_DestroyFontsTexture();
115
+ IMGUI_IMPL_API void ImGui_ImplVulkan_SetMinImageCount(uint32_t min_image_count); // To override MinImageCount after initialization (e.g. if swap chain is recreated)
116
+
117
+ // Register a texture (VkDescriptorSet == ImTextureID)
118
+ // FIXME: This is experimental in the sense that we are unsure how to best design/tackle this problem
119
+ // Please post to https://github.com/ocornut/imgui/pull/914 if you have suggestions.
120
+ IMGUI_IMPL_API VkDescriptorSet ImGui_ImplVulkan_AddTexture(VkSampler sampler, VkImageView image_view, VkImageLayout image_layout);
121
+ IMGUI_IMPL_API void ImGui_ImplVulkan_RemoveTexture(VkDescriptorSet descriptor_set);
122
+
123
+ // Optional: load Vulkan functions with a custom function loader
124
+ // This is only useful with IMGUI_IMPL_VULKAN_NO_PROTOTYPES / VK_NO_PROTOTYPES
125
+ IMGUI_IMPL_API bool ImGui_ImplVulkan_LoadFunctions(PFN_vkVoidFunction(*loader_func)(const char* function_name, void* user_data), void* user_data = nullptr);
126
+
127
+ // [BETA] Selected render state data shared with callbacks.
128
+ // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplVulkan_RenderDrawData() call.
129
+ // (Please open an issue if you feel you need access to more data)
130
+ struct ImGui_ImplVulkan_RenderState
131
+ {
132
+ VkCommandBuffer CommandBuffer;
133
+ VkPipeline Pipeline;
134
+ VkPipelineLayout PipelineLayout;
135
+ };
136
+
137
+ //-------------------------------------------------------------------------
138
+ // Internal / Miscellaneous Vulkan Helpers
139
+ // (Used by example's main.cpp. Used by multi-viewport features. PROBABLY NOT used by your own engine/app.)
140
+ //-------------------------------------------------------------------------
141
+ // You probably do NOT need to use or care about those functions.
142
+ // Those functions only exist because:
143
+ // 1) they facilitate the readability and maintenance of the multiple main.cpp examples files.
144
+ // 2) the multi-viewport / platform window implementation needs them internally.
145
+ // Generally we avoid exposing any kind of superfluous high-level helpers in the bindings,
146
+ // but it is too much code to duplicate everywhere so we exceptionally expose them.
147
+ //
148
+ // Your engine/app will likely _already_ have code to setup all that stuff (swap chain, render pass, frame buffers, etc.).
149
+ // You may read this code to learn about Vulkan, but it is recommended you use you own custom tailored code to do equivalent work.
150
+ // (The ImGui_ImplVulkanH_XXX functions do not interact with any of the state used by the regular ImGui_ImplVulkan_XXX functions)
151
+ //-------------------------------------------------------------------------
152
+
153
+ struct ImGui_ImplVulkanH_Frame;
154
+ struct ImGui_ImplVulkanH_Window;
155
+
156
+ // Helpers
157
+ IMGUI_IMPL_API void ImGui_ImplVulkanH_CreateOrResizeWindow(VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, ImGui_ImplVulkanH_Window* wd, uint32_t queue_family, const VkAllocationCallbacks* allocator, int w, int h, uint32_t min_image_count);
158
+ IMGUI_IMPL_API void ImGui_ImplVulkanH_DestroyWindow(VkInstance instance, VkDevice device, ImGui_ImplVulkanH_Window* wd, const VkAllocationCallbacks* allocator);
159
+ IMGUI_IMPL_API VkSurfaceFormatKHR ImGui_ImplVulkanH_SelectSurfaceFormat(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkFormat* request_formats, int request_formats_count, VkColorSpaceKHR request_color_space);
160
+ IMGUI_IMPL_API VkPresentModeKHR ImGui_ImplVulkanH_SelectPresentMode(VkPhysicalDevice physical_device, VkSurfaceKHR surface, const VkPresentModeKHR* request_modes, int request_modes_count);
161
+ IMGUI_IMPL_API int ImGui_ImplVulkanH_GetMinImageCountFromPresentMode(VkPresentModeKHR present_mode);
162
+
163
+ // Helper structure to hold the data needed by one rendering frame
164
+ // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.)
165
+ // [Please zero-clear before use!]
166
+ struct ImGui_ImplVulkanH_Frame
167
+ {
168
+ VkCommandPool CommandPool;
169
+ VkCommandBuffer CommandBuffer;
170
+ VkFence Fence;
171
+ VkImage Backbuffer;
172
+ VkImageView BackbufferView;
173
+ VkFramebuffer Framebuffer;
174
+ };
175
+
176
+ struct ImGui_ImplVulkanH_FrameSemaphores
177
+ {
178
+ VkSemaphore ImageAcquiredSemaphore;
179
+ VkSemaphore RenderCompleteSemaphore;
180
+ };
181
+
182
+ // Helper structure to hold the data needed by one rendering context into one OS window
183
+ // (Used by example's main.cpp. Used by multi-viewport features. Probably NOT used by your own engine/app.)
184
+ struct ImGui_ImplVulkanH_Window
185
+ {
186
+ int Width;
187
+ int Height;
188
+ VkSwapchainKHR Swapchain;
189
+ VkSurfaceKHR Surface;
190
+ VkSurfaceFormatKHR SurfaceFormat;
191
+ VkPresentModeKHR PresentMode;
192
+ VkRenderPass RenderPass;
193
+ bool UseDynamicRendering;
194
+ bool ClearEnable;
195
+ VkClearValue ClearValue;
196
+ uint32_t FrameIndex; // Current frame being rendered to (0 <= FrameIndex < FrameInFlightCount)
197
+ uint32_t ImageCount; // Number of simultaneous in-flight frames (returned by vkGetSwapchainImagesKHR, usually derived from min_image_count)
198
+ uint32_t SemaphoreCount; // Number of simultaneous in-flight frames + 1, to be able to use it in vkAcquireNextImageKHR
199
+ uint32_t SemaphoreIndex; // Current set of swapchain wait semaphores we're using (needs to be distinct from per frame data)
200
+ ImGui_ImplVulkanH_Frame* Frames;
201
+ ImGui_ImplVulkanH_FrameSemaphores* FrameSemaphores;
202
+
203
+ ImGui_ImplVulkanH_Window()
204
+ {
205
+ memset((void*)this, 0, sizeof(*this));
206
+ PresentMode = (VkPresentModeKHR)~0; // Ensure we get an error if user doesn't set this.
207
+ ClearEnable = true;
208
+ }
209
+ };
210
+
211
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_wgpu.cpp ADDED
@@ -0,0 +1,860 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer for WebGPU
2
+ // This needs to be used along with a Platform Binding (e.g. GLFW)
3
+ // (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.)
4
+
5
+ // Implemented features:
6
+ // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
7
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
8
+ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
9
+ // Missing features:
10
+ // [ ] Renderer: Multi-viewport support (multiple windows). Not meaningful on the web.
11
+
12
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
13
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
14
+ // Learn about Dear ImGui:
15
+ // - FAQ https://dearimgui.com/faq
16
+ // - Getting Started https://dearimgui.com/getting-started
17
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
18
+ // - Introduction, links and more at the top of imgui.cpp
19
+
20
+ // CHANGELOG
21
+ // (minor and older changes stripped away, please see git history for details)
22
+ // 2024-10-14: Update Dawn support for change of string usages. (#8082, #8083)
23
+ // 2024-10-07: Expose selected render state in ImGui_ImplWGPU_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
24
+ // 2024-10-07: Changed default texture sampler to Clamp instead of Repeat/Wrap.
25
+ // 2024-09-16: Added support for optional IMGUI_IMPL_WEBGPU_BACKEND_DAWN / IMGUI_IMPL_WEBGPU_BACKEND_WGPU define to handle ever-changing native implementations. (#7977)
26
+ // 2024-01-22: Added configurable PipelineMultisampleState struct. (#7240)
27
+ // 2024-01-22: (Breaking) ImGui_ImplWGPU_Init() now takes a ImGui_ImplWGPU_InitInfo structure instead of variety of parameters, allowing for easier further changes.
28
+ // 2024-01-22: Fixed pipeline layout leak. (#7245)
29
+ // 2024-01-17: Explicitly fill all of WGPUDepthStencilState since standard removed defaults.
30
+ // 2023-07-13: Use WGPUShaderModuleWGSLDescriptor's code instead of source. use WGPUMipmapFilterMode_Linear instead of WGPUFilterMode_Linear. (#6602)
31
+ // 2023-04-11: Align buffer sizes. Use WGSL shaders instead of precompiled SPIR-V.
32
+ // 2023-04-11: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
33
+ // 2023-01-25: Revert automatic pipeline layout generation (see https://github.com/gpuweb/gpuweb/issues/2470)
34
+ // 2022-11-24: Fixed validation error with default depth buffer settings.
35
+ // 2022-11-10: Fixed rendering when a depth buffer is enabled. Added 'WGPUTextureFormat depth_format' parameter to ImGui_ImplWGPU_Init().
36
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
37
+ // 2021-11-29: Passing explicit buffer sizes to wgpuRenderPassEncoderSetVertexBuffer()/wgpuRenderPassEncoderSetIndexBuffer().
38
+ // 2021-08-24: Fixed for latest specs.
39
+ // 2021-05-24: Add support for draw_data->FramebufferScale.
40
+ // 2021-05-19: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
41
+ // 2021-05-16: Update to latest WebGPU specs (compatible with Emscripten 2.0.20 and Chrome Canary 92).
42
+ // 2021-02-18: Change blending equation to preserve alpha in output buffer.
43
+ // 2021-01-28: Initial version.
44
+
45
+ // When targeting native platforms (i.e. NOT emscripten), one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN
46
+ // or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided. See imgui_impl_wgpu.h for more details.
47
+ #ifndef __EMSCRIPTEN__
48
+ #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) == defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
49
+ #error exactly one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be defined!
50
+ #endif
51
+ #else
52
+ #if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
53
+ #error neither IMGUI_IMPL_WEBGPU_BACKEND_DAWN nor IMGUI_IMPL_WEBGPU_BACKEND_WGPU may be defined if targeting emscripten!
54
+ #endif
55
+ #endif
56
+
57
+ #include "imgui.h"
58
+ #ifndef IMGUI_DISABLE
59
+ #include "imgui_impl_wgpu.h"
60
+ #include <limits.h>
61
+ #include <webgpu/webgpu.h>
62
+
63
+ // Dear ImGui prototypes from imgui_internal.h
64
+ extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed = 0);
65
+ #define MEMALIGN(_SIZE,_ALIGN) (((_SIZE) + ((_ALIGN) - 1)) & ~((_ALIGN) - 1)) // Memory align (copied from IM_ALIGN() macro).
66
+
67
+ // WebGPU data
68
+ struct RenderResources
69
+ {
70
+ WGPUTexture FontTexture = nullptr; // Font texture
71
+ WGPUTextureView FontTextureView = nullptr; // Texture view for font texture
72
+ WGPUSampler Sampler = nullptr; // Sampler for the font texture
73
+ WGPUBuffer Uniforms = nullptr; // Shader uniforms
74
+ WGPUBindGroup CommonBindGroup = nullptr; // Resources bind-group to bind the common resources to pipeline
75
+ ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map)
76
+ WGPUBindGroup ImageBindGroup = nullptr; // Default font-resource of Dear ImGui
77
+ WGPUBindGroupLayout ImageBindGroupLayout = nullptr; // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM
78
+ };
79
+
80
+ struct FrameResources
81
+ {
82
+ WGPUBuffer IndexBuffer;
83
+ WGPUBuffer VertexBuffer;
84
+ ImDrawIdx* IndexBufferHost;
85
+ ImDrawVert* VertexBufferHost;
86
+ int IndexBufferSize;
87
+ int VertexBufferSize;
88
+ };
89
+
90
+ struct Uniforms
91
+ {
92
+ float MVP[4][4];
93
+ float Gamma;
94
+ };
95
+
96
+ struct ImGui_ImplWGPU_Data
97
+ {
98
+ ImGui_ImplWGPU_InitInfo initInfo;
99
+ WGPUDevice wgpuDevice = nullptr;
100
+ WGPUQueue defaultQueue = nullptr;
101
+ WGPUTextureFormat renderTargetFormat = WGPUTextureFormat_Undefined;
102
+ WGPUTextureFormat depthStencilFormat = WGPUTextureFormat_Undefined;
103
+ WGPURenderPipeline pipelineState = nullptr;
104
+
105
+ RenderResources renderResources;
106
+ FrameResources* pFrameResources = nullptr;
107
+ unsigned int numFramesInFlight = 0;
108
+ unsigned int frameIndex = UINT_MAX;
109
+ };
110
+
111
+ // Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
112
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
113
+ static ImGui_ImplWGPU_Data* ImGui_ImplWGPU_GetBackendData()
114
+ {
115
+ return ImGui::GetCurrentContext() ? (ImGui_ImplWGPU_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
116
+ }
117
+
118
+ //-----------------------------------------------------------------------------
119
+ // SHADERS
120
+ //-----------------------------------------------------------------------------
121
+
122
+ static const char __shader_vert_wgsl[] = R"(
123
+ struct VertexInput {
124
+ @location(0) position: vec2<f32>,
125
+ @location(1) uv: vec2<f32>,
126
+ @location(2) color: vec4<f32>,
127
+ };
128
+
129
+ struct VertexOutput {
130
+ @builtin(position) position: vec4<f32>,
131
+ @location(0) color: vec4<f32>,
132
+ @location(1) uv: vec2<f32>,
133
+ };
134
+
135
+ struct Uniforms {
136
+ mvp: mat4x4<f32>,
137
+ gamma: f32,
138
+ };
139
+
140
+ @group(0) @binding(0) var<uniform> uniforms: Uniforms;
141
+
142
+ @vertex
143
+ fn main(in: VertexInput) -> VertexOutput {
144
+ var out: VertexOutput;
145
+ out.position = uniforms.mvp * vec4<f32>(in.position, 0.0, 1.0);
146
+ out.color = in.color;
147
+ out.uv = in.uv;
148
+ return out;
149
+ }
150
+ )";
151
+
152
+ static const char __shader_frag_wgsl[] = R"(
153
+ struct VertexOutput {
154
+ @builtin(position) position: vec4<f32>,
155
+ @location(0) color: vec4<f32>,
156
+ @location(1) uv: vec2<f32>,
157
+ };
158
+
159
+ struct Uniforms {
160
+ mvp: mat4x4<f32>,
161
+ gamma: f32,
162
+ };
163
+
164
+ @group(0) @binding(0) var<uniform> uniforms: Uniforms;
165
+ @group(0) @binding(1) var s: sampler;
166
+ @group(1) @binding(0) var t: texture_2d<f32>;
167
+
168
+ @fragment
169
+ fn main(in: VertexOutput) -> @location(0) vec4<f32> {
170
+ let color = in.color * textureSample(t, s, in.uv);
171
+ let corrected_color = pow(color.rgb, vec3<f32>(uniforms.gamma));
172
+ return vec4<f32>(corrected_color, color.a);
173
+ }
174
+ )";
175
+
176
+ static void SafeRelease(ImDrawIdx*& res)
177
+ {
178
+ if (res)
179
+ delete[] res;
180
+ res = nullptr;
181
+ }
182
+ static void SafeRelease(ImDrawVert*& res)
183
+ {
184
+ if (res)
185
+ delete[] res;
186
+ res = nullptr;
187
+ }
188
+ static void SafeRelease(WGPUBindGroupLayout& res)
189
+ {
190
+ if (res)
191
+ wgpuBindGroupLayoutRelease(res);
192
+ res = nullptr;
193
+ }
194
+ static void SafeRelease(WGPUBindGroup& res)
195
+ {
196
+ if (res)
197
+ wgpuBindGroupRelease(res);
198
+ res = nullptr;
199
+ }
200
+ static void SafeRelease(WGPUBuffer& res)
201
+ {
202
+ if (res)
203
+ wgpuBufferRelease(res);
204
+ res = nullptr;
205
+ }
206
+ static void SafeRelease(WGPUPipelineLayout& res)
207
+ {
208
+ if (res)
209
+ wgpuPipelineLayoutRelease(res);
210
+ res = nullptr;
211
+ }
212
+ static void SafeRelease(WGPURenderPipeline& res)
213
+ {
214
+ if (res)
215
+ wgpuRenderPipelineRelease(res);
216
+ res = nullptr;
217
+ }
218
+ static void SafeRelease(WGPUSampler& res)
219
+ {
220
+ if (res)
221
+ wgpuSamplerRelease(res);
222
+ res = nullptr;
223
+ }
224
+ static void SafeRelease(WGPUShaderModule& res)
225
+ {
226
+ if (res)
227
+ wgpuShaderModuleRelease(res);
228
+ res = nullptr;
229
+ }
230
+ static void SafeRelease(WGPUTextureView& res)
231
+ {
232
+ if (res)
233
+ wgpuTextureViewRelease(res);
234
+ res = nullptr;
235
+ }
236
+ static void SafeRelease(WGPUTexture& res)
237
+ {
238
+ if (res)
239
+ wgpuTextureRelease(res);
240
+ res = nullptr;
241
+ }
242
+
243
+ static void SafeRelease(RenderResources& res)
244
+ {
245
+ SafeRelease(res.FontTexture);
246
+ SafeRelease(res.FontTextureView);
247
+ SafeRelease(res.Sampler);
248
+ SafeRelease(res.Uniforms);
249
+ SafeRelease(res.CommonBindGroup);
250
+ SafeRelease(res.ImageBindGroup);
251
+ SafeRelease(res.ImageBindGroupLayout);
252
+ };
253
+
254
+ static void SafeRelease(FrameResources& res)
255
+ {
256
+ SafeRelease(res.IndexBuffer);
257
+ SafeRelease(res.VertexBuffer);
258
+ SafeRelease(res.IndexBufferHost);
259
+ SafeRelease(res.VertexBufferHost);
260
+ }
261
+
262
+ static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(const char* wgsl_source)
263
+ {
264
+ ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
265
+
266
+ #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
267
+ WGPUShaderSourceWGSL wgsl_desc = {};
268
+ wgsl_desc.chain.sType = WGPUSType_ShaderSourceWGSL;
269
+ wgsl_desc.code = { wgsl_source, WGPU_STRLEN };
270
+ #else
271
+ WGPUShaderModuleWGSLDescriptor wgsl_desc = {};
272
+ wgsl_desc.chain.sType = WGPUSType_ShaderModuleWGSLDescriptor;
273
+ wgsl_desc.code = wgsl_source;
274
+ #endif
275
+
276
+ WGPUShaderModuleDescriptor desc = {};
277
+ desc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&wgsl_desc);
278
+
279
+ WGPUProgrammableStageDescriptor stage_desc = {};
280
+ stage_desc.module = wgpuDeviceCreateShaderModule(bd->wgpuDevice, &desc);
281
+ #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
282
+ stage_desc.entryPoint = { "main", WGPU_STRLEN };
283
+ #else
284
+ stage_desc.entryPoint = "main";
285
+ #endif
286
+ return stage_desc;
287
+ }
288
+
289
+ static WGPUBindGroup ImGui_ImplWGPU_CreateImageBindGroup(WGPUBindGroupLayout layout, WGPUTextureView texture)
290
+ {
291
+ ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
292
+ WGPUBindGroupEntry image_bg_entries[] = { { nullptr, 0, 0, 0, 0, 0, texture } };
293
+
294
+ WGPUBindGroupDescriptor image_bg_descriptor = {};
295
+ image_bg_descriptor.layout = layout;
296
+ image_bg_descriptor.entryCount = sizeof(image_bg_entries) / sizeof(WGPUBindGroupEntry);
297
+ image_bg_descriptor.entries = image_bg_entries;
298
+ return wgpuDeviceCreateBindGroup(bd->wgpuDevice, &image_bg_descriptor);
299
+ }
300
+
301
+ static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPassEncoder ctx, FrameResources* fr)
302
+ {
303
+ ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
304
+
305
+ // Setup orthographic projection matrix into our constant buffer
306
+ // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
307
+ {
308
+ float L = draw_data->DisplayPos.x;
309
+ float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
310
+ float T = draw_data->DisplayPos.y;
311
+ float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
312
+ float mvp[4][4] =
313
+ {
314
+ { 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
315
+ { 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
316
+ { 0.0f, 0.0f, 0.5f, 0.0f },
317
+ { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
318
+ };
319
+ wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, MVP), mvp, sizeof(Uniforms::MVP));
320
+ float gamma;
321
+ switch (bd->renderTargetFormat)
322
+ {
323
+ case WGPUTextureFormat_ASTC10x10UnormSrgb:
324
+ case WGPUTextureFormat_ASTC10x5UnormSrgb:
325
+ case WGPUTextureFormat_ASTC10x6UnormSrgb:
326
+ case WGPUTextureFormat_ASTC10x8UnormSrgb:
327
+ case WGPUTextureFormat_ASTC12x10UnormSrgb:
328
+ case WGPUTextureFormat_ASTC12x12UnormSrgb:
329
+ case WGPUTextureFormat_ASTC4x4UnormSrgb:
330
+ case WGPUTextureFormat_ASTC5x5UnormSrgb:
331
+ case WGPUTextureFormat_ASTC6x5UnormSrgb:
332
+ case WGPUTextureFormat_ASTC6x6UnormSrgb:
333
+ case WGPUTextureFormat_ASTC8x5UnormSrgb:
334
+ case WGPUTextureFormat_ASTC8x6UnormSrgb:
335
+ case WGPUTextureFormat_ASTC8x8UnormSrgb:
336
+ case WGPUTextureFormat_BC1RGBAUnormSrgb:
337
+ case WGPUTextureFormat_BC2RGBAUnormSrgb:
338
+ case WGPUTextureFormat_BC3RGBAUnormSrgb:
339
+ case WGPUTextureFormat_BC7RGBAUnormSrgb:
340
+ case WGPUTextureFormat_BGRA8UnormSrgb:
341
+ case WGPUTextureFormat_ETC2RGB8A1UnormSrgb:
342
+ case WGPUTextureFormat_ETC2RGB8UnormSrgb:
343
+ case WGPUTextureFormat_ETC2RGBA8UnormSrgb:
344
+ case WGPUTextureFormat_RGBA8UnormSrgb:
345
+ gamma = 2.2f;
346
+ break;
347
+ default:
348
+ gamma = 1.0f;
349
+ }
350
+ wgpuQueueWriteBuffer(bd->defaultQueue, bd->renderResources.Uniforms, offsetof(Uniforms, Gamma), &gamma, sizeof(Uniforms::Gamma));
351
+ }
352
+
353
+ // Setup viewport
354
+ wgpuRenderPassEncoderSetViewport(ctx, 0, 0, draw_data->FramebufferScale.x * draw_data->DisplaySize.x, draw_data->FramebufferScale.y * draw_data->DisplaySize.y, 0, 1);
355
+
356
+ // Bind shader and vertex buffers
357
+ wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, fr->VertexBufferSize * sizeof(ImDrawVert));
358
+ wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, fr->IndexBufferSize * sizeof(ImDrawIdx));
359
+ wgpuRenderPassEncoderSetPipeline(ctx, bd->pipelineState);
360
+ wgpuRenderPassEncoderSetBindGroup(ctx, 0, bd->renderResources.CommonBindGroup, 0, nullptr);
361
+
362
+ // Setup blend factor
363
+ WGPUColor blend_color = { 0.f, 0.f, 0.f, 0.f };
364
+ wgpuRenderPassEncoderSetBlendConstant(ctx, &blend_color);
365
+ }
366
+
367
+ // Render function
368
+ // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
369
+ void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder)
370
+ {
371
+ // Avoid rendering when minimized
372
+ int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
373
+ int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
374
+ if (fb_width <= 0 || fb_height <= 0 || draw_data->CmdListsCount == 0)
375
+ return;
376
+
377
+ // FIXME: Assuming that this only gets called once per frame!
378
+ // If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
379
+ ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
380
+ bd->frameIndex = bd->frameIndex + 1;
381
+ FrameResources* fr = &bd->pFrameResources[bd->frameIndex % bd->numFramesInFlight];
382
+
383
+ // Create and grow vertex/index buffers if needed
384
+ if (fr->VertexBuffer == nullptr || fr->VertexBufferSize < draw_data->TotalVtxCount)
385
+ {
386
+ if (fr->VertexBuffer)
387
+ {
388
+ wgpuBufferDestroy(fr->VertexBuffer);
389
+ wgpuBufferRelease(fr->VertexBuffer);
390
+ }
391
+ SafeRelease(fr->VertexBufferHost);
392
+ fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
393
+
394
+ WGPUBufferDescriptor vb_desc =
395
+ {
396
+ nullptr,
397
+ "Dear ImGui Vertex buffer",
398
+ #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
399
+ WGPU_STRLEN,
400
+ #endif
401
+ WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
402
+ MEMALIGN(fr->VertexBufferSize * sizeof(ImDrawVert), 4),
403
+ false
404
+ };
405
+ fr->VertexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &vb_desc);
406
+ if (!fr->VertexBuffer)
407
+ return;
408
+
409
+ fr->VertexBufferHost = new ImDrawVert[fr->VertexBufferSize];
410
+ }
411
+ if (fr->IndexBuffer == nullptr || fr->IndexBufferSize < draw_data->TotalIdxCount)
412
+ {
413
+ if (fr->IndexBuffer)
414
+ {
415
+ wgpuBufferDestroy(fr->IndexBuffer);
416
+ wgpuBufferRelease(fr->IndexBuffer);
417
+ }
418
+ SafeRelease(fr->IndexBufferHost);
419
+ fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
420
+
421
+ WGPUBufferDescriptor ib_desc =
422
+ {
423
+ nullptr,
424
+ "Dear ImGui Index buffer",
425
+ #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
426
+ WGPU_STRLEN,
427
+ #endif
428
+ WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
429
+ MEMALIGN(fr->IndexBufferSize * sizeof(ImDrawIdx), 4),
430
+ false
431
+ };
432
+ fr->IndexBuffer = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ib_desc);
433
+ if (!fr->IndexBuffer)
434
+ return;
435
+
436
+ fr->IndexBufferHost = new ImDrawIdx[fr->IndexBufferSize];
437
+ }
438
+
439
+ // Upload vertex/index data into a single contiguous GPU buffer
440
+ ImDrawVert* vtx_dst = (ImDrawVert*)fr->VertexBufferHost;
441
+ ImDrawIdx* idx_dst = (ImDrawIdx*)fr->IndexBufferHost;
442
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
443
+ {
444
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
445
+ memcpy(vtx_dst, draw_list->VtxBuffer.Data, draw_list->VtxBuffer.Size * sizeof(ImDrawVert));
446
+ memcpy(idx_dst, draw_list->IdxBuffer.Data, draw_list->IdxBuffer.Size * sizeof(ImDrawIdx));
447
+ vtx_dst += draw_list->VtxBuffer.Size;
448
+ idx_dst += draw_list->IdxBuffer.Size;
449
+ }
450
+ int64_t vb_write_size = MEMALIGN((char*)vtx_dst - (char*)fr->VertexBufferHost, 4);
451
+ int64_t ib_write_size = MEMALIGN((char*)idx_dst - (char*)fr->IndexBufferHost, 4);
452
+ wgpuQueueWriteBuffer(bd->defaultQueue, fr->VertexBuffer, 0, fr->VertexBufferHost, vb_write_size);
453
+ wgpuQueueWriteBuffer(bd->defaultQueue, fr->IndexBuffer, 0, fr->IndexBufferHost, ib_write_size);
454
+
455
+ // Setup desired render state
456
+ ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
457
+
458
+ // Setup render state structure (for callbacks and custom texture bindings)
459
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
460
+ ImGui_ImplWGPU_RenderState render_state;
461
+ render_state.Device = bd->wgpuDevice;
462
+ render_state.RenderPassEncoder = pass_encoder;
463
+ platform_io.Renderer_RenderState = &render_state;
464
+
465
+ // Render command lists
466
+ // (Because we merged all buffers into a single one, we maintain our own offset into them)
467
+ int global_vtx_offset = 0;
468
+ int global_idx_offset = 0;
469
+ ImVec2 clip_scale = draw_data->FramebufferScale;
470
+ ImVec2 clip_off = draw_data->DisplayPos;
471
+ for (int n = 0; n < draw_data->CmdListsCount; n++)
472
+ {
473
+ const ImDrawList* draw_list = draw_data->CmdLists[n];
474
+ for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
475
+ {
476
+ const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
477
+ if (pcmd->UserCallback != nullptr)
478
+ {
479
+ // User callback, registered via ImDrawList::AddCallback()
480
+ // (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
481
+ if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
482
+ ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
483
+ else
484
+ pcmd->UserCallback(draw_list, pcmd);
485
+ }
486
+ else
487
+ {
488
+ // Bind custom texture
489
+ ImTextureID tex_id = pcmd->GetTexID();
490
+ ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id));
491
+ auto bind_group = bd->renderResources.ImageBindGroups.GetVoidPtr(tex_id_hash);
492
+ if (bind_group)
493
+ {
494
+ wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, nullptr);
495
+ }
496
+ else
497
+ {
498
+ WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bd->renderResources.ImageBindGroupLayout, (WGPUTextureView)tex_id);
499
+ bd->renderResources.ImageBindGroups.SetVoidPtr(tex_id_hash, image_bind_group);
500
+ wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, image_bind_group, 0, nullptr);
501
+ }
502
+
503
+ // Project scissor/clipping rectangles into framebuffer space
504
+ ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
505
+ ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
506
+
507
+ // Clamp to viewport as wgpuRenderPassEncoderSetScissorRect() won't accept values that are off bounds
508
+ if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
509
+ if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
510
+ if (clip_max.x > fb_width) { clip_max.x = (float)fb_width; }
511
+ if (clip_max.y > fb_height) { clip_max.y = (float)fb_height; }
512
+ if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
513
+ continue;
514
+
515
+ // Apply scissor/clipping rectangle, Draw
516
+ wgpuRenderPassEncoderSetScissorRect(pass_encoder, (uint32_t)clip_min.x, (uint32_t)clip_min.y, (uint32_t)(clip_max.x - clip_min.x), (uint32_t)(clip_max.y - clip_min.y));
517
+ wgpuRenderPassEncoderDrawIndexed(pass_encoder, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
518
+ }
519
+ }
520
+ global_idx_offset += draw_list->IdxBuffer.Size;
521
+ global_vtx_offset += draw_list->VtxBuffer.Size;
522
+ }
523
+ platform_io.Renderer_RenderState = nullptr;
524
+ }
525
+
526
+ static void ImGui_ImplWGPU_CreateFontsTexture()
527
+ {
528
+ // Build texture atlas
529
+ ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
530
+ ImGuiIO& io = ImGui::GetIO();
531
+ unsigned char* pixels;
532
+ int width, height, size_pp;
533
+ io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &size_pp);
534
+
535
+ // Upload texture to graphics system
536
+ {
537
+ WGPUTextureDescriptor tex_desc = {};
538
+ #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
539
+ tex_desc.label = { "Dear ImGui Font Texture", WGPU_STRLEN };
540
+ #else
541
+ tex_desc.label = "Dear ImGui Font Texture";
542
+ #endif
543
+ tex_desc.dimension = WGPUTextureDimension_2D;
544
+ tex_desc.size.width = width;
545
+ tex_desc.size.height = height;
546
+ tex_desc.size.depthOrArrayLayers = 1;
547
+ tex_desc.sampleCount = 1;
548
+ tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
549
+ tex_desc.mipLevelCount = 1;
550
+ tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_TextureBinding;
551
+ bd->renderResources.FontTexture = wgpuDeviceCreateTexture(bd->wgpuDevice, &tex_desc);
552
+
553
+ WGPUTextureViewDescriptor tex_view_desc = {};
554
+ tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm;
555
+ tex_view_desc.dimension = WGPUTextureViewDimension_2D;
556
+ tex_view_desc.baseMipLevel = 0;
557
+ tex_view_desc.mipLevelCount = 1;
558
+ tex_view_desc.baseArrayLayer = 0;
559
+ tex_view_desc.arrayLayerCount = 1;
560
+ tex_view_desc.aspect = WGPUTextureAspect_All;
561
+ bd->renderResources.FontTextureView = wgpuTextureCreateView(bd->renderResources.FontTexture, &tex_view_desc);
562
+ }
563
+
564
+ // Upload texture data
565
+ {
566
+ WGPUImageCopyTexture dst_view = {};
567
+ dst_view.texture = bd->renderResources.FontTexture;
568
+ dst_view.mipLevel = 0;
569
+ dst_view.origin = { 0, 0, 0 };
570
+ dst_view.aspect = WGPUTextureAspect_All;
571
+ WGPUTextureDataLayout layout = {};
572
+ layout.offset = 0;
573
+ layout.bytesPerRow = width * size_pp;
574
+ layout.rowsPerImage = height;
575
+ WGPUExtent3D size = { (uint32_t)width, (uint32_t)height, 1 };
576
+ wgpuQueueWriteTexture(bd->defaultQueue, &dst_view, pixels, (uint32_t)(width * size_pp * height), &layout, &size);
577
+ }
578
+
579
+ // Create the associated sampler
580
+ // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
581
+ {
582
+ WGPUSamplerDescriptor sampler_desc = {};
583
+ sampler_desc.minFilter = WGPUFilterMode_Linear;
584
+ sampler_desc.magFilter = WGPUFilterMode_Linear;
585
+ sampler_desc.mipmapFilter = WGPUMipmapFilterMode_Linear;
586
+ sampler_desc.addressModeU = WGPUAddressMode_ClampToEdge;
587
+ sampler_desc.addressModeV = WGPUAddressMode_ClampToEdge;
588
+ sampler_desc.addressModeW = WGPUAddressMode_ClampToEdge;
589
+ sampler_desc.maxAnisotropy = 1;
590
+ bd->renderResources.Sampler = wgpuDeviceCreateSampler(bd->wgpuDevice, &sampler_desc);
591
+ }
592
+
593
+ // Store our identifier
594
+ static_assert(sizeof(ImTextureID) >= sizeof(bd->renderResources.FontTexture), "Can't pack descriptor handle into TexID, 32-bit not supported yet.");
595
+ io.Fonts->SetTexID((ImTextureID)bd->renderResources.FontTextureView);
596
+ }
597
+
598
+ static void ImGui_ImplWGPU_CreateUniformBuffer()
599
+ {
600
+ ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
601
+ WGPUBufferDescriptor ub_desc =
602
+ {
603
+ nullptr,
604
+ "Dear ImGui Uniform buffer",
605
+ #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
606
+ WGPU_STRLEN,
607
+ #endif
608
+ WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
609
+ MEMALIGN(sizeof(Uniforms), 16),
610
+ false
611
+ };
612
+ bd->renderResources.Uniforms = wgpuDeviceCreateBuffer(bd->wgpuDevice, &ub_desc);
613
+ }
614
+
615
+ bool ImGui_ImplWGPU_CreateDeviceObjects()
616
+ {
617
+ ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
618
+ if (!bd->wgpuDevice)
619
+ return false;
620
+ if (bd->pipelineState)
621
+ ImGui_ImplWGPU_InvalidateDeviceObjects();
622
+
623
+ // Create render pipeline
624
+ WGPURenderPipelineDescriptor graphics_pipeline_desc = {};
625
+ graphics_pipeline_desc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
626
+ graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
627
+ graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW;
628
+ graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None;
629
+ graphics_pipeline_desc.multisample = bd->initInfo.PipelineMultisampleState;
630
+
631
+ // Bind group layouts
632
+ WGPUBindGroupLayoutEntry common_bg_layout_entries[2] = {};
633
+ common_bg_layout_entries[0].binding = 0;
634
+ common_bg_layout_entries[0].visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment;
635
+ common_bg_layout_entries[0].buffer.type = WGPUBufferBindingType_Uniform;
636
+ common_bg_layout_entries[1].binding = 1;
637
+ common_bg_layout_entries[1].visibility = WGPUShaderStage_Fragment;
638
+ common_bg_layout_entries[1].sampler.type = WGPUSamplerBindingType_Filtering;
639
+
640
+ WGPUBindGroupLayoutEntry image_bg_layout_entries[1] = {};
641
+ image_bg_layout_entries[0].binding = 0;
642
+ image_bg_layout_entries[0].visibility = WGPUShaderStage_Fragment;
643
+ image_bg_layout_entries[0].texture.sampleType = WGPUTextureSampleType_Float;
644
+ image_bg_layout_entries[0].texture.viewDimension = WGPUTextureViewDimension_2D;
645
+
646
+ WGPUBindGroupLayoutDescriptor common_bg_layout_desc = {};
647
+ common_bg_layout_desc.entryCount = 2;
648
+ common_bg_layout_desc.entries = common_bg_layout_entries;
649
+
650
+ WGPUBindGroupLayoutDescriptor image_bg_layout_desc = {};
651
+ image_bg_layout_desc.entryCount = 1;
652
+ image_bg_layout_desc.entries = image_bg_layout_entries;
653
+
654
+ WGPUBindGroupLayout bg_layouts[2];
655
+ bg_layouts[0] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &common_bg_layout_desc);
656
+ bg_layouts[1] = wgpuDeviceCreateBindGroupLayout(bd->wgpuDevice, &image_bg_layout_desc);
657
+
658
+ WGPUPipelineLayoutDescriptor layout_desc = {};
659
+ layout_desc.bindGroupLayoutCount = 2;
660
+ layout_desc.bindGroupLayouts = bg_layouts;
661
+ graphics_pipeline_desc.layout = wgpuDeviceCreatePipelineLayout(bd->wgpuDevice, &layout_desc);
662
+
663
+ // Create the vertex shader
664
+ WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_vert_wgsl);
665
+ graphics_pipeline_desc.vertex.module = vertex_shader_desc.module;
666
+ graphics_pipeline_desc.vertex.entryPoint = vertex_shader_desc.entryPoint;
667
+
668
+ // Vertex input configuration
669
+ WGPUVertexAttribute attribute_desc[] =
670
+ {
671
+ { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, pos), 0 },
672
+ { WGPUVertexFormat_Float32x2, (uint64_t)offsetof(ImDrawVert, uv), 1 },
673
+ { WGPUVertexFormat_Unorm8x4, (uint64_t)offsetof(ImDrawVert, col), 2 },
674
+ };
675
+
676
+ WGPUVertexBufferLayout buffer_layouts[1];
677
+ buffer_layouts[0].arrayStride = sizeof(ImDrawVert);
678
+ buffer_layouts[0].stepMode = WGPUVertexStepMode_Vertex;
679
+ buffer_layouts[0].attributeCount = 3;
680
+ buffer_layouts[0].attributes = attribute_desc;
681
+
682
+ graphics_pipeline_desc.vertex.bufferCount = 1;
683
+ graphics_pipeline_desc.vertex.buffers = buffer_layouts;
684
+
685
+ // Create the pixel shader
686
+ WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__shader_frag_wgsl);
687
+
688
+ // Create the blending setup
689
+ WGPUBlendState blend_state = {};
690
+ blend_state.alpha.operation = WGPUBlendOperation_Add;
691
+ blend_state.alpha.srcFactor = WGPUBlendFactor_One;
692
+ blend_state.alpha.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
693
+ blend_state.color.operation = WGPUBlendOperation_Add;
694
+ blend_state.color.srcFactor = WGPUBlendFactor_SrcAlpha;
695
+ blend_state.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
696
+
697
+ WGPUColorTargetState color_state = {};
698
+ color_state.format = bd->renderTargetFormat;
699
+ color_state.blend = &blend_state;
700
+ color_state.writeMask = WGPUColorWriteMask_All;
701
+
702
+ WGPUFragmentState fragment_state = {};
703
+ fragment_state.module = pixel_shader_desc.module;
704
+ fragment_state.entryPoint = pixel_shader_desc.entryPoint;
705
+ fragment_state.targetCount = 1;
706
+ fragment_state.targets = &color_state;
707
+
708
+ graphics_pipeline_desc.fragment = &fragment_state;
709
+
710
+ // Create depth-stencil State
711
+ WGPUDepthStencilState depth_stencil_state = {};
712
+ depth_stencil_state.format = bd->depthStencilFormat;
713
+ #ifdef IMGUI_IMPL_WEBGPU_BACKEND_DAWN
714
+ depth_stencil_state.depthWriteEnabled = WGPUOptionalBool_False;
715
+ #else
716
+ depth_stencil_state.depthWriteEnabled = false;
717
+ #endif
718
+ depth_stencil_state.depthCompare = WGPUCompareFunction_Always;
719
+ depth_stencil_state.stencilFront.compare = WGPUCompareFunction_Always;
720
+ depth_stencil_state.stencilFront.failOp = WGPUStencilOperation_Keep;
721
+ depth_stencil_state.stencilFront.depthFailOp = WGPUStencilOperation_Keep;
722
+ depth_stencil_state.stencilFront.passOp = WGPUStencilOperation_Keep;
723
+ depth_stencil_state.stencilBack.compare = WGPUCompareFunction_Always;
724
+ depth_stencil_state.stencilBack.failOp = WGPUStencilOperation_Keep;
725
+ depth_stencil_state.stencilBack.depthFailOp = WGPUStencilOperation_Keep;
726
+ depth_stencil_state.stencilBack.passOp = WGPUStencilOperation_Keep;
727
+
728
+ // Configure disabled depth-stencil state
729
+ graphics_pipeline_desc.depthStencil = (bd->depthStencilFormat == WGPUTextureFormat_Undefined) ? nullptr : &depth_stencil_state;
730
+
731
+ bd->pipelineState = wgpuDeviceCreateRenderPipeline(bd->wgpuDevice, &graphics_pipeline_desc);
732
+
733
+ ImGui_ImplWGPU_CreateFontsTexture();
734
+ ImGui_ImplWGPU_CreateUniformBuffer();
735
+
736
+ // Create resource bind group
737
+ WGPUBindGroupEntry common_bg_entries[] =
738
+ {
739
+ { nullptr, 0, bd->renderResources.Uniforms, 0, MEMALIGN(sizeof(Uniforms), 16), 0, 0 },
740
+ { nullptr, 1, 0, 0, 0, bd->renderResources.Sampler, 0 },
741
+ };
742
+
743
+ WGPUBindGroupDescriptor common_bg_descriptor = {};
744
+ common_bg_descriptor.layout = bg_layouts[0];
745
+ common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry);
746
+ common_bg_descriptor.entries = common_bg_entries;
747
+ bd->renderResources.CommonBindGroup = wgpuDeviceCreateBindGroup(bd->wgpuDevice, &common_bg_descriptor);
748
+
749
+ WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bg_layouts[1], bd->renderResources.FontTextureView);
750
+ bd->renderResources.ImageBindGroup = image_bind_group;
751
+ bd->renderResources.ImageBindGroupLayout = bg_layouts[1];
752
+ bd->renderResources.ImageBindGroups.SetVoidPtr(ImHashData(&bd->renderResources.FontTextureView, sizeof(ImTextureID)), image_bind_group);
753
+
754
+ SafeRelease(vertex_shader_desc.module);
755
+ SafeRelease(pixel_shader_desc.module);
756
+ SafeRelease(graphics_pipeline_desc.layout);
757
+ SafeRelease(bg_layouts[0]);
758
+
759
+ return true;
760
+ }
761
+
762
+ void ImGui_ImplWGPU_InvalidateDeviceObjects()
763
+ {
764
+ ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
765
+ if (!bd->wgpuDevice)
766
+ return;
767
+
768
+ SafeRelease(bd->pipelineState);
769
+ SafeRelease(bd->renderResources);
770
+
771
+ ImGuiIO& io = ImGui::GetIO();
772
+ io.Fonts->SetTexID(0); // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
773
+
774
+ for (unsigned int i = 0; i < bd->numFramesInFlight; i++)
775
+ SafeRelease(bd->pFrameResources[i]);
776
+ }
777
+
778
+ bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info)
779
+ {
780
+ ImGuiIO& io = ImGui::GetIO();
781
+ IMGUI_CHECKVERSION();
782
+ IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
783
+
784
+ // Setup backend capabilities flags
785
+ ImGui_ImplWGPU_Data* bd = IM_NEW(ImGui_ImplWGPU_Data)();
786
+ io.BackendRendererUserData = (void*)bd;
787
+ #if defined(__EMSCRIPTEN__)
788
+ io.BackendRendererName = "imgui_impl_webgpu_emscripten";
789
+ #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
790
+ io.BackendRendererName = "imgui_impl_webgpu_dawn";
791
+ #elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
792
+ io.BackendRendererName = "imgui_impl_webgpu_wgpu";
793
+ #else
794
+ io.BackendRendererName = "imgui_impl_webgpu";
795
+ #endif
796
+ io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
797
+
798
+ bd->initInfo = *init_info;
799
+ bd->wgpuDevice = init_info->Device;
800
+ bd->defaultQueue = wgpuDeviceGetQueue(bd->wgpuDevice);
801
+ bd->renderTargetFormat = init_info->RenderTargetFormat;
802
+ bd->depthStencilFormat = init_info->DepthStencilFormat;
803
+ bd->numFramesInFlight = init_info->NumFramesInFlight;
804
+ bd->frameIndex = UINT_MAX;
805
+
806
+ bd->renderResources.FontTexture = nullptr;
807
+ bd->renderResources.FontTextureView = nullptr;
808
+ bd->renderResources.Sampler = nullptr;
809
+ bd->renderResources.Uniforms = nullptr;
810
+ bd->renderResources.CommonBindGroup = nullptr;
811
+ bd->renderResources.ImageBindGroups.Data.reserve(100);
812
+ bd->renderResources.ImageBindGroup = nullptr;
813
+ bd->renderResources.ImageBindGroupLayout = nullptr;
814
+
815
+ // Create buffers with a default size (they will later be grown as needed)
816
+ bd->pFrameResources = new FrameResources[bd->numFramesInFlight];
817
+ for (unsigned int i = 0; i < bd->numFramesInFlight; i++)
818
+ {
819
+ FrameResources* fr = &bd->pFrameResources[i];
820
+ fr->IndexBuffer = nullptr;
821
+ fr->VertexBuffer = nullptr;
822
+ fr->IndexBufferHost = nullptr;
823
+ fr->VertexBufferHost = nullptr;
824
+ fr->IndexBufferSize = 10000;
825
+ fr->VertexBufferSize = 5000;
826
+ }
827
+
828
+ return true;
829
+ }
830
+
831
+ void ImGui_ImplWGPU_Shutdown()
832
+ {
833
+ ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
834
+ IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
835
+ ImGuiIO& io = ImGui::GetIO();
836
+
837
+ ImGui_ImplWGPU_InvalidateDeviceObjects();
838
+ delete[] bd->pFrameResources;
839
+ bd->pFrameResources = nullptr;
840
+ wgpuQueueRelease(bd->defaultQueue);
841
+ bd->wgpuDevice = nullptr;
842
+ bd->numFramesInFlight = 0;
843
+ bd->frameIndex = UINT_MAX;
844
+
845
+ io.BackendRendererName = nullptr;
846
+ io.BackendRendererUserData = nullptr;
847
+ io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
848
+ IM_DELETE(bd);
849
+ }
850
+
851
+ void ImGui_ImplWGPU_NewFrame()
852
+ {
853
+ ImGui_ImplWGPU_Data* bd = ImGui_ImplWGPU_GetBackendData();
854
+ if (!bd->pipelineState)
855
+ ImGui_ImplWGPU_CreateDeviceObjects();
856
+ }
857
+
858
+ //-----------------------------------------------------------------------------
859
+
860
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_wgpu.h ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Renderer for WebGPU
2
+ // This needs to be used along with a Platform Binding (e.g. GLFW)
3
+ // (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.)
4
+
5
+ // Important note to dawn and/or wgpu users: when targeting native platforms (i.e. NOT emscripten),
6
+ // one of IMGUI_IMPL_WEBGPU_BACKEND_DAWN or IMGUI_IMPL_WEBGPU_BACKEND_WGPU must be provided.
7
+ // Add #define to your imconfig.h file, or as a compilation flag in your build system.
8
+ // This requirement will be removed once WebGPU stabilizes and backends converge on a unified interface.
9
+ //#define IMGUI_IMPL_WEBGPU_BACKEND_DAWN
10
+ //#define IMGUI_IMPL_WEBGPU_BACKEND_WGPU
11
+
12
+ // Implemented features:
13
+ // [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
14
+ // [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
15
+ // [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
16
+ // Missing features:
17
+ // [ ] Renderer: Multi-viewport support (multiple windows). Not meaningful on the web.
18
+
19
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
20
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
21
+ // Learn about Dear ImGui:
22
+ // - FAQ https://dearimgui.com/faq
23
+ // - Getting Started https://dearimgui.com/getting-started
24
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
25
+ // - Introduction, links and more at the top of imgui.cpp
26
+
27
+ #pragma once
28
+ #include "imgui.h" // IMGUI_IMPL_API
29
+ #ifndef IMGUI_DISABLE
30
+
31
+ #include <webgpu/webgpu.h>
32
+
33
+ // Initialization data, for ImGui_ImplWGPU_Init()
34
+ struct ImGui_ImplWGPU_InitInfo
35
+ {
36
+ WGPUDevice Device;
37
+ int NumFramesInFlight = 3;
38
+ WGPUTextureFormat RenderTargetFormat = WGPUTextureFormat_Undefined;
39
+ WGPUTextureFormat DepthStencilFormat = WGPUTextureFormat_Undefined;
40
+ WGPUMultisampleState PipelineMultisampleState = {};
41
+
42
+ ImGui_ImplWGPU_InitInfo()
43
+ {
44
+ PipelineMultisampleState.count = 1;
45
+ PipelineMultisampleState.mask = UINT32_MAX;
46
+ PipelineMultisampleState.alphaToCoverageEnabled = false;
47
+ }
48
+ };
49
+
50
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
51
+ IMGUI_IMPL_API bool ImGui_ImplWGPU_Init(ImGui_ImplWGPU_InitInfo* init_info);
52
+ IMGUI_IMPL_API void ImGui_ImplWGPU_Shutdown();
53
+ IMGUI_IMPL_API void ImGui_ImplWGPU_NewFrame();
54
+ IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder);
55
+
56
+ // Use if you want to reset your rendering device without losing Dear ImGui state.
57
+ IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects();
58
+ IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects();
59
+
60
+ // [BETA] Selected render state data shared with callbacks.
61
+ // This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplWGPU_RenderDrawData() call.
62
+ // (Please open an issue if you feel you need access to more data)
63
+ struct ImGui_ImplWGPU_RenderState
64
+ {
65
+ WGPUDevice Device;
66
+ WGPURenderPassEncoder RenderPassEncoder;
67
+ };
68
+
69
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_win32.cpp ADDED
@@ -0,0 +1,1419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications)
2
+ // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
3
+
4
+ // Implemented features:
5
+ // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
6
+ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
7
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values are obsolete since 1.87 and not supported since 1.91.5]
8
+ // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
9
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
10
+ // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
11
+
12
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
13
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
14
+ // Learn about Dear ImGui:
15
+ // - FAQ https://dearimgui.com/faq
16
+ // - Getting Started https://dearimgui.com/getting-started
17
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
18
+ // - Introduction, links and more at the top of imgui.cpp
19
+
20
+ // Configuration flags to add in your imconfig file:
21
+ //#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD // Disable gamepad support. This was meaningful before <1.81 but we now load XInput dynamically so the option is now less relevant.
22
+
23
+ // CHANGELOG
24
+ // (minor and older changes stripped away, please see git history for details)
25
+ // 2024-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
26
+ // 2024-11-21: [Docking] Fixed a crash when multiple processes are running with multi-viewports, caused by misusage of GetProp(). (#8162, #8069)
27
+ // 2024-10-28: [Docking] Rely on property stored inside HWND to retrieve context/viewport, should facilitate attempt to use this for parallel contexts. (#8069)
28
+ // 2024-09-16: [Docking] Inputs: fixed an issue where a viewport destroyed while clicking would hog mouse tracking and temporary lead to incorrect update of HoveredWindow. (#7971)
29
+ // 2024-07-08: Inputs: Fixed ImGuiMod_Super being mapped to VK_APPS instead of VK_LWIN||VK_RWIN. (#7768)
30
+ // 2023-10-05: Inputs: Added support for extra ImGuiKey values: F13 to F24 function keys, app back/forward keys.
31
+ // 2023-09-25: Inputs: Synthesize key-down event on key-up for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit it (same behavior as GLFW/SDL).
32
+ // 2023-09-07: Inputs: Added support for keyboard codepage conversion for when application is compiled in MBCS mode and using a non-Unicode window.
33
+ // 2023-04-19: Added ImGui_ImplWin32_InitForOpenGL() to facilitate combining raw Win32/Winapi with OpenGL. (#3218)
34
+ // 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen. (#2702)
35
+ // 2023-02-15: Inputs: Use WM_NCMOUSEMOVE / WM_NCMOUSELEAVE to track mouse position over non-client area (e.g. OS decorations) when app is not focused. (#6045, #6162)
36
+ // 2023-02-02: Inputs: Flipping WM_MOUSEHWHEEL (horizontal mouse-wheel) value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463)
37
+ // 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
38
+ // 2022-09-28: Inputs: Convert WM_CHAR values with MultiByteToWideChar() when window class was registered as MBCS (not Unicode).
39
+ // 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
40
+ // 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
41
+ // 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
42
+ // 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
43
+ // 2022-01-17: Inputs: always update key mods next and before a key event (not in NewFrame) to fix input queue with very low framerates.
44
+ // 2022-01-12: Inputs: Update mouse inputs using WM_MOUSEMOVE/WM_MOUSELEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass it to future input queue API.
45
+ // 2022-01-12: Inputs: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted.
46
+ // 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
47
+ // 2021-12-16: Inputs: Fill VK_LCONTROL/VK_RCONTROL/VK_LSHIFT/VK_RSHIFT/VK_LMENU/VK_RMENU for completeness.
48
+ // 2021-08-17: Calling io.AddFocusEvent() on WM_SETFOCUS/WM_KILLFOCUS messages.
49
+ // 2021-08-02: Inputs: Fixed keyboard modifiers being reported when host window doesn't have focus.
50
+ // 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using TrackMouseEvent() to receive WM_MOUSELEAVE events).
51
+ // 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
52
+ // 2021-06-08: Fixed ImGui_ImplWin32_EnableDpiAwareness() and ImGui_ImplWin32_GetDpiScaleForMonitor() to handle Windows 8.1/10 features without a manifest (per-monitor DPI, and properly calls SetProcessDpiAwareness() on 8.1).
53
+ // 2021-03-23: Inputs: Clearing keyboard down array when losing focus (WM_KILLFOCUS).
54
+ // 2021-02-18: Added ImGui_ImplWin32_EnableAlphaCompositing(). Non Visual Studio users will need to link with dwmapi.lib (MinGW/gcc: use -ldwmapi).
55
+ // 2021-02-17: Fixed ImGui_ImplWin32_EnableDpiAwareness() attempting to get SetProcessDpiAwareness from shcore.dll on Windows 8 whereas it is only supported on Windows 8.1.
56
+ // 2021-01-25: Inputs: Dynamically loading XInput DLL.
57
+ // 2020-12-04: Misc: Fixed setting of io.DisplaySize to invalid/uninitialized data when after hwnd has been closed.
58
+ // 2020-03-03: Inputs: Calling AddInputCharacterUTF16() to support surrogate pairs leading to codepoint >= 0x10000 (for more complete CJK inputs)
59
+ // 2020-02-17: Added ImGui_ImplWin32_EnableDpiAwareness(), ImGui_ImplWin32_GetDpiScaleForHwnd(), ImGui_ImplWin32_GetDpiScaleForMonitor() helper functions.
60
+ // 2020-01-14: Inputs: Added support for #define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD/IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT.
61
+ // 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
62
+ // 2019-05-11: Inputs: Don't filter value from WM_CHAR before calling AddInputCharacter().
63
+ // 2019-01-17: Misc: Using GetForegroundWindow()+IsChild() instead of GetActiveWindow() to be compatible with windows created in a different thread or parent.
64
+ // 2019-01-17: Inputs: Added support for mouse buttons 4 and 5 via WM_XBUTTON* messages.
65
+ // 2019-01-15: Inputs: Added support for XInput gamepads (if ImGuiConfigFlags_NavEnableGamepad is set by user application).
66
+ // 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
67
+ // 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
68
+ // 2018-06-10: Inputs: Fixed handling of mouse wheel messages to support fine position messages (typically sent by track-pads).
69
+ // 2018-06-08: Misc: Extracted imgui_impl_win32.cpp/.h away from the old combined DX9/DX10/DX11/DX12 examples.
70
+ // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag.
71
+ // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling).
72
+ // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
73
+ // 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set).
74
+ // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
75
+ // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
76
+ // 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert.
77
+ // 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag.
78
+ // 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read.
79
+ // 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging.
80
+ // 2016-11-12: Inputs: Only call Win32 ::SetCursor(nullptr) when io.MouseDrawCursor is set.
81
+
82
+ #include "imgui.h"
83
+ #ifndef IMGUI_DISABLE
84
+ #include "imgui_impl_win32.h"
85
+ #ifndef WIN32_LEAN_AND_MEAN
86
+ #define WIN32_LEAN_AND_MEAN
87
+ #endif
88
+ #include <windows.h>
89
+ #include <windowsx.h> // GET_X_LPARAM(), GET_Y_LPARAM()
90
+ #include <tchar.h>
91
+ #include <dwmapi.h>
92
+
93
+ // Using XInput for gamepad (will load DLL dynamically)
94
+ #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
95
+ #include <xinput.h>
96
+ typedef DWORD(WINAPI* PFN_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*);
97
+ typedef DWORD(WINAPI* PFN_XInputGetState)(DWORD, XINPUT_STATE*);
98
+ #endif
99
+
100
+ // Clang/GCC warnings with -Weverything
101
+ #if defined(__clang__)
102
+ #pragma clang diagnostic push
103
+ #pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
104
+ #endif
105
+ #if defined(__GNUC__)
106
+ #pragma GCC diagnostic push
107
+ #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
108
+ #pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
109
+ #endif
110
+
111
+ // Forward Declarations
112
+ static void ImGui_ImplWin32_InitMultiViewportSupport(bool platform_has_own_dc);
113
+ static void ImGui_ImplWin32_ShutdownMultiViewportSupport();
114
+ static void ImGui_ImplWin32_UpdateMonitors();
115
+
116
+ struct ImGui_ImplWin32_Data
117
+ {
118
+ HWND hWnd;
119
+ HWND MouseHwnd;
120
+ int MouseTrackedArea; // 0: not tracked, 1: client area, 2: non-client area
121
+ int MouseButtonsDown;
122
+ INT64 Time;
123
+ INT64 TicksPerSecond;
124
+ ImGuiMouseCursor LastMouseCursor;
125
+ UINT32 KeyboardCodePage;
126
+ bool WantUpdateMonitors;
127
+
128
+ #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
129
+ bool HasGamepad;
130
+ bool WantUpdateHasGamepad;
131
+ HMODULE XInputDLL;
132
+ PFN_XInputGetCapabilities XInputGetCapabilities;
133
+ PFN_XInputGetState XInputGetState;
134
+ #endif
135
+
136
+ ImGui_ImplWin32_Data() { memset((void*)this, 0, sizeof(*this)); }
137
+ };
138
+
139
+ // Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
140
+ // It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
141
+ // FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
142
+ // FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
143
+ static ImGui_ImplWin32_Data* ImGui_ImplWin32_GetBackendData()
144
+ {
145
+ return ImGui::GetCurrentContext() ? (ImGui_ImplWin32_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
146
+ }
147
+ static ImGui_ImplWin32_Data* ImGui_ImplWin32_GetBackendData(ImGuiIO& io)
148
+ {
149
+ return (ImGui_ImplWin32_Data*)io.BackendPlatformUserData;
150
+ }
151
+
152
+ // Functions
153
+ static void ImGui_ImplWin32_UpdateKeyboardCodePage(ImGuiIO& io)
154
+ {
155
+ // Retrieve keyboard code page, required for handling of non-Unicode Windows.
156
+ ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(io);
157
+ HKL keyboard_layout = ::GetKeyboardLayout(0);
158
+ LCID keyboard_lcid = MAKELCID(HIWORD(keyboard_layout), SORT_DEFAULT);
159
+ if (::GetLocaleInfoA(keyboard_lcid, (LOCALE_RETURN_NUMBER | LOCALE_IDEFAULTANSICODEPAGE), (LPSTR)&bd->KeyboardCodePage, sizeof(bd->KeyboardCodePage)) == 0)
160
+ bd->KeyboardCodePage = CP_ACP; // Fallback to default ANSI code page when fails.
161
+ }
162
+
163
+ static bool ImGui_ImplWin32_InitEx(void* hwnd, bool platform_has_own_dc)
164
+ {
165
+ ImGuiIO& io = ImGui::GetIO();
166
+ IMGUI_CHECKVERSION();
167
+ IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
168
+
169
+ INT64 perf_frequency, perf_counter;
170
+ if (!::QueryPerformanceFrequency((LARGE_INTEGER*)&perf_frequency))
171
+ return false;
172
+ if (!::QueryPerformanceCounter((LARGE_INTEGER*)&perf_counter))
173
+ return false;
174
+
175
+ // Setup backend capabilities flags
176
+ ImGui_ImplWin32_Data* bd = IM_NEW(ImGui_ImplWin32_Data)();
177
+ io.BackendPlatformUserData = (void*)bd;
178
+ io.BackendPlatformName = "imgui_impl_win32";
179
+ io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
180
+ io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
181
+ io.BackendFlags |= ImGuiBackendFlags_PlatformHasViewports; // We can create multi-viewports on the Platform side (optional)
182
+ io.BackendFlags |= ImGuiBackendFlags_HasMouseHoveredViewport; // We can call io.AddMouseViewportEvent() with correct data (optional)
183
+
184
+ bd->hWnd = (HWND)hwnd;
185
+ bd->TicksPerSecond = perf_frequency;
186
+ bd->Time = perf_counter;
187
+ bd->LastMouseCursor = ImGuiMouseCursor_COUNT;
188
+ ImGui_ImplWin32_UpdateKeyboardCodePage(io);
189
+
190
+ // Update monitor a first time during init
191
+ ImGui_ImplWin32_UpdateMonitors();
192
+
193
+ // Our mouse update function expect PlatformHandle to be filled for the main viewport
194
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
195
+ main_viewport->PlatformHandle = main_viewport->PlatformHandleRaw = (void*)bd->hWnd;
196
+
197
+ // Be aware that GetPropA()/SetPropA() may be accessed from other processes.
198
+ // So as we store a pointer in IMGUI_CONTEXT we need to make sure we only call GetPropA() on windows owned by our process.
199
+ ::SetPropA(bd->hWnd, "IMGUI_CONTEXT", ImGui::GetCurrentContext());
200
+ ImGui_ImplWin32_InitMultiViewportSupport(platform_has_own_dc);
201
+
202
+ // Dynamically load XInput library
203
+ #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
204
+ bd->WantUpdateHasGamepad = true;
205
+ const char* xinput_dll_names[] =
206
+ {
207
+ "xinput1_4.dll", // Windows 8+
208
+ "xinput1_3.dll", // DirectX SDK
209
+ "xinput9_1_0.dll", // Windows Vista, Windows 7
210
+ "xinput1_2.dll", // DirectX SDK
211
+ "xinput1_1.dll" // DirectX SDK
212
+ };
213
+ for (int n = 0; n < IM_ARRAYSIZE(xinput_dll_names); n++)
214
+ if (HMODULE dll = ::LoadLibraryA(xinput_dll_names[n]))
215
+ {
216
+ bd->XInputDLL = dll;
217
+ bd->XInputGetCapabilities = (PFN_XInputGetCapabilities)::GetProcAddress(dll, "XInputGetCapabilities");
218
+ bd->XInputGetState = (PFN_XInputGetState)::GetProcAddress(dll, "XInputGetState");
219
+ break;
220
+ }
221
+ #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
222
+
223
+ return true;
224
+ }
225
+
226
+ IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd)
227
+ {
228
+ return ImGui_ImplWin32_InitEx(hwnd, false);
229
+ }
230
+
231
+ IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd)
232
+ {
233
+ // OpenGL needs CS_OWNDC
234
+ return ImGui_ImplWin32_InitEx(hwnd, true);
235
+ }
236
+
237
+ void ImGui_ImplWin32_Shutdown()
238
+ {
239
+ ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
240
+ IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
241
+ ImGuiIO& io = ImGui::GetIO();
242
+
243
+ ::SetPropA(bd->hWnd, "IMGUI_CONTEXT", nullptr);
244
+ ImGui_ImplWin32_ShutdownMultiViewportSupport();
245
+
246
+ // Unload XInput library
247
+ #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
248
+ if (bd->XInputDLL)
249
+ ::FreeLibrary(bd->XInputDLL);
250
+ #endif // IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
251
+
252
+ io.BackendPlatformName = nullptr;
253
+ io.BackendPlatformUserData = nullptr;
254
+ io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_PlatformHasViewports | ImGuiBackendFlags_HasMouseHoveredViewport);
255
+ IM_DELETE(bd);
256
+ }
257
+
258
+ static bool ImGui_ImplWin32_UpdateMouseCursor(ImGuiIO& io, ImGuiMouseCursor imgui_cursor)
259
+ {
260
+ if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
261
+ return false;
262
+
263
+ if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
264
+ {
265
+ // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
266
+ ::SetCursor(nullptr);
267
+ }
268
+ else
269
+ {
270
+ // Show OS mouse cursor
271
+ LPTSTR win32_cursor = IDC_ARROW;
272
+ switch (imgui_cursor)
273
+ {
274
+ case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break;
275
+ case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break;
276
+ case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break;
277
+ case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break;
278
+ case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break;
279
+ case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break;
280
+ case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break;
281
+ case ImGuiMouseCursor_Hand: win32_cursor = IDC_HAND; break;
282
+ case ImGuiMouseCursor_NotAllowed: win32_cursor = IDC_NO; break;
283
+ }
284
+ ::SetCursor(::LoadCursor(nullptr, win32_cursor));
285
+ }
286
+ return true;
287
+ }
288
+
289
+ static bool IsVkDown(int vk)
290
+ {
291
+ return (::GetKeyState(vk) & 0x8000) != 0;
292
+ }
293
+
294
+ static void ImGui_ImplWin32_AddKeyEvent(ImGuiIO& io, ImGuiKey key, bool down, int native_keycode, int native_scancode = -1)
295
+ {
296
+ io.AddKeyEvent(key, down);
297
+ io.SetKeyEventNativeData(key, native_keycode, native_scancode); // To support legacy indexing (<1.87 user code)
298
+ IM_UNUSED(native_scancode);
299
+ }
300
+
301
+ static void ImGui_ImplWin32_ProcessKeyEventsWorkarounds(ImGuiIO& io)
302
+ {
303
+ // Left & right Shift keys: when both are pressed together, Windows tend to not generate the WM_KEYUP event for the first released one.
304
+ if (ImGui::IsKeyDown(ImGuiKey_LeftShift) && !IsVkDown(VK_LSHIFT))
305
+ ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_LeftShift, false, VK_LSHIFT);
306
+ if (ImGui::IsKeyDown(ImGuiKey_RightShift) && !IsVkDown(VK_RSHIFT))
307
+ ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_RightShift, false, VK_RSHIFT);
308
+
309
+ // Sometimes WM_KEYUP for Win key is not passed down to the app (e.g. for Win+V on some setups, according to GLFW).
310
+ if (ImGui::IsKeyDown(ImGuiKey_LeftSuper) && !IsVkDown(VK_LWIN))
311
+ ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_LeftSuper, false, VK_LWIN);
312
+ if (ImGui::IsKeyDown(ImGuiKey_RightSuper) && !IsVkDown(VK_RWIN))
313
+ ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_RightSuper, false, VK_RWIN);
314
+ }
315
+
316
+ static void ImGui_ImplWin32_UpdateKeyModifiers(ImGuiIO& io)
317
+ {
318
+ io.AddKeyEvent(ImGuiMod_Ctrl, IsVkDown(VK_CONTROL));
319
+ io.AddKeyEvent(ImGuiMod_Shift, IsVkDown(VK_SHIFT));
320
+ io.AddKeyEvent(ImGuiMod_Alt, IsVkDown(VK_MENU));
321
+ io.AddKeyEvent(ImGuiMod_Super, IsVkDown(VK_LWIN) || IsVkDown(VK_RWIN));
322
+ }
323
+
324
+ static ImGuiViewport* ImGui_ImplWin32_FindViewportByPlatformHandle(ImGuiPlatformIO& platform_io, HWND hwnd)
325
+ {
326
+ // We cannot use ImGui::FindViewportByPlatformHandle() because it doesn't take a context.
327
+ // When called from ImGui_ImplWin32_WndProcHandler_PlatformWindow() we don't assume that context is bound.
328
+ //return ImGui::FindViewportByPlatformHandle((void*)hwnd);
329
+ for (ImGuiViewport* viewport : platform_io.Viewports)
330
+ if (viewport->PlatformHandle == hwnd)
331
+ return viewport;
332
+ return nullptr;
333
+ }
334
+
335
+ // This code supports multi-viewports (multiple OS Windows mapped into different Dear ImGui viewports)
336
+ // Because of that, it is a little more complicated than your typical single-viewport binding code!
337
+ static void ImGui_ImplWin32_UpdateMouseData(ImGuiIO& io, ImGuiPlatformIO& platform_io)
338
+ {
339
+ ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(io);
340
+ IM_ASSERT(bd->hWnd != 0);
341
+
342
+ POINT mouse_screen_pos;
343
+ bool has_mouse_screen_pos = ::GetCursorPos(&mouse_screen_pos) != 0;
344
+
345
+ HWND focused_window = ::GetForegroundWindow();
346
+ const bool is_app_focused = (focused_window && (focused_window == bd->hWnd || ::IsChild(focused_window, bd->hWnd) || ImGui_ImplWin32_FindViewportByPlatformHandle(platform_io, focused_window)));
347
+ if (is_app_focused)
348
+ {
349
+ // (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when io.ConfigNavMoveSetMousePos is enabled by user)
350
+ // When multi-viewports are enabled, all Dear ImGui positions are same as OS positions.
351
+ if (io.WantSetMousePos)
352
+ {
353
+ POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y };
354
+ if ((io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) == 0)
355
+ ::ClientToScreen(focused_window, &pos);
356
+ ::SetCursorPos(pos.x, pos.y);
357
+ }
358
+
359
+ // (Optional) Fallback to provide mouse position when focused (WM_MOUSEMOVE already provides this when hovered or captured)
360
+ // This also fills a short gap when clicking non-client area: WM_NCMOUSELEAVE -> modal OS move -> gap -> WM_NCMOUSEMOVE
361
+ if (!io.WantSetMousePos && bd->MouseTrackedArea == 0 && has_mouse_screen_pos)
362
+ {
363
+ // Single viewport mode: mouse position in client window coordinates (io.MousePos is (0,0) when the mouse is on the upper-left corner of the app window)
364
+ // (This is the position you can get with ::GetCursorPos() + ::ScreenToClient() or WM_MOUSEMOVE.)
365
+ // Multi-viewport mode: mouse position in OS absolute coordinates (io.MousePos is (0,0) when the mouse is on the upper-left of the primary monitor)
366
+ // (This is the position you can get with ::GetCursorPos() or WM_MOUSEMOVE + ::ClientToScreen(). In theory adding viewport->Pos to a client position would also be the same.)
367
+ POINT mouse_pos = mouse_screen_pos;
368
+ if (!(io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable))
369
+ ::ScreenToClient(bd->hWnd, &mouse_pos);
370
+ io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y);
371
+ }
372
+ }
373
+
374
+ // (Optional) When using multiple viewports: call io.AddMouseViewportEvent() with the viewport the OS mouse cursor is hovering.
375
+ // If ImGuiBackendFlags_HasMouseHoveredViewport is not set by the backend, Dear imGui will ignore this field and infer the information using its flawed heuristic.
376
+ // - [X] Win32 backend correctly ignore viewports with the _NoInputs flag (here using ::WindowFromPoint with WM_NCHITTEST + HTTRANSPARENT in WndProc does that)
377
+ // Some backend are not able to handle that correctly. If a backend report an hovered viewport that has the _NoInputs flag (e.g. when dragging a window
378
+ // for docking, the viewport has the _NoInputs flag in order to allow us to find the viewport under), then Dear ImGui is forced to ignore the value reported
379
+ // by the backend, and use its flawed heuristic to guess the viewport behind.
380
+ // - [X] Win32 backend correctly reports this regardless of another viewport behind focused and dragged from (we need this to find a useful drag and drop target).
381
+ ImGuiID mouse_viewport_id = 0;
382
+ if (has_mouse_screen_pos)
383
+ if (HWND hovered_hwnd = ::WindowFromPoint(mouse_screen_pos))
384
+ if (ImGuiViewport* viewport = ImGui_ImplWin32_FindViewportByPlatformHandle(platform_io, hovered_hwnd))
385
+ mouse_viewport_id = viewport->ID;
386
+ io.AddMouseViewportEvent(mouse_viewport_id);
387
+ }
388
+
389
+ // Gamepad navigation mapping
390
+ static void ImGui_ImplWin32_UpdateGamepads(ImGuiIO& io)
391
+ {
392
+ #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
393
+ ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(io);
394
+ //if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
395
+ // return;
396
+
397
+ // Calling XInputGetState() every frame on disconnected gamepads is unfortunately too slow.
398
+ // Instead we refresh gamepad availability by calling XInputGetCapabilities() _only_ after receiving WM_DEVICECHANGE.
399
+ if (bd->WantUpdateHasGamepad)
400
+ {
401
+ XINPUT_CAPABILITIES caps = {};
402
+ bd->HasGamepad = bd->XInputGetCapabilities ? (bd->XInputGetCapabilities(0, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS) : false;
403
+ bd->WantUpdateHasGamepad = false;
404
+ }
405
+
406
+ io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
407
+ XINPUT_STATE xinput_state;
408
+ XINPUT_GAMEPAD& gamepad = xinput_state.Gamepad;
409
+ if (!bd->HasGamepad || bd->XInputGetState == nullptr || bd->XInputGetState(0, &xinput_state) != ERROR_SUCCESS)
410
+ return;
411
+ io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
412
+
413
+ #define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V)
414
+ #define MAP_BUTTON(KEY_NO, BUTTON_ENUM) { io.AddKeyEvent(KEY_NO, (gamepad.wButtons & BUTTON_ENUM) != 0); }
415
+ #define MAP_ANALOG(KEY_NO, VALUE, V0, V1) { float vn = (float)(VALUE - V0) / (float)(V1 - V0); io.AddKeyAnalogEvent(KEY_NO, vn > 0.10f, IM_SATURATE(vn)); }
416
+ MAP_BUTTON(ImGuiKey_GamepadStart, XINPUT_GAMEPAD_START);
417
+ MAP_BUTTON(ImGuiKey_GamepadBack, XINPUT_GAMEPAD_BACK);
418
+ MAP_BUTTON(ImGuiKey_GamepadFaceLeft, XINPUT_GAMEPAD_X);
419
+ MAP_BUTTON(ImGuiKey_GamepadFaceRight, XINPUT_GAMEPAD_B);
420
+ MAP_BUTTON(ImGuiKey_GamepadFaceUp, XINPUT_GAMEPAD_Y);
421
+ MAP_BUTTON(ImGuiKey_GamepadFaceDown, XINPUT_GAMEPAD_A);
422
+ MAP_BUTTON(ImGuiKey_GamepadDpadLeft, XINPUT_GAMEPAD_DPAD_LEFT);
423
+ MAP_BUTTON(ImGuiKey_GamepadDpadRight, XINPUT_GAMEPAD_DPAD_RIGHT);
424
+ MAP_BUTTON(ImGuiKey_GamepadDpadUp, XINPUT_GAMEPAD_DPAD_UP);
425
+ MAP_BUTTON(ImGuiKey_GamepadDpadDown, XINPUT_GAMEPAD_DPAD_DOWN);
426
+ MAP_BUTTON(ImGuiKey_GamepadL1, XINPUT_GAMEPAD_LEFT_SHOULDER);
427
+ MAP_BUTTON(ImGuiKey_GamepadR1, XINPUT_GAMEPAD_RIGHT_SHOULDER);
428
+ MAP_ANALOG(ImGuiKey_GamepadL2, gamepad.bLeftTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255);
429
+ MAP_ANALOG(ImGuiKey_GamepadR2, gamepad.bRightTrigger, XINPUT_GAMEPAD_TRIGGER_THRESHOLD, 255);
430
+ MAP_BUTTON(ImGuiKey_GamepadL3, XINPUT_GAMEPAD_LEFT_THUMB);
431
+ MAP_BUTTON(ImGuiKey_GamepadR3, XINPUT_GAMEPAD_RIGHT_THUMB);
432
+ MAP_ANALOG(ImGuiKey_GamepadLStickLeft, gamepad.sThumbLX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
433
+ MAP_ANALOG(ImGuiKey_GamepadLStickRight, gamepad.sThumbLX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
434
+ MAP_ANALOG(ImGuiKey_GamepadLStickUp, gamepad.sThumbLY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
435
+ MAP_ANALOG(ImGuiKey_GamepadLStickDown, gamepad.sThumbLY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
436
+ MAP_ANALOG(ImGuiKey_GamepadRStickLeft, gamepad.sThumbRX, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
437
+ MAP_ANALOG(ImGuiKey_GamepadRStickRight, gamepad.sThumbRX, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
438
+ MAP_ANALOG(ImGuiKey_GamepadRStickUp, gamepad.sThumbRY, +XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, +32767);
439
+ MAP_ANALOG(ImGuiKey_GamepadRStickDown, gamepad.sThumbRY, -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE, -32768);
440
+ #undef MAP_BUTTON
441
+ #undef MAP_ANALOG
442
+ #else // #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
443
+ IM_UNUSED(io);
444
+ #endif
445
+ }
446
+
447
+ static BOOL CALLBACK ImGui_ImplWin32_UpdateMonitors_EnumFunc(HMONITOR monitor, HDC, LPRECT, LPARAM)
448
+ {
449
+ MONITORINFO info = {};
450
+ info.cbSize = sizeof(MONITORINFO);
451
+ if (!::GetMonitorInfo(monitor, &info))
452
+ return TRUE;
453
+ ImGuiPlatformMonitor imgui_monitor;
454
+ imgui_monitor.MainPos = ImVec2((float)info.rcMonitor.left, (float)info.rcMonitor.top);
455
+ imgui_monitor.MainSize = ImVec2((float)(info.rcMonitor.right - info.rcMonitor.left), (float)(info.rcMonitor.bottom - info.rcMonitor.top));
456
+ imgui_monitor.WorkPos = ImVec2((float)info.rcWork.left, (float)info.rcWork.top);
457
+ imgui_monitor.WorkSize = ImVec2((float)(info.rcWork.right - info.rcWork.left), (float)(info.rcWork.bottom - info.rcWork.top));
458
+ imgui_monitor.DpiScale = ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
459
+ imgui_monitor.PlatformHandle = (void*)monitor;
460
+ if (imgui_monitor.DpiScale <= 0.0f)
461
+ return TRUE; // Some accessibility applications are declaring virtual monitors with a DPI of 0, see #7902.
462
+ ImGuiPlatformIO& io = ImGui::GetPlatformIO();
463
+ if (info.dwFlags & MONITORINFOF_PRIMARY)
464
+ io.Monitors.push_front(imgui_monitor);
465
+ else
466
+ io.Monitors.push_back(imgui_monitor);
467
+ return TRUE;
468
+ }
469
+
470
+ static void ImGui_ImplWin32_UpdateMonitors()
471
+ {
472
+ ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
473
+ ImGui::GetPlatformIO().Monitors.resize(0);
474
+ ::EnumDisplayMonitors(nullptr, nullptr, ImGui_ImplWin32_UpdateMonitors_EnumFunc, 0);
475
+ bd->WantUpdateMonitors = false;
476
+ }
477
+
478
+ void ImGui_ImplWin32_NewFrame()
479
+ {
480
+ ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
481
+ IM_ASSERT(bd != nullptr && "Context or backend not initialized? Did you call ImGui_ImplWin32_Init()?");
482
+ ImGuiIO& io = ImGui::GetIO();
483
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
484
+
485
+ // Setup display size (every frame to accommodate for window resizing)
486
+ RECT rect = { 0, 0, 0, 0 };
487
+ ::GetClientRect(bd->hWnd, &rect);
488
+ io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top));
489
+ if (bd->WantUpdateMonitors)
490
+ ImGui_ImplWin32_UpdateMonitors();
491
+
492
+ // Setup time step
493
+ INT64 current_time = 0;
494
+ ::QueryPerformanceCounter((LARGE_INTEGER*)&current_time);
495
+ io.DeltaTime = (float)(current_time - bd->Time) / bd->TicksPerSecond;
496
+ bd->Time = current_time;
497
+
498
+ // Update OS mouse position
499
+ ImGui_ImplWin32_UpdateMouseData(io, platform_io);
500
+
501
+ // Process workarounds for known Windows key handling issues
502
+ ImGui_ImplWin32_ProcessKeyEventsWorkarounds(io);
503
+
504
+ // Update OS mouse cursor with the cursor requested by imgui
505
+ ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
506
+ if (bd->LastMouseCursor != mouse_cursor)
507
+ {
508
+ bd->LastMouseCursor = mouse_cursor;
509
+ ImGui_ImplWin32_UpdateMouseCursor(io, mouse_cursor);
510
+ }
511
+
512
+ // Update game controllers (if enabled and available)
513
+ ImGui_ImplWin32_UpdateGamepads(io);
514
+ }
515
+
516
+ // Map VK_xxx to ImGuiKey_xxx.
517
+ // Not static to allow third-party code to use that if they want to (but undocumented)
518
+ ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam);
519
+ ImGuiKey ImGui_ImplWin32_KeyEventToImGuiKey(WPARAM wParam, LPARAM lParam)
520
+ {
521
+ // There is no distinct VK_xxx for keypad enter, instead it is VK_RETURN + KF_EXTENDED.
522
+ if ((wParam == VK_RETURN) && (HIWORD(lParam) & KF_EXTENDED))
523
+ return ImGuiKey_KeypadEnter;
524
+
525
+ switch (wParam)
526
+ {
527
+ case VK_TAB: return ImGuiKey_Tab;
528
+ case VK_LEFT: return ImGuiKey_LeftArrow;
529
+ case VK_RIGHT: return ImGuiKey_RightArrow;
530
+ case VK_UP: return ImGuiKey_UpArrow;
531
+ case VK_DOWN: return ImGuiKey_DownArrow;
532
+ case VK_PRIOR: return ImGuiKey_PageUp;
533
+ case VK_NEXT: return ImGuiKey_PageDown;
534
+ case VK_HOME: return ImGuiKey_Home;
535
+ case VK_END: return ImGuiKey_End;
536
+ case VK_INSERT: return ImGuiKey_Insert;
537
+ case VK_DELETE: return ImGuiKey_Delete;
538
+ case VK_BACK: return ImGuiKey_Backspace;
539
+ case VK_SPACE: return ImGuiKey_Space;
540
+ case VK_RETURN: return ImGuiKey_Enter;
541
+ case VK_ESCAPE: return ImGuiKey_Escape;
542
+ case VK_OEM_7: return ImGuiKey_Apostrophe;
543
+ case VK_OEM_COMMA: return ImGuiKey_Comma;
544
+ case VK_OEM_MINUS: return ImGuiKey_Minus;
545
+ case VK_OEM_PERIOD: return ImGuiKey_Period;
546
+ case VK_OEM_2: return ImGuiKey_Slash;
547
+ case VK_OEM_1: return ImGuiKey_Semicolon;
548
+ case VK_OEM_PLUS: return ImGuiKey_Equal;
549
+ case VK_OEM_4: return ImGuiKey_LeftBracket;
550
+ case VK_OEM_5: return ImGuiKey_Backslash;
551
+ case VK_OEM_6: return ImGuiKey_RightBracket;
552
+ case VK_OEM_3: return ImGuiKey_GraveAccent;
553
+ case VK_CAPITAL: return ImGuiKey_CapsLock;
554
+ case VK_SCROLL: return ImGuiKey_ScrollLock;
555
+ case VK_NUMLOCK: return ImGuiKey_NumLock;
556
+ case VK_SNAPSHOT: return ImGuiKey_PrintScreen;
557
+ case VK_PAUSE: return ImGuiKey_Pause;
558
+ case VK_NUMPAD0: return ImGuiKey_Keypad0;
559
+ case VK_NUMPAD1: return ImGuiKey_Keypad1;
560
+ case VK_NUMPAD2: return ImGuiKey_Keypad2;
561
+ case VK_NUMPAD3: return ImGuiKey_Keypad3;
562
+ case VK_NUMPAD4: return ImGuiKey_Keypad4;
563
+ case VK_NUMPAD5: return ImGuiKey_Keypad5;
564
+ case VK_NUMPAD6: return ImGuiKey_Keypad6;
565
+ case VK_NUMPAD7: return ImGuiKey_Keypad7;
566
+ case VK_NUMPAD8: return ImGuiKey_Keypad8;
567
+ case VK_NUMPAD9: return ImGuiKey_Keypad9;
568
+ case VK_DECIMAL: return ImGuiKey_KeypadDecimal;
569
+ case VK_DIVIDE: return ImGuiKey_KeypadDivide;
570
+ case VK_MULTIPLY: return ImGuiKey_KeypadMultiply;
571
+ case VK_SUBTRACT: return ImGuiKey_KeypadSubtract;
572
+ case VK_ADD: return ImGuiKey_KeypadAdd;
573
+ case VK_LSHIFT: return ImGuiKey_LeftShift;
574
+ case VK_LCONTROL: return ImGuiKey_LeftCtrl;
575
+ case VK_LMENU: return ImGuiKey_LeftAlt;
576
+ case VK_LWIN: return ImGuiKey_LeftSuper;
577
+ case VK_RSHIFT: return ImGuiKey_RightShift;
578
+ case VK_RCONTROL: return ImGuiKey_RightCtrl;
579
+ case VK_RMENU: return ImGuiKey_RightAlt;
580
+ case VK_RWIN: return ImGuiKey_RightSuper;
581
+ case VK_APPS: return ImGuiKey_Menu;
582
+ case '0': return ImGuiKey_0;
583
+ case '1': return ImGuiKey_1;
584
+ case '2': return ImGuiKey_2;
585
+ case '3': return ImGuiKey_3;
586
+ case '4': return ImGuiKey_4;
587
+ case '5': return ImGuiKey_5;
588
+ case '6': return ImGuiKey_6;
589
+ case '7': return ImGuiKey_7;
590
+ case '8': return ImGuiKey_8;
591
+ case '9': return ImGuiKey_9;
592
+ case 'A': return ImGuiKey_A;
593
+ case 'B': return ImGuiKey_B;
594
+ case 'C': return ImGuiKey_C;
595
+ case 'D': return ImGuiKey_D;
596
+ case 'E': return ImGuiKey_E;
597
+ case 'F': return ImGuiKey_F;
598
+ case 'G': return ImGuiKey_G;
599
+ case 'H': return ImGuiKey_H;
600
+ case 'I': return ImGuiKey_I;
601
+ case 'J': return ImGuiKey_J;
602
+ case 'K': return ImGuiKey_K;
603
+ case 'L': return ImGuiKey_L;
604
+ case 'M': return ImGuiKey_M;
605
+ case 'N': return ImGuiKey_N;
606
+ case 'O': return ImGuiKey_O;
607
+ case 'P': return ImGuiKey_P;
608
+ case 'Q': return ImGuiKey_Q;
609
+ case 'R': return ImGuiKey_R;
610
+ case 'S': return ImGuiKey_S;
611
+ case 'T': return ImGuiKey_T;
612
+ case 'U': return ImGuiKey_U;
613
+ case 'V': return ImGuiKey_V;
614
+ case 'W': return ImGuiKey_W;
615
+ case 'X': return ImGuiKey_X;
616
+ case 'Y': return ImGuiKey_Y;
617
+ case 'Z': return ImGuiKey_Z;
618
+ case VK_F1: return ImGuiKey_F1;
619
+ case VK_F2: return ImGuiKey_F2;
620
+ case VK_F3: return ImGuiKey_F3;
621
+ case VK_F4: return ImGuiKey_F4;
622
+ case VK_F5: return ImGuiKey_F5;
623
+ case VK_F6: return ImGuiKey_F6;
624
+ case VK_F7: return ImGuiKey_F7;
625
+ case VK_F8: return ImGuiKey_F8;
626
+ case VK_F9: return ImGuiKey_F9;
627
+ case VK_F10: return ImGuiKey_F10;
628
+ case VK_F11: return ImGuiKey_F11;
629
+ case VK_F12: return ImGuiKey_F12;
630
+ case VK_F13: return ImGuiKey_F13;
631
+ case VK_F14: return ImGuiKey_F14;
632
+ case VK_F15: return ImGuiKey_F15;
633
+ case VK_F16: return ImGuiKey_F16;
634
+ case VK_F17: return ImGuiKey_F17;
635
+ case VK_F18: return ImGuiKey_F18;
636
+ case VK_F19: return ImGuiKey_F19;
637
+ case VK_F20: return ImGuiKey_F20;
638
+ case VK_F21: return ImGuiKey_F21;
639
+ case VK_F22: return ImGuiKey_F22;
640
+ case VK_F23: return ImGuiKey_F23;
641
+ case VK_F24: return ImGuiKey_F24;
642
+ case VK_BROWSER_BACK: return ImGuiKey_AppBack;
643
+ case VK_BROWSER_FORWARD: return ImGuiKey_AppForward;
644
+ default: return ImGuiKey_None;
645
+ }
646
+ }
647
+
648
+ // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions.
649
+ #ifndef WM_MOUSEHWHEEL
650
+ #define WM_MOUSEHWHEEL 0x020E
651
+ #endif
652
+ #ifndef DBT_DEVNODES_CHANGED
653
+ #define DBT_DEVNODES_CHANGED 0x0007
654
+ #endif
655
+
656
+ // Helper to obtain the source of mouse messages.
657
+ // See https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages
658
+ // Prefer to call this at the top of the message handler to avoid the possibility of other Win32 calls interfering with this.
659
+ static ImGuiMouseSource ImGui_ImplWin32_GetMouseSourceFromMessageExtraInfo()
660
+ {
661
+ LPARAM extra_info = ::GetMessageExtraInfo();
662
+ if ((extra_info & 0xFFFFFF80) == 0xFF515700)
663
+ return ImGuiMouseSource_Pen;
664
+ if ((extra_info & 0xFFFFFF80) == 0xFF515780)
665
+ return ImGuiMouseSource_TouchScreen;
666
+ return ImGuiMouseSource_Mouse;
667
+ }
668
+
669
+ // Win32 message handler (process Win32 mouse/keyboard inputs, etc.)
670
+ // Call from your application's message handler. Keep calling your message handler unless this function returns TRUE.
671
+ // When implementing your own backend, you can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if Dear ImGui wants to use your inputs.
672
+ // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
673
+ // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
674
+ // Generally you may always pass all inputs to Dear ImGui, and hide them from your application based on those two flags.
675
+ // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag.
676
+
677
+ // Copy either line into your .cpp file to forward declare the function:
678
+ extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); // Use ImGui::GetCurrentContext()
679
+ extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandlerEx(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam, ImGuiIO& io); // Doesn't use ImGui::GetCurrentContext()
680
+
681
+ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
682
+ {
683
+ // Most backends don't have silent checks like this one, but we need it because WndProc are called early in CreateWindow().
684
+ // We silently allow both context or just only backend data to be nullptr.
685
+ if (ImGui::GetCurrentContext() == nullptr)
686
+ return 0;
687
+ return ImGui_ImplWin32_WndProcHandlerEx(hwnd, msg, wParam, lParam, ImGui::GetIO());
688
+ }
689
+
690
+ // This version is in theory thread-safe in the sense that no path should access ImGui::GetCurrentContext().
691
+ IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandlerEx(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, ImGuiIO& io)
692
+ {
693
+ ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData(io);
694
+ if (bd == nullptr)
695
+ return 0;
696
+ switch (msg)
697
+ {
698
+ case WM_MOUSEMOVE:
699
+ case WM_NCMOUSEMOVE:
700
+ {
701
+ // We need to call TrackMouseEvent in order to receive WM_MOUSELEAVE events
702
+ ImGuiMouseSource mouse_source = ImGui_ImplWin32_GetMouseSourceFromMessageExtraInfo();
703
+ const int area = (msg == WM_MOUSEMOVE) ? 1 : 2;
704
+ bd->MouseHwnd = hwnd;
705
+ if (bd->MouseTrackedArea != area)
706
+ {
707
+ TRACKMOUSEEVENT tme_cancel = { sizeof(tme_cancel), TME_CANCEL, hwnd, 0 };
708
+ TRACKMOUSEEVENT tme_track = { sizeof(tme_track), (DWORD)((area == 2) ? (TME_LEAVE | TME_NONCLIENT) : TME_LEAVE), hwnd, 0 };
709
+ if (bd->MouseTrackedArea != 0)
710
+ ::TrackMouseEvent(&tme_cancel);
711
+ ::TrackMouseEvent(&tme_track);
712
+ bd->MouseTrackedArea = area;
713
+ }
714
+ POINT mouse_pos = { (LONG)GET_X_LPARAM(lParam), (LONG)GET_Y_LPARAM(lParam) };
715
+ bool want_absolute_pos = (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) != 0;
716
+ if (msg == WM_MOUSEMOVE && want_absolute_pos) // WM_MOUSEMOVE are client-relative coordinates.
717
+ ::ClientToScreen(hwnd, &mouse_pos);
718
+ if (msg == WM_NCMOUSEMOVE && !want_absolute_pos) // WM_NCMOUSEMOVE are absolute coordinates.
719
+ ::ScreenToClient(hwnd, &mouse_pos);
720
+ io.AddMouseSourceEvent(mouse_source);
721
+ io.AddMousePosEvent((float)mouse_pos.x, (float)mouse_pos.y);
722
+ return 0;
723
+ }
724
+ case WM_MOUSELEAVE:
725
+ case WM_NCMOUSELEAVE:
726
+ {
727
+ const int area = (msg == WM_MOUSELEAVE) ? 1 : 2;
728
+ if (bd->MouseTrackedArea == area)
729
+ {
730
+ if (bd->MouseHwnd == hwnd)
731
+ bd->MouseHwnd = nullptr;
732
+ bd->MouseTrackedArea = 0;
733
+ io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
734
+ }
735
+ return 0;
736
+ }
737
+ case WM_DESTROY:
738
+ if (bd->MouseHwnd == hwnd && bd->MouseTrackedArea != 0)
739
+ {
740
+ TRACKMOUSEEVENT tme_cancel = { sizeof(tme_cancel), TME_CANCEL, hwnd, 0 };
741
+ ::TrackMouseEvent(&tme_cancel);
742
+ bd->MouseHwnd = nullptr;
743
+ bd->MouseTrackedArea = 0;
744
+ io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
745
+ }
746
+ return 0;
747
+ case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK:
748
+ case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK:
749
+ case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK:
750
+ case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK:
751
+ {
752
+ ImGuiMouseSource mouse_source = ImGui_ImplWin32_GetMouseSourceFromMessageExtraInfo();
753
+ int button = 0;
754
+ if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) { button = 0; }
755
+ if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) { button = 1; }
756
+ if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) { button = 2; }
757
+ if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
758
+ if (bd->MouseButtonsDown == 0 && ::GetCapture() == nullptr)
759
+ ::SetCapture(hwnd); // Allow us to read mouse coordinates when dragging mouse outside of our window bounds.
760
+ bd->MouseButtonsDown |= 1 << button;
761
+ io.AddMouseSourceEvent(mouse_source);
762
+ io.AddMouseButtonEvent(button, true);
763
+ return 0;
764
+ }
765
+ case WM_LBUTTONUP:
766
+ case WM_RBUTTONUP:
767
+ case WM_MBUTTONUP:
768
+ case WM_XBUTTONUP:
769
+ {
770
+ ImGuiMouseSource mouse_source = ImGui_ImplWin32_GetMouseSourceFromMessageExtraInfo();
771
+ int button = 0;
772
+ if (msg == WM_LBUTTONUP) { button = 0; }
773
+ if (msg == WM_RBUTTONUP) { button = 1; }
774
+ if (msg == WM_MBUTTONUP) { button = 2; }
775
+ if (msg == WM_XBUTTONUP) { button = (GET_XBUTTON_WPARAM(wParam) == XBUTTON1) ? 3 : 4; }
776
+ bd->MouseButtonsDown &= ~(1 << button);
777
+ if (bd->MouseButtonsDown == 0 && ::GetCapture() == hwnd)
778
+ ::ReleaseCapture();
779
+ io.AddMouseSourceEvent(mouse_source);
780
+ io.AddMouseButtonEvent(button, false);
781
+ return 0;
782
+ }
783
+ case WM_MOUSEWHEEL:
784
+ io.AddMouseWheelEvent(0.0f, (float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA);
785
+ return 0;
786
+ case WM_MOUSEHWHEEL:
787
+ io.AddMouseWheelEvent(-(float)GET_WHEEL_DELTA_WPARAM(wParam) / (float)WHEEL_DELTA, 0.0f);
788
+ return 0;
789
+ case WM_KEYDOWN:
790
+ case WM_KEYUP:
791
+ case WM_SYSKEYDOWN:
792
+ case WM_SYSKEYUP:
793
+ {
794
+ const bool is_key_down = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN);
795
+ if (wParam < 256)
796
+ {
797
+ // Submit modifiers
798
+ ImGui_ImplWin32_UpdateKeyModifiers(io);
799
+
800
+ // Obtain virtual key code and convert to ImGuiKey
801
+ const ImGuiKey key = ImGui_ImplWin32_KeyEventToImGuiKey(wParam, lParam);
802
+ const int vk = (int)wParam;
803
+ const int scancode = (int)LOBYTE(HIWORD(lParam));
804
+
805
+ // Special behavior for VK_SNAPSHOT / ImGuiKey_PrintScreen as Windows doesn't emit the key down event.
806
+ if (key == ImGuiKey_PrintScreen && !is_key_down)
807
+ ImGui_ImplWin32_AddKeyEvent(io, key, true, vk, scancode);
808
+
809
+ // Submit key event
810
+ if (key != ImGuiKey_None)
811
+ ImGui_ImplWin32_AddKeyEvent(io, key, is_key_down, vk, scancode);
812
+
813
+ // Submit individual left/right modifier events
814
+ if (vk == VK_SHIFT)
815
+ {
816
+ // Important: Shift keys tend to get stuck when pressed together, missing key-up events are corrected in ImGui_ImplWin32_ProcessKeyEventsWorkarounds()
817
+ if (IsVkDown(VK_LSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_LeftShift, is_key_down, VK_LSHIFT, scancode); }
818
+ if (IsVkDown(VK_RSHIFT) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_RightShift, is_key_down, VK_RSHIFT, scancode); }
819
+ }
820
+ else if (vk == VK_CONTROL)
821
+ {
822
+ if (IsVkDown(VK_LCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_LeftCtrl, is_key_down, VK_LCONTROL, scancode); }
823
+ if (IsVkDown(VK_RCONTROL) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_RightCtrl, is_key_down, VK_RCONTROL, scancode); }
824
+ }
825
+ else if (vk == VK_MENU)
826
+ {
827
+ if (IsVkDown(VK_LMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_LeftAlt, is_key_down, VK_LMENU, scancode); }
828
+ if (IsVkDown(VK_RMENU) == is_key_down) { ImGui_ImplWin32_AddKeyEvent(io, ImGuiKey_RightAlt, is_key_down, VK_RMENU, scancode); }
829
+ }
830
+ }
831
+ return 0;
832
+ }
833
+ case WM_SETFOCUS:
834
+ case WM_KILLFOCUS:
835
+ io.AddFocusEvent(msg == WM_SETFOCUS);
836
+ return 0;
837
+ case WM_INPUTLANGCHANGE:
838
+ ImGui_ImplWin32_UpdateKeyboardCodePage(io);
839
+ return 0;
840
+ case WM_CHAR:
841
+ if (::IsWindowUnicode(hwnd))
842
+ {
843
+ // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
844
+ if (wParam > 0 && wParam < 0x10000)
845
+ io.AddInputCharacterUTF16((unsigned short)wParam);
846
+ }
847
+ else
848
+ {
849
+ wchar_t wch = 0;
850
+ ::MultiByteToWideChar(bd->KeyboardCodePage, MB_PRECOMPOSED, (char*)&wParam, 1, &wch, 1);
851
+ io.AddInputCharacter(wch);
852
+ }
853
+ return 0;
854
+ case WM_SETCURSOR:
855
+ // This is required to restore cursor when transitioning from e.g resize borders to client area.
856
+ if (LOWORD(lParam) == HTCLIENT && ImGui_ImplWin32_UpdateMouseCursor(io, bd->LastMouseCursor))
857
+ return 1;
858
+ return 0;
859
+ case WM_DEVICECHANGE:
860
+ #ifndef IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
861
+ if ((UINT)wParam == DBT_DEVNODES_CHANGED)
862
+ bd->WantUpdateHasGamepad = true;
863
+ #endif
864
+ return 0;
865
+ case WM_DISPLAYCHANGE:
866
+ bd->WantUpdateMonitors = true;
867
+ return 0;
868
+ }
869
+ return 0;
870
+ }
871
+
872
+
873
+ //--------------------------------------------------------------------------------------------------------
874
+ // DPI-related helpers (optional)
875
+ //--------------------------------------------------------------------------------------------------------
876
+ // - Use to enable DPI awareness without having to create an application manifest.
877
+ // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
878
+ // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
879
+ // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
880
+ // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
881
+ //---------------------------------------------------------------------------------------------------------
882
+ // This is the scheme successfully used by GLFW (from which we borrowed some of the code) and other apps aiming to be highly portable.
883
+ // ImGui_ImplWin32_EnableDpiAwareness() is just a helper called by main.cpp, we don't call it automatically.
884
+ // If you are trying to implement your own backend for your own engine, you may ignore that noise.
885
+ //---------------------------------------------------------------------------------------------------------
886
+
887
+ // Perform our own check with RtlVerifyVersionInfo() instead of using functions from <VersionHelpers.h> as they
888
+ // require a manifest to be functional for checks above 8.1. See https://github.com/ocornut/imgui/issues/4200
889
+ static BOOL _IsWindowsVersionOrGreater(WORD major, WORD minor, WORD)
890
+ {
891
+ typedef LONG(WINAPI* PFN_RtlVerifyVersionInfo)(OSVERSIONINFOEXW*, ULONG, ULONGLONG);
892
+ static PFN_RtlVerifyVersionInfo RtlVerifyVersionInfoFn = nullptr;
893
+ if (RtlVerifyVersionInfoFn == nullptr)
894
+ if (HMODULE ntdllModule = ::GetModuleHandleA("ntdll.dll"))
895
+ RtlVerifyVersionInfoFn = (PFN_RtlVerifyVersionInfo)GetProcAddress(ntdllModule, "RtlVerifyVersionInfo");
896
+ if (RtlVerifyVersionInfoFn == nullptr)
897
+ return FALSE;
898
+
899
+ RTL_OSVERSIONINFOEXW versionInfo = { };
900
+ ULONGLONG conditionMask = 0;
901
+ versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
902
+ versionInfo.dwMajorVersion = major;
903
+ versionInfo.dwMinorVersion = minor;
904
+ VER_SET_CONDITION(conditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
905
+ VER_SET_CONDITION(conditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
906
+ return (RtlVerifyVersionInfoFn(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION, conditionMask) == 0) ? TRUE : FALSE;
907
+ }
908
+
909
+ #define _IsWindowsVistaOrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0600), LOBYTE(0x0600), 0) // _WIN32_WINNT_VISTA
910
+ #define _IsWindows8OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0602), LOBYTE(0x0602), 0) // _WIN32_WINNT_WIN8
911
+ #define _IsWindows8Point1OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0603), LOBYTE(0x0603), 0) // _WIN32_WINNT_WINBLUE
912
+ #define _IsWindows10OrGreater() _IsWindowsVersionOrGreater(HIBYTE(0x0A00), LOBYTE(0x0A00), 0) // _WIN32_WINNT_WINTHRESHOLD / _WIN32_WINNT_WIN10
913
+
914
+ #ifndef DPI_ENUMS_DECLARED
915
+ typedef enum { PROCESS_DPI_UNAWARE = 0, PROCESS_SYSTEM_DPI_AWARE = 1, PROCESS_PER_MONITOR_DPI_AWARE = 2 } PROCESS_DPI_AWARENESS;
916
+ typedef enum { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE;
917
+ #endif
918
+ #ifndef _DPI_AWARENESS_CONTEXTS_
919
+ DECLARE_HANDLE(DPI_AWARENESS_CONTEXT);
920
+ #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE (DPI_AWARENESS_CONTEXT)-3
921
+ #endif
922
+ #ifndef DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
923
+ #define DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 (DPI_AWARENESS_CONTEXT)-4
924
+ #endif
925
+ typedef HRESULT(WINAPI* PFN_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS); // Shcore.lib + dll, Windows 8.1+
926
+ typedef HRESULT(WINAPI* PFN_GetDpiForMonitor)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*); // Shcore.lib + dll, Windows 8.1+
927
+ typedef DPI_AWARENESS_CONTEXT(WINAPI* PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); // User32.lib + dll, Windows 10 v1607+ (Creators Update)
928
+
929
+ // Helper function to enable DPI awareness without setting up a manifest
930
+ void ImGui_ImplWin32_EnableDpiAwareness()
931
+ {
932
+ // Make sure monitors will be updated with latest correct scaling
933
+ if (ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData())
934
+ bd->WantUpdateMonitors = true;
935
+
936
+ if (_IsWindows10OrGreater())
937
+ {
938
+ static HINSTANCE user32_dll = ::LoadLibraryA("user32.dll"); // Reference counted per-process
939
+ if (PFN_SetThreadDpiAwarenessContext SetThreadDpiAwarenessContextFn = (PFN_SetThreadDpiAwarenessContext)::GetProcAddress(user32_dll, "SetThreadDpiAwarenessContext"))
940
+ {
941
+ SetThreadDpiAwarenessContextFn(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
942
+ return;
943
+ }
944
+ }
945
+ if (_IsWindows8Point1OrGreater())
946
+ {
947
+ static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
948
+ if (PFN_SetProcessDpiAwareness SetProcessDpiAwarenessFn = (PFN_SetProcessDpiAwareness)::GetProcAddress(shcore_dll, "SetProcessDpiAwareness"))
949
+ {
950
+ SetProcessDpiAwarenessFn(PROCESS_PER_MONITOR_DPI_AWARE);
951
+ return;
952
+ }
953
+ }
954
+ #if _WIN32_WINNT >= 0x0600
955
+ ::SetProcessDPIAware();
956
+ #endif
957
+ }
958
+
959
+ #if defined(_MSC_VER) && !defined(NOGDI)
960
+ #pragma comment(lib, "gdi32") // Link with gdi32.lib for GetDeviceCaps(). MinGW will require linking with '-lgdi32'
961
+ #endif
962
+
963
+ float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor)
964
+ {
965
+ UINT xdpi = 96, ydpi = 96;
966
+ if (_IsWindows8Point1OrGreater())
967
+ {
968
+ static HINSTANCE shcore_dll = ::LoadLibraryA("shcore.dll"); // Reference counted per-process
969
+ static PFN_GetDpiForMonitor GetDpiForMonitorFn = nullptr;
970
+ if (GetDpiForMonitorFn == nullptr && shcore_dll != nullptr)
971
+ GetDpiForMonitorFn = (PFN_GetDpiForMonitor)::GetProcAddress(shcore_dll, "GetDpiForMonitor");
972
+ if (GetDpiForMonitorFn != nullptr)
973
+ {
974
+ GetDpiForMonitorFn((HMONITOR)monitor, MDT_EFFECTIVE_DPI, &xdpi, &ydpi);
975
+ IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert!
976
+ return xdpi / 96.0f;
977
+ }
978
+ }
979
+ #ifndef NOGDI
980
+ const HDC dc = ::GetDC(nullptr);
981
+ xdpi = ::GetDeviceCaps(dc, LOGPIXELSX);
982
+ ydpi = ::GetDeviceCaps(dc, LOGPIXELSY);
983
+ IM_ASSERT(xdpi == ydpi); // Please contact me if you hit this assert!
984
+ ::ReleaseDC(nullptr, dc);
985
+ #endif
986
+ return xdpi / 96.0f;
987
+ }
988
+
989
+ float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd)
990
+ {
991
+ HMONITOR monitor = ::MonitorFromWindow((HWND)hwnd, MONITOR_DEFAULTTONEAREST);
992
+ return ImGui_ImplWin32_GetDpiScaleForMonitor(monitor);
993
+ }
994
+
995
+ //---------------------------------------------------------------------------------------------------------
996
+ // Transparency related helpers (optional)
997
+ //--------------------------------------------------------------------------------------------------------
998
+
999
+ #if defined(_MSC_VER)
1000
+ #pragma comment(lib, "dwmapi") // Link with dwmapi.lib. MinGW will require linking with '-ldwmapi'
1001
+ #endif
1002
+
1003
+ // [experimental]
1004
+ // Borrowed from GLFW's function updateFramebufferTransparency() in src/win32_window.c
1005
+ // (the Dwm* functions are Vista era functions but we are borrowing logic from GLFW)
1006
+ void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd)
1007
+ {
1008
+ if (!_IsWindowsVistaOrGreater())
1009
+ return;
1010
+
1011
+ BOOL composition;
1012
+ if (FAILED(::DwmIsCompositionEnabled(&composition)) || !composition)
1013
+ return;
1014
+
1015
+ BOOL opaque;
1016
+ DWORD color;
1017
+ if (_IsWindows8OrGreater() || (SUCCEEDED(::DwmGetColorizationColor(&color, &opaque)) && !opaque))
1018
+ {
1019
+ HRGN region = ::CreateRectRgn(0, 0, -1, -1);
1020
+ DWM_BLURBEHIND bb = {};
1021
+ bb.dwFlags = DWM_BB_ENABLE | DWM_BB_BLURREGION;
1022
+ bb.hRgnBlur = region;
1023
+ bb.fEnable = TRUE;
1024
+ ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb);
1025
+ ::DeleteObject(region);
1026
+ }
1027
+ else
1028
+ {
1029
+ DWM_BLURBEHIND bb = {};
1030
+ bb.dwFlags = DWM_BB_ENABLE;
1031
+ ::DwmEnableBlurBehindWindow((HWND)hwnd, &bb);
1032
+ }
1033
+ }
1034
+
1035
+ //---------------------------------------------------------------------------------------------------------
1036
+ // MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
1037
+ // This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
1038
+ // If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
1039
+ //--------------------------------------------------------------------------------------------------------
1040
+
1041
+ // Helper structure we store in the void* RendererUserData field of each ImGuiViewport to easily retrieve our backend data.
1042
+ struct ImGui_ImplWin32_ViewportData
1043
+ {
1044
+ HWND Hwnd;
1045
+ HWND HwndParent;
1046
+ bool HwndOwned;
1047
+ DWORD DwStyle;
1048
+ DWORD DwExStyle;
1049
+
1050
+ ImGui_ImplWin32_ViewportData() { Hwnd = HwndParent = nullptr; HwndOwned = false; DwStyle = DwExStyle = 0; }
1051
+ ~ImGui_ImplWin32_ViewportData() { IM_ASSERT(Hwnd == nullptr); }
1052
+ };
1053
+
1054
+ static void ImGui_ImplWin32_GetWin32StyleFromViewportFlags(ImGuiViewportFlags flags, DWORD* out_style, DWORD* out_ex_style)
1055
+ {
1056
+ if (flags & ImGuiViewportFlags_NoDecoration)
1057
+ *out_style = WS_POPUP;
1058
+ else
1059
+ *out_style = WS_OVERLAPPEDWINDOW;
1060
+
1061
+ if (flags & ImGuiViewportFlags_NoTaskBarIcon)
1062
+ *out_ex_style = WS_EX_TOOLWINDOW;
1063
+ else
1064
+ *out_ex_style = WS_EX_APPWINDOW;
1065
+
1066
+ if (flags & ImGuiViewportFlags_TopMost)
1067
+ *out_ex_style |= WS_EX_TOPMOST;
1068
+ }
1069
+
1070
+ static HWND ImGui_ImplWin32_GetHwndFromViewportID(ImGuiID viewport_id)
1071
+ {
1072
+ if (viewport_id != 0)
1073
+ if (ImGuiViewport* viewport = ImGui::FindViewportByID(viewport_id))
1074
+ return (HWND)viewport->PlatformHandle;
1075
+ return nullptr;
1076
+ }
1077
+
1078
+ static void ImGui_ImplWin32_CreateWindow(ImGuiViewport* viewport)
1079
+ {
1080
+ ImGui_ImplWin32_ViewportData* vd = IM_NEW(ImGui_ImplWin32_ViewportData)();
1081
+ viewport->PlatformUserData = vd;
1082
+
1083
+ // Select style and parent window
1084
+ ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &vd->DwStyle, &vd->DwExStyle);
1085
+ vd->HwndParent = ImGui_ImplWin32_GetHwndFromViewportID(viewport->ParentViewportId);
1086
+
1087
+ // Create window
1088
+ RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) };
1089
+ ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle);
1090
+ vd->Hwnd = ::CreateWindowExW(
1091
+ vd->DwExStyle, L"ImGui Platform", L"Untitled", vd->DwStyle, // Style, class name, window name
1092
+ rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, // Window area
1093
+ vd->HwndParent, nullptr, ::GetModuleHandle(nullptr), nullptr); // Owner window, Menu, Instance, Param
1094
+ vd->HwndOwned = true;
1095
+ viewport->PlatformRequestResize = false;
1096
+ viewport->PlatformHandle = viewport->PlatformHandleRaw = vd->Hwnd;
1097
+
1098
+ // Secondary viewports store their imgui context
1099
+ ::SetPropA(vd->Hwnd, "IMGUI_CONTEXT", ImGui::GetCurrentContext());
1100
+ }
1101
+
1102
+ static void ImGui_ImplWin32_DestroyWindow(ImGuiViewport* viewport)
1103
+ {
1104
+ ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
1105
+ if (ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData)
1106
+ {
1107
+ if (::GetCapture() == vd->Hwnd)
1108
+ {
1109
+ // Transfer capture so if we started dragging from a window that later disappears, we'll still receive the MOUSEUP event.
1110
+ ::ReleaseCapture();
1111
+ ::SetCapture(bd->hWnd);
1112
+ }
1113
+ if (vd->Hwnd && vd->HwndOwned)
1114
+ ::DestroyWindow(vd->Hwnd);
1115
+ vd->Hwnd = nullptr;
1116
+ IM_DELETE(vd);
1117
+ }
1118
+ viewport->PlatformUserData = viewport->PlatformHandle = nullptr;
1119
+ }
1120
+
1121
+ static void ImGui_ImplWin32_ShowWindow(ImGuiViewport* viewport)
1122
+ {
1123
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1124
+ IM_ASSERT(vd->Hwnd != 0);
1125
+
1126
+ // ShowParent() also brings parent to front, which is not always desirable,
1127
+ // so we temporarily disable parenting. (#7354)
1128
+ if (vd->HwndParent != NULL)
1129
+ ::SetWindowLongPtr(vd->Hwnd, GWLP_HWNDPARENT, (LONG_PTR)nullptr);
1130
+
1131
+ if (viewport->Flags & ImGuiViewportFlags_NoFocusOnAppearing)
1132
+ ::ShowWindow(vd->Hwnd, SW_SHOWNA);
1133
+ else
1134
+ ::ShowWindow(vd->Hwnd, SW_SHOW);
1135
+
1136
+ // Restore
1137
+ if (vd->HwndParent != NULL)
1138
+ ::SetWindowLongPtr(vd->Hwnd, GWLP_HWNDPARENT, (LONG_PTR)vd->HwndParent);
1139
+ }
1140
+
1141
+ static void ImGui_ImplWin32_UpdateWindow(ImGuiViewport* viewport)
1142
+ {
1143
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1144
+ IM_ASSERT(vd->Hwnd != 0);
1145
+
1146
+ // Update Win32 parent if it changed _after_ creation
1147
+ // Unlike style settings derived from configuration flags, this is more likely to change for advanced apps that are manipulating ParentViewportID manually.
1148
+ HWND new_parent = ImGui_ImplWin32_GetHwndFromViewportID(viewport->ParentViewportId);
1149
+ if (new_parent != vd->HwndParent)
1150
+ {
1151
+ // Win32 windows can either have a "Parent" (for WS_CHILD window) or an "Owner" (which among other thing keeps window above its owner).
1152
+ // Our Dear Imgui-side concept of parenting only mostly care about what Win32 call "Owner".
1153
+ // The parent parameter of CreateWindowEx() sets up Parent OR Owner depending on WS_CHILD flag. In our case an Owner as we never use WS_CHILD.
1154
+ // Calling ::SetParent() here would be incorrect: it will create a full child relation, alter coordinate system and clipping.
1155
+ // Calling ::SetWindowLongPtr() with GWLP_HWNDPARENT seems correct although poorly documented.
1156
+ // https://devblogs.microsoft.com/oldnewthing/20100315-00/?p=14613
1157
+ vd->HwndParent = new_parent;
1158
+ ::SetWindowLongPtr(vd->Hwnd, GWLP_HWNDPARENT, (LONG_PTR)vd->HwndParent);
1159
+ }
1160
+
1161
+ // (Optional) Update Win32 style if it changed _after_ creation.
1162
+ // Generally they won't change unless configuration flags are changed, but advanced uses (such as manually rewriting viewport flags) make this useful.
1163
+ DWORD new_style;
1164
+ DWORD new_ex_style;
1165
+ ImGui_ImplWin32_GetWin32StyleFromViewportFlags(viewport->Flags, &new_style, &new_ex_style);
1166
+
1167
+ // Only reapply the flags that have been changed from our point of view (as other flags are being modified by Windows)
1168
+ if (vd->DwStyle != new_style || vd->DwExStyle != new_ex_style)
1169
+ {
1170
+ // (Optional) Update TopMost state if it changed _after_ creation
1171
+ bool top_most_changed = (vd->DwExStyle & WS_EX_TOPMOST) != (new_ex_style & WS_EX_TOPMOST);
1172
+ HWND insert_after = top_most_changed ? ((viewport->Flags & ImGuiViewportFlags_TopMost) ? HWND_TOPMOST : HWND_NOTOPMOST) : 0;
1173
+ UINT swp_flag = top_most_changed ? 0 : SWP_NOZORDER;
1174
+
1175
+ // Apply flags and position (since it is affected by flags)
1176
+ vd->DwStyle = new_style;
1177
+ vd->DwExStyle = new_ex_style;
1178
+ ::SetWindowLong(vd->Hwnd, GWL_STYLE, vd->DwStyle);
1179
+ ::SetWindowLong(vd->Hwnd, GWL_EXSTYLE, vd->DwExStyle);
1180
+ RECT rect = { (LONG)viewport->Pos.x, (LONG)viewport->Pos.y, (LONG)(viewport->Pos.x + viewport->Size.x), (LONG)(viewport->Pos.y + viewport->Size.y) };
1181
+ ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); // Client to Screen
1182
+ ::SetWindowPos(vd->Hwnd, insert_after, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, swp_flag | SWP_NOACTIVATE | SWP_FRAMECHANGED);
1183
+ ::ShowWindow(vd->Hwnd, SW_SHOWNA); // This is necessary when we alter the style
1184
+ viewport->PlatformRequestMove = viewport->PlatformRequestResize = true;
1185
+ }
1186
+ }
1187
+
1188
+ static ImVec2 ImGui_ImplWin32_GetWindowPos(ImGuiViewport* viewport)
1189
+ {
1190
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1191
+ IM_ASSERT(vd->Hwnd != 0);
1192
+ POINT pos = { 0, 0 };
1193
+ ::ClientToScreen(vd->Hwnd, &pos);
1194
+ return ImVec2((float)pos.x, (float)pos.y);
1195
+ }
1196
+
1197
+ static void ImGui_ImplWin32_UpdateWin32StyleFromWindow(ImGuiViewport* viewport)
1198
+ {
1199
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1200
+ vd->DwStyle = ::GetWindowLongW(vd->Hwnd, GWL_STYLE);
1201
+ vd->DwExStyle = ::GetWindowLongW(vd->Hwnd, GWL_EXSTYLE);
1202
+ }
1203
+
1204
+ static void ImGui_ImplWin32_SetWindowPos(ImGuiViewport* viewport, ImVec2 pos)
1205
+ {
1206
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1207
+ IM_ASSERT(vd->Hwnd != 0);
1208
+ RECT rect = { (LONG)pos.x, (LONG)pos.y, (LONG)pos.x, (LONG)pos.y };
1209
+ if (viewport->Flags & ImGuiViewportFlags_OwnedByApp)
1210
+ ImGui_ImplWin32_UpdateWin32StyleFromWindow(viewport); // Not our window, poll style before using
1211
+ ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle);
1212
+ ::SetWindowPos(vd->Hwnd, nullptr, rect.left, rect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
1213
+ }
1214
+
1215
+ static ImVec2 ImGui_ImplWin32_GetWindowSize(ImGuiViewport* viewport)
1216
+ {
1217
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1218
+ IM_ASSERT(vd->Hwnd != 0);
1219
+ RECT rect;
1220
+ ::GetClientRect(vd->Hwnd, &rect);
1221
+ return ImVec2(float(rect.right - rect.left), float(rect.bottom - rect.top));
1222
+ }
1223
+
1224
+ static void ImGui_ImplWin32_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
1225
+ {
1226
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1227
+ IM_ASSERT(vd->Hwnd != 0);
1228
+ RECT rect = { 0, 0, (LONG)size.x, (LONG)size.y };
1229
+ if (viewport->Flags & ImGuiViewportFlags_OwnedByApp)
1230
+ ImGui_ImplWin32_UpdateWin32StyleFromWindow(viewport); // Not our window, poll style before using
1231
+ ::AdjustWindowRectEx(&rect, vd->DwStyle, FALSE, vd->DwExStyle); // Client to Screen
1232
+ ::SetWindowPos(vd->Hwnd, nullptr, 0, 0, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
1233
+ }
1234
+
1235
+ static void ImGui_ImplWin32_SetWindowFocus(ImGuiViewport* viewport)
1236
+ {
1237
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1238
+ IM_ASSERT(vd->Hwnd != 0);
1239
+ ::BringWindowToTop(vd->Hwnd);
1240
+ ::SetForegroundWindow(vd->Hwnd);
1241
+ ::SetFocus(vd->Hwnd);
1242
+ }
1243
+
1244
+ static bool ImGui_ImplWin32_GetWindowFocus(ImGuiViewport* viewport)
1245
+ {
1246
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1247
+ IM_ASSERT(vd->Hwnd != 0);
1248
+ return ::GetForegroundWindow() == vd->Hwnd;
1249
+ }
1250
+
1251
+ static bool ImGui_ImplWin32_GetWindowMinimized(ImGuiViewport* viewport)
1252
+ {
1253
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1254
+ IM_ASSERT(vd->Hwnd != 0);
1255
+ return ::IsIconic(vd->Hwnd) != 0;
1256
+ }
1257
+
1258
+ static void ImGui_ImplWin32_SetWindowTitle(ImGuiViewport* viewport, const char* title)
1259
+ {
1260
+ // ::SetWindowTextA() doesn't properly handle UTF-8 so we explicitely convert our string.
1261
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1262
+ IM_ASSERT(vd->Hwnd != 0);
1263
+ int n = ::MultiByteToWideChar(CP_UTF8, 0, title, -1, nullptr, 0);
1264
+ ImVector<wchar_t> title_w;
1265
+ title_w.resize(n);
1266
+ ::MultiByteToWideChar(CP_UTF8, 0, title, -1, title_w.Data, n);
1267
+ ::SetWindowTextW(vd->Hwnd, title_w.Data);
1268
+ }
1269
+
1270
+ static void ImGui_ImplWin32_SetWindowAlpha(ImGuiViewport* viewport, float alpha)
1271
+ {
1272
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1273
+ IM_ASSERT(vd->Hwnd != 0);
1274
+ IM_ASSERT(alpha >= 0.0f && alpha <= 1.0f);
1275
+ if (alpha < 1.0f)
1276
+ {
1277
+ DWORD ex_style = ::GetWindowLongW(vd->Hwnd, GWL_EXSTYLE) | WS_EX_LAYERED;
1278
+ ::SetWindowLongW(vd->Hwnd, GWL_EXSTYLE, ex_style);
1279
+ ::SetLayeredWindowAttributes(vd->Hwnd, 0, (BYTE)(255 * alpha), LWA_ALPHA);
1280
+ }
1281
+ else
1282
+ {
1283
+ DWORD ex_style = ::GetWindowLongW(vd->Hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED;
1284
+ ::SetWindowLongW(vd->Hwnd, GWL_EXSTYLE, ex_style);
1285
+ }
1286
+ }
1287
+
1288
+ static float ImGui_ImplWin32_GetWindowDpiScale(ImGuiViewport* viewport)
1289
+ {
1290
+ ImGui_ImplWin32_ViewportData* vd = (ImGui_ImplWin32_ViewportData*)viewport->PlatformUserData;
1291
+ IM_ASSERT(vd->Hwnd != 0);
1292
+ return ImGui_ImplWin32_GetDpiScaleForHwnd(vd->Hwnd);
1293
+ }
1294
+
1295
+ // FIXME-DPI: Testing DPI related ideas
1296
+ static void ImGui_ImplWin32_OnChangedViewport(ImGuiViewport* viewport)
1297
+ {
1298
+ (void)viewport;
1299
+ #if 0
1300
+ ImGuiStyle default_style;
1301
+ //default_style.WindowPadding = ImVec2(0, 0);
1302
+ //default_style.WindowBorderSize = 0.0f;
1303
+ //default_style.ItemSpacing.y = 3.0f;
1304
+ //default_style.FramePadding = ImVec2(0, 0);
1305
+ default_style.ScaleAllSizes(viewport->DpiScale);
1306
+ ImGuiStyle& style = ImGui::GetStyle();
1307
+ style = default_style;
1308
+ #endif
1309
+ }
1310
+
1311
+ namespace ImGui { extern ImGuiIO& GetIOEx(ImGuiContext*); extern ImGuiPlatformIO& GetPlatformIOEx(ImGuiContext*); }
1312
+
1313
+ static LRESULT CALLBACK ImGui_ImplWin32_WndProcHandler_PlatformWindow(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1314
+ {
1315
+ // Allow secondary viewport WndProc to be called regardless of current context
1316
+ ImGuiContext* ctx = (ImGuiContext*)::GetPropA(hWnd, "IMGUI_CONTEXT");
1317
+ if (ctx == NULL)
1318
+ return DefWindowProc(hWnd, msg, wParam, lParam); // unlike ImGui_ImplWin32_WndProcHandler() we are called directly by Windows, we can't just return 0.
1319
+
1320
+ ImGuiIO& io = ImGui::GetIOEx(ctx);
1321
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIOEx(ctx);
1322
+ LRESULT result = 0;
1323
+ if (ImGui_ImplWin32_WndProcHandlerEx(hWnd, msg, wParam, lParam, io))
1324
+ result = true;
1325
+ else if (ImGuiViewport* viewport = ImGui_ImplWin32_FindViewportByPlatformHandle(platform_io, hWnd))
1326
+ {
1327
+ switch (msg)
1328
+ {
1329
+ case WM_CLOSE:
1330
+ viewport->PlatformRequestClose = true;
1331
+ break;
1332
+ case WM_MOVE:
1333
+ viewport->PlatformRequestMove = true;
1334
+ break;
1335
+ case WM_SIZE:
1336
+ viewport->PlatformRequestResize = true;
1337
+ break;
1338
+ case WM_MOUSEACTIVATE:
1339
+ if (viewport->Flags & ImGuiViewportFlags_NoFocusOnClick)
1340
+ result = MA_NOACTIVATE;
1341
+ break;
1342
+ case WM_NCHITTEST:
1343
+ // Let mouse pass-through the window. This will allow the backend to call io.AddMouseViewportEvent() correctly. (which is optional).
1344
+ // The ImGuiViewportFlags_NoInputs flag is set while dragging a viewport, as want to detect the window behind the one we are dragging.
1345
+ // If you cannot easily access those viewport flags from your windowing/event code: you may manually synchronize its state e.g. in
1346
+ // your main loop after calling UpdatePlatformWindows(). Iterate all viewports/platform windows and pass the flag to your windowing system.
1347
+ if (viewport->Flags & ImGuiViewportFlags_NoInputs)
1348
+ result = HTTRANSPARENT;
1349
+ break;
1350
+ }
1351
+ }
1352
+ if (result == 0)
1353
+ result = DefWindowProc(hWnd, msg, wParam, lParam);
1354
+ return result;
1355
+ }
1356
+
1357
+ static void ImGui_ImplWin32_InitMultiViewportSupport(bool platform_has_own_dc)
1358
+ {
1359
+ WNDCLASSEXW wcex;
1360
+ wcex.cbSize = sizeof(WNDCLASSEXW);
1361
+ wcex.style = CS_HREDRAW | CS_VREDRAW | (platform_has_own_dc ? CS_OWNDC : 0);
1362
+ wcex.lpfnWndProc = ImGui_ImplWin32_WndProcHandler_PlatformWindow;
1363
+ wcex.cbClsExtra = 0;
1364
+ wcex.cbWndExtra = 0;
1365
+ wcex.hInstance = ::GetModuleHandle(nullptr);
1366
+ wcex.hIcon = nullptr;
1367
+ wcex.hCursor = nullptr;
1368
+ wcex.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
1369
+ wcex.lpszMenuName = nullptr;
1370
+ wcex.lpszClassName = L"ImGui Platform";
1371
+ wcex.hIconSm = nullptr;
1372
+ ::RegisterClassExW(&wcex);
1373
+
1374
+ ImGui_ImplWin32_UpdateMonitors();
1375
+
1376
+ // Register platform interface (will be coupled with a renderer interface)
1377
+ ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
1378
+ platform_io.Platform_CreateWindow = ImGui_ImplWin32_CreateWindow;
1379
+ platform_io.Platform_DestroyWindow = ImGui_ImplWin32_DestroyWindow;
1380
+ platform_io.Platform_ShowWindow = ImGui_ImplWin32_ShowWindow;
1381
+ platform_io.Platform_SetWindowPos = ImGui_ImplWin32_SetWindowPos;
1382
+ platform_io.Platform_GetWindowPos = ImGui_ImplWin32_GetWindowPos;
1383
+ platform_io.Platform_SetWindowSize = ImGui_ImplWin32_SetWindowSize;
1384
+ platform_io.Platform_GetWindowSize = ImGui_ImplWin32_GetWindowSize;
1385
+ platform_io.Platform_SetWindowFocus = ImGui_ImplWin32_SetWindowFocus;
1386
+ platform_io.Platform_GetWindowFocus = ImGui_ImplWin32_GetWindowFocus;
1387
+ platform_io.Platform_GetWindowMinimized = ImGui_ImplWin32_GetWindowMinimized;
1388
+ platform_io.Platform_SetWindowTitle = ImGui_ImplWin32_SetWindowTitle;
1389
+ platform_io.Platform_SetWindowAlpha = ImGui_ImplWin32_SetWindowAlpha;
1390
+ platform_io.Platform_UpdateWindow = ImGui_ImplWin32_UpdateWindow;
1391
+ platform_io.Platform_GetWindowDpiScale = ImGui_ImplWin32_GetWindowDpiScale; // FIXME-DPI
1392
+ platform_io.Platform_OnChangedViewport = ImGui_ImplWin32_OnChangedViewport; // FIXME-DPI
1393
+
1394
+ // Register main window handle (which is owned by the main application, not by us)
1395
+ // This is mostly for simplicity and consistency, so that our code (e.g. mouse handling etc.) can use same logic for main and secondary viewports.
1396
+ ImGuiViewport* main_viewport = ImGui::GetMainViewport();
1397
+ ImGui_ImplWin32_Data* bd = ImGui_ImplWin32_GetBackendData();
1398
+ ImGui_ImplWin32_ViewportData* vd = IM_NEW(ImGui_ImplWin32_ViewportData)();
1399
+ vd->Hwnd = bd->hWnd;
1400
+ vd->HwndOwned = false;
1401
+ main_viewport->PlatformUserData = vd;
1402
+ }
1403
+
1404
+ static void ImGui_ImplWin32_ShutdownMultiViewportSupport()
1405
+ {
1406
+ ::UnregisterClass(_T("ImGui Platform"), ::GetModuleHandle(nullptr));
1407
+ ImGui::DestroyPlatformWindows();
1408
+ }
1409
+
1410
+ //---------------------------------------------------------------------------------------------------------
1411
+
1412
+ #if defined(__GNUC__)
1413
+ #pragma GCC diagnostic pop
1414
+ #endif
1415
+ #if defined(__clang__)
1416
+ #pragma clang diagnostic pop
1417
+ #endif
1418
+
1419
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/imgui_impl_win32.h ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // dear imgui: Platform Backend for Windows (standard windows API for 32-bits AND 64-bits applications)
2
+ // This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
3
+
4
+ // Implemented features:
5
+ // [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
6
+ // [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen/Pen.
7
+ // [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy VK_* values are obsolete since 1.87 and not supported since 1.91.5]
8
+ // [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
9
+ // [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
10
+ // [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
11
+
12
+ // You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
13
+ // Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
14
+ // Learn about Dear ImGui:
15
+ // - FAQ https://dearimgui.com/faq
16
+ // - Getting Started https://dearimgui.com/getting-started
17
+ // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
18
+ // - Introduction, links and more at the top of imgui.cpp
19
+
20
+ #pragma once
21
+ #include "imgui.h" // IMGUI_IMPL_API
22
+ #ifndef IMGUI_DISABLE
23
+
24
+ // Follow "Getting Started" link and check examples/ folder to learn about using backends!
25
+ IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd);
26
+ IMGUI_IMPL_API bool ImGui_ImplWin32_InitForOpenGL(void* hwnd);
27
+ IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown();
28
+ IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame();
29
+
30
+ // Win32 message handler your application need to call.
31
+ // - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on <windows.h> from this helper.
32
+ // - You should COPY the line below into your .cpp code to forward declare the function and then you can call it.
33
+ // - Call from your application's message handler. Keep calling your message handler unless this function returns TRUE.
34
+
35
+ #if 0
36
+ extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
37
+ #endif
38
+
39
+ // DPI-related helpers (optional)
40
+ // - Use to enable DPI awareness without having to create an application manifest.
41
+ // - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
42
+ // - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
43
+ // but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
44
+ // neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
45
+ IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness();
46
+ IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd
47
+ IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor
48
+
49
+ // Transparency related helpers (optional) [experimental]
50
+ // - Use to enable alpha compositing transparency with the desktop.
51
+ // - Use together with e.g. clearing your framebuffer with zero-alpha.
52
+ IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd); // HWND hwnd
53
+
54
+ #endif // #ifndef IMGUI_DISABLE
3rdparty/imgui/backends/vulkan/generate_spv.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ ## -V: create SPIR-V binary
3
+ ## -x: save binary output as text-based 32-bit hexadecimal numbers
4
+ ## -o: output file
5
+ glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag
6
+ glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert
3rdparty/imgui/backends/vulkan/glsl_shader.frag ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #version 450 core
2
+ layout(location = 0) out vec4 fColor;
3
+
4
+ layout(set=0, binding=0) uniform sampler2D sTexture;
5
+
6
+ layout(location = 0) in struct {
7
+ vec4 Color;
8
+ vec2 UV;
9
+ } In;
10
+
11
+ void main()
12
+ {
13
+ fColor = In.Color * texture(sTexture, In.UV.st);
14
+ }
3rdparty/imgui/backends/vulkan/glsl_shader.vert ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #version 450 core
2
+ layout(location = 0) in vec2 aPos;
3
+ layout(location = 1) in vec2 aUV;
4
+ layout(location = 2) in vec4 aColor;
5
+
6
+ layout(push_constant) uniform uPushConstant {
7
+ vec2 uScale;
8
+ vec2 uTranslate;
9
+ } pc;
10
+
11
+ out gl_PerVertex {
12
+ vec4 gl_Position;
13
+ };
14
+
15
+ layout(location = 0) out struct {
16
+ vec4 Color;
17
+ vec2 UV;
18
+ } Out;
19
+
20
+ void main()
21
+ {
22
+ Out.Color = aColor;
23
+ Out.UV = aUV;
24
+ gl_Position = vec4(aPos * pc.uScale + pc.uTranslate, 0, 1);
25
+ }
3rdparty/imgui/imconfig.h ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //-----------------------------------------------------------------------------
2
+ // DEAR IMGUI COMPILE-TIME OPTIONS
3
+ // Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
4
+ // You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
5
+ //-----------------------------------------------------------------------------
6
+ // A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it)
7
+ // B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template.
8
+ //-----------------------------------------------------------------------------
9
+ // You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp
10
+ // files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
11
+ // Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
12
+ // Call IMGUI_CHECKVERSION() from your .cpp file to verify that the data structures your files are using are matching the ones imgui.cpp is using.
13
+ //-----------------------------------------------------------------------------
14
+
15
+ #pragma once
16
+
17
+ //---- Define assertion handler. Defaults to calling assert().
18
+ // If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
19
+ //#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
20
+ //#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
21
+
22
+ //---- Define attributes of all API symbols declarations, e.g. for DLL under Windows
23
+ // Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
24
+ // - Windows DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
25
+ // for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
26
+ //#define IMGUI_API __declspec(dllexport) // MSVC Windows: DLL export
27
+ //#define IMGUI_API __declspec(dllimport) // MSVC Windows: DLL import
28
+ //#define IMGUI_API __attribute__((visibility("default"))) // GCC/Clang: override visibility when set is hidden
29
+
30
+ //---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names.
31
+ //#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
32
+
33
+ //---- Disable all of Dear ImGui or don't implement standard windows/tools.
34
+ // It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp.
35
+ //#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
36
+ //#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty.
37
+ //#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty.
38
+
39
+ //---- Don't implement some functions to reduce linkage requirements.
40
+ //#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a)
41
+ //#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW)
42
+ //#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a)
43
+ //#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME).
44
+ //#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).
45
+ //#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS // Don't implement default platform_io.Platform_OpenInShellFn() handler (Win32: ShellExecute(), require shell32.lib/.a, Mac/Linux: use system("")).
46
+ //#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)
47
+ //#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
48
+ //#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
49
+ //#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
50
+ //#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
51
+ //#define IMGUI_DISABLE_DEFAULT_FONT // Disable default embedded font (ProggyClean.ttf), remove ~9.5 KB from output binary. AddFontDefault() will assert.
52
+ //#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
53
+
54
+ //---- Enable Test Engine / Automation features.
55
+ //#define IMGUI_ENABLE_TEST_ENGINE // Enable imgui_test_engine hooks. Generally set automatically by include "imgui_te_config.h", see Test Engine for details.
56
+
57
+ //---- Include imgui_user.h at the end of imgui.h as a convenience
58
+ // May be convenient for some users to only explicitly include vanilla imgui.h and have extra stuff included.
59
+ //#define IMGUI_INCLUDE_IMGUI_USER_H
60
+ //#define IMGUI_USER_H_FILENAME "my_folder/my_imgui_user.h"
61
+
62
+ //---- Pack vertex colors as BGRA8 instead of RGBA8 (to avoid converting from one to another). Need dedicated backend support.
63
+ //#define IMGUI_USE_BGRA_PACKED_COLOR
64
+
65
+ //---- Use legacy CRC32-adler tables (used before 1.91.6), in order to preserve old .ini data that you cannot afford to invalidate.
66
+ //#define IMGUI_USE_LEGACY_CRC32_ADLER
67
+
68
+ //---- Use 32-bit for ImWchar (default is 16-bit) to support Unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
69
+ //#define IMGUI_USE_WCHAR32
70
+
71
+ //---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
72
+ // By default the embedded implementations are declared static and not available outside of Dear ImGui sources files.
73
+ //#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
74
+ //#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
75
+ //#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if IMGUI_USE_STB_SPRINTF is defined.
76
+ //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
77
+ //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
78
+ //#define IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION // only disabled if IMGUI_USE_STB_SPRINTF is defined.
79
+
80
+ //---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)
81
+ // Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h.
82
+ //#define IMGUI_USE_STB_SPRINTF
83
+
84
+ //---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui)
85
+ // Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided).
86
+ // On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.
87
+ //#define IMGUI_ENABLE_FREETYPE
88
+
89
+ //---- Use FreeType + plutosvg or lunasvg to render OpenType SVG fonts (SVGinOT)
90
+ // Only works in combination with IMGUI_ENABLE_FREETYPE.
91
+ // - lunasvg is currently easier to acquire/install, as e.g. it is part of vcpkg.
92
+ // - plutosvg will support more fonts and may load them faster. It currently requires to be built manually but it is fairly easy. See misc/freetype/README for instructions.
93
+ // - Both require headers to be available in the include path + program to be linked with the library code (not provided).
94
+ // - (note: lunasvg implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement)
95
+ //#define IMGUI_ENABLE_FREETYPE_PLUTOSVG
96
+ //#define IMGUI_ENABLE_FREETYPE_LUNASVG
97
+
98
+ //---- Use stb_truetype to build and rasterize the font atlas (default)
99
+ // The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.
100
+ //#define IMGUI_ENABLE_STB_TRUETYPE
101
+
102
+ //---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
103
+ // This will be inlined as part of ImVec2 and ImVec4 class declarations.
104
+ /*
105
+ #define IM_VEC2_CLASS_EXTRA \
106
+ constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \
107
+ operator MyVec2() const { return MyVec2(x,y); }
108
+
109
+ #define IM_VEC4_CLASS_EXTRA \
110
+ constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \
111
+ operator MyVec4() const { return MyVec4(x,y,z,w); }
112
+ */
113
+ //---- ...Or use Dear ImGui's own very basic math operators.
114
+ //#define IMGUI_DEFINE_MATH_OPERATORS
115
+
116
+ //---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices.
117
+ // Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices).
118
+ // Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer.
119
+ // Read about ImGuiBackendFlags_RendererHasVtxOffset for details.
120
+ //#define ImDrawIdx unsigned int
121
+
122
+ //---- Override ImDrawCallback signature (will need to modify renderer backends accordingly)
123
+ //struct ImDrawList;
124
+ //struct ImDrawCmd;
125
+ //typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);
126
+ //#define ImDrawCallback MyImDrawCallback
127
+
128
+ //---- Debug Tools: Macro to break in Debugger (we provide a default implementation of this in the codebase)
129
+ // (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)
130
+ //#define IM_DEBUG_BREAK IM_ASSERT(0)
131
+ //#define IM_DEBUG_BREAK __debugbreak()
132
+
133
+ //---- Debug Tools: Enable slower asserts
134
+ //#define IMGUI_DEBUG_PARANOID
135
+
136
+ //---- Tip: You can add extra functions within the ImGui:: namespace from anywhere (e.g. your own sources/header files)
137
+ /*
138
+ namespace ImGui
139
+ {
140
+ void MyFunction(const char* name, MyMatrix44* mtx);
141
+ }
142
+ */
3rdparty/imgui/imgui.cpp ADDED
The diff for this file is too large to render. See raw diff
 
3rdparty/imgui/imgui.h ADDED
The diff for this file is too large to render. See raw diff
 
3rdparty/imgui/imgui.vcxproj ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3
+ <ItemGroup Label="ProjectConfigurations">
4
+ <ProjectConfiguration Include="Debug|Win32">
5
+ <Configuration>Debug</Configuration>
6
+ <Platform>Win32</Platform>
7
+ </ProjectConfiguration>
8
+ <ProjectConfiguration Include="Release|Win32">
9
+ <Configuration>Release</Configuration>
10
+ <Platform>Win32</Platform>
11
+ </ProjectConfiguration>
12
+ <ProjectConfiguration Include="Debug|x64">
13
+ <Configuration>Debug</Configuration>
14
+ <Platform>x64</Platform>
15
+ </ProjectConfiguration>
16
+ <ProjectConfiguration Include="Release|x64">
17
+ <Configuration>Release</Configuration>
18
+ <Platform>x64</Platform>
19
+ </ProjectConfiguration>
20
+ </ItemGroup>
21
+ <PropertyGroup Label="Globals">
22
+ <VCProjectVersion>17.0</VCProjectVersion>
23
+ <Keyword>Win32Proj</Keyword>
24
+ <ProjectGuid>{08de3ce9-d0c0-4426-aaa6-1ada88494be3}</ProjectGuid>
25
+ <RootNamespace>imgui</RootNamespace>
26
+ <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
27
+ </PropertyGroup>
28
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
29
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
30
+ <ConfigurationType>StaticLibrary</ConfigurationType>
31
+ <UseDebugLibraries>true</UseDebugLibraries>
32
+ <PlatformToolset>v143</PlatformToolset>
33
+ <CharacterSet>Unicode</CharacterSet>
34
+ </PropertyGroup>
35
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
36
+ <ConfigurationType>StaticLibrary</ConfigurationType>
37
+ <UseDebugLibraries>false</UseDebugLibraries>
38
+ <PlatformToolset>v143</PlatformToolset>
39
+ <WholeProgramOptimization>true</WholeProgramOptimization>
40
+ <CharacterSet>Unicode</CharacterSet>
41
+ </PropertyGroup>
42
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
43
+ <ConfigurationType>StaticLibrary</ConfigurationType>
44
+ <UseDebugLibraries>true</UseDebugLibraries>
45
+ <PlatformToolset>v143</PlatformToolset>
46
+ <CharacterSet>Unicode</CharacterSet>
47
+ </PropertyGroup>
48
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
49
+ <ConfigurationType>StaticLibrary</ConfigurationType>
50
+ <UseDebugLibraries>false</UseDebugLibraries>
51
+ <PlatformToolset>v143</PlatformToolset>
52
+ <WholeProgramOptimization>true</WholeProgramOptimization>
53
+ <CharacterSet>Unicode</CharacterSet>
54
+ </PropertyGroup>
55
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
56
+ <ImportGroup Label="ExtensionSettings">
57
+ </ImportGroup>
58
+ <ImportGroup Label="Shared">
59
+ </ImportGroup>
60
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
61
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
62
+ </ImportGroup>
63
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
64
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
65
+ </ImportGroup>
66
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
67
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
68
+ </ImportGroup>
69
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
70
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
71
+ </ImportGroup>
72
+ <PropertyGroup Label="UserMacros" />
73
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
74
+ <ClCompile>
75
+ <WarningLevel>Level3</WarningLevel>
76
+ <SDLCheck>true</SDLCheck>
77
+ <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
78
+ <ConformanceMode>true</ConformanceMode>
79
+ <PrecompiledHeader>Use</PrecompiledHeader>
80
+ <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
81
+ </ClCompile>
82
+ <Link>
83
+ <SubSystem>
84
+ </SubSystem>
85
+ <GenerateDebugInformation>true</GenerateDebugInformation>
86
+ </Link>
87
+ </ItemDefinitionGroup>
88
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
89
+ <ClCompile>
90
+ <WarningLevel>Level3</WarningLevel>
91
+ <FunctionLevelLinking>true</FunctionLevelLinking>
92
+ <IntrinsicFunctions>true</IntrinsicFunctions>
93
+ <SDLCheck>true</SDLCheck>
94
+ <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
95
+ <ConformanceMode>true</ConformanceMode>
96
+ <PrecompiledHeader>Use</PrecompiledHeader>
97
+ <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
98
+ </ClCompile>
99
+ <Link>
100
+ <SubSystem>
101
+ </SubSystem>
102
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
103
+ <OptimizeReferences>true</OptimizeReferences>
104
+ <GenerateDebugInformation>true</GenerateDebugInformation>
105
+ </Link>
106
+ </ItemDefinitionGroup>
107
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
108
+ <ClCompile>
109
+ <WarningLevel>Level3</WarningLevel>
110
+ <SDLCheck>true</SDLCheck>
111
+ <PreprocessorDefinitions>_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
112
+ <ConformanceMode>true</ConformanceMode>
113
+ <PrecompiledHeader>Use</PrecompiledHeader>
114
+ <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
115
+ </ClCompile>
116
+ <Link>
117
+ <SubSystem>
118
+ </SubSystem>
119
+ <GenerateDebugInformation>true</GenerateDebugInformation>
120
+ </Link>
121
+ </ItemDefinitionGroup>
122
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
123
+ <ClCompile>
124
+ <WarningLevel>Level3</WarningLevel>
125
+ <FunctionLevelLinking>true</FunctionLevelLinking>
126
+ <IntrinsicFunctions>true</IntrinsicFunctions>
127
+ <SDLCheck>true</SDLCheck>
128
+ <PreprocessorDefinitions>NDEBUG;_LIB;WIN32;_WINDOWS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;_USE_MATH_DEFINES;IMGUI_ENABLE_FREETYPE;CMAKE_INTDIR="Release";%(PreprocessorDefinitions)</PreprocessorDefinitions>
129
+ <ConformanceMode>true</ConformanceMode>
130
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
131
+ <PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
132
+ <AdditionalIncludeDirectories>E:\huggingface\imradv3\3rdparty\imgui;E:\huggingface\imradv3\3rdparty\freetype\include;E:\huggingface\imradv3\3rdparty\glfw\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
133
+ </ClCompile>
134
+ <Link>
135
+ <SubSystem>
136
+ </SubSystem>
137
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
138
+ <OptimizeReferences>true</OptimizeReferences>
139
+ <GenerateDebugInformation>true</GenerateDebugInformation>
140
+ </Link>
141
+ </ItemDefinitionGroup>
142
+ <ItemGroup>
143
+ <ClCompile Include=".\imgui.cpp" />
144
+ <ClCompile Include=".\imgui_demo.cpp" />
145
+ <ClCompile Include=".\imgui_draw.cpp" />
146
+ <ClCompile Include=".\imgui_tables.cpp" />
147
+ <ClCompile Include=".\imgui_widgets.cpp" />
148
+ <ClInclude Include=".\imconfig.h" />
149
+ <ClInclude Include=".\imgui.h" />
150
+ <ClInclude Include=".\imgui_internal.h" />
151
+ <ClInclude Include=".\imstb_rectpack.h" />
152
+ <ClInclude Include=".\imstb_textedit.h" />
153
+ <ClInclude Include=".\imstb_truetype.h" />
154
+ <ClCompile Include=".\misc\cpp\imgui_stdlib.cpp" />
155
+ <ClCompile Include=".\misc\freetype\imgui_freetype.cpp" />
156
+ <ClCompile Include=".\backends\imgui_impl_opengl3.cpp" />
157
+ <ClCompile Include=".\backends\imgui_impl_glfw.cpp" />
158
+ </ItemGroup>
159
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
160
+ <ImportGroup Label="ExtensionTargets">
161
+ </ImportGroup>
162
+ </Project>
3rdparty/imgui/imgui_demo.cpp ADDED
The diff for this file is too large to render. See raw diff
 
3rdparty/imgui/imgui_draw.cpp ADDED
The diff for this file is too large to render. See raw diff
 
3rdparty/imgui/imgui_internal.h ADDED
The diff for this file is too large to render. See raw diff
 
3rdparty/imgui/imgui_tables.cpp ADDED
The diff for this file is too large to render. See raw diff