-
Notifications
You must be signed in to change notification settings - Fork 174
/
imgui-SFML.cpp
1468 lines (1289 loc) · 50.7 KB
/
imgui-SFML.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "imgui-SFML.h"
#include <imgui.h>
#include <SFML/Config.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderTexture.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/OpenGL.hpp>
#include <SFML/Window/Clipboard.hpp>
#include <SFML/Window/Cursor.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Touch.hpp>
#include <SFML/Window/Window.hpp>
#include <cassert>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <memory>
#include <vector>
#if defined(__APPLE__)
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#ifdef ANDROID
#ifdef USE_JNI
#include <SFML/System/NativeActivity.hpp>
#include <android/native_activity.h>
#include <jni.h>
int openKeyboardIME()
{
ANativeActivity* activity = sf::getNativeActivity();
JavaVM* vm = activity->vm;
JNIEnv* env = activity->env;
JavaVMAttachArgs attachargs;
attachargs.version = JNI_VERSION_1_6;
attachargs.name = "NativeThread";
attachargs.group = nullptr;
jint res = vm->AttachCurrentThread(&env, &attachargs);
if (res == JNI_ERR)
return EXIT_FAILURE;
jclass natact = env->FindClass("android/app/NativeActivity");
jclass context = env->FindClass("android/content/Context");
jfieldID fid = env->GetStaticFieldID(context, "INPUT_METHOD_SERVICE", "Ljava/lang/String;");
jobject svcstr = env->GetStaticObjectField(context, fid);
jmethodID getss = env->GetMethodID(natact, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
jobject imm_obj = env->CallObjectMethod(activity->clazz, getss, svcstr);
jclass imm_cls = env->GetObjectClass(imm_obj);
jmethodID toggleSoftInput = env->GetMethodID(imm_cls, "toggleSoftInput", "(II)V");
env->CallVoidMethod(imm_obj, toggleSoftInput, 2, 0);
env->DeleteLocalRef(imm_obj);
env->DeleteLocalRef(imm_cls);
env->DeleteLocalRef(svcstr);
env->DeleteLocalRef(context);
env->DeleteLocalRef(natact);
vm->DetachCurrentThread();
return EXIT_SUCCESS;
}
int closeKeyboardIME()
{
ANativeActivity* activity = sf::getNativeActivity();
JavaVM* vm = activity->vm;
JNIEnv* env = activity->env;
JavaVMAttachArgs attachargs;
attachargs.version = JNI_VERSION_1_6;
attachargs.name = "NativeThread";
attachargs.group = nullptr;
jint res = vm->AttachCurrentThread(&env, &attachargs);
if (res == JNI_ERR)
return EXIT_FAILURE;
jclass natact = env->FindClass("android/app/NativeActivity");
jclass context = env->FindClass("android/content/Context");
jfieldID fid = env->GetStaticFieldID(context, "INPUT_METHOD_SERVICE", "Ljava/lang/String;");
jobject svcstr = env->GetStaticObjectField(context, fid);
jmethodID getss = env->GetMethodID(natact, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
jobject imm_obj = env->CallObjectMethod(activity->clazz, getss, svcstr);
jclass imm_cls = env->GetObjectClass(imm_obj);
jmethodID toggleSoftInput = env->GetMethodID(imm_cls, "toggleSoftInput", "(II)V");
env->CallVoidMethod(imm_obj, toggleSoftInput, 1, 0);
env->DeleteLocalRef(imm_obj);
env->DeleteLocalRef(imm_cls);
env->DeleteLocalRef(svcstr);
env->DeleteLocalRef(context);
env->DeleteLocalRef(natact);
vm->DetachCurrentThread();
return EXIT_SUCCESS;
}
#endif
#endif
static_assert(sizeof(GLuint) <= sizeof(ImTextureID), "ImTextureID is not large enough to fit GLuint.");
namespace
{
// various helper functions
[[nodiscard]] ImColor toImColor(sf::Color c)
{
return {int{c.r}, int{c.g}, int{c.b}, int{c.a}};
}
[[nodiscard]] ImVec2 toImVec2(const sf::Vector2f& v)
{
return {v.x, v.y};
}
[[nodiscard]] sf::Vector2f toSfVector2f(const ImVec2& v)
{
return {v.x, v.y};
}
[[nodiscard]] ImVec2 getTopLeftAbsolute(const sf::FloatRect& rect)
{
return toImVec2(toSfVector2f(ImGui::GetCursorScreenPos()) + rect.position);
}
[[nodiscard]] ImVec2 getDownRightAbsolute(const sf::FloatRect& rect)
{
return toImVec2(toSfVector2f(ImGui::GetCursorScreenPos()) + rect.position + rect.size);
}
[[nodiscard]] ImTextureID convertGLTextureHandleToImTextureID(GLuint glTextureHandle)
{
ImTextureID textureID{};
std::memcpy(&textureID, &glTextureHandle, sizeof(GLuint));
return textureID;
}
[[nodiscard]] GLuint convertImTextureIDToGLTextureHandle(ImTextureID textureID)
{
GLuint glTextureHandle = 0;
std::memcpy(&glTextureHandle, &textureID, sizeof(GLuint));
return glTextureHandle;
}
struct SpriteTextureData
{
ImVec2 uv0;
ImVec2 uv1;
ImTextureID textureID{};
};
[[nodiscard]] SpriteTextureData getSpriteTextureData(const sf::Sprite& sprite)
{
const sf::Texture& texture(sprite.getTexture());
const sf::Vector2f textureSize(texture.getSize());
const sf::FloatRect textureRect(sprite.getTextureRect());
return {toImVec2(textureRect.position.componentWiseDiv(textureSize)),
toImVec2((textureRect.position + textureRect.size).componentWiseDiv(textureSize)),
convertGLTextureHandleToImTextureID(texture.getNativeHandle())};
}
void RenderDrawLists(ImDrawData* draw_data); // rendering callback function prototype
// Default mapping is XInput gamepad mapping
void initDefaultJoystickMapping();
// data
constexpr unsigned int NULL_JOYSTICK_ID = sf::Joystick::Count;
// Returns first id of connected joystick
[[nodiscard]] unsigned int getConnectedJoystickId()
{
for (unsigned int i = 0; i < sf::Joystick::Count; ++i)
{
if (sf::Joystick::isConnected(i))
return i;
}
return NULL_JOYSTICK_ID;
}
void updateJoystickButtonState(ImGuiIO& io);
void updateJoystickDPadState(ImGuiIO& io);
void updateJoystickAxisState(ImGuiIO& io);
// clipboard functions
void setClipboardText(ImGuiContext* /*ctx*/, const char* text)
{
sf::Clipboard::setString(sf::String::fromUtf8(text, text + std::strlen(text)));
}
[[nodiscard]] const char* getClipboardText(ImGuiContext* /*ctx*/)
{
static std::string s_clipboardText;
auto tmp = sf::Clipboard::getString().toUtf8();
s_clipboardText.assign(tmp.begin(), tmp.end());
return s_clipboardText.c_str();
}
// mouse cursors
void updateMouseCursor(sf::Window& window);
// Key mappings
[[nodiscard]] ImGuiKey keycodeToImGuiKey(sf::Keyboard::Key code);
[[nodiscard]] ImGuiKey keycodeToImGuiMod(sf::Keyboard::Key code);
struct StickInfo
{
sf::Joystick::Axis xAxis{sf::Joystick::Axis::X};
sf::Joystick::Axis yAxis{sf::Joystick::Axis::Y};
bool xInverted{false};
bool yInverted{false};
float threshold{15};
};
struct TriggerInfo
{
sf::Joystick::Axis axis{sf::Joystick::Axis::Z};
float threshold{0};
};
struct WindowContext
{
const sf::Window* window;
ImGuiContext* imContext{ImGui::CreateContext()};
std::optional<sf::Texture> fontTexture; // internal font atlas which is used if user doesn't set
// a custom sf::Texture.
bool windowHasFocus;
bool mouseMoved{false};
bool mousePressed[3] = {false};
ImGuiMouseCursor lastCursor{ImGuiMouseCursor_COUNT};
bool touchDown[3] = {false};
sf::Vector2i touchPos;
unsigned int joystickId{getConnectedJoystickId()};
ImGuiKey joystickMapping[sf::Joystick::ButtonCount] = {ImGuiKey_None};
StickInfo dPadInfo;
StickInfo lStickInfo;
StickInfo rStickInfo;
TriggerInfo lTriggerInfo;
TriggerInfo rTriggerInfo;
std::optional<sf::Cursor> mouseCursors[ImGuiMouseCursor_COUNT];
#ifdef ANDROID
#ifdef USE_JNI
bool wantTextInput{false};
#endif
#endif
WindowContext(const sf::Window* w) : window(w), windowHasFocus(window->hasFocus())
{
}
~WindowContext()
{
ImGui::DestroyContext(imContext);
}
WindowContext(const WindowContext&) = delete; // non construction-copyable
WindowContext& operator=(const WindowContext&) = delete; // non copyable
};
std::vector<std::unique_ptr<WindowContext>> s_windowContexts;
WindowContext* s_currWindowCtx = nullptr;
} // end of anonymous namespace
namespace ImGui
{
namespace SFML
{
bool Init(sf::RenderWindow& window, bool loadDefaultFont)
{
return Init(window, window, loadDefaultFont);
}
bool Init(sf::Window& window, sf::RenderTarget& target, bool loadDefaultFont)
{
return Init(window, sf::Vector2f(target.getSize()), loadDefaultFont);
}
bool Init(sf::Window& window, const sf::Vector2f& displaySize, bool loadDefaultFont)
{
s_currWindowCtx = s_windowContexts.emplace_back(std::make_unique<WindowContext>(&window)).get();
ImGui::SetCurrentContext(s_currWindowCtx->imContext);
ImGuiIO& io = ImGui::GetIO();
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
// tell ImGui which features we support
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos;
io.BackendPlatformName = "imgui_impl_sfml";
s_currWindowCtx->joystickId = getConnectedJoystickId();
initDefaultJoystickMapping();
// init rendering
io.DisplaySize = toImVec2(displaySize);
// clipboard
platform_io.Platform_SetClipboardTextFn = setClipboardText;
platform_io.Platform_GetClipboardTextFn = getClipboardText;
// load mouse cursors
const auto loadMouseCursor = [](ImGuiMouseCursor imguiCursorType, sf::Cursor::Type sfmlCursorType)
{ s_currWindowCtx->mouseCursors[imguiCursorType] = sf::Cursor::createFromSystem(sfmlCursorType); };
loadMouseCursor(ImGuiMouseCursor_Arrow, sf::Cursor::Type::Arrow);
loadMouseCursor(ImGuiMouseCursor_TextInput, sf::Cursor::Type::Text);
loadMouseCursor(ImGuiMouseCursor_ResizeAll, sf::Cursor::Type::SizeAll);
loadMouseCursor(ImGuiMouseCursor_ResizeNS, sf::Cursor::Type::SizeVertical);
loadMouseCursor(ImGuiMouseCursor_ResizeEW, sf::Cursor::Type::SizeHorizontal);
loadMouseCursor(ImGuiMouseCursor_ResizeNESW, sf::Cursor::Type::SizeBottomLeftTopRight);
loadMouseCursor(ImGuiMouseCursor_ResizeNWSE, sf::Cursor::Type::SizeTopLeftBottomRight);
loadMouseCursor(ImGuiMouseCursor_Hand, sf::Cursor::Type::Hand);
if (loadDefaultFont)
{
// this will load default font automatically
// No need to call AddDefaultFont
return UpdateFontTexture();
}
return true;
}
void SetCurrentWindow(const sf::Window& window)
{
auto found = std::find_if(s_windowContexts.begin(),
s_windowContexts.end(),
[&](std::unique_ptr<WindowContext>& ctx)
{ return ctx->window->getNativeHandle() == window.getNativeHandle(); });
assert(found != s_windowContexts.end() &&
"Failed to find the window. Forgot to call ImGui::SFML::Init for the window?");
s_currWindowCtx = found->get();
ImGui::SetCurrentContext(s_currWindowCtx->imContext);
}
void ProcessEvent(const sf::Window& window, const sf::Event& event)
{
SetCurrentWindow(window);
assert(s_currWindowCtx && "No current window is set - forgot to call ImGui::SFML::Init?");
ImGuiIO& io = ImGui::GetIO();
if (s_currWindowCtx->windowHasFocus)
{
if (const auto* resized = event.getIf<sf::Event::Resized>())
{
io.DisplaySize = ImVec2(static_cast<float>(resized->size.x), static_cast<float>(resized->size.y));
}
else if (const auto* mouseMoved = event.getIf<sf::Event::MouseMoved>())
{
io.AddMousePosEvent(static_cast<float>(mouseMoved->position.x), static_cast<float>(mouseMoved->position.y));
s_currWindowCtx->mouseMoved = true;
}
else if (const auto* mouseButtonPressed = event.getIf<sf::Event::MouseButtonPressed>())
{
const int button = static_cast<int>(mouseButtonPressed->button);
if (button >= 0 && button < 3)
{
s_currWindowCtx->mousePressed[static_cast<int>(mouseButtonPressed->button)] = true;
io.AddMouseButtonEvent(button, true);
}
}
else if (const auto* mouseButtonReleased = event.getIf<sf::Event::MouseButtonReleased>())
{
const int button = static_cast<int>(mouseButtonReleased->button);
if (button >= 0 && button < 3)
io.AddMouseButtonEvent(button, false);
}
else if (const auto* touchBegan = event.getIf<sf::Event::TouchBegan>())
{
s_currWindowCtx->mouseMoved = false;
const unsigned int button = touchBegan->finger;
if (button < 3)
s_currWindowCtx->touchDown[touchBegan->finger] = true;
}
else if (event.is<sf::Event::TouchEnded>())
{
s_currWindowCtx->mouseMoved = false;
}
else if (const auto* mouseWheelScrolled = event.getIf<sf::Event::MouseWheelScrolled>())
{
if (mouseWheelScrolled->wheel == sf::Mouse::Wheel::Vertical ||
(mouseWheelScrolled->wheel == sf::Mouse::Wheel::Horizontal && io.KeyShift))
{
io.AddMouseWheelEvent(0, mouseWheelScrolled->delta);
}
else if (mouseWheelScrolled->wheel == sf::Mouse::Wheel::Horizontal)
{
io.AddMouseWheelEvent(mouseWheelScrolled->delta, 0);
}
}
const auto handleKeyChanged = [&io](const auto& keyChanged, bool down)
{
const ImGuiKey mod = keycodeToImGuiMod(keyChanged.code);
// The modifier booleans are not reliable when it's the modifier
// itself that's being pressed. Detect these presses directly.
if (mod != ImGuiKey_None)
{
io.AddKeyEvent(mod, down);
}
else
{
io.AddKeyEvent(ImGuiMod_Ctrl, keyChanged.control);
io.AddKeyEvent(ImGuiMod_Shift, keyChanged.shift);
io.AddKeyEvent(ImGuiMod_Alt, keyChanged.alt);
io.AddKeyEvent(ImGuiMod_Super, keyChanged.system);
}
const ImGuiKey key = keycodeToImGuiKey(keyChanged.code);
io.AddKeyEvent(key, down);
io.SetKeyEventNativeData(key, static_cast<int>(keyChanged.code), -1);
};
if (const auto* keyPressed = event.getIf<sf::Event::KeyPressed>())
{
handleKeyChanged(*keyPressed, true);
}
else if (const auto* keyReleased = event.getIf<sf::Event::KeyReleased>())
{
handleKeyChanged(*keyReleased, false);
}
else if (const auto* textEntered = event.getIf<sf::Event::TextEntered>())
{
// Don't handle the event for unprintable characters
if (textEntered->unicode >= ' ' && textEntered->unicode != 127)
io.AddInputCharacter(textEntered->unicode);
}
else if (const auto* joystickConnected = event.getIf<sf::Event::JoystickConnected>())
{
if (s_currWindowCtx->joystickId == NULL_JOYSTICK_ID)
s_currWindowCtx->joystickId = joystickConnected->joystickId;
}
else if (const auto* joystickDisconnected = event.getIf<sf::Event::JoystickDisconnected>())
{
if (s_currWindowCtx->joystickId == joystickDisconnected->joystickId)
// used gamepad was disconnected
s_currWindowCtx->joystickId = getConnectedJoystickId();
}
}
if (event.is<sf::Event::FocusLost>())
{
io.AddFocusEvent(false);
s_currWindowCtx->windowHasFocus = false;
}
if (event.is<sf::Event::FocusGained>())
{
io.AddFocusEvent(true);
s_currWindowCtx->windowHasFocus = true;
}
}
void Update(sf::RenderWindow& window, sf::Time dt)
{
Update(window, window, dt);
}
void Update(sf::Window& window, sf::RenderTarget& target, sf::Time dt)
{
SetCurrentWindow(window);
assert(s_currWindowCtx);
// Update OS/hardware mouse cursor if imgui isn't drawing a software cursor
const ImGuiMouseCursor mouse_cursor = ImGui::GetIO().MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor();
if (s_currWindowCtx->lastCursor != mouse_cursor)
{
s_currWindowCtx->lastCursor = mouse_cursor;
updateMouseCursor(window);
}
if (!s_currWindowCtx->mouseMoved)
{
if (sf::Touch::isDown(0))
s_currWindowCtx->touchPos = sf::Touch::getPosition(0, window);
Update(s_currWindowCtx->touchPos, sf::Vector2f(target.getSize()), dt);
}
else
{
Update(sf::Mouse::getPosition(window), sf::Vector2f(target.getSize()), dt);
}
}
void Update(const sf::Vector2i& mousePos, const sf::Vector2f& displaySize, sf::Time dt)
{
assert(s_currWindowCtx && "No current window is set - forgot to call ImGui::SFML::Init?");
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = toImVec2(displaySize);
io.DeltaTime = dt.asSeconds();
if (s_currWindowCtx->windowHasFocus)
{
if (io.WantSetMousePos)
{
const sf::Vector2i newMousePos(static_cast<int>(io.MousePos.x), static_cast<int>(io.MousePos.y));
sf::Mouse::setPosition(newMousePos);
}
else
{
io.MousePos = ImVec2(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y));
}
for (unsigned int i = 0; i < 3; i++)
{
io.MouseDown[i] = s_currWindowCtx->touchDown[i] || sf::Touch::isDown(i) ||
s_currWindowCtx->mousePressed[i] || sf::Mouse::isButtonPressed((sf::Mouse::Button)i);
s_currWindowCtx->mousePressed[i] = false;
s_currWindowCtx->touchDown[i] = false;
}
}
#ifdef ANDROID
#ifdef USE_JNI
if (io.WantTextInput && !s_currWindowCtx->wantTextInput)
{
openKeyboardIME();
s_currWindowCtx->wantTextInput = true;
}
if (!io.WantTextInput && s_currWindowCtx->wantTextInput)
{
closeKeyboardIME();
s_currWindowCtx->wantTextInput = false;
}
#endif
#endif
assert(io.Fonts->Fonts.Size > 0); // You forgot to create and set up font
// atlas (see createFontTexture)
// gamepad navigation
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) && s_currWindowCtx->joystickId != NULL_JOYSTICK_ID)
{
updateJoystickButtonState(io);
updateJoystickDPadState(io);
updateJoystickAxisState(io);
}
ImGui::NewFrame();
}
void Render(sf::RenderWindow& window)
{
SetCurrentWindow(window);
Render(static_cast<sf::RenderTarget&>(window));
}
void Render(sf::RenderTarget& target)
{
target.resetGLStates();
target.pushGLStates();
ImGui::Render();
RenderDrawLists(ImGui::GetDrawData());
target.popGLStates();
}
void Render()
{
ImGui::Render();
RenderDrawLists(ImGui::GetDrawData());
}
void Shutdown(const sf::Window& window)
{
const bool needReplacement = (s_currWindowCtx->window->getNativeHandle() == window.getNativeHandle());
// remove window's context
auto found = std::find_if(s_windowContexts.begin(),
s_windowContexts.end(),
[&](std::unique_ptr<WindowContext>& ctx)
{ return ctx->window->getNativeHandle() == window.getNativeHandle(); });
assert(found != s_windowContexts.end() &&
"Window wasn't inited properly: forgot to call ImGui::SFML::Init(window)?");
s_windowContexts.erase(found); // s_currWindowCtx can become invalid here!
// set current context to some window for convenience if needed
if (needReplacement)
{
auto it = s_windowContexts.begin();
if (it != s_windowContexts.end())
{
// set to some other window
s_currWindowCtx = it->get();
ImGui::SetCurrentContext(s_currWindowCtx->imContext);
}
else
{
// no alternatives...
s_currWindowCtx = nullptr;
ImGui::SetCurrentContext(nullptr);
}
}
}
void Shutdown()
{
s_currWindowCtx = nullptr;
ImGui::SetCurrentContext(nullptr);
s_windowContexts.clear();
}
bool UpdateFontTexture()
{
assert(s_currWindowCtx);
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels = nullptr;
int width = 0;
int height = 0;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
sf::Texture newTexture;
if (!newTexture.resize({static_cast<unsigned>(width), static_cast<unsigned>(height)}))
{
return false;
}
newTexture.update(pixels);
ImTextureID texID = convertGLTextureHandleToImTextureID(newTexture.getNativeHandle());
io.Fonts->SetTexID(texID);
s_currWindowCtx->fontTexture = std::move(newTexture);
return true;
}
std::optional<sf::Texture>& GetFontTexture()
{
assert(s_currWindowCtx);
return s_currWindowCtx->fontTexture;
}
void SetActiveJoystickId(unsigned int joystickId)
{
assert(s_currWindowCtx);
assert(joystickId < sf::Joystick::Count);
s_currWindowCtx->joystickId = joystickId;
}
void SetJoystickDPadThreshold(float threshold)
{
assert(s_currWindowCtx);
assert(threshold >= 0.f && threshold <= 100.f);
s_currWindowCtx->dPadInfo.threshold = threshold;
}
void SetJoystickLStickThreshold(float threshold)
{
assert(s_currWindowCtx);
assert(threshold >= 0.f && threshold <= 100.f);
s_currWindowCtx->lStickInfo.threshold = threshold;
}
void SetJoystickRStickThreshold(float threshold)
{
assert(s_currWindowCtx);
assert(threshold >= 0.f && threshold <= 100.f);
s_currWindowCtx->rStickInfo.threshold = threshold;
}
void SetJoystickLTriggerThreshold(float threshold)
{
assert(s_currWindowCtx);
assert(threshold >= -100.f && threshold <= 100.f);
s_currWindowCtx->lTriggerInfo.threshold = threshold;
}
void SetJoystickRTriggerThreshold(float threshold)
{
assert(s_currWindowCtx);
assert(threshold >= -100.f && threshold <= 100.f);
s_currWindowCtx->rTriggerInfo.threshold = threshold;
}
void SetJoystickMapping(int key, unsigned int joystickButton)
{
assert(s_currWindowCtx);
assert(key >= ImGuiKey_NamedKey_BEGIN);
assert(key < ImGuiKey_NamedKey_END);
assert(joystickButton < sf::Joystick::ButtonCount);
s_currWindowCtx->joystickMapping[joystickButton] = static_cast<ImGuiKey>(key);
}
void SetDPadXAxis(sf::Joystick::Axis dPadXAxis, bool inverted)
{
assert(s_currWindowCtx);
s_currWindowCtx->dPadInfo.xAxis = dPadXAxis;
s_currWindowCtx->dPadInfo.xInverted = inverted;
}
void SetDPadYAxis(sf::Joystick::Axis dPadYAxis, bool inverted)
{
assert(s_currWindowCtx);
s_currWindowCtx->dPadInfo.yAxis = dPadYAxis;
s_currWindowCtx->dPadInfo.yInverted = inverted;
}
void SetLStickXAxis(sf::Joystick::Axis lStickXAxis, bool inverted)
{
assert(s_currWindowCtx);
s_currWindowCtx->lStickInfo.xAxis = lStickXAxis;
s_currWindowCtx->lStickInfo.xInverted = inverted;
}
void SetLStickYAxis(sf::Joystick::Axis lStickYAxis, bool inverted)
{
assert(s_currWindowCtx);
s_currWindowCtx->lStickInfo.yAxis = lStickYAxis;
s_currWindowCtx->lStickInfo.yInverted = inverted;
}
void SetRStickXAxis(sf::Joystick::Axis rStickXAxis, bool inverted)
{
assert(s_currWindowCtx);
s_currWindowCtx->rStickInfo.xAxis = rStickXAxis;
s_currWindowCtx->rStickInfo.xInverted = inverted;
}
void SetRStickYAxis(sf::Joystick::Axis rStickYAxis, bool inverted)
{
assert(s_currWindowCtx);
s_currWindowCtx->rStickInfo.yAxis = rStickYAxis;
s_currWindowCtx->rStickInfo.yInverted = inverted;
}
void SetLTriggerAxis(sf::Joystick::Axis lTriggerAxis)
{
assert(s_currWindowCtx);
s_currWindowCtx->rTriggerInfo.axis = lTriggerAxis;
}
void SetRTriggerAxis(sf::Joystick::Axis rTriggerAxis)
{
assert(s_currWindowCtx);
s_currWindowCtx->rTriggerInfo.axis = rTriggerAxis;
}
} // end of namespace SFML
/////////////// Image Overloads for sf::Texture
void Image(const sf::Texture& texture, const sf::Color& tintColor, const sf::Color& borderColor)
{
Image(texture, sf::Vector2f(texture.getSize()), tintColor, borderColor);
}
void Image(const sf::Texture& texture, const sf::Vector2f& size, const sf::Color& tintColor, const sf::Color& borderColor)
{
ImTextureID textureID = convertGLTextureHandleToImTextureID(texture.getNativeHandle());
ImGui::Image(textureID, toImVec2(size), ImVec2(0, 0), ImVec2(1, 1), toImColor(tintColor), toImColor(borderColor));
}
/////////////// Image Overloads for sf::RenderTexture
void Image(const sf::RenderTexture& texture, const sf::Color& tintColor, const sf::Color& borderColor)
{
Image(texture, sf::Vector2f(texture.getSize()), tintColor, borderColor);
}
void Image(const sf::RenderTexture& texture, const sf::Vector2f& size, const sf::Color& tintColor, const sf::Color& borderColor)
{
ImTextureID textureID = convertGLTextureHandleToImTextureID(texture.getTexture().getNativeHandle());
ImGui::Image(textureID,
toImVec2(size),
ImVec2(0, 1),
ImVec2(1, 0), // flipped vertically,
// because textures in
// sf::RenderTexture are
// stored this way
toImColor(tintColor),
toImColor(borderColor));
}
/////////////// Image Overloads for sf::Sprite
void Image(const sf::Sprite& sprite, const sf::Color& tintColor, const sf::Color& borderColor)
{
Image(sprite, sprite.getGlobalBounds().size, tintColor, borderColor);
}
void Image(const sf::Sprite& sprite, const sf::Vector2f& size, const sf::Color& tintColor, const sf::Color& borderColor)
{
auto [uv0, uv1, textureID] = getSpriteTextureData(sprite);
ImGui::Image(textureID, toImVec2(size), uv0, uv1, toImColor(tintColor), toImColor(borderColor));
}
/////////////// Image Button Overloads for sf::Texture
bool ImageButton(const char* id,
const sf::Texture& texture,
const sf::Vector2f& size,
const sf::Color& bgColor,
const sf::Color& tintColor)
{
ImTextureID textureID = convertGLTextureHandleToImTextureID(texture.getNativeHandle());
return ImGui::ImageButton(id, textureID, toImVec2(size), ImVec2(0, 0), ImVec2(1, 1), toImColor(bgColor), toImColor(tintColor));
}
/////////////// Image Button Overloads for sf::RenderTexture
bool ImageButton(const char* id,
const sf::RenderTexture& texture,
const sf::Vector2f& size,
const sf::Color& bgColor,
const sf::Color& tintColor)
{
ImTextureID textureID = convertGLTextureHandleToImTextureID(texture.getTexture().getNativeHandle());
return ImGui::ImageButton(id,
textureID,
toImVec2(size),
ImVec2(0, 1),
ImVec2(1, 0), // flipped vertically, because textures in
// sf::RenderTexture are stored this way
toImColor(bgColor),
toImColor(tintColor));
}
/////////////// Image Button Overloads for sf::Sprite
bool ImageButton(const char* id, const sf::Sprite& sprite, const sf::Vector2f& size, const sf::Color& bgColor, const sf::Color& tintColor)
{
auto [uv0, uv1, textureID] = getSpriteTextureData(sprite);
return ImGui::ImageButton(id, textureID, toImVec2(size), uv0, uv1, toImColor(bgColor), toImColor(tintColor));
}
/////////////// Draw_list Overloads
void DrawLine(const sf::Vector2f& a, const sf::Vector2f& b, const sf::Color& color, float thickness)
{
ImDrawList* draw_list = ImGui::GetWindowDrawList();
const ImVec2 pos = ImGui::GetCursorScreenPos();
draw_list->AddLine(ImVec2(a.x + pos.x, a.y + pos.y),
ImVec2(b.x + pos.x, b.y + pos.y),
ColorConvertFloat4ToU32(toImColor(color)),
thickness);
}
void DrawRect(const sf::FloatRect& rect, const sf::Color& color, float rounding, int rounding_corners, float thickness)
{
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddRect(getTopLeftAbsolute(rect),
getDownRightAbsolute(rect),
ColorConvertFloat4ToU32(toImColor(color)),
rounding,
rounding_corners,
thickness);
}
void DrawRectFilled(const sf::FloatRect& rect, const sf::Color& color, float rounding, int rounding_corners)
{
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddRectFilled(getTopLeftAbsolute(rect),
getDownRightAbsolute(rect),
ColorConvertFloat4ToU32(toImColor(color)),
rounding,
rounding_corners);
}
} // end of namespace ImGui
namespace
{
// copied from imgui/backends/imgui_impl_opengl2.cpp
void SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height)
{
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor
// enabled, vertex/texcoord/color pointers, polygon fill.
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// 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
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
glEnable(GL_SCISSOR_TEST);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glEnable(GL_TEXTURE_2D);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glShadeModel(GL_SMOOTH);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
// Setup viewport, orthographic projection matrix
// 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.
glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
#ifdef GL_VERSION_ES_CL_1_1
glOrthof(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);
#else
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);
#endif
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
}
// Rendering callback
void RenderDrawLists(ImDrawData* draw_data)
{
ImGui::GetDrawData();
if (draw_data->CmdListsCount == 0)
{
return;
}
const ImGuiIO& io = ImGui::GetIO();
assert(io.Fonts->TexID != (ImTextureID) nullptr); // You forgot to create and set font texture
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates !=
// framebuffer coordinates)
const int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
const int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
if (fb_width == 0 || fb_height == 0)
return;
draw_data->ScaleClipRects(io.DisplayFramebufferScale);
// Backup GL state
// Backup GL state
GLint last_texture = 0;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
GLint last_polygon_mode[2];
glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
GLint last_viewport[4];
glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4];
glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
GLint last_shade_model = 0;
glGetIntegerv(GL_SHADE_MODEL, &last_shade_model);
GLint last_tex_env_mode = 0;
glGetTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &last_tex_env_mode);
#ifdef GL_VERSION_ES_CL_1_1
GLint last_array_buffer;
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
GLint last_element_array_buffer;
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
#else
glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
#endif
// Setup desired GL state
SetupRenderState(draw_data, fb_width, fb_height);
// Will project scissor/clipping rectangles into framebuffer space
const ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
const ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display
// which are often (2,2)
// Render command lists
for (int n = 0; n < draw_data->CmdListsCount; n++)
{