OpenTTD Source 20260711-master-g3fb3006dff
sdl2_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 "sdl2_v.h"
23#include <SDL.h>
24#ifdef __EMSCRIPTEN__
25# include <emscripten.h>
26# include <emscripten/html5.h>
27#endif
28
29#include "../safeguards.h"
30
31void VideoDriver_SDL_Base::MakeDirty(int left, int top, int width, int height)
32{
33 Rect r = {left, top, left + width, top + height};
34 this->dirty_rect = BoundingRect(this->dirty_rect, r);
35}
36
38{
39 if (!CopyPalette(this->local_palette)) return;
40 this->MakeDirty(0, 0, _screen.width, _screen.height);
41}
42
45 { 640, 480 },
46 { 800, 600 },
47 { 1024, 768 },
48 { 1152, 864 },
49 { 1280, 800 },
50 { 1280, 960 },
51 { 1280, 1024 },
52 { 1400, 1050 },
53 { 1600, 1200 },
54 { 1680, 1050 },
55 { 1920, 1200 }
56};
57
59static void FindResolutions()
60{
61 _resolutions.clear();
62
63 for (int display = 0; display < SDL_GetNumVideoDisplays(); display++) {
64 for (int i = 0; i < SDL_GetNumDisplayModes(display); i++) {
65 SDL_DisplayMode mode;
66 SDL_GetDisplayMode(display, i, &mode);
67
68 if (mode.w < 640 || mode.h < 480) continue;
69 if (std::ranges::find(_resolutions, Dimension(mode.w, mode.h)) != _resolutions.end()) continue;
70 _resolutions.emplace_back(mode.w, mode.h);
71 }
72 }
73
74 /* We have found no resolutions, show the default list */
75 if (_resolutions.empty()) {
76 _resolutions.assign(std::begin(_default_resolutions), std::end(_default_resolutions));
77 }
78
79 SortResolutions();
80}
81
87static void GetAvailableVideoMode(uint *w, uint *h)
88{
89 /* All modes available? */
90 if (!_fullscreen || _resolutions.empty()) return;
91
92 /* Is the wanted mode among the available modes? */
93 if (std::ranges::find(_resolutions, Dimension(*w, *h)) != _resolutions.end()) return;
94
95 /* Use the closest possible resolution */
96 uint best = 0;
97 uint delta = Delta(_resolutions[0].width, *w) * Delta(_resolutions[0].height, *h);
98 for (uint i = 1; i != _resolutions.size(); ++i) {
99 uint newdelta = Delta(_resolutions[i].width, *w) * Delta(_resolutions[i].height, *h);
100 if (newdelta < delta) {
101 best = i;
102 delta = newdelta;
103 }
104 }
105 *w = _resolutions[best].width;
106 *h = _resolutions[best].height;
107}
108
114static uint FindStartupDisplay(uint startup_display)
115{
116 int num_displays = SDL_GetNumVideoDisplays();
117
118 /* If the user indicated a valid monitor, use that. */
119 if (IsInsideBS(startup_display, 0, num_displays)) return startup_display;
120
121 /* Mouse position decides which display to use. */
122 int mx, my;
123 SDL_GetGlobalMouseState(&mx, &my);
124 for (int display = 0; display < num_displays; ++display) {
125 SDL_Rect r;
126 if (SDL_GetDisplayBounds(display, &r) == 0 && IsInsideBS(mx, r.x, r.w) && IsInsideBS(my, r.y, r.h)) {
127 Debug(driver, 1, "SDL2: Mouse is at ({}, {}), use display {} ({}, {}, {}, {})", mx, my, display, r.x, r.y, r.w, r.h);
128 return display;
129 }
130 }
131
132 return 0;
133}
134
141void VideoDriver_SDL_Base::ClientSizeChanged(int w, int h, bool force)
142{
143 /* Allocate backing store of the new size. */
144 if (this->AllocateBackingStore(w, h, force)) {
145 CopyPalette(this->local_palette, true);
146
148
150 }
151}
152
153bool VideoDriver_SDL_Base::CreateMainWindow(uint w, uint h, uint flags)
154{
155 if (this->sdl_window != nullptr) return true;
156
157 flags |= SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE;
158
159 if (_fullscreen) {
160 flags |= SDL_WINDOW_FULLSCREEN;
161 }
162
163 int x = SDL_WINDOWPOS_UNDEFINED, y = SDL_WINDOWPOS_UNDEFINED;
164 SDL_Rect r;
165 if (SDL_GetDisplayBounds(this->startup_display, &r) == 0) {
166 x = r.x + std::max(0, r.w - static_cast<int>(w)) / 2;
167 y = r.y + std::max(0, r.h - static_cast<int>(h)) / 4; // decent desktops have taskbars at the bottom
168 }
169
170 std::string caption = VideoDriver::GetCaption();
171 this->sdl_window = SDL_CreateWindow(
172 caption.c_str(),
173 x, y,
174 w, h,
175 flags);
176
177 if (this->sdl_window == nullptr) {
178 Debug(driver, 0, "SDL2: Couldn't allocate a window to draw on: {}", SDL_GetError());
179 return false;
180 }
181
182 std::string icon_path = FioFindFullPath(Subdirectory::Baseset, "openttd.32.bmp");
183 if (!icon_path.empty()) {
184 /* Give the application an icon */
185 SDL_Surface *icon = SDL_LoadBMP(icon_path.c_str());
186 if (icon != nullptr) {
187 /* Get the colourkey, which will be magenta */
188 uint32_t rgbmap = SDL_MapRGB(icon->format, 255, 0, 255);
189
190 SDL_SetColorKey(icon, SDL_TRUE, rgbmap);
191 SDL_SetWindowIcon(this->sdl_window, icon);
192 SDL_FreeSurface(icon);
193 }
194 }
195
196 return true;
197}
198
206bool VideoDriver_SDL_Base::CreateMainSurface(uint w, uint h, bool resize)
207{
208 GetAvailableVideoMode(&w, &h);
209 Debug(driver, 1, "SDL2: using mode {}x{}", w, h);
210
211 if (!this->CreateMainWindow(w, h)) return false;
212 if (resize) SDL_SetWindowSize(this->sdl_window, w, h);
213 this->ClientSizeChanged(w, h, true);
214
215 /* When in full screen, we will always have the mouse cursor
216 * within the window, even though SDL does not give us the
217 * appropriate event to know this. */
218 if (_fullscreen) _cursor.in_window = true;
219
220 return true;
221}
222
224{
225 /* Emscripten never claims the pointer, so we do not need to change the cursor visibility. */
226#ifndef __EMSCRIPTEN__
227 SDL_ShowCursor(0);
228#endif
229}
230
235{
236 if (!this->edit_box_focused) {
237 SDL_StartTextInput();
238 this->edit_box_focused = true;
239 }
240}
241
246{
247 if (this->edit_box_focused) {
248 SDL_StopTextInput();
249 this->edit_box_focused = false;
250 }
251}
252
254{
255 std::vector<int> rates = {};
256 for (int i = 0; i < SDL_GetNumVideoDisplays(); i++) {
257 SDL_DisplayMode mode = {};
258 if (SDL_GetDisplayMode(i, 0, &mode) != 0) continue;
259 if (mode.refresh_rate != 0) rates.push_back(mode.refresh_rate);
260 }
261 return rates;
262}
263
264
267 const SDL_Keycode vk_from;
269 const uint8_t count;
270 const bool unprintable;
271
280 constexpr SDLVkMapping(SDL_Keycode vk_first, SDL_Keycode vk_last, WindowKeyCodes map_first, [[maybe_unused]] WindowKeyCodes map_last, bool unprintable)
281 : vk_from(vk_first), map_to(map_first), count(vk_last - vk_first + 1), unprintable(unprintable)
282 {
283 assert(vk_first < vk_last);
284 assert(map_first < map_last);
285 assert(this->count == static_cast<uint>(map_last - map_first + 1));
286 }
287
296};
297
299static constexpr SDLVkMapping _vk_mapping[] = {
300 /* All unprintable characters */
301 { SDLK_PAGEUP, WKC_PAGEUP, true },
302 { SDLK_PAGEDOWN, WKC_PAGEDOWN, true },
303 { SDLK_UP, WKC_UP, true },
304 { SDLK_DOWN, WKC_DOWN, true },
305 { SDLK_LEFT, WKC_LEFT, true },
306 { SDLK_RIGHT, WKC_RIGHT, true },
307
308 { SDLK_HOME, WKC_HOME, true },
309 { SDLK_END, WKC_END, true },
310
311 { SDLK_INSERT, WKC_INSERT, true },
312 { SDLK_DELETE, WKC_DELETE, true },
313
314 { SDLK_ESCAPE, WKC_ESC, true },
315 { SDLK_PAUSE, WKC_PAUSE, true },
316 { SDLK_BACKSPACE, WKC_BACKSPACE, true },
317
318 { SDLK_F1, SDLK_F12, WKC_F1, WKC_F12, true },
319
320 /* Map letters & digits */
321 { SDLK_a, SDLK_z, WindowKeyCodes{'A'}, WindowKeyCodes{'Z'}, false },
322 { SDLK_0, SDLK_9, WindowKeyCodes{'0'}, WindowKeyCodes{'9'}, false },
323
324 { SDLK_SPACE, WKC_SPACE, false },
325 { SDLK_RETURN, WKC_RETURN, false },
326 { SDLK_TAB, WKC_TAB, false },
327
328 /* Numeric part. */
329 { SDLK_KP_1, SDLK_KP_9, WindowKeyCodes{'1'}, WindowKeyCodes{'9'}, false },
330 { SDLK_KP_0, WindowKeyCodes{'0'}, false },
331 { SDLK_KP_DIVIDE, WKC_NUM_DIV, false },
332 { SDLK_KP_MULTIPLY, WKC_NUM_MUL, false },
333 { SDLK_KP_MINUS, WKC_NUM_MINUS, false },
334 { SDLK_KP_PLUS, WKC_NUM_PLUS, false },
335 { SDLK_KP_ENTER, WKC_NUM_ENTER, false },
336 { SDLK_KP_PERIOD, WKC_NUM_DECIMAL, false },
337
338 /* Other non-letter keys */
339 { SDLK_SLASH, WKC_SLASH, false },
340 { SDLK_SEMICOLON, WKC_SEMICOLON, false },
341 { SDLK_EQUALS, WKC_EQUALS, false },
342 { SDLK_LEFTBRACKET, WKC_L_BRACKET, false },
343 { SDLK_BACKSLASH, WKC_BACKSLASH, false },
344 { SDLK_RIGHTBRACKET, WKC_R_BRACKET, false },
345
346 { SDLK_QUOTE, WKC_SINGLEQUOTE, false },
347 { SDLK_COMMA, WKC_COMMA, false },
348 { SDLK_MINUS, WKC_MINUS, false },
349 { SDLK_PERIOD, WKC_PERIOD, false },
350};
351
358static uint ConvertSdlKeyIntoMy(SDL_Keysym *sym, char32_t *character)
359{
360 uint key = 0;
361 bool unprintable = false;
362
363 for (const auto &map : _vk_mapping) {
364 if (IsInsideBS(sym->sym, map.vk_from, map.count)) {
365 key = sym->sym - map.vk_from + map.map_to;
366 unprintable = map.unprintable;
367 break;
368 }
369 }
370
371 /* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
372 if (sym->scancode == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
373
374 /* META are the command keys on mac */
375 if (sym->mod & KMOD_GUI) key |= WKC_META;
376 if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
377 if (sym->mod & KMOD_CTRL) key |= WKC_CTRL;
378 if (sym->mod & KMOD_ALT) key |= WKC_ALT;
379
380 /* The mod keys have no character. Prevent '?' */
381 if (sym->mod & KMOD_GUI ||
382 sym->mod & KMOD_CTRL ||
383 sym->mod & KMOD_ALT ||
384 unprintable) {
385 *character = '\0';
386 } else {
387 *character = sym->sym;
388 }
389
390 return key;
391}
392
398static uint ConvertSdlKeycodeIntoMy(SDL_Keycode kc)
399{
400 uint key = 0;
401
402 for (const auto &map : _vk_mapping) {
403 if (IsInsideBS(kc, map.vk_from, map.count)) {
404 key = kc - map.vk_from + map.map_to;
405 break;
406 }
407 }
408
409 /* check scancode for BACKQUOTE key, because we want the key left
410 * of "1", not anything else (on non-US keyboards) */
411 SDL_Scancode sc = SDL_GetScancodeFromKey(kc);
412 if (sc == SDL_SCANCODE_GRAVE) key = WKC_BACKQUOTE;
413
414 return key;
415}
416
418{
419 SDL_Event ev;
420
421 if (!SDL_PollEvent(&ev)) return false;
422
423 switch (ev.type) {
424 case SDL_MOUSEMOTION: {
425 int32_t x = ev.motion.x;
426 int32_t y = ev.motion.y;
427
428 if (_cursor.fix_at) {
429 /* Get all queued mouse events now in case we have to warp the cursor. In the
430 * end, we only care about the current mouse position and not bygone events. */
431 while (SDL_PeepEvents(&ev, 1, SDL_GETEVENT, SDL_MOUSEMOTION, SDL_MOUSEMOTION)) {
432 x = ev.motion.x;
433 y = ev.motion.y;
434 }
435 }
436
437 if (_cursor.UpdateCursorPosition(x, y)) {
438 SDL_WarpMouseInWindow(this->sdl_window, _cursor.pos.x, _cursor.pos.y);
439 }
441 break;
442 }
443
444 case SDL_MOUSEWHEEL: {
445 if (ev.wheel.y > 0) {
446 _cursor.wheel--;
447 } else if (ev.wheel.y < 0) {
448 _cursor.wheel++;
449 }
450
451 /* Handle 2D scrolling. */
452 const float SCROLL_BUILTIN_MULTIPLIER = 14.0f;
453#if SDL_VERSION_ATLEAST(2, 18, 0)
454 _cursor.v_wheel -= ev.wheel.preciseY * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
455 _cursor.h_wheel += ev.wheel.preciseX * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
456#else
457 _cursor.v_wheel -= static_cast<float>(ev.wheel.y * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier);
458 _cursor.h_wheel += static_cast<float>(ev.wheel.x * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier);
459#endif
460 _cursor.wheel_moved = true;
461 break;
462 }
463
464 case SDL_MOUSEBUTTONDOWN:
465 if (_rightclick_emulate && SDL_GetModState() & KMOD_CTRL) {
466 ev.button.button = SDL_BUTTON_RIGHT;
467 }
468
469 switch (ev.button.button) {
470 case SDL_BUTTON_LEFT:
471 _left_button_down = true;
472 break;
473
474 case SDL_BUTTON_RIGHT:
475 _right_button_down = true;
477 break;
478
479 default: break;
480 }
482 break;
483
484 case SDL_MOUSEBUTTONUP:
486 _right_button_down = false;
487 _left_button_down = false;
488 _left_button_clicked = false;
489 } else if (ev.button.button == SDL_BUTTON_LEFT) {
490 _left_button_down = false;
491 _left_button_clicked = false;
492 } else if (ev.button.button == SDL_BUTTON_RIGHT) {
493 _right_button_down = false;
494 }
496 break;
497
498 case SDL_QUIT:
499 HandleExitGameRequest();
500 break;
501
502 case SDL_KEYDOWN: // Toggle full-screen on ALT + ENTER/F
503 if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_GUI)) &&
504 (ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
505 if (ev.key.repeat == 0) ToggleFullScreen(!_fullscreen);
506 } else {
507 char32_t character;
508
509 uint keycode = ConvertSdlKeyIntoMy(&ev.key.keysym, &character);
510 /* Only handle non-text keys here. Text is handled in
511 * SDL_TEXTINPUT below. */
512 if (!this->edit_box_focused ||
513 keycode == WKC_DELETE ||
514 keycode == WKC_NUM_ENTER ||
515 keycode == WKC_LEFT ||
516 keycode == WKC_RIGHT ||
517 keycode == WKC_UP ||
518 keycode == WKC_DOWN ||
519 keycode == WKC_HOME ||
520 keycode == WKC_END ||
521 keycode & WKC_META ||
522 keycode & WKC_CTRL ||
523 keycode & WKC_ALT ||
524 (keycode >= WKC_F1 && keycode <= WKC_F12) ||
525 !IsValidChar(character, CS_ALPHANUMERAL)) {
526 HandleKeypress(keycode, character);
527 }
528 }
529 break;
530
531 case SDL_TEXTINPUT: {
532 if (!this->edit_box_focused) break;
533 SDL_Keycode kc = SDL_GetKeyFromName(ev.text.text);
534 uint keycode = ConvertSdlKeycodeIntoMy(kc);
535
536 if (keycode == WKC_BACKQUOTE && FocusedWindowIsConsole()) {
537 auto [len, c] = DecodeUtf8(ev.text.text);
538 if (len > 0) HandleKeypress(keycode, c);
539 } else {
540 HandleTextInput(ev.text.text);
541 }
542 break;
543 }
544 case SDL_WINDOWEVENT: {
545 if (ev.window.event == SDL_WINDOWEVENT_EXPOSED) {
546 /* Force a redraw of the entire screen. */
547 this->MakeDirty(0, 0, _screen.width, _screen.height);
548 } else if (ev.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
549 int w = std::max(ev.window.data1, 64);
550 int h = std::max(ev.window.data2, 64);
551 CreateMainSurface(w, h, w != ev.window.data1 || h != ev.window.data2);
552 } else if (ev.window.event == SDL_WINDOWEVENT_ENTER) {
553 /* mouse entered the window, enable cursor */
554 _cursor.in_window = true;
555 /* Ensure pointer lock will not occur. */
556 SDL_SetRelativeMouseMode(SDL_FALSE);
557 } else if (ev.window.event == SDL_WINDOWEVENT_LEAVE) {
558 /* mouse left the window, undraw cursor */
559 UndrawMouseCursor();
560 _cursor.in_window = false;
561 }
562 break;
563 }
564 }
565
566 return true;
567}
568
573static std::optional<std::string_view> InitializeSDL()
574{
575 /* Check if the video-driver is already initialized. */
576 if (SDL_WasInit(SDL_INIT_VIDEO) != 0) return std::nullopt;
577
578#ifdef SDL_HINT_APP_NAME
579 SDL_SetHint(SDL_HINT_APP_NAME, "OpenTTD");
580#endif
581
582 if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) return SDL_GetError();
583 return std::nullopt;
584}
585
590std::optional<std::string_view> VideoDriver_SDL_Base::Initialize()
591{
592 this->UpdateAutoResolution();
593
594 auto error = InitializeSDL();
595 if (error) return error;
596
598 Debug(driver, 2, "Resolution for display: {}x{}", _cur_resolution.width, _cur_resolution.height);
599
600 return std::nullopt;
601}
602
603std::optional<std::string_view> VideoDriver_SDL_Base::Start(const StringList &param)
604{
605 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
606
607 auto error = this->Initialize();
608 if (error) return error;
609
610#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE
611 if (GetDriverParamBool(param, "no_mouse_capture")) {
612 /* By default SDL captures the mouse, while a button is pressed.
613 * This is annoying during debugging, when OpenTTD is suspended while the button was pressed.
614 */
615 if (!SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0")) return SDL_GetError();
616 }
617#endif
618
619 this->startup_display = FindStartupDisplay(GetDriverParamInt(param, "display", -1));
620
621 if (!CreateMainSurface(_cur_resolution.width, _cur_resolution.height, false)) {
622 return SDL_GetError();
623 }
624
625 const char *dname = SDL_GetCurrentVideoDriver();
626 Debug(driver, 1, "SDL2: using driver '{}'", dname);
627
628 this->driver_info = this->GetName();
629 this->driver_info += " (";
630 this->driver_info += dname;
631 this->driver_info += ")";
632
634
635 SDL_StopTextInput();
636 this->edit_box_focused = false;
637
638#ifdef __EMSCRIPTEN__
639 this->is_game_threaded = false;
640#else
641 this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
642#endif
643
644 return std::nullopt;
645}
646
648{
649 SDL_QuitSubSystem(SDL_INIT_VIDEO);
650 if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
651 SDL_Quit(); // If there's nothing left, quit SDL
652 }
653}
654
656{
657 uint32_t mod = SDL_GetModState();
658 const Uint8 *keys = SDL_GetKeyboardState(nullptr);
659
660 bool old_ctrl_pressed = _ctrl_pressed;
661
662 _ctrl_pressed = !!(mod & KMOD_CTRL);
663 _shift_pressed = !!(mod & KMOD_SHIFT);
664
665 /* Speedup when pressing tab, except when using ALT+TAB
666 * to switch to another application. */
667 this->fast_forward_key_pressed = keys[SDL_SCANCODE_TAB] && (mod & KMOD_ALT) == 0;
668
669 /* Determine which directional keys are down. */
670 _dirkeys.Set(DirectionKey::Left, keys[SDL_SCANCODE_LEFT]);
671 _dirkeys.Set(DirectionKey::Up, keys[SDL_SCANCODE_UP]);
672 _dirkeys.Set(DirectionKey::Right, keys[SDL_SCANCODE_RIGHT]);
673 _dirkeys.Set(DirectionKey::Down, keys[SDL_SCANCODE_DOWN]);
674
675 if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
676}
677
680{
681 if (_exit_game) {
682#ifdef __EMSCRIPTEN__
683 /* Emscripten is event-driven, and as such the main loop is inside
684 * the browser. So if _exit_game goes true, the main loop ends (the
685 * cancel call), but we still have to call the cleanup that is
686 * normally done at the end of the main loop for non-Emscripten.
687 * After that, Emscripten just halts, and the HTML shows a nice
688 * "bye, see you next time" message. */
689 extern void PostMainLoop();
690 PostMainLoop();
691
692 emscripten_cancel_main_loop();
693 emscripten_exit_pointerlock();
694 /* In effect, the game ends here. As emscripten_set_main_loop() caused
695 * the stack to be unwound, the code after MainLoop() in
696 * openttd_main() is never executed. */
697 if (_game_mode == GameMode::Bootstrap) {
698 EM_ASM(if (window["openttd_bootstrap_reload"]) openttd_bootstrap_reload());
699 } else {
700 EM_ASM(if (window["openttd_exit"]) openttd_exit());
701 }
702#endif
703 return;
704 }
705
706 this->Tick();
707
708/* Emscripten is running an event-based mainloop; there is already some
709 * downtime between each iteration, so no need to sleep. */
710#ifndef __EMSCRIPTEN__
711 this->SleepTillNextTick();
712#endif
713}
714
716{
717#ifdef __EMSCRIPTEN__
718 /* Run the main loop event-driven, based on RequestAnimationFrame. */
719 emscripten_set_main_loop_arg(&this->EmscriptenLoop, this, 0, 1);
720#else
721 this->StartGameThread();
722
723 while (!_exit_game) {
724 LoopOnce();
725 }
726
727 this->StopGameThread();
728#endif
729}
730
732{
733 return CreateMainSurface(w, h, true);
734}
735
737{
738 /* Remember current window size */
739 int w, h;
740 SDL_GetWindowSize(this->sdl_window, &w, &h);
741
742 if (fullscreen) {
743 /* Find fullscreen window size */
744 SDL_DisplayMode dm;
745 if (SDL_GetCurrentDisplayMode(SDL_GetWindowDisplayIndex(this->sdl_window), &dm) < 0) {
746 Debug(driver, 0, "SDL_GetCurrentDisplayMode() failed: {}", SDL_GetError());
747 } else {
748 SDL_SetWindowSize(this->sdl_window, dm.w, dm.h);
749 }
750 }
751
752 Debug(driver, 1, "SDL2: Setting {}", fullscreen ? "fullscreen" : "windowed");
753 int ret = SDL_SetWindowFullscreen(this->sdl_window, fullscreen ? SDL_WINDOW_FULLSCREEN : 0);
754 if (ret == 0) {
755 /* Switching resolution succeeded, set fullscreen value of window. */
756 _fullscreen = fullscreen;
757 if (!fullscreen) SDL_SetWindowSize(this->sdl_window, w, h);
758 } else {
759 Debug(driver, 0, "SDL_SetWindowFullscreen() failed: {}", SDL_GetError());
760 }
761
762 InvalidateWindowClassesData(WindowClass::GameOptions, 3);
763 return ret == 0;
764}
765
767{
768 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
769 int w, h;
770 SDL_GetWindowSize(this->sdl_window, &w, &h);
771 return CreateMainSurface(w, h, false);
772}
773
775{
776 SDL_DisplayMode mode;
777 if (SDL_GetCurrentDisplayMode(this->startup_display, &mode) != 0) return VideoDriver::GetScreenSize();
778
779 return { static_cast<uint>(mode.w), static_cast<uint>(mode.h) };
780}
781
783{
784 if (this->buffer_locked) return false;
785 this->buffer_locked = true;
786
787 _screen.dst_ptr = this->GetVideoPointer();
788 assert(_screen.dst_ptr != nullptr);
789
790 return true;
791}
792
794{
795 if (_screen.dst_ptr != nullptr) {
796 /* Hand video buffer back to the drawing backend. */
797 this->ReleaseVideoPointer();
798 _screen.dst_ptr = nullptr;
799 }
800
801 this->buffer_locked = false;
802}
803
805{
806 if (inhibited) {
807 SDL_DisableScreenSaver();
808 } else {
809 SDL_EnableScreenSaver();
810 }
811}
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:211
virtual std::string_view GetName() const =0
Get the name of this driver.
std::optional< std::string_view > Start(const StringList &param) override
Start this driver.
Definition sdl2_v.cpp:603
bool buffer_locked
Video buffer was locked by the main thread.
Definition sdl2_v.h:55
Dimension GetScreenSize() const override
Get the resolution of the main screen.
Definition sdl2_v.cpp:774
bool PollEvent() override
Process a single system event.
Definition sdl2_v.cpp:417
void EditBoxLostFocus() override
This is called to indicate that an edit box has lost focus, text input mode should be disabled.
Definition sdl2_v.cpp:245
virtual void ReleaseVideoPointer()=0
Hand video buffer back to the painting backend.
void ClaimMousePointer() override
Claim the exclusive rights for the mouse pointer.
Definition sdl2_v.cpp:223
virtual void * GetVideoPointer()=0
Get a pointer to the video buffer.
void LoopOnce()
Run a single tick of the game/main loop.
Definition sdl2_v.cpp:679
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
Definition sdl2_v.cpp:766
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 sdl2_v.cpp:655
Palette local_palette
Current palette to use for drawing.
Definition sdl2_v.h:54
void MainLoop() override
Perform the actual drawing.
Definition sdl2_v.cpp:715
std::optional< std::string_view > Initialize()
Initialize the driver.
Definition sdl2_v.cpp:590
std::string driver_info
Information string about selected driver.
Definition sdl2_v.h:57
void UnlockVideoBuffer() override
Unlock a previously locked video buffer.
Definition sdl2_v.cpp:793
void ClientSizeChanged(int w, int h, bool force)
Indicate to the driver the client-size might have changed.
Definition sdl2_v.cpp:141
int startup_display
The display to show OpenTTD on when starting.
Definition sdl2_v.h:110
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
Definition sdl2_v.cpp:31
virtual bool CreateMainWindow(uint w, uint h, uint flags=0)
Create the main window.
Definition sdl2_v.cpp:153
std::vector< int > GetListOfMonitorRefreshRates() override
Get a list of refresh rates of each available monitor.
Definition sdl2_v.cpp:253
void SetScreensaverInhibited(bool inhibited) override
Prevents the system from going to sleep.
Definition sdl2_v.cpp:804
bool edit_box_focused
This is true to indicate that keyboard input is in text input mode, and SDL_TEXTINPUT events are enab...
Definition sdl2_v.h:108
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
Definition sdl2_v.cpp:731
void Stop() override
Stop this driver.
Definition sdl2_v.cpp:647
bool CreateMainSurface(uint w, uint h, bool resize)
Create/update the surfaces to draw OpenTTD on.
Definition sdl2_v.cpp:206
bool LockVideoBuffer() override
Make sure the video buffer is ready for drawing.
Definition sdl2_v.cpp:782
void EditBoxGainedFocus() override
This is called to indicate that an edit box has gained focus, text input mode should be enabled.
Definition sdl2_v.cpp:234
Rect dirty_rect
Rectangle encompassing the dirty area of the video buffer.
Definition sdl2_v.h:56
void CheckPaletteAnim() override
Process any pending palette animation.
Definition sdl2_v.cpp:37
struct SDL_Window * sdl_window
Main SDL window.
Definition sdl2_v.h:53
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
Definition sdl2_v.cpp:736
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.
static const Dimension _default_resolutions[]
List of common display/window sizes.
Definition cocoa_v.mm:50
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
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
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:146
Functions for standard in/out file operations.
@ Baseset
Subdirectory for all base data (base sets, intro game).
Definition fileio_type.h:96
Types for recording game performance data.
Rect BoundingRect(const Rect &r1, const Rect &r2)
Compute the bounding rectangle around two rectangles.
Geometry functions.
bool _shift_pressed
Is Shift pressed?
Definition gfx.cpp:40
bool _left_button_down
Is left mouse button pressed?
Definition gfx.cpp:42
bool _ctrl_pressed
Is Ctrl pressed?
Definition gfx.cpp:39
bool _left_button_clicked
Is left mouse button clicked?
Definition gfx.cpp:43
bool _right_button_clicked
Is right mouse button clicked?
Definition gfx.cpp:45
DirectionKeys _dirkeys
Pressed direction keys.
Definition gfx.cpp:35
bool _right_button_down
Is right mouse button pressed?
Definition gfx.cpp:44
Functions related to the gfx engine.
void HandleCtrlChanged()
State of CONTROL key has changed.
Definition window.cpp:2715
void GameSizeChanged()
Size of the application screen changed.
Definition main_gui.cpp:597
void HandleMouseEvents()
Handle a mouse event from the video driver.
Definition window.cpp:2979
void HandleKeypress(uint keycode, char32_t key)
Handle keyboard input.
Definition window.cpp:2659
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:2751
@ Down
Down.
Definition gfx_type.h:438
@ Right
Right.
Definition gfx_type.h:437
@ Left
Left.
Definition gfx_type.h:435
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:1553
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 sdl2_v.cpp:87
static void FindResolutions()
Find and store all possible resolutions into _resolutions.
Definition sdl2_v.cpp:59
static std::optional< std::string_view > InitializeSDL()
Initialize the SDL backend if needed.
Definition sdl2_v.cpp:573
static uint ConvertSdlKeycodeIntoMy(SDL_Keycode kc)
Convert a SDL_Keycode into our own key codes.
Definition sdl2_v.cpp:398
static uint ConvertSdlKeyIntoMy(SDL_Keysym *sym, char32_t *character)
Convert the SDL key into our WindowKeyCode and the printable character (if any).
Definition sdl2_v.cpp:358
static uint FindStartupDisplay(uint startup_display)
Find the display we want to start OpenTTD on.
Definition sdl2_v.cpp:114
Base of the SDL2 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:375
@ 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 sdl2_v.cpp:266
const uint8_t count
The number of keycodes that are to be mapped.
Definition sdl2_v.cpp:269
const WindowKeyCodes map_to
The first of the OpenTTD keycodes of this mapping.
Definition sdl2_v.cpp:268
const bool unprintable
Whether this keycode is unprintable.
Definition sdl2_v.cpp:270
constexpr SDLVkMapping(SDL_Keycode vk_from, WindowKeyCodes map_to, bool unprintable)
Create a mapping for a single keycode.
Definition sdl2_v.cpp:294
const SDL_Keycode vk_from
The first of the SDL keycodes of this mapping.
Definition sdl2_v.cpp:267
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 sdl2_v.cpp:280
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:467
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:3333
Window functions not directly related to making/drawing windows.