OpenTTD Source 20261112-master-gbcbec5e63f
sdl3_v.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD 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, version 2.
4 * OpenTTD 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.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../stdafx.h"
11#include "../openttd.h"
12#include "../gfx_func.h"
14#include "../thread.h"
15#include "../progress.h"
16#include "../core/math_func.hpp"
18#include "../core/utf8.hpp"
19#include "../fileio_func.h"
20#include "../framerate_type.h"
21#include "../window_func.h"
22#include "sdl3_v.h"
23#include <SDL3/SDL.h>
24#include <SDL3/SDL_events.h>
25#include <SDL3/SDL_init.h>
26#include <SDL3/SDL_video.h>
27#ifdef __EMSCRIPTEN__
28# include <emscripten.h>
29# include <emscripten/html5.h>
30#endif
31
32#include "../safeguards.h"
33
34void VideoDriver_SDL_Base::MakeDirty(int left, int top, int width, int height)
35{
36 Rect r = {left, top, left + width, top + height};
37 this->dirty_rect = BoundingRect(this->dirty_rect, r);
38}
39
41{
42 if (!CopyPalette(this->local_palette)) return;
43 this->MakeDirty(0, 0, _screen.width, _screen.height);
44}
45
51template <typename T>
52class SDLRange {
53 T *data = nullptr;
54 int count = 0;
55public:
61 template <typename Func, typename ... Args>
62 SDLRange(Func func, Args... args) { this->data = func(args..., &this->count); }
64 ~SDLRange() { SDL_free(this->data); }
65
66 SDLRange(SDLRange &) = delete;
67 SDLRange& operator= (const SDLRange&) = delete;
68
73 constexpr T* begin() const { return this->data; }
74
79 constexpr T* end() const { return this->data + count; }
80
85 constexpr size_t size() const { return this->count; }
86};
87
90 { 640, 480 },
91 { 800, 600 },
92 { 1024, 768 },
93 { 1152, 864 },
94 { 1280, 800 },
95 { 1280, 960 },
96 { 1280, 1024 },
97 { 1400, 1050 },
98 { 1600, 1200 },
99 { 1680, 1050 },
100 { 1920, 1200 }
101};
102
104static void FindResolutions()
105{
106 _resolutions.clear();
107
108 for (SDL_DisplayID display : SDLRange<SDL_DisplayID>(SDL_GetDisplays)) {
109 for (SDL_DisplayMode *mode : SDLRange<SDL_DisplayMode*>(SDL_GetFullscreenDisplayModes, display)) {
110 if (mode->w < 640 || mode->h < 480) continue;
111 if (std::ranges::find(_resolutions, Dimension(mode->w, mode->h)) != _resolutions.end()) continue;
112 _resolutions.emplace_back(mode->w, mode->h);
113 }
114 }
115
116 /* We have found no resolutions, show the default list */
117 if (_resolutions.empty()) {
118 _resolutions.assign(std::begin(_default_resolutions), std::end(_default_resolutions));
119 }
120
121 SortResolutions();
122}
123
129static void GetAvailableVideoMode(uint *w, uint *h)
130{
131 /* All modes available? */
132 if (!_fullscreen || _resolutions.empty()) return;
133
134 /* Is the wanted mode among the available modes? */
135 if (std::ranges::find(_resolutions, Dimension(*w, *h)) != _resolutions.end()) return;
136
137 /* Use the closest possible resolution */
138 uint best = 0;
139 uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
140 for (uint i = 1; i != _resolutions.size(); ++i) {
141 uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
142 if (newdelta < delta) {
143 best = i;
144 delta = newdelta;
145 }
146 }
147 *w = _resolutions[best].width;
148 *h = _resolutions[best].height;
149}
150
156static uint FindStartupDisplay(uint startup_display)
157{
158 SDLRange<SDL_DisplayID> displays{SDL_GetDisplays};
159
160 /* If the user indicated a valid monitor, use that. */
161 if (IsInsideBS(startup_display, 0, displays.size())) return startup_display;
162
163 /* Mouse position decides which display to use. */
164 float mx, my;
165 SDL_GetGlobalMouseState(&mx, &my);
166 for (SDL_DisplayID display : displays) {
167 SDL_Rect r;
168 if (SDL_GetDisplayBounds(display, &r) == 0 && IsInsideBS(mx, r.x, r.w) && IsInsideBS(my, r.y, r.h)) {
169 Debug(Facility::Driver, Severity::Error, "SDL3: Mouse is at ({}, {}), use display {} ({}, {}, {}, {})", mx, my, display, r.x, r.y, r.w, r.h);
170 return display;
171 }
172 }
173
174 return 0;
175}
176
183void VideoDriver_SDL_Base::ClientSizeChanged(int w, int h, bool force)
184{
185 /* Allocate backing store of the new size. */
186 if (this->AllocateBackingStore(w, h, force)) {
187 CopyPalette(this->local_palette, true);
188
190
192 }
193}
194
195bool VideoDriver_SDL_Base::CreateMainWindow(uint w, uint h, uint flags)
196{
197 if (this->sdl_window != nullptr) return true;
198
199 flags |= SDL_WINDOW_RESIZABLE;
200
201 if (_fullscreen) {
202 flags |= SDL_WINDOW_FULLSCREEN;
203 }
204
205 std::string caption = VideoDriver::GetCaption();
206 this->sdl_window = SDL_CreateWindow(caption.c_str(), w, h, flags);
207
208 if (this->sdl_window == nullptr) {
209 Debug(Facility::Driver, Severity::Critical, "SDL3: Couldn't allocate a window to draw on: {}", SDL_GetError());
210 return false;
211 }
212
213 std::string icon_path = FioFindFullPath(Subdirectory::Baseset, "openttd.32.bmp");
214 if (!icon_path.empty()) {
215 /* Give the application an icon */
216 SDL_Surface *icon = SDL_LoadBMP(icon_path.c_str());
217 if (icon != nullptr) {
218 /* Get the colourkey, which will be magenta */
219 uint32_t rgbmap = SDL_MapSurfaceRGB(icon, 255, 0, 255);
220 if (!SDL_SetSurfaceColorKey(icon, true, rgbmap)) {
221 Debug(Facility::Driver, Severity::Error, "SDL3: SDL_SetSurfaceColorKey failed: {}", SDL_GetError());
222 }
223
224 SDL_SetWindowIcon(this->sdl_window, icon);
225 SDL_DestroySurface(icon);
226 }
227 }
228
229 return true;
230}
231
239bool VideoDriver_SDL_Base::CreateMainSurface(uint w, uint h, bool resize)
240{
241 GetAvailableVideoMode(&w, &h);
242 Debug(Facility::Driver, Severity::Error, "SDL3: using mode {}x{}", w, h);
243
244 if (!this->CreateMainWindow(w, h)) return false;
245 if (resize) SDL_SetWindowSize(this->sdl_window, w, h);
246 this->ClientSizeChanged(w, h, true);
247
248 /* When in full screen, we will always have the mouse cursor
249 * within the window, even though SDL does not give us the
250 * appropriate event to know this. */
251 if (_fullscreen) _cursor.in_window = true;
252
253 return true;
254}
255
257{
258 /* Emscripten never claims the pointer, so we do not need to change the cursor visibility. */
259#ifndef __EMSCRIPTEN__
260 SDL_HideCursor();
261#endif
262}
263
268{
269 if (!this->edit_box_focused) {
270 SDL_StartTextInput(this->sdl_window);
271 this->edit_box_focused = true;
272 }
273}
274
279{
280 if (this->edit_box_focused) {
281 SDL_StopTextInput(this->sdl_window);
282 this->edit_box_focused = false;
283 }
284}
285
287{
288 std::vector<int> rates = {};
289 for (SDL_DisplayID display : SDLRange<SDL_DisplayID>(SDL_GetDisplays)) {
290 for (SDL_DisplayMode *mode : SDLRange<SDL_DisplayMode*>(SDL_GetFullscreenDisplayModes, display)) {
291 if (mode->refresh_rate != 0) rates.push_back(mode->refresh_rate);
292 }
293 }
294 return rates;
295}
296
297
300 const SDL_Keycode vk_from;
302 const uint8_t count;
303 const bool unprintable;
304
313 constexpr SDLVkMapping(SDL_Keycode vk_first, SDL_Keycode vk_last, WindowKeyCodes map_first, [[maybe_unused]] WindowKeyCodes map_last, bool unprintable)
314 : vk_from(vk_first), map_to(map_first), count(vk_last - vk_first + 1), unprintable(unprintable)
315 {
316 assert(vk_first < vk_last);
317 assert(map_first < map_last);
318 assert(this->count == static_cast<uint>(map_last - map_first + 1));
319 }
320
329};
330
332static constexpr SDLVkMapping _vk_mapping[] = {
333 /* All unprintable characters */
334 { SDLK_PAGEUP, WKC_PAGEUP, true },
335 { SDLK_PAGEDOWN, WKC_PAGEDOWN, true },
336 { SDLK_UP, WKC_UP, true },
337 { SDLK_DOWN, WKC_DOWN, true },
338 { SDLK_LEFT, WKC_LEFT, true },
339 { SDLK_RIGHT, WKC_RIGHT, true },
340
341 { SDLK_HOME, WKC_HOME, true },
342 { SDLK_END, WKC_END, true },
343
344 { SDLK_INSERT, WKC_INSERT, true },
345 { SDLK_DELETE, WKC_DELETE, true },
346
347 { SDLK_ESCAPE, WKC_ESC, true },
348 { SDLK_PAUSE, WKC_PAUSE, true },
349 { SDLK_BACKSPACE, WKC_BACKSPACE, true },
350
351 { SDLK_F1, SDLK_F12, WKC_F1, WKC_F12, true },
352
353 /* Map letters & digits */
354 { SDLK_A, SDLK_Z, WindowKeyCodes{'A'}, WindowKeyCodes{'Z'}, false },
355 { SDLK_0, SDLK_9, WindowKeyCodes{'0'}, WindowKeyCodes{'9'}, false },
356
357 { SDLK_SPACE, WKC_SPACE, false },
358 { SDLK_RETURN, WKC_RETURN, false },
359 { SDLK_TAB, WKC_TAB, false },
360
361 /* Numeric part. */
362 { SDLK_KP_1, SDLK_KP_9, WindowKeyCodes{'1'}, WindowKeyCodes{'9'}, false },
363 { SDLK_KP_0, WindowKeyCodes{'0'}, false },
364 { SDLK_KP_DIVIDE, WKC_NUM_DIV, false },
365 { SDLK_KP_MULTIPLY, WKC_NUM_MUL, false },
366 { SDLK_KP_MINUS, WKC_NUM_MINUS, false },
367 { SDLK_KP_PLUS, WKC_NUM_PLUS, false },
368 { SDLK_KP_ENTER, WKC_NUM_ENTER, false },
369 { SDLK_KP_PERIOD, WKC_NUM_DECIMAL, false },
370
371 /* Other non-letter keys */
372 { SDLK_SLASH, WKC_SLASH, false },
373 { SDLK_SEMICOLON, WKC_SEMICOLON, false },
374 { SDLK_EQUALS, WKC_EQUALS, false },
375 { SDLK_LEFTBRACKET, WKC_L_BRACKET, false },
376 { SDLK_BACKSLASH, WKC_BACKSLASH, false },
377 { SDLK_RIGHTBRACKET, WKC_R_BRACKET, false },
378
379 { SDLK_APOSTROPHE, WKC_SINGLEQUOTE, false },
380 { SDLK_COMMA, WKC_COMMA, false },
381 { SDLK_MINUS, WKC_MINUS, false },
382 { SDLK_PERIOD, WKC_PERIOD, false },
383};
384
391static uint ConvertSdlKeyIntoMy(SDL_KeyboardEvent *key_event, char32_t *character)
392{
393 uint key = 0;
394 bool unprintable = false;
395
396 for (const auto &map : _vk_mapping) {
397 if (IsInsideBS(key_event->key, map.vk_from, map.count)) {
398 key = key_event->key - map.vk_from + map.map_to;
399 unprintable = map.unprintable;
400 break;
401 }
402 }
403
404 /* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
405 if (key_event->scancode == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
406
407 /* META are the command keys on mac */
408 if (key_event->mod & SDL_KMOD_GUI) key |= WKC_META;
409 if (key_event->mod & SDL_KMOD_SHIFT) key |= WKC_SHIFT;
410 if (key_event->mod & SDL_KMOD_CTRL) key |= WKC_CTRL;
411 if (key_event->mod & SDL_KMOD_ALT) key |= WKC_ALT;
412
413 /* The mod keys have no character. Prevent '?' */
414 if (key_event->mod & SDL_KMOD_GUI ||
415 key_event->mod & SDL_KMOD_CTRL ||
416 key_event->mod & SDL_KMOD_ALT ||
417 unprintable) {
418 *character = '\0';
419 } else {
420 *character = key_event->key;
421 }
422
423 return key;
424}
425
431static uint ConvertSdlKeycodeIntoMy(SDL_Keycode kc)
432{
433 uint key = 0;
434
435 for (const auto &map : _vk_mapping) {
436 if (IsInsideBS(kc, map.vk_from, map.count)) {
437 key = kc - map.vk_from + map.map_to;
438 break;
439 }
440 }
441
442 /* check scancode for BACKQUOTE key, because we want the key left
443 * of "1", not anything else (on non-US keyboards) */
444 SDL_Scancode sc = SDL_GetScancodeFromKey(kc, nullptr);
445 if (sc == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
446
447 return key;
448}
449
451{
452 SDL_Event ev;
453
454 if (!SDL_PollEvent(&ev)) return false;
455
456 switch (ev.type) {
457 case SDL_EVENT_MOUSE_MOTION: {
458 int32_t x = ev.motion.x;
459 int32_t y = ev.motion.y;
460
461 if (_cursor.fix_at) {
462 /* Get all queued mouse events now in case we have to warp the cursor. In the
463 * end, we only care about the current mouse position and not bygone events. */
464 while (SDL_PeepEvents(&ev, 1, SDL_GETEVENT, SDL_EVENT_MOUSE_MOTION, SDL_EVENT_MOUSE_MOTION)) {
465 x = ev.motion.x;
466 y = ev.motion.y;
467 }
468 }
469
470 if (_cursor.UpdateCursorPosition(x, y)) {
471 SDL_WarpMouseInWindow(this->sdl_window, _cursor.pos.x, _cursor.pos.y);
472 }
474 break;
475 }
476
477 case SDL_EVENT_MOUSE_WHEEL: {
478 if (ev.wheel.y > 0) {
479 _cursor.wheel--;
480 } else if (ev.wheel.y < 0) {
481 _cursor.wheel++;
482 }
483
484 /* Handle 2D scrolling. */
485 const float SCROLL_BUILTIN_MULTIPLIER = 14.0f;
486 _cursor.v_wheel -= ev.wheel.y * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
487 _cursor.h_wheel += ev.wheel.x * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
488 _cursor.wheel_moved = true;
489 break;
490 }
491
492 case SDL_EVENT_MOUSE_BUTTON_DOWN:
493 if (_rightclick_emulate && SDL_GetModState() & SDL_KMOD_CTRL) {
494 ev.button.button = SDL_BUTTON_RIGHT;
495 }
496
497 switch (ev.button.button) {
498 case SDL_BUTTON_LEFT:
500 break;
501
502 case SDL_BUTTON_RIGHT:
505 break;
506
507 case SDL_BUTTON_MIDDLE:
510 break;
511
512 case SDL_BUTTON_X1:
515 break;
516
517 case SDL_BUTTON_X2:
520 break;
521
522 default: break;
523 }
525 break;
526
527 case SDL_EVENT_MOUSE_BUTTON_UP:
531 } else if (ev.button.button == SDL_BUTTON_LEFT) {
534 } else if (ev.button.button == SDL_BUTTON_RIGHT) {
536 } else if (ev.button.button == SDL_BUTTON_MIDDLE) {
538 } else if (ev.button.button == SDL_BUTTON_X1) {
540 } else if (ev.button.button == SDL_BUTTON_X2) {
542 }
544 break;
545
546 case SDL_EVENT_QUIT:
547 HandleExitGameRequest();
548 break;
549
550 case SDL_EVENT_KEY_DOWN: // Toggle full-screen on ALT + ENTER/F
551 if ((ev.key.mod & (SDL_KMOD_ALT | SDL_KMOD_GUI)) &&
552 (ev.key.key == SDLK_RETURN || ev.key.key == SDLK_F)) {
553 if (ev.key.repeat == 0) ToggleFullScreen(!_fullscreen);
554 } else {
555 char32_t character;
556
557 uint keycode = ConvertSdlKeyIntoMy(&ev.key, &character);
558 /* Only handle non-text keys here. Text is handled in
559 * SDL_EVENT_TEXT_INPUT below. */
560 if (!this->edit_box_focused ||
561 keycode == WKC_DELETE ||
562 keycode == WKC_NUM_ENTER ||
563 keycode == WKC_LEFT ||
564 keycode == WKC_RIGHT ||
565 keycode == WKC_UP ||
566 keycode == WKC_DOWN ||
567 keycode == WKC_HOME ||
568 keycode == WKC_END ||
569 keycode & WKC_META ||
570 keycode & WKC_CTRL ||
571 keycode & WKC_ALT ||
572 (keycode >= WKC_F1 && keycode <= WKC_F12) ||
573 !IsValidChar(character, CS_ALPHANUMERAL)) {
574 HandleKeypress(keycode, character);
575 }
576 }
577 break;
578
579 case SDL_EVENT_TEXT_INPUT: {
580 if (!this->edit_box_focused) break;
581 SDL_Keycode kc = SDL_GetKeyFromName(ev.text.text);
582 uint keycode = ConvertSdlKeycodeIntoMy(kc);
583
584 if (keycode == WKC_BACKQUOTE && FocusedWindowIsConsole()) {
585 auto [len, c] = DecodeUtf8(ev.text.text);
586 if (len > 0) HandleKeypress(keycode, c);
587 } else {
588 HandleTextInput(ev.text.text);
589 }
590 break;
591 }
592
593 case SDL_EVENT_WINDOW_EXPOSED:
594 /* Force a redraw of the entire screen. */
595 this->MakeDirty(0, 0, _screen.width, _screen.height);
596 break;
597
598 case SDL_EVENT_WINDOW_RESIZED:
599 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED: {
600 int w = std::max(ev.window.data1, 64);
601 int h = std::max(ev.window.data2, 64);
602 CreateMainSurface(w, h, w != ev.window.data1 || h != ev.window.data2);
603 break;
604 }
605
606 case SDL_EVENT_WINDOW_MOUSE_ENTER:
607 /* mouse entered the window, enable cursor */
608 _cursor.in_window = true;
609 /* Ensure pointer lock will not occur. */
610 SDL_SetWindowRelativeMouseMode(this->sdl_window, false);
611 break;
612
613 case SDL_EVENT_WINDOW_MOUSE_LEAVE:
614 /* mouse left the window, undraw cursor */
615 UndrawMouseCursor();
616 _cursor.in_window = false;
617 break;
618 }
619
620 return true;
621}
622
627static std::optional<std::string_view> InitializeSDL()
628{
629 /* Check if the video-driver is already initialized. */
630 if (SDL_WasInit(SDL_INIT_VIDEO)) return std::nullopt;
631
632#ifdef SDL_HINT_APP_NAME
633 SDL_SetHint(SDL_HINT_APP_NAME, "OpenTTD");
634#endif
635
636 if (!SDL_InitSubSystem(SDL_INIT_VIDEO)) return SDL_GetError();
637 return std::nullopt;
638}
639
644std::optional<std::string_view> VideoDriver_SDL_Base::Initialize()
645{
646 this->UpdateAutoResolution();
647
648 auto error = InitializeSDL();
649 if (error) return error;
650
652 Debug(Facility::Driver, Severity::Warning, "Resolution for display: {}x{}", _cur_resolution.width, _cur_resolution.height);
653
654 return std::nullopt;
655}
656
657std::optional<std::string_view> VideoDriver_SDL_Base::Start(const StringList &param)
658{
659 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
660
661 auto error = this->Initialize();
662 if (error) return error;
663
664#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE
665 if (GetDriverParamBool(param, "no_mouse_capture")) {
666 /* By default SDL captures the mouse, while a button is pressed.
667 * This is annoying during debugging, when OpenTTD is suspended while the button was pressed.
668 */
669 if (!SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0")) return SDL_GetError();
670 }
671#endif
672
673 this->startup_display = FindStartupDisplay(GetDriverParamInt(param, "display", -1));
674
675 if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height, false)) {
676 return SDL_GetError();
677 }
678
679 const char *dname = SDL_GetCurrentVideoDriver();
680 Debug(Facility::Driver, Severity::Error, "SDL3: using driver '{}'", dname);
681
682 this->driver_info = this->GetName();
683 this->driver_info += " (";
684 this->driver_info += dname;
685 this->driver_info += ")";
686
688
689 SDL_StopTextInput(this->sdl_window);
690 this->edit_box_focused = false;
691
692#ifdef __EMSCRIPTEN__
693 this->is_game_threaded = false;
694#else
695 this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
696#endif
697
698 return std::nullopt;
699}
700
702{
703 SDL_QuitSubSystem(SDL_INIT_VIDEO);
704 if (!SDL_WasInit(SDL_INIT_AUDIO)) {
705 SDL_Quit(); // If there's nothing left, quit SDL
706 }
707}
708
710{
711 uint32_t mod = SDL_GetModState();
712 const bool *key_states = SDL_GetKeyboardState(nullptr);
713
714 bool old_ctrl_pressed = IsCtrlPressed();
715
716 _input_pressed.Set(ControlInput::Ctrl, (mod & SDL_KMOD_CTRL) != 0);
717 _input_pressed.Set(ControlInput::Shift, (mod & SDL_KMOD_SHIFT) != 0);
718
719 /* Speedup when pressing tab, except when using ALT+TAB
720 * to switch to another application. */
721 this->fast_forward_key_pressed = key_states[SDL_SCANCODE_TAB] && (mod & SDL_KMOD_ALT) == 0;
722
723 /* Determine which directional keys are down. */
724 _dirkeys.Set(DirectionKey::Left, key_states[SDL_SCANCODE_LEFT]);
725 _dirkeys.Set(DirectionKey::Up, key_states[SDL_SCANCODE_UP]);
726 _dirkeys.Set(DirectionKey::Right, key_states[SDL_SCANCODE_RIGHT]);
727 _dirkeys.Set(DirectionKey::Down, key_states[SDL_SCANCODE_DOWN]);
728
729 if (old_ctrl_pressed != IsCtrlPressed()) HandleCtrlChanged();
730}
731
734{
735 if (_exit_game) {
736#ifdef __EMSCRIPTEN__
737 /* Emscripten is event-driven, and as such the main loop is inside
738 * the browser. So if _exit_game goes true, the main loop ends (the
739 * cancel call), but we still have to call the cleanup that is
740 * normally done at the end of the main loop for non-Emscripten.
741 * After that, Emscripten just halts, and the HTML shows a nice
742 * "bye, see you next time" message. */
743 extern void PostMainLoop();
744 PostMainLoop();
745
746 emscripten_cancel_main_loop();
747 emscripten_exit_pointerlock();
748 /* In effect, the game ends here. As emscripten_set_main_loop() caused
749 * the stack to be unwound, the code after MainLoop() in
750 * openttd_main() is never executed. */
751 if (_game_mode == GameMode::Bootstrap) {
752 EM_ASM(if (window["openttd_bootstrap_reload"]) openttd_bootstrap_reload());
753 } else {
754 EM_ASM(if (window["openttd_exit"]) openttd_exit());
755 }
756#endif
757 return;
758 }
759
760 this->Tick();
761
762/* Emscripten is running an event-based mainloop; there is already some
763 * downtime between each iteration, so no need to sleep. */
764#ifndef __EMSCRIPTEN__
765 this->SleepTillNextTick();
766#endif
767}
768
770{
771#ifdef __EMSCRIPTEN__
772 /* Run the main loop event-driven, based on RequestAnimationFrame. */
773 emscripten_set_main_loop_arg(&this->EmscriptenLoop, this, 0, 1);
774#else
775 this->StartGameThread();
776
777 while (!_exit_game) {
778 LoopOnce();
779 }
780
781 this->StopGameThread();
782#endif
783}
784
786{
787 return CreateMainSurface(w, h, true);
788}
789
791{
792 /* Remember current window size */
793 int w, h;
794 SDL_GetWindowSize(this->sdl_window, &w, &h);
795
796 if (fullscreen) {
797 /* Find fullscreen window size */
798 const SDL_DisplayMode *dm = SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(this->sdl_window));
799 if (dm == nullptr) {
800 Debug(Facility::Driver, Severity::Critical, "SDL_GetCurrentDisplayMode() failed: {}", SDL_GetError());
801 } else {
802 SDL_SetWindowSize(this->sdl_window, dm->w, dm->h);
803 }
804 }
805
806 Debug(Facility::Driver, Severity::Error, "SDL3: Setting {}", fullscreen ? "fullscreen" : "windowed");
807 bool success = SDL_SetWindowFullscreen(this->sdl_window, fullscreen);
808 if (success) {
809 /* Switching resolution succeeded, set fullscreen value of window. */
810 _fullscreen = fullscreen;
811 if (!fullscreen) SDL_SetWindowSize(this->sdl_window, w, h);
812 } else {
813 Debug(Facility::Driver, Severity::Critical, "SDL_SetWindowFullscreen() failed: {}", SDL_GetError());
814 }
815
816 InvalidateWindowClassesData(WindowClass::GameOptions, 3);
817 return success;
818}
819
821{
822 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
823 int w, h;
824 SDL_GetWindowSize(this->sdl_window, &w, &h);
825 return CreateMainSurface(w, h, false);
826}
827
829{
830 const SDL_DisplayMode *mode = SDL_GetCurrentDisplayMode(SDL_GetDisplayForWindow(this->sdl_window));
831 if (mode == nullptr) return VideoDriver::GetScreenSize();
832
833 return { static_cast<uint>(mode->w), static_cast<uint>(mode->h) };
834}
835
837{
838 if (this->buffer_locked) return false;
839 this->buffer_locked = true;
840
841 _screen.dst_ptr = this->GetVideoPointer();
842 assert(_screen.dst_ptr != nullptr);
843
844 return true;
845}
846
848{
849 if (_screen.dst_ptr != nullptr) {
850 /* Hand video buffer back to the drawing backend. */
851 this->ReleaseVideoPointer();
852 _screen.dst_ptr = nullptr;
853 }
854
855 this->buffer_locked = false;
856}
857
859{
860 if (inhibited) {
861 SDL_DisableScreenSaver();
862 } else {
863 SDL_EnableScreenSaver();
864 }
865}
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:139
virtual void PostResize()
Post resize event.
Definition base.hpp:210
virtual std::string_view GetName() const =0
Get the name of this driver.
Helper to map some SDL functions to behave like a std::range.
Definition sdl3_v.cpp:52
~SDLRange()
Free the data.
Definition sdl3_v.cpp:64
constexpr T * begin() const
Iterator to the begin of the data.
Definition sdl3_v.cpp:73
SDLRange & operator=(const SDLRange &)=delete
Do not assign.
SDLRange(Func func, Args... args)
Create the range.
Definition sdl3_v.cpp:62
constexpr T * end() const
Iterator to the end of the data.
Definition sdl3_v.cpp:79
int count
The number of elements.
Definition sdl3_v.cpp:54
T * data
The base pointer of the array.
Definition sdl3_v.cpp:53
SDLRange(SDLRange &)=delete
Do not copy.
constexpr size_t size() const
The number of elements in this range.
Definition sdl3_v.cpp:85
std::optional< std::string_view > Start(const StringList &param) override
Start this driver.
Definition sdl3_v.cpp:657
bool buffer_locked
Video buffer was locked by the main thread.
Definition sdl3_v.h:54
Dimension GetScreenSize() const override
Get the resolution of the main screen.
Definition sdl3_v.cpp:828
bool PollEvent() override
Process a single system event.
Definition sdl3_v.cpp:450
void EditBoxLostFocus() override
This is called to indicate that an edit box has lost focus, text input mode should be disabled.
Definition sdl3_v.cpp:278
virtual void ReleaseVideoPointer()=0
Hand video buffer back to the painting backend.
void ClaimMousePointer() override
Claim the exclusive rights for the mouse pointer.
Definition sdl3_v.cpp:256
virtual void * GetVideoPointer()=0
Get a pointer to the video buffer.
void LoopOnce()
Run a single tick of the game/main loop.
Definition sdl3_v.cpp:733
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
Definition sdl3_v.cpp:820
virtual bool AllocateBackingStore(int w, int h, bool force=false)=0
(Re-)create the backing store.
void InputLoop() override
Handle input logic, is CTRL pressed, should we fast-forward, etc.
Definition sdl3_v.cpp:709
Palette local_palette
Current palette to use for drawing.
Definition sdl3_v.h:53
void MainLoop() override
Perform the actual drawing.
Definition sdl3_v.cpp:769
std::optional< std::string_view > Initialize()
Initialize the driver.
Definition sdl3_v.cpp:644
std::string driver_info
Information string about selected driver.
Definition sdl3_v.h:56
void UnlockVideoBuffer() override
Unlock a previously locked video buffer.
Definition sdl3_v.cpp:847
void ClientSizeChanged(int w, int h, bool force)
Indicate to the driver the client-size might have changed.
Definition sdl3_v.cpp:183
int startup_display
The display to show OpenTTD on when starting.
Definition sdl3_v.h:109
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
Definition sdl3_v.cpp:34
virtual bool CreateMainWindow(uint w, uint h, uint flags=0)
Create the main window.
Definition sdl3_v.cpp:195
std::vector< int > GetListOfMonitorRefreshRates() override
Get a list of refresh rates of each available monitor.
Definition sdl3_v.cpp:286
void SetScreensaverInhibited(bool inhibited) override
Prevents the system from going to sleep.
Definition sdl3_v.cpp:858
bool edit_box_focused
This is true to indicate that keyboard input is in text input mode, and SDL_TEXTINPUT events are enab...
Definition sdl3_v.h:107
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
Definition sdl3_v.cpp:785
void Stop() override
Stop this driver.
Definition sdl3_v.cpp:701
bool CreateMainSurface(uint w, uint h, bool resize)
Create/update the surfaces to draw OpenTTD on.
Definition sdl3_v.cpp:239
bool LockVideoBuffer() override
Make sure the video buffer is ready for drawing.
Definition sdl3_v.cpp:836
void EditBoxGainedFocus() override
This is called to indicate that an edit box has gained focus, text input mode should be enabled.
Definition sdl3_v.cpp:267
Rect dirty_rect
Rectangle encompassing the dirty area of the video buffer.
Definition sdl3_v.h:55
void CheckPaletteAnim() override
Process any pending palette animation.
Definition sdl3_v.cpp:40
struct SDL_Window * sdl_window
Main SDL window.
Definition sdl3_v.h:52
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
Definition sdl3_v.cpp:790
virtual Dimension GetScreenSize() const
Get the resolution of the main screen.
bool fast_forward_key_pressed
The fast-forward key is being pressed.
void Tick()
Give the video-driver a tick.
void SleepTillNextTick()
Sleep till the next tick is about to happen.
void StartGameThread()
Start the loop for game-tick.
static std::string GetCaption()
Get the caption to use for the game's title bar.
void StopGameThread()
Stop the loop for the game-tick.
void UpdateAutoResolution()
Apply resolution auto-detection and clamp to sensible defaults.
bool is_game_threaded
Whether the game is allowed to use threads; cleared in the driver implementation constructors if requ...
static const Dimension _default_resolutions[]
List of common display/window sizes.
Definition cocoa_v.mm:50
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Driver
Driver message facility.
Definition debug_type.h:29
@ Warning
Warning, wrong but okay if you don't know.
Definition debug_type.h:17
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Error
Error, but we are recovering.
Definition debug_type.h:16
int GetDriverParamInt(const StringList &parm, std::string_view name, int def)
Get an integer parameter the list of parameters.
Definition driver.cpp:79
bool GetDriverParamBool(const StringList &parm, std::string_view name)
Get a boolean parameter the list of parameters.
Definition driver.cpp:67
std::vector< Dimension > _resolutions
List of resolutions.
Definition driver.cpp:28
Dimension _cur_resolution
The current resolution.
Definition driver.cpp:29
bool _rightclick_emulate
Whether right clicking is emulated.
Definition driver.cpp:30
#define T
Climate temperate.
Definition engines.h:91
Factory to 'query' all available blitters.
std::string FioFindFullPath(Subdirectory subdir, std::string_view filename)
Find a path to the filename in one of the search directories.
Definition fileio.cpp:145
Functions for standard in/out file operations.
@ Baseset
Subdirectory for all base data (base sets, intro game).
Definition fileio_type.h:95
Types for recording game performance data.
Rect BoundingRect(const Rect &r1, const Rect &r2)
Compute the bounding rectangle around two rectangles.
Geometry functions.
ControlInputs _input_pressed
Control inputs that are currently pressed.
Definition gfx.cpp:34
ControlInputs _input_clicked
Control inputs that have been actioned.
Definition gfx.cpp:35
DirectionKeys _dirkeys
Pressed direction keys.
Definition gfx.cpp:36
Functions related to the gfx engine.
void HandleCtrlChanged()
State of CONTROL key has changed.
Definition window.cpp:2771
void GameSizeChanged()
Size of the application screen changed.
Definition main_gui.cpp:592
void HandleMouseEvents()
Handle a mouse event from the video driver.
Definition window.cpp:3032
bool IsCtrlPressed()
Test if the ctrl key is pressed.
Definition gfx_func.h:82
void HandleKeypress(uint keycode, char32_t key)
Handle keyboard input.
Definition window.cpp:2715
void HandleTextInput(std::string_view str, bool marked=false, std::optional< size_t > caret=std::nullopt, std::optional< size_t > insert_location=std::nullopt, std::optional< size_t > replacement_end=std::nullopt)
Handle text input.
Definition window.cpp:2807
@ Down
Down.
Definition gfx_type.h:438
@ Right
Right.
Definition gfx_type.h:437
@ Left
Left.
Definition gfx_type.h:435
@ Ctrl
Ctrl modifier is pressed.
Definition gfx_type.h:449
@ X2
X2 mouse button is pressed.
Definition gfx_type.h:448
@ Shift
Shift modifier is pressed.
Definition gfx_type.h:450
@ Right
Right mouse button is pressed.
Definition gfx_type.h:445
@ Left
Left mouse button is pressed.
Definition gfx_type.h:444
@ Middle
Middle mouse button is pressed.
Definition gfx_type.h:446
@ X1
X1 mouse button is pressed.
Definition gfx_type.h:447
WindowKeyCodes
Definition gfx_type.h:29
@ WKC_BACKSLASH
\ Backslash
Definition gfx_type.h:101
@ WKC_MINUS
Definition gfx_type.h:106
@ WKC_COMMA
, Comma
Definition gfx_type.h:104
@ WKC_PERIOD
. Period
Definition gfx_type.h:105
@ WKC_EQUALS
= Equals
Definition gfx_type.h:99
@ WKC_SLASH
/ Forward slash
Definition gfx_type.h:97
@ WKC_SINGLEQUOTE
' Single quote
Definition gfx_type.h:103
@ WKC_R_BRACKET
] Right square bracket
Definition gfx_type.h:102
@ WKC_L_BRACKET
[ Left square bracket
Definition gfx_type.h:100
@ WKC_SEMICOLON
; Semicolon
Definition gfx_type.h:98
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
Integer math functions.
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr T Delta(const T a, const T b)
Returns the (absolute) difference between two (scalar) variables.
Some generic types.
@ Bootstrap
In the content bootstrap process.
Definition openttd.h:22
bool CopyPalette(Palette &local_palette, bool force_copy)
Copy the current palette if the palette was updated.
Definition palette.cpp:230
Functions related to modal progress.
A number of safeguards to prevent using unsafe methods.
static void GetAvailableVideoMode(uint *w, uint *h)
Get the best resolution given the requested width and height.
Definition sdl3_v.cpp:129
static uint ConvertSdlKeyIntoMy(SDL_KeyboardEvent *key_event, char32_t *character)
Convert the SDL key into our WindowKeyCode and the printable character (if any).
Definition sdl3_v.cpp:391
static void FindResolutions()
Find and store all possible resolutions into _resolutions.
Definition sdl3_v.cpp:104
static std::optional< std::string_view > InitializeSDL()
Initialize the SDL backend if needed.
Definition sdl3_v.cpp:627
static uint ConvertSdlKeycodeIntoMy(SDL_Keycode kc)
Convert a SDL_Keycode into our own key codes.
Definition sdl3_v.cpp:431
static uint FindStartupDisplay(uint startup_display)
Find the display we want to start OpenTTD on.
Definition sdl3_v.cpp:156
Base of the SDL3 video driver.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Definition of base types and functions in a cross-platform compatible way.
bool IsValidChar(char32_t key, CharSetFilter afilter)
Only allow certain keys.
Definition string.cpp:374
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition string_type.h:25
std::vector< std::string > StringList
Type for a list of strings.
Definition string_type.h:61
Dimensions (a width and height) of a rectangle in 2D.
Specification of a rectangle with absolute coordinates of all edges.
Mapping from keycodes in the SDL world to OpenTTD's world.
Definition sdl3_v.cpp:299
const uint8_t count
The number of keycodes that are to be mapped.
Definition sdl3_v.cpp:302
const WindowKeyCodes map_to
The first of the OpenTTD keycodes of this mapping.
Definition sdl3_v.cpp:301
const bool unprintable
Whether this keycode is unprintable.
Definition sdl3_v.cpp:303
constexpr SDLVkMapping(SDL_Keycode vk_from, WindowKeyCodes map_to, bool unprintable)
Create a mapping for a single keycode.
Definition sdl3_v.cpp:327
const SDL_Keycode vk_from
The first of the SDL keycodes of this mapping.
Definition sdl3_v.cpp:300
constexpr SDLVkMapping(SDL_Keycode vk_first, SDL_Keycode vk_last, WindowKeyCodes map_first, WindowKeyCodes map_last, bool unprintable)
Create a mapping for several consecutive keycodes.
Definition sdl3_v.cpp:313
Base of all threads.
std::pair< size_t, char32_t > DecodeUtf8(std::string_view buf)
Decode a character from UTF-8.
Definition utf8.cpp:46
Handling of UTF-8 encoded data.
bool FocusedWindowIsConsole()
Check if a console is focused.
Definition window.cpp:470
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3395
Window functions not directly related to making/drawing windows.