-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathsdl2_ui.cpp
1419 lines (1227 loc) · 43.4 KB
/
sdl2_ui.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
/*
* This file is part of EasyRPG Player.
*
* EasyRPG Player is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EasyRPG Player is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include "game_config.h"
#include "system.h"
#include "sdl2_ui.h"
#include "scene.h"
#ifdef _WIN32
# include <windows.h>
# include <SDL_syswm.h>
# include <dwmapi.h>
#elif defined(__ANDROID__)
# include <jni.h>
# include <SDL_system.h>
#elif defined(EMSCRIPTEN)
# include <emscripten.h>
#elif defined(__WIIU__)
# include "platform/wiiu/main.h"
#endif
#include "icon.h"
#include "color.h"
#include "graphics.h"
#include "keys.h"
#include "output.h"
#include "player.h"
#include "bitmap.h"
#include "lcf/scope_guard.h"
#if defined(__APPLE__) && TARGET_OS_OSX
# include "platform/macos/macos_utils.h"
#endif
#ifdef SUPPORT_AUDIO
# if AUDIO_AESND
# include "platform/wii/audio.h"
# else
# include "sdl_audio.h"
# endif
AudioInterface& Sdl2Ui::GetAudio() {
return *audio_;
}
#endif
static uint32_t GetDefaultFormat() {
#ifdef WORDS_BIGENDIAN
return SDL_PIXELFORMAT_ABGR32;
#else
return SDL_PIXELFORMAT_RGBA32;
#endif
}
/**
* Return preference for the given sdl format.
* Higher numbers are better, -1 means unsupported.
* We prefer formats which have fast paths in pixman.
*/
static int GetFormatRank(uint32_t fmt) {
switch (fmt) {
#ifdef WORDS_BIGENDIAN
case SDL_PIXELFORMAT_RGBA32:
return 0;
case SDL_PIXELFORMAT_BGRA32:
return 0;
case SDL_PIXELFORMAT_ARGB32:
return 1;
case SDL_PIXELFORMAT_ABGR32:
return 2;
#else
case SDL_PIXELFORMAT_RGBA32:
return 2;
case SDL_PIXELFORMAT_BGRA32:
return 2;
case SDL_PIXELFORMAT_ARGB32:
return 1;
case SDL_PIXELFORMAT_ABGR32:
return 0;
#endif
default:
return -1;
}
}
static DynamicFormat GetDynamicFormat(uint32_t fmt) {
switch (fmt) {
case SDL_PIXELFORMAT_RGBA32:
return format_R8G8B8A8_n().format();
case SDL_PIXELFORMAT_BGRA32:
return format_B8G8R8A8_n().format();
case SDL_PIXELFORMAT_ARGB32:
return format_A8R8G8B8_n().format();
case SDL_PIXELFORMAT_ABGR32:
return format_A8B8G8R8_n().format();
default:
return DynamicFormat();
}
}
static uint32_t SelectFormat(const SDL_RendererInfo& rinfo, bool print_all) {
uint32_t current_fmt = SDL_PIXELFORMAT_UNKNOWN;
int current_rank = -1;
for (int i = 0; i < static_cast<int>(rinfo.num_texture_formats); ++i) {
const auto fmt = rinfo.texture_formats[i];
int rank = GetFormatRank(fmt);
if (rank >= 0) {
if (rank > current_rank) {
current_fmt = fmt;
current_rank = rank;
}
Output::Debug("SDL2: Detected format ({}) {} : rank=({})",
i, SDL_GetPixelFormatName(fmt), rank);
} else {
if (print_all) {
Output::Debug("SDL2: Detected format ({}) {} : Not Supported",
i, SDL_GetPixelFormatName(fmt));
}
}
}
return current_fmt;
}
#ifdef _WIN32
HWND GetWindowHandle(SDL_Window* window) {
SDL_SysWMinfo wminfo;
SDL_VERSION(&wminfo.version)
SDL_bool success = SDL_GetWindowWMInfo(window, &wminfo);
if (success < 0)
Output::Error("Wrong SDL version");
return wminfo.info.win.window;
}
#endif
static int FilterUntilFocus(const SDL_Event* evnt);
#if defined(USE_KEYBOARD) && defined(SUPPORT_KEYBOARD)
static Input::Keys::InputKey SdlKey2InputKey(SDL_Keycode sdlkey);
#endif
#if defined(USE_JOYSTICK) && defined(SUPPORT_JOYSTICK)
static Input::Keys::InputKey SdlJKey2InputKey(int button_index);
#endif
Sdl2Ui::Sdl2Ui(long width, long height, const Game_Config& cfg) : BaseUi(cfg)
{
// Set some SDL environment variables before starting. These are platform
// dependent, so every port needs to set them manually
#ifdef __LINUX__
// Set the application class name
setenv("SDL_VIDEO_X11_WMCLASS", GAME_TITLE, 0);
#endif
#ifdef EMSCRIPTEN
SDL_SetHint(SDL_HINT_EMSCRIPTEN_ASYNCIFY, "0");
// Only handle keyboard events when the canvas has focus
SDL_SetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT, "#canvas");
#endif
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
Output::Error("Couldn't initialize SDL.\n{}\n", SDL_GetError());
}
RequestVideoMode(width, height,
cfg.video.window_zoom.Get(),
cfg.video.fullscreen.Get(),
cfg.video.vsync.Get());
SetTitle(GAME_TITLE);
#if (defined(USE_JOYSTICK) && defined(SUPPORT_JOYSTICK)) || (defined(USE_JOYSTICK_AXIS) && defined(SUPPORT_JOYSTICK_AXIS))
if (SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER) < 0) {
Output::Warning("Couldn't initialize joystick. {}", SDL_GetError());
}
SDL_JoystickEventState(SDL_ENABLE);
sdl_joystick = SDL_JoystickOpen(0);
#endif
#if defined(USE_MOUSE) && defined(SUPPORT_MOUSE)
ShowCursor(true);
#else
ShowCursor(false);
#endif
#ifdef SUPPORT_AUDIO
# ifdef AUDIO_AESND
audio_ = std::make_unique<WiiAudio>(cfg.audio);
# else
audio_ = std::make_unique<SdlAudio>(cfg.audio);
# endif
#endif
}
Sdl2Ui::~Sdl2Ui() {
if (sdl_joystick) {
SDL_JoystickClose(sdl_joystick);
}
if (sdl_texture_game) {
SDL_DestroyTexture(sdl_texture_game);
}
if (sdl_texture_scaled) {
SDL_DestroyTexture(sdl_texture_scaled);
}
if (sdl_renderer) {
SDL_DestroyRenderer(sdl_renderer);
}
if (sdl_window) {
SDL_DestroyWindow(sdl_window);
}
SDL_Quit();
}
bool Sdl2Ui::vChangeDisplaySurfaceResolution(int new_width, int new_height) {
SDL_Texture* new_sdl_texture_game = SDL_CreateTexture(sdl_renderer,
texture_format,
SDL_TEXTUREACCESS_STREAMING,
new_width, new_height);
if (!new_sdl_texture_game) {
Output::Warning("ChangeDisplaySurfaceResolution SDL_CreateTexture failed: {}", SDL_GetError());
return false;
}
if (sdl_texture_game) {
SDL_DestroyTexture(sdl_texture_game);
}
sdl_texture_game = new_sdl_texture_game;
BitmapRef new_main_surface = Bitmap::Create(new_width, new_height, Color(0, 0, 0, 255));
if (!new_main_surface) {
Output::Warning("ChangeDisplaySurfaceResolution Bitmap::Create failed");
return false;
}
main_surface = new_main_surface;
window.size_changed = true;
BeginDisplayModeChange();
current_display_mode.width = new_width;
current_display_mode.height = new_height;
EndDisplayModeChange();
return true;
}
void Sdl2Ui::RequestVideoMode(int width, int height, int zoom, bool fullscreen, bool vsync) {
BeginDisplayModeChange();
// SDL2 documentation says that resolution dependent code should not be used
// anymore. The library takes care of it now.
current_display_mode.width = width;
current_display_mode.height = height;
current_display_mode.bpp = 32;
current_display_mode.zoom = zoom;
current_display_mode.vsync = vsync;
EndDisplayModeChange();
// Work around some SDL bugs, window properties are incorrect when started
// as full screen, e.g. height lacks title bar size, icon is not added, etc.
if (fullscreen)
ToggleFullscreen();
}
void Sdl2Ui::BeginDisplayModeChange() {
last_display_mode = current_display_mode;
current_display_mode.effective = false;
}
void Sdl2Ui::EndDisplayModeChange() {
// Check if the new display mode is different from last one
if (current_display_mode.flags != last_display_mode.flags ||
current_display_mode.zoom != last_display_mode.zoom ||
current_display_mode.width != last_display_mode.width ||
current_display_mode.height != last_display_mode.height) {
if (!RefreshDisplayMode()) {
// Mode change failed, check if last one was effective
if (last_display_mode.effective) {
current_display_mode = last_display_mode;
// Try a rollback to last mode
if (!RefreshDisplayMode()) {
Output::Error("Couldn't rollback to last display mode.\n{}", SDL_GetError());
}
} else {
Output::Error("Couldn't set display mode.\n{}", SDL_GetError());
}
}
current_display_mode.effective = true;
#ifdef EMSCRIPTEN
SetIsFullscreen(true);
#else
SetIsFullscreen((current_display_mode.flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP);
#endif
}
}
bool Sdl2Ui::RefreshDisplayMode() {
uint32_t flags = current_display_mode.flags;
int display_width = current_display_mode.width;
int display_height = current_display_mode.height;
bool& vsync = current_display_mode.vsync;
#ifdef SUPPORT_ZOOM
int display_width_zoomed = display_width * current_display_mode.zoom;
int display_height_zoomed = display_height * current_display_mode.zoom;
#else
int display_width_zoomed = display_width;
int display_height_zoomed = display_height;
#endif
if (!sdl_window) {
#ifdef __ANDROID__
// Workaround SDL bug: https://bugzilla.libsdl.org/show_bug.cgi?id=2291
// Set back buffer format to 565
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
#endif
#if defined(__APPLE__) && TARGET_OS_OSX
// Use OpenGL on Mac only -- to work around an SDL Metal deficiency
// where it will always use discrete GPU.
// See SDL source code:
// http://hg.libsdl.org/SDL/file/aa9d7c43a982/src/render/metal/SDL_render_metal.m#l1613
SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl");
#endif
#if defined(EMSCRIPTEN) || defined(_WIN32)
// FIXME: This will not DPI-scale on Windows due to SDL2 limitations.
// Is properly fixed in SDL3. See #2764
flags |= SDL_WINDOW_ALLOW_HIGHDPI;
#endif
// Create our window
if (vcfg.window_x.Get() < 0 || vcfg.window_y.Get() < 0 || vcfg.window_height.Get() <= 0 || vcfg.window_width.Get() <= 0) {
sdl_window = SDL_CreateWindow(GAME_TITLE,
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
display_width_zoomed, display_height_zoomed,
SDL_WINDOW_RESIZABLE | flags);
} else {
sdl_window = SDL_CreateWindow(GAME_TITLE,
vcfg.window_x.Get(),
vcfg.window_y.Get(),
vcfg.window_width.Get(), vcfg.window_height.Get(),
SDL_WINDOW_RESIZABLE | flags);
}
if (!sdl_window) {
Output::Debug("SDL_CreateWindow failed : {}", SDL_GetError());
return false;
}
SDL_GetWindowSize(sdl_window, &window.width, &window.height);
window.size_changed = true;
auto window_sg = lcf::makeScopeGuard([&]() {
SDL_DestroyWindow(sdl_window);
sdl_window = nullptr;
});
SetAppIcon();
uint32_t renderer_flags = 0;
if (vsync) {
renderer_flags |= SDL_RENDERER_PRESENTVSYNC;
}
sdl_renderer = SDL_CreateRenderer(sdl_window, -1, renderer_flags);
if (!sdl_renderer) {
Output::Debug("SDL_CreateRenderer failed : {}", SDL_GetError());
return false;
}
auto renderer_sg = lcf::makeScopeGuard([&]() {
SDL_DestroyRenderer(sdl_renderer);
sdl_renderer = nullptr;
});
SDL_RendererInfo rinfo = {};
if (SDL_GetRendererInfo(sdl_renderer, &rinfo) == 0) {
Output::Debug("SDL2: RendererInfo hw={} sw={} vsync={}",
!!(rinfo.flags & SDL_RENDERER_ACCELERATED),
!!(rinfo.flags & SDL_RENDERER_SOFTWARE),
!!(rinfo.flags & SDL_RENDERER_PRESENTVSYNC)
);
texture_format = SelectFormat(rinfo, false);
} else {
Output::Debug("SDL_GetRendererInfo failed : {}", SDL_GetError());
}
vsync = rinfo.flags & SDL_RENDERER_PRESENTVSYNC;
SetFrameRateSynchronized(vsync);
if (texture_format == SDL_PIXELFORMAT_UNKNOWN) {
texture_format = GetDefaultFormat();
Output::Debug("SDL2: None of the ({}) detected formats were supported! Falling back to {}. This will likely cause performance degredation.",
rinfo.num_texture_formats, SDL_GetPixelFormatName(texture_format));
// Run again to print all the formats on this system.
SelectFormat(rinfo, true);
}
Output::Debug("SDL2: Selected Pixel Format {}", SDL_GetPixelFormatName(texture_format));
// Flush display
SDL_RenderClear(sdl_renderer);
SDL_RenderPresent(sdl_renderer);
sdl_texture_game = SDL_CreateTexture(sdl_renderer,
texture_format,
SDL_TEXTUREACCESS_STREAMING,
display_width, display_height);
if (!sdl_texture_game) {
Output::Debug("SDL_CreateTexture failed : {}", SDL_GetError());
return false;
}
#ifdef _WIN32
HWND window = GetWindowHandle(sdl_window);
// Not using the enum names because this will fail to build when not using a recent Windows 11 SDK
int window_rounding = 1; // DWMWCP_DONOTROUND
DwmSetWindowAttribute(window, 33 /* DWMWA_WINDOW_CORNER_PREFERENCE */, &window_rounding, sizeof(window_rounding));
#endif
renderer_sg.Dismiss();
window_sg.Dismiss();
} else {
// Browser handles fast resizing for emscripten, TODO: use fullscreen API
#ifndef EMSCRIPTEN
bool is_fullscreen = (flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP;
if (is_fullscreen) {
SDL_SetWindowFullscreen(sdl_window, SDL_WINDOW_FULLSCREEN_DESKTOP);
} else {
SDL_SetWindowFullscreen(sdl_window, 0);
if ((last_display_mode.flags & SDL_WINDOW_FULLSCREEN_DESKTOP)
== SDL_WINDOW_FULLSCREEN_DESKTOP) {
// Restore to pre-fullscreen size
SDL_SetWindowSize(sdl_window, 0, 0);
} else {
SDL_SetWindowSize(sdl_window, display_width_zoomed, display_height_zoomed);
}
}
#endif
}
// Need to set up icon again, some platforms recreate the window when
// creating the renderer (i.e. Windows), see also comment in SetAppIcon()
SetAppIcon();
uint32_t sdl_pixel_fmt = GetDefaultFormat();
int a, w, h;
if (SDL_QueryTexture(sdl_texture_game, &sdl_pixel_fmt, &a, &w, &h) != 0) {
Output::Debug("SDL_QueryTexture failed : {}", SDL_GetError());
return false;
}
auto format = GetDynamicFormat(sdl_pixel_fmt);
Bitmap::SetFormat(Bitmap::ChooseFormat(format));
if (!main_surface) {
// Drawing surface will be the window itself
main_surface = Bitmap::Create(
display_width, display_height, Color(0, 0, 0, 255));
}
return true;
}
void Sdl2Ui::ToggleFullscreen() {
BeginDisplayModeChange();
if ((current_display_mode.flags & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) {
current_display_mode.flags &= ~SDL_WINDOW_FULLSCREEN_DESKTOP;
} else {
current_display_mode.flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
SDL_GetWindowPosition(sdl_window, &window_mode_metrics.x, &window_mode_metrics.y);
window_mode_metrics.width = window.width;
window_mode_metrics.height = window.height;
}
EndDisplayModeChange();
}
void Sdl2Ui::ToggleZoom() {
#ifdef SUPPORT_ZOOM
BeginDisplayModeChange();
// Work around a SDL bug which doesn't demaximize the window when the size
// is changed
int flags = SDL_GetWindowFlags(sdl_window);
if ((flags & SDL_WINDOW_MAXIMIZED) == SDL_WINDOW_MAXIMIZED) {
SDL_RestoreWindow(sdl_window);
}
// get current window size, calculate next bigger zoom factor
int w, h;
SDL_GetWindowSize(sdl_window, &w, &h);
last_display_mode.zoom = std::min(w / main_surface->width(), h / main_surface->height());
current_display_mode.zoom = last_display_mode.zoom + 1;
// get maximum usable window size
int display_index = SDL_GetWindowDisplayIndex(sdl_window);
SDL_Rect max_mode;
// this takes account of the menu bar and dock on macOS and task bar on windows
SDL_GetDisplayUsableBounds(display_index, &max_mode);
// reset zoom, if it does not fit
if ((max_mode.h < main_surface->height() * current_display_mode.zoom) ||
(max_mode.w < main_surface->width() * current_display_mode.zoom)) {
current_display_mode.zoom = 1;
}
EndDisplayModeChange();
#endif
}
bool Sdl2Ui::ProcessEvents() {
#if defined(__WIIU__)
if (!WiiU_ProcessProcUI()) {
return false;
}
#endif
SDL_Event evnt;
#if defined(USE_MOUSE) && defined(SUPPORT_MOUSE)
// Reset Mouse scroll
keys[Input::Keys::MOUSE_SCROLLUP] = false;
keys[Input::Keys::MOUSE_SCROLLDOWN] = false;
#endif
// Poll SDL events and process them
while (SDL_PollEvent(&evnt)) {
ProcessEvent(evnt);
if (Player::exit_flag)
break;
}
return true;
}
void Sdl2Ui::SetScalingMode(ConfigEnum::ScalingMode mode) {
window.size_changed = true;
vcfg.scaling_mode.Set(mode);
}
void Sdl2Ui::ToggleStretch() {
window.size_changed = true;
vcfg.stretch.Toggle();
}
void Sdl2Ui::ToggleVsync() {
#if SDL_VERSION_ATLEAST(2, 0, 18)
// Modifying vsync requires recreating the renderer
vcfg.vsync.Toggle();
if (SDL_RenderSetVSync(sdl_renderer, int(vcfg.vsync.Get())) == 0) {
current_display_mode.vsync = vcfg.vsync.Get();
SetFrameRateSynchronized(vcfg.vsync.Get());
} else {
Output::Warning("Unable to toggle vsync. This is likely a problem with your system configuration.");
}
#else
Output::Warning("Cannot toogle vsync: SDL2 version too old (must be 2.0.18)");
#endif
}
void Sdl2Ui::UpdateDisplay() {
struct zoom_params {
int zoom;
bool is_anchor_percent;
int x;
int y;
};
zoom_params params{100,true,50,50};
auto st = Scene::instance->type;
if (st == Scene::Battle || st == Scene::Map) {
params.zoom = Graphics::GetZoomData().GetScale();
params.is_anchor_percent = Graphics::GetZoomData().IsOriginPercentage();
params.x = Graphics::GetZoomData().GetOriginX();
params.y = Graphics::GetZoomData().GetOriginY();
}
#ifdef __WIIU__
if (vcfg.scaling_mode.Get() == ConfigEnum::ScalingMode::Bilinear && window.scale > 0.f) {
// Workaround WiiU bug: Bilinear uses a render target and for these the format is not converted
void* target_pixels;
int target_pitch;
SDL_LockTexture(sdl_texture_game, nullptr, &target_pixels, &target_pitch);
SDL_ConvertPixels(main_surface->width(), main_surface->height(), GetDefaultFormat(), main_surface->pixels(),
main_surface->pitch(), SDL_PIXELFORMAT_RGBA8888, target_pixels, target_pitch);
SDL_UnlockTexture(sdl_texture_game);
} else {
SDL_UpdateTexture(sdl_texture_game, nullptr, main_surface->pixels(), main_surface->pitch());
}
#else
// SDL_UpdateTexture was found to be faster than SDL_LockTexture / SDL_UnlockTexture.
SDL_UpdateTexture(sdl_texture_game, nullptr, main_surface->pixels(), main_surface->pitch());
#endif
if (window.size_changed && window.width > 0 && window.height > 0) {
// Based on SDL2 function UpdateLogicalSize
window.size_changed = false;
float width_float = static_cast<float>(window.width);
float height_float = static_cast<float>(window.height);
float want_aspect = (float)main_surface->width() / main_surface->height();
float real_aspect = width_float / height_float;
auto do_stretch = [this]() {
if (vcfg.stretch.Get()) {
viewport.x = 0;
viewport.w = window.width;
}
};
if (vcfg.scaling_mode.Get() == ConfigEnum::ScalingMode::Integer) {
// Integer division on purpose
if (want_aspect > real_aspect) {
window.scale = static_cast<float>(window.width / main_surface->width());
} else {
window.scale = static_cast<float>(window.height / main_surface->height());
}
viewport.w = static_cast<int>(ceilf(main_surface->width() * window.scale));
viewport.x = (window.width - viewport.w) / 2;
viewport.h = static_cast<int>(ceilf(main_surface->height() * window.scale));
viewport.y = (window.height - viewport.h) / 2;
do_stretch();
SDL_RenderSetViewport(sdl_renderer, &viewport);
} else if (fabs(want_aspect - real_aspect) < 0.0001) {
// The aspect ratios are the same, let SDL2 scale it
window.scale = width_float / main_surface->width();
SDL_RenderSetViewport(sdl_renderer, nullptr);
// Only used here for the mouse coordinates
viewport.x = 0;
viewport.y = 0;
viewport.w = window.width;
viewport.h = window.height;
} else if (want_aspect > real_aspect) {
// Letterboxing (black bars top and bottom)
window.scale = width_float / main_surface->width();
viewport.x = 0;
viewport.w = window.width;
viewport.h = static_cast<int>(ceilf(main_surface->height() * window.scale));
viewport.y = (window.height - viewport.h) / 2;
do_stretch();
SDL_RenderSetViewport(sdl_renderer, &viewport);
} else {
// black bars left and right
window.scale = height_float / main_surface->height();
viewport.y = 0;
viewport.h = window.height;
viewport.w = static_cast<int>(ceilf(main_surface->width() * window.scale));
viewport.x = (window.width - viewport.w) / 2;
do_stretch();
SDL_RenderSetViewport(sdl_renderer, &viewport);
}
if (vcfg.scaling_mode.Get() == ConfigEnum::ScalingMode::Bilinear && window.scale > 0.f) {
if (sdl_texture_scaled) {
SDL_DestroyTexture(sdl_texture_scaled);
}
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
sdl_texture_scaled = SDL_CreateTexture(sdl_renderer, texture_format, SDL_TEXTUREACCESS_TARGET,
static_cast<int>(ceilf(window.scale)) * main_surface->width(), static_cast<int>(ceilf(window.scale)) * main_surface->height());
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest");
if (!sdl_texture_scaled) {
Output::Debug("SDL_CreateTexture failed : {}", SDL_GetError());
}
}
}
SDL_RenderClear(sdl_renderer);
if (vcfg.scaling_mode.Get() == ConfigEnum::ScalingMode::Bilinear && window.scale > 0.f) {
// Calculate zoom parameters
float zoom_scale = params.zoom / 100.0f;
// Calculate source rectangle (the area we want to show)
SDL_Rect src_rect;
int zoomed_width = static_cast<int>(main_surface->width() * zoom_scale);
int zoomed_height = static_cast<int>(main_surface->height() * zoom_scale);
// Calculate anchor points
int anchor_pixel_x = params.is_anchor_percent ?
(params.x * main_surface->width() / 100) :
params.x;
int anchor_pixel_y = params.is_anchor_percent ?
(params.y * main_surface->height() / 100) :
params.y;
// Calculate the top-left corner of the source rectangle
src_rect.x = anchor_pixel_x - (main_surface->width() / (2 * zoom_scale));
src_rect.y = anchor_pixel_y - (main_surface->height() / (2 * zoom_scale));
src_rect.w = main_surface->width() / zoom_scale;
src_rect.h = main_surface->height() / zoom_scale;
// Clamp source rectangle to texture bounds
if (src_rect.x < 0) src_rect.x = 0;
if (src_rect.y < 0) src_rect.y = 0;
if (src_rect.x + src_rect.w > main_surface->width())
src_rect.x = main_surface->width() - src_rect.w;
if (src_rect.y + src_rect.h > main_surface->height())
src_rect.y = main_surface->height() - src_rect.h;
// Render game texture on the scaled texture
SDL_SetRenderTarget(sdl_renderer, sdl_texture_scaled);
SDL_RenderClear(sdl_renderer);
SDL_RenderCopy(sdl_renderer, sdl_texture_game, &src_rect, nullptr);
SDL_SetRenderTarget(sdl_renderer, nullptr);
SDL_RenderCopy(sdl_renderer, sdl_texture_scaled, nullptr, nullptr);
}
else {
// Handle non-bilinear case with zoom
float zoom_scale = params.zoom / 100.0f;
SDL_Rect src_rect;
int anchor_pixel_x = params.is_anchor_percent ?
(params.x * main_surface->width() / 100) :
params.x;
int anchor_pixel_y = params.is_anchor_percent ?
(params.y * main_surface->height() / 100) :
params.y;
src_rect.x = anchor_pixel_x - (main_surface->width() / (2 * zoom_scale));
src_rect.y = anchor_pixel_y - (main_surface->height() / (2 * zoom_scale));
src_rect.w = main_surface->width() / zoom_scale;
src_rect.h = main_surface->height() / zoom_scale;
// Clamp source rectangle
if (src_rect.x < 0) src_rect.x = 0;
if (src_rect.y < 0) src_rect.y = 0;
if (src_rect.x + src_rect.w > main_surface->width())
src_rect.x = main_surface->width() - src_rect.w;
if (src_rect.y + src_rect.h > main_surface->height())
src_rect.y = main_surface->height() - src_rect.h;
SDL_RenderCopy(sdl_renderer, sdl_texture_game, &src_rect, nullptr);
}
SDL_RenderPresent(sdl_renderer);
}
void Sdl2Ui::SetTitle(const std::string &title) {
SDL_SetWindowTitle(sdl_window, title.c_str());
}
bool Sdl2Ui::ShowCursor(bool flag) {
bool temp_flag = cursor_visible;
cursor_visible = flag;
SDL_ShowCursor(flag ? SDL_ENABLE : SDL_DISABLE);
return temp_flag;
}
bool Sdl2Ui::HandleErrorOutput(const std::string &message) {
std::string title = Player::GetFullVersionString();
// Manually Restore window from fullscreen, since message would not be visible otherwise
if ((current_display_mode.flags & SDL_WINDOW_FULLSCREEN_DESKTOP)
== SDL_WINDOW_FULLSCREEN_DESKTOP) {
SDL_SetWindowFullscreen(sdl_window, 0);
SDL_SetWindowSize(sdl_window, 0, 0);
}
if(SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title.c_str(),
message.c_str(), sdl_window) != 0) {
return false;
}
return true;
}
void Sdl2Ui::ProcessEvent(SDL_Event &evnt) {
switch (evnt.type) {
case SDL_WINDOWEVENT:
ProcessWindowEvent(evnt);
return;
case SDL_QUIT:
Player::exit_flag = true;
return;
case SDL_KEYDOWN:
ProcessKeyDownEvent(evnt);
return;
case SDL_KEYUP:
ProcessKeyUpEvent(evnt);
return;
case SDL_MOUSEMOTION:
ProcessMouseMotionEvent(evnt);
return;
case SDL_MOUSEWHEEL:
ProcessMouseWheelEvent(evnt);
return;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
ProcessMouseButtonEvent(evnt);
return;
case SDL_CONTROLLERDEVICEADDED:
ProcessControllerAdded(evnt);
return;
case SDL_CONTROLLERDEVICEREMOVED:
ProcessControllerRemoved(evnt);
return;
case SDL_CONTROLLERBUTTONDOWN:
case SDL_CONTROLLERBUTTONUP:
ProcessControllerButtonEvent(evnt);
return;
case SDL_CONTROLLERAXISMOTION:
ProcessControllerAxisEvent(evnt);
return;
case SDL_FINGERDOWN:
case SDL_FINGERUP:
case SDL_FINGERMOTION:
ProcessFingerEvent(evnt);
return;
}
}
void Sdl2Ui::ProcessWindowEvent(SDL_Event &evnt) {
int state = evnt.window.event;
if (state == SDL_WINDOWEVENT_FOCUS_LOST) {
auto cfg = vcfg;
vGetConfig(cfg);
if (!cfg.pause_when_focus_lost.Get()) {
return;
}
Player::Pause();
bool last = ShowCursor(true);
// Filter SDL events until focus is regained
SDL_Event wait_event;
while (SDL_WaitEvent(&wait_event)) {
if (FilterUntilFocus(&wait_event)) {
break;
}
}
ShowCursor(last);
Player::Resume();
ResetKeys();
return;
}
#if defined(USE_MOUSE_OR_TOUCH) && defined(SUPPORT_MOUSE_OR_TOUCH)
if (state == SDL_WINDOWEVENT_ENTER) {
mouse_focus = true;
} else if (state == SDL_WINDOWEVENT_LEAVE) {
mouse_focus = false;
}
#endif
if (state == SDL_WINDOWEVENT_SIZE_CHANGED || state == SDL_WINDOWEVENT_RESIZED) {
window.width = evnt.window.data1;
window.height = evnt.window.data2;
#ifdef EMSCRIPTEN
double display_ratio = emscripten_get_device_pixel_ratio();
window.width = static_cast<int>(window.width * display_ratio);
window.height = static_cast<int>(window.height * display_ratio);
#endif
window.size_changed = true;
}
}
void Sdl2Ui::ProcessKeyDownEvent(SDL_Event &evnt) {
#if defined(USE_KEYBOARD) && defined(SUPPORT_KEYBOARD)
if (evnt.key.keysym.sym == SDLK_F4 && (evnt.key.keysym.mod & KMOD_LALT)) {
// Close program on LeftAlt+F4
Player::exit_flag = true;
return;
} else if (evnt.key.keysym.sym == SDLK_RETURN ||
evnt.key.keysym.sym == SDLK_KP_ENTER) {
if (evnt.key.keysym.mod & KMOD_LALT || (evnt.key.keysym.mod & KMOD_RALT)) {
// Toggle fullscreen on Alt+Enter
ToggleFullscreen();
return;
}
}
// Update key state
keys[SdlKey2InputKey(evnt.key.keysym.scancode)] = true;
#else
/* unused */
(void) evnt;
#endif
}
void Sdl2Ui::ProcessKeyUpEvent(SDL_Event &evnt) {
#if defined(USE_KEYBOARD) && defined(SUPPORT_KEYBOARD)
keys[SdlKey2InputKey(evnt.key.keysym.scancode)] = false;
#else
/* unused */
(void) evnt;
#endif
}
void Sdl2Ui::ProcessMouseMotionEvent(SDL_Event& evnt) {
#if defined(USE_MOUSE_OR_TOUCH) && defined(SUPPORT_MOUSE_OR_TOUCH)
mouse_focus = true;
int xw = viewport.w;
int yh = viewport.h;
if (xw == 0 || yh == 0) {
// Startup. No viewport yet
return;
}
#ifdef EMSCRIPTEN
double display_ratio = emscripten_get_device_pixel_ratio();
mouse_pos.x = (evnt.motion.x * display_ratio - viewport.x) * main_surface->width() / xw;
mouse_pos.y = (evnt.motion.y * display_ratio - viewport.y) * main_surface->height() / yh;
#else
mouse_pos.x = (evnt.motion.x - viewport.x) * main_surface->width() / xw;
mouse_pos.y = (evnt.motion.y - viewport.y) * main_surface->height() / yh;
#endif
#else
/* unused */
(void) evnt;
#endif
}
void Sdl2Ui::ProcessMouseWheelEvent(SDL_Event& evnt) {
#if defined(USE_MOUSE) && defined(SUPPORT_MOUSE)
// Ignore Finger (touch) events here
if (evnt.wheel.which == SDL_TOUCH_MOUSEID)
return;
int amount = evnt.wheel.y;
// translate direction
if (evnt.wheel.direction == SDL_MOUSEWHEEL_FLIPPED)
amount *= -1;
keys[Input::Keys::MOUSE_SCROLLUP] = amount > 0;
keys[Input::Keys::MOUSE_SCROLLDOWN] = amount < 0;
#else
/* unused */
(void) evnt;
#endif
}
void Sdl2Ui::ProcessMouseButtonEvent(SDL_Event& evnt) {
#if defined(USE_MOUSE) && defined(SUPPORT_MOUSE)
// Ignore Finger (touch) events here
if (evnt.button.which == SDL_TOUCH_MOUSEID)
return;
switch (evnt.button.button) {
case SDL_BUTTON_LEFT: