OpenTTD Source 20261112-master-gbcbec5e63f
win32_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 "../error_func.h"
13#include "../gfx_func.h"
14#include "../os/windows/win32.h"
17#include "../core/math_func.hpp"
19#include "../texteff.hpp"
20#include "../thread.h"
21#include "../progress.h"
22#include "../window_gui.h"
23#include "../window_func.h"
24#include "../framerate_type.h"
25#include "../library_loader.h"
26#include "../core/utf8.hpp"
27#include "win32_v.h"
28#include <windows.h>
29#include <imm.h>
30#include <objbase.h>
31#include <versionhelpers.h>
32#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
33#include <winrt/Windows.UI.ViewManagement.h>
34#endif
35
36#ifdef WITH_OPENGL
37#include <GL/gl.h>
38#include "../3rdparty/opengl/glext.h"
39#include "../3rdparty/opengl/wglext.h"
40#include "opengl.h"
41#endif /* WITH_OPENGL */
42
43#include "../safeguards.h"
44
45/* Missing define in MinGW headers. */
46#ifndef MAPVK_VK_TO_CHAR
47#define MAPVK_VK_TO_CHAR (2)
48#endif
49
50#ifndef PM_QS_INPUT
51#define PM_QS_INPUT 0x20000
52#endif
53
54#ifndef WM_DPICHANGED
55#define WM_DPICHANGED 0x02E0
56#endif
57
59static Dimension _bck_resolution;
60DWORD _imm_props;
61
63{
64 MyShowCursor(false, true);
65}
66
68 uint8_t vk_from;
69 uint8_t vk_count;
70 uint8_t map_to;
71};
72
73#define AS(x, z) {x, 1, z}
74#define AM(x, y, z, w) {x, y - x + 1, z}
75
76static const Win32VkMapping _vk_mapping[] = {
77 /* Pageup stuff + up/down */
78 AM(VK_PRIOR, VK_DOWN, WKC_PAGEUP, WKC_DOWN),
79 /* Map letters & digits */
80 AM('A', 'Z', 'A', 'Z'),
81 AM('0', '9', '0', '9'),
82
83 AS(VK_ESCAPE, WKC_ESC),
84 AS(VK_PAUSE, WKC_PAUSE),
85 AS(VK_BACK, WKC_BACKSPACE),
86 AM(VK_INSERT, VK_DELETE, WKC_INSERT, WKC_DELETE),
87
88 AS(VK_SPACE, WKC_SPACE),
89 AS(VK_RETURN, WKC_RETURN),
90 AS(VK_TAB, WKC_TAB),
91
92 /* Function keys */
93 AM(VK_F1, VK_F12, WKC_F1, WKC_F12),
94
95 /* Numeric part */
96 AM(VK_NUMPAD0, VK_NUMPAD9, '0', '9'),
97 AS(VK_DIVIDE, WKC_NUM_DIV),
98 AS(VK_MULTIPLY, WKC_NUM_MUL),
99 AS(VK_SUBTRACT, WKC_NUM_MINUS),
100 AS(VK_ADD, WKC_NUM_PLUS),
101 AS(VK_DECIMAL, WKC_NUM_DECIMAL),
102
103 /* Other non-letter keys */
104 AS(0xBF, WKC_SLASH),
105 AS(0xBA, WKC_SEMICOLON),
106 AS(0xBB, WKC_EQUALS),
107 AS(0xDB, WKC_L_BRACKET),
108 AS(0xDC, WKC_BACKSLASH),
109 AS(0xDD, WKC_R_BRACKET),
110
111 AS(0xDE, WKC_SINGLEQUOTE),
112 AS(0xBC, WKC_COMMA),
113 AS(0xBD, WKC_MINUS),
114 AS(0xBE, WKC_PERIOD)
115};
116
117static uint MapWindowsKey(uint sym)
118{
119 uint key = 0;
120
121 for (const auto &map : _vk_mapping) {
122 if (IsInsideBS(sym, map.vk_from, map.vk_count)) {
123 key = sym - map.vk_from + map.map_to;
124 break;
125 }
126 }
127
128 if (GetAsyncKeyState(VK_SHIFT) < 0) key |= WKC_SHIFT;
129 if (GetAsyncKeyState(VK_CONTROL) < 0) key |= WKC_CTRL;
130 if (GetAsyncKeyState(VK_MENU) < 0) key |= WKC_ALT;
131 return key;
132}
133
139{
140 /* Check modes for the relevant fullscreen bpp */
142}
143
150bool VideoDriver_Win32Base::MakeWindow(bool full_screen, bool resize)
151{
152 /* full_screen is whether the new window should be fullscreen,
153 * _wnd.fullscreen is whether the current window is. */
154 _fullscreen = full_screen;
155
156 /* recreate window? */
157 if ((full_screen != this->fullscreen) && this->main_wnd) {
158 DestroyWindow(this->main_wnd);
159 this->main_wnd = 0;
160 }
161
162 if (full_screen) {
163 DEVMODE settings{};
164 settings.dmSize = sizeof(settings);
165 settings.dmFields =
166 DM_BITSPERPEL |
167 DM_PELSWIDTH |
168 DM_PELSHEIGHT;
169 settings.dmBitsPerPel = this->GetFullscreenBpp();
170 settings.dmPelsWidth = this->width_org;
171 settings.dmPelsHeight = this->height_org;
172
173 /* Check for 8 bpp support. */
174 if (settings.dmBitsPerPel == 8 && ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
175 settings.dmBitsPerPel = 32;
176 }
177
178 /* Test fullscreen with current resolution, if it fails use desktop resolution. */
179 if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
180 RECT r;
181 GetWindowRect(GetDesktopWindow(), &r);
182 /* Guard against recursion. If we already failed here once, just fall through to
183 * the next ChangeDisplaySettings call which will fail and error out appropriately. */
184 if ((int)settings.dmPelsWidth != r.right - r.left || (int)settings.dmPelsHeight != r.bottom - r.top) {
185 return this->ChangeResolution(r.right - r.left, r.bottom - r.top);
186 }
187 }
188
189 if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
190 this->MakeWindow(false, resize); // don't care about the result
191 return false; // the request failed
192 }
193 } else if (this->fullscreen) {
194 /* restore display? */
195 ChangeDisplaySettings(nullptr, 0);
196 /* restore the resolution */
197 this->width = _bck_resolution.width;
198 this->height = _bck_resolution.height;
199 }
200
201 {
202 RECT r;
203 DWORD style, showstyle;
204 int w, h;
205
206 showstyle = SW_SHOWNORMAL;
207 this->fullscreen = full_screen;
208 if (this->fullscreen) {
209 style = WS_POPUP;
210 SetRect(&r, 0, 0, this->width_org, this->height_org);
211 } else {
212 style = WS_OVERLAPPEDWINDOW;
213 /* On window creation, check if we were in maximize mode before */
214 if (_window_maximize) showstyle = SW_SHOWMAXIMIZED;
215 SetRect(&r, 0, 0, this->width, this->height);
216 }
217
218 AdjustWindowRect(&r, style, FALSE);
219 w = r.right - r.left;
220 h = r.bottom - r.top;
221
222 if (this->main_wnd != nullptr) {
223 if (!_window_maximize && resize) SetWindowPos(this->main_wnd, 0, 0, 0, w, h, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOMOVE);
224 } else {
225 int x = 0;
226 int y = 0;
227
228 /* For windowed mode, center on the workspace of the primary display. */
229 if (!this->fullscreen) {
230 MONITORINFO mi;
231 mi.cbSize = sizeof(mi);
232 GetMonitorInfo(MonitorFromWindow(0, MONITOR_DEFAULTTOPRIMARY), &mi);
233
234 x = (mi.rcWork.right - mi.rcWork.left - w) / 2;
235 y = (mi.rcWork.bottom - mi.rcWork.top - h) / 2;
236 }
237
238 std::string caption = VideoDriver::GetCaption();
239 this->main_wnd = CreateWindow(L"OTTD", OTTD2FS(caption).c_str(), style, x, y, w, h, 0, 0, GetModuleHandle(nullptr), this);
240 if (this->main_wnd == nullptr) UserError("CreateWindow failed");
241 ShowWindow(this->main_wnd, showstyle);
242 }
243 }
244
246
248 return true;
249}
250
257static LRESULT HandleCharMsg(uint keycode, char32_t charcode)
258{
259 static char32_t prev_char = 0;
260
261 /* Did we get a lead surrogate? If yes, store and exit. */
262 if (Utf16IsLeadSurrogate(charcode)) {
263 if (prev_char != 0) Debug(Facility::Driver, Severity::Error, "Got two UTF-16 lead surrogates, dropping the first one");
264 prev_char = charcode;
265 return 0;
266 }
267
268 /* Stored lead surrogate and incoming trail surrogate? Combine and forward to input handling. */
269 if (prev_char != 0) {
270 if (Utf16IsTrailSurrogate(charcode)) {
271 charcode = Utf16DecodeSurrogate(prev_char, charcode);
272 } else {
273 Debug(Facility::Driver, Severity::Error, "Got an UTF-16 lead surrogate without a trail surrogate, dropping the lead surrogate");
274 }
275 }
276 prev_char = 0;
277
278 HandleKeypress(keycode, charcode);
279
280 return 0;
281}
282
288{
289 return (_imm_props & IME_PROP_AT_CARET) && !(_imm_props & IME_PROP_SPECIAL_UI);
290}
291
296static void SetCompositionPos(HWND hwnd)
297{
298 HIMC hIMC = ImmGetContext(hwnd);
299 if (hIMC != nullptr) {
300 COMPOSITIONFORM cf;
301 cf.dwStyle = CFS_POINT;
302
303 if (EditBoxInGlobalFocus()) {
304 /* Get caret position. */
305 Point pt = _focused_window->GetCaretPosition();
306 cf.ptCurrentPos.x = _focused_window->left + pt.x;
307 cf.ptCurrentPos.y = _focused_window->top + pt.y;
308 } else {
309 cf.ptCurrentPos.x = 0;
310 cf.ptCurrentPos.y = 0;
311 }
312 ImmSetCompositionWindow(hIMC, &cf);
313 }
314 ImmReleaseContext(hwnd, hIMC);
315}
316
321static void SetCandidatePos(HWND hwnd)
322{
323 HIMC hIMC = ImmGetContext(hwnd);
324 if (hIMC != nullptr) {
325 CANDIDATEFORM cf;
326 cf.dwIndex = 0;
327 cf.dwStyle = CFS_EXCLUDE;
328
329 if (EditBoxInGlobalFocus()) {
330 Point pt = _focused_window->GetCaretPosition();
331 cf.ptCurrentPos.x = _focused_window->left + pt.x;
332 cf.ptCurrentPos.y = _focused_window->top + pt.y;
333 if (_focused_window->window_class == WindowClass::Console) {
334 cf.rcArea.left = _focused_window->left;
335 cf.rcArea.top = _focused_window->top;
336 cf.rcArea.right = _focused_window->left + _focused_window->width;
337 cf.rcArea.bottom = _focused_window->top + _focused_window->height;
338 } else {
339 cf.rcArea.left = _focused_window->left + _focused_window->nested_focus->pos_x;
340 cf.rcArea.top = _focused_window->top + _focused_window->nested_focus->pos_y;
341 cf.rcArea.right = cf.rcArea.left + _focused_window->nested_focus->current_x;
342 cf.rcArea.bottom = cf.rcArea.top + _focused_window->nested_focus->current_y;
343 }
344 } else {
345 cf.ptCurrentPos.x = 0;
346 cf.ptCurrentPos.y = 0;
347 SetRectEmpty(&cf.rcArea);
348 }
349 ImmSetCandidateWindow(hIMC, &cf);
350 }
351 ImmReleaseContext(hwnd, hIMC);
352}
353
361static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
362{
363 HIMC hIMC = ImmGetContext(hwnd);
364
365 if (hIMC != nullptr) {
366 if (lParam & GCS_RESULTSTR) {
367 /* Read result string from the IME. */
368 LONG len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, nullptr, 0); // Length is always in bytes, even in UNICODE build.
369 std::wstring str(len + 1, L'\0');
370 len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, str.data(), len);
371 str[len / sizeof(wchar_t)] = L'\0';
372
373 /* Transmit text to windowing system. */
374 if (len > 0) {
375 HandleTextInput({}, true); // Clear marked string.
377 }
378 SetCompositionPos(hwnd);
379
380 /* Don't pass the result string on to the default window proc. */
381 lParam &= ~(GCS_RESULTSTR | GCS_RESULTCLAUSE | GCS_RESULTREADCLAUSE | GCS_RESULTREADSTR);
382 }
383
384 if ((lParam & GCS_COMPSTR) && DrawIMECompositionString()) {
385 /* Read composition string from the IME. */
386 LONG len = ImmGetCompositionString(hIMC, GCS_COMPSTR, nullptr, 0); // Length is always in bytes, even in UNICODE build.
387 std::wstring str(len + 1, L'\0');
388 len = ImmGetCompositionString(hIMC, GCS_COMPSTR, str.data(), len);
389 str[len / sizeof(wchar_t)] = L'\0';
390
391 if (len > 0) {
392 static char utf8_buf[1024];
393 convert_from_fs(str, utf8_buf);
394
395 /* Convert caret position from bytes in the input string to a position in the UTF-8 encoded string. */
396 LONG caret_bytes = ImmGetCompositionString(hIMC, GCS_CURSORPOS, nullptr, 0);
397 Utf8View view(utf8_buf);
398 auto caret = view.begin();
399 const auto end = view.end();
400 for (const wchar_t *c = str.c_str(); *c != '\0' && caret != end && caret_bytes > 0; c++, caret_bytes--) {
401 /* Skip DBCS lead bytes or leading surrogates. */
402 if (Utf16IsLeadSurrogate(*c)) {
403 c++;
404 caret_bytes--;
405 }
406 ++caret;
407 }
408
409 HandleTextInput(utf8_buf, true, caret.GetByteOffset());
410 } else {
411 HandleTextInput({}, true);
412 }
413
414 lParam &= ~(GCS_COMPSTR | GCS_COMPATTR | GCS_COMPCLAUSE | GCS_CURSORPOS | GCS_DELTASTART);
415 }
416 }
417 ImmReleaseContext(hwnd, hIMC);
418
419 return lParam != 0 ? DefWindowProc(hwnd, WM_IME_COMPOSITION, wParam, lParam) : 0;
420}
421
426static void CancelIMEComposition(HWND hwnd)
427{
428 HIMC hIMC = ImmGetContext(hwnd);
429 if (hIMC != nullptr) ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
430 ImmReleaseContext(hwnd, hIMC);
431 /* Clear any marked string from the current edit box. */
432 HandleTextInput({}, true);
433}
434
435#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
436/* We only use WinRT functions on Windows 10 or later. Unfortunately, newer Windows SDKs are now
437 * linking the two functions below directly instead of using dynamic linking as previously.
438 * To avoid any runtime linking errors on Windows 7 or older, we stub in our own dynamic
439 * linking trampoline. */
440
441static LibraryLoader _combase("combase.dll");
442
443extern "C" int32_t __stdcall WINRT_IMPL_RoOriginateLanguageException(int32_t error, void *message, void *languageException) noexcept
444{
445 typedef BOOL(WINAPI *PFNRoOriginateLanguageException)(int32_t, void *, void *);
446 static PFNRoOriginateLanguageException RoOriginateLanguageException = _combase.GetFunction("RoOriginateLanguageException");
447
448 if (RoOriginateLanguageException != nullptr) {
449 return RoOriginateLanguageException(error, message, languageException);
450 } else {
451 return TRUE;
452 }
453}
454
455extern "C" int32_t __stdcall WINRT_IMPL_RoGetActivationFactory(void *classId, winrt::guid const &iid, void **factory) noexcept
456{
457 typedef BOOL(WINAPI *PFNRoGetActivationFactory)(void *, winrt::guid const &, void **);
458 static PFNRoGetActivationFactory RoGetActivationFactory = _combase.GetFunction("RoGetActivationFactory");
459
460 if (RoGetActivationFactory != nullptr) {
461 return RoGetActivationFactory(classId, iid, factory);
462 } else {
463 *factory = nullptr;
464 return winrt::impl::error_class_not_available;
465 }
466}
467#endif
468
469static bool IsDarkModeEnabled()
470{
471 /* Only build if SDK is Windows 10 1803 or later. */
472#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
473 if (IsWindows10OrGreater()) {
474 try {
475 /*
476 * The official documented way to find out if the system is running in dark mode is to
477 * check the brightness of the current theme's colour.
478 * See: https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/ui/apply-windows-themes#know-when-dark-mode-is-enabled
479 *
480 * There are other variants floating around on the Internet, but they all rely on internal,
481 * undocumented Windows functions that may or may not work in the future.
482 */
483 winrt::Windows::UI::ViewManagement::UISettings settings;
484 auto foreground = settings.GetColorValue(winrt::Windows::UI::ViewManagement::UIColorType::Foreground);
485
486 /* If the Foreground colour is a light colour, the system is running in dark mode. */
487 return ((5 * foreground.G) + (2 * foreground.R) + foreground.B) > (8 * 128);
488 } catch (...) {
489 /* Some kind of error, like a too old Windows version. Just return false. */
490 return false;
491 }
492 }
493#endif /* defined(_MSC_VER) && defined(NTDDI_WIN10_RS4) */
494
495 return false;
496}
497
498static void SetDarkModeForWindow(HWND hWnd, bool dark_mode)
499{
500 /* Only build if SDK is Windows 10+. */
501#if defined(NTDDI_WIN10)
502 if (!IsWindows10OrGreater()) return;
503
504 /* This function is documented, but not supported on all Windows 10/11 SDK builds. For this
505 * reason, the code uses dynamic loading and ignores any errors for a best-effort result. */
506 static LibraryLoader _dwmapi("dwmapi.dll");
507 typedef HRESULT(WINAPI *PFNDWMSETWINDOWATTRIBUTE)(HWND, DWORD, LPCVOID, DWORD);
508 static const PFNDWMSETWINDOWATTRIBUTE DwmSetWindowAttribute = _dwmapi.GetFunction("DwmSetWindowAttribute");
509
510 if (DwmSetWindowAttribute != nullptr) {
511 /* Contrary to the published documentation, DWMWA_USE_IMMERSIVE_DARK_MODE does not change the
512 * window chrome according to the current theme, but forces it to either light or dark mode.
513 * As such, the set value has to depend on the current theming mode.*/
514 BOOL value = dark_mode ? TRUE : FALSE;
515 if (DwmSetWindowAttribute(hWnd, 20 /* DWMWA_USE_IMMERSIVE_DARK_MODE */, &value, sizeof(value)) != S_OK) {
516 DwmSetWindowAttribute(hWnd, 19 /* DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 */, &value, sizeof(value)); // Ignore errors. It works or it doesn't.
517 }
518 }
519#endif /* defined(NTDDI_WIN10) */
520}
521
522LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
523{
524 static uint32_t keycode = 0;
525 static bool console = false;
526
527 const float SCROLL_BUILTIN_MULTIPLIER = 14.0f / WHEEL_DELTA;
528
529 VideoDriver_Win32Base *video_driver = (VideoDriver_Win32Base *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
530
531 switch (msg) {
532 case WM_CREATE:
533 SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)((LPCREATESTRUCT)lParam)->lpCreateParams);
534 _cursor.in_window = false; // Win32 has mouse tracking.
535 SetCompositionPos(hwnd);
536 _imm_props = ImmGetProperty(GetKeyboardLayout(0), IGP_PROPERTY);
537
538 /* Enable dark mode theming for window chrome. */
539 SetDarkModeForWindow(hwnd, IsDarkModeEnabled());
540 break;
541
542 case WM_SETTINGCHANGE:
543 /* Synchronize dark mode theming state. */
544 SetDarkModeForWindow(hwnd, IsDarkModeEnabled());
545 break;
546
547 case WM_PAINT: {
548 RECT r;
549 GetUpdateRect(hwnd, &r, FALSE);
550 video_driver->MakeDirty(r.left, r.top, r.right - r.left, r.bottom - r.top);
551
552 ValidateRect(hwnd, nullptr);
553 return 0;
554 }
555
556 case WM_PALETTECHANGED:
557 if ((HWND)wParam == hwnd) return 0;
558 [[fallthrough]];
559
560 case WM_QUERYNEWPALETTE:
561 video_driver->PaletteChanged(hwnd);
562 return 0;
563
564 case WM_CLOSE:
565 HandleExitGameRequest();
566 return 0;
567
568 case WM_DESTROY:
569 if (_window_maximize) _cur_resolution = _bck_resolution;
570 return 0;
571
572 case WM_LBUTTONDOWN:
573 SetCapture(hwnd);
576 return 0;
577
578 case WM_LBUTTONUP:
579 ReleaseCapture();
583 return 0;
584
585 case WM_RBUTTONDOWN:
586 SetCapture(hwnd);
590 return 0;
591
592 case WM_RBUTTONUP:
593 ReleaseCapture();
596 return 0;
597
598 case WM_MBUTTONDOWN:
599 SetCapture(hwnd);
603 return 0;
604
605 case WM_MBUTTONUP:
606 ReleaseCapture();
609 return 0;
610
611 case WM_XBUTTONDOWN:
612 SetCapture(hwnd);
613 if ((wParam & MK_XBUTTON1) != 0) {
617 }
618 if ((wParam & MK_XBUTTON2) != 0) {
622 }
623 return TRUE;
624
625 case WM_XBUTTONUP:
626 ReleaseCapture();
627 if ((wParam & MK_XBUTTON1) == 0) {
630 }
631 if ((wParam & MK_XBUTTON2) == 0) {
634 }
635 return TRUE;
636
637 case WM_MOUSELEAVE:
638 UndrawMouseCursor();
639 _cursor.in_window = false;
640
641 if (!_input_pressed.Any({ControlInput::Left, ControlInput::Right})) MyShowCursor(true);
642 return 0;
643
644 case WM_MOUSEMOVE: {
645 int x = (int16_t)LOWORD(lParam);
646 int y = (int16_t)HIWORD(lParam);
647
648 /* If the mouse was not in the window and it has moved it means it has
649 * come into the window, so start drawing the mouse. Also start
650 * tracking the mouse for exiting the window */
651 if (!_cursor.in_window) {
652 _cursor.in_window = true;
653 TRACKMOUSEEVENT tme;
654 tme.cbSize = sizeof(tme);
655 tme.dwFlags = TME_LEAVE;
656 tme.hwndTrack = hwnd;
657
658 TrackMouseEvent(&tme);
659 }
660
661 if (_cursor.fix_at) {
662 /* Get all queued mouse events now in case we have to warp the cursor. In the
663 * end, we only care about the current mouse position and not bygone events. */
664 MSG m;
665 while (PeekMessage(&m, hwnd, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE | PM_NOYIELD | PM_QS_INPUT)) {
666 x = (int16_t)LOWORD(m.lParam);
667 y = (int16_t)HIWORD(m.lParam);
668 }
669 }
670
671 if (_cursor.UpdateCursorPosition(x, y)) {
672 POINT pt;
673 pt.x = _cursor.pos.x;
674 pt.y = _cursor.pos.y;
675 ClientToScreen(hwnd, &pt);
676 SetCursorPos(pt.x, pt.y);
677 }
678 MyShowCursor(false);
680 return 0;
681 }
682
683 case WM_INPUTLANGCHANGE:
684 _imm_props = ImmGetProperty(GetKeyboardLayout(0), IGP_PROPERTY);
685 break;
686
687 case WM_IME_SETCONTEXT:
688 /* Don't show the composition window if we draw the string ourself. */
689 if (DrawIMECompositionString()) lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
690 break;
691
692 case WM_IME_STARTCOMPOSITION:
693 SetCompositionPos(hwnd);
694 if (DrawIMECompositionString()) return 0;
695 break;
696
697 case WM_IME_COMPOSITION:
698 return HandleIMEComposition(hwnd, wParam, lParam);
699
700 case WM_IME_ENDCOMPOSITION:
701 /* Clear any pending composition string. */
702 HandleTextInput({}, true);
703 if (DrawIMECompositionString()) return 0;
704 break;
705
706 case WM_IME_NOTIFY:
707 if (wParam == IMN_OPENCANDIDATE) SetCandidatePos(hwnd);
708 break;
709
710 case WM_DEADCHAR:
711 console = GB(lParam, 16, 8) == 41;
712 return 0;
713
714 case WM_CHAR: {
715 uint scancode = GB(lParam, 16, 8);
716 uint charcode = wParam;
717
718 /* If the console key is a dead-key, we need to press it twice to get a WM_CHAR message.
719 * But we then get two WM_CHAR messages, so ignore the first one */
720 if (console && scancode == 41) {
721 console = false;
722 return 0;
723 }
724
725 /* IMEs and other input methods sometimes send a WM_CHAR without a WM_KEYDOWN,
726 * clear the keycode so a previous WM_KEYDOWN doesn't become 'stuck'. */
727 uint cur_keycode = keycode;
728 keycode = 0;
729
730 return HandleCharMsg(cur_keycode, charcode);
731 }
732
733 case WM_KEYDOWN: {
734 /* No matter the keyboard layout, we will map the '~' to the console. */
735 uint scancode = GB(lParam, 16, 8);
736 keycode = scancode == 41 ? (uint)WKC_BACKQUOTE : MapWindowsKey(wParam);
737
738 uint charcode = MapVirtualKey(wParam, MAPVK_VK_TO_CHAR);
739
740 /* No character translation? */
741 if (charcode == 0) {
742 HandleKeypress(keycode, 0);
743 return 0;
744 }
745
746 /* If an edit box is in focus, wait for the corresponding WM_CHAR message. */
747 if (!EditBoxInGlobalFocus()) {
748 /* Is the console key a dead key? If yes, ignore the first key down event. */
749 if (HasBit(charcode, 31) && !console) {
750 if (scancode == 41) {
751 console = true;
752 return 0;
753 }
754 }
755 console = false;
756
757 /* IMEs and other input methods sometimes send a WM_CHAR without a WM_KEYDOWN,
758 * clear the keycode so a previous WM_KEYDOWN doesn't become 'stuck'. */
759 uint cur_keycode = keycode;
760 keycode = 0;
761
762 return HandleCharMsg(cur_keycode, LOWORD(charcode));
763 }
764
765 return 0;
766 }
767
768 case WM_SYSKEYDOWN: // user presses F10 or Alt, both activating the title-menu
769 switch (wParam) {
770 case VK_RETURN:
771 case 'F': // Full Screen on ALT + ENTER/F
772 ToggleFullScreen(!video_driver->fullscreen);
773 return 0;
774
775 case VK_MENU: // Just ALT
776 return 0; // do nothing
777
778 case VK_F10: // F10, ignore activation of menu
779 HandleKeypress(MapWindowsKey(wParam), 0);
780 return 0;
781
782 default: // ALT in combination with something else
783 HandleKeypress(MapWindowsKey(wParam), 0);
784 break;
785 }
786 break;
787
788 case WM_SIZE:
789 if (wParam != SIZE_MINIMIZED) {
790 /* Set maximized flag when we maximize (obviously), but also when we
791 * switched to fullscreen from a maximized state */
792 _window_maximize = (wParam == SIZE_MAXIMIZED || (_window_maximize && _fullscreen));
793 if (_window_maximize || _fullscreen) _bck_resolution = _cur_resolution;
794 video_driver->ClientSizeChanged(LOWORD(lParam), HIWORD(lParam));
795 }
796 return 0;
797
798 case WM_SIZING: {
799 RECT *r = (RECT*)lParam;
800 RECT r2;
801 int w, h;
802
803 SetRect(&r2, 0, 0, 0, 0);
804 AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
805
806 w = r->right - r->left - (r2.right - r2.left);
807 h = r->bottom - r->top - (r2.bottom - r2.top);
808 w = std::max(w, 64);
809 h = std::max(h, 64);
810 SetRect(&r2, 0, 0, w, h);
811
812 AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
813 w = r2.right - r2.left;
814 h = r2.bottom - r2.top;
815
816 switch (wParam) {
817 case WMSZ_BOTTOM:
818 r->bottom = r->top + h;
819 break;
820
821 case WMSZ_BOTTOMLEFT:
822 r->bottom = r->top + h;
823 r->left = r->right - w;
824 break;
825
826 case WMSZ_BOTTOMRIGHT:
827 r->bottom = r->top + h;
828 r->right = r->left + w;
829 break;
830
831 case WMSZ_LEFT:
832 r->left = r->right - w;
833 break;
834
835 case WMSZ_RIGHT:
836 r->right = r->left + w;
837 break;
838
839 case WMSZ_TOP:
840 r->top = r->bottom - h;
841 break;
842
843 case WMSZ_TOPLEFT:
844 r->top = r->bottom - h;
845 r->left = r->right - w;
846 break;
847
848 case WMSZ_TOPRIGHT:
849 r->top = r->bottom - h;
850 r->right = r->left + w;
851 break;
852 }
853 return TRUE;
854 }
855
856 case WM_DPICHANGED: {
857 auto did_adjust = AdjustGUIZoom(true);
858
859 /* Resize the window to match the new DPI setting. */
860 RECT *prcNewWindow = (RECT *)lParam;
861 SetWindowPos(hwnd,
862 nullptr,
863 prcNewWindow->left,
864 prcNewWindow->top,
865 prcNewWindow->right - prcNewWindow->left,
866 prcNewWindow->bottom - prcNewWindow->top,
867 SWP_NOZORDER | SWP_NOACTIVATE);
868
869 if (did_adjust) ReInitAllWindows(true);
870
871 return 0;
872 }
873
874/* needed for wheel */
875#if !defined(WM_MOUSEWHEEL)
876# define WM_MOUSEWHEEL 0x020A
877#endif /* WM_MOUSEWHEEL */
878#if !defined(WM_MOUSEHWHEEL)
879# define WM_MOUSEHWHEEL 0x020E
880#endif /* WM_MOUSEHWHEEL */
881#if !defined(GET_WHEEL_DELTA_WPARAM)
882# define GET_WHEEL_DELTA_WPARAM(wparam) ((short)HIWORD(wparam))
883#endif /* GET_WHEEL_DELTA_WPARAM */
884
885 case WM_MOUSEWHEEL: {
886 int delta = GET_WHEEL_DELTA_WPARAM(wParam);
887
888 if (delta < 0) {
889 _cursor.wheel++;
890 } else if (delta > 0) {
891 _cursor.wheel--;
892 }
893
894 _cursor.v_wheel -= static_cast<float>(delta) * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
895 _cursor.wheel_moved = true;
897 return 0;
898 }
899
900 case WM_MOUSEHWHEEL: {
901 int delta = GET_WHEEL_DELTA_WPARAM(wParam);
902
903 _cursor.h_wheel += static_cast<float>(delta) * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
904 _cursor.wheel_moved = true;
906 return 0;
907 }
908
909 case WM_SETFOCUS:
910 video_driver->has_focus = true;
911 SetCompositionPos(hwnd);
912 break;
913
914 case WM_KILLFOCUS:
915 video_driver->has_focus = false;
916 break;
917
918 case WM_ACTIVATE: {
919 /* Don't do anything if we are closing openttd */
920 if (_exit_game) break;
921
922 bool active = (LOWORD(wParam) != WA_INACTIVE);
923 bool minimized = (HIWORD(wParam) != 0);
924 if (video_driver->fullscreen) {
925 if (active && minimized) {
926 /* Restore the game window */
927 Dimension d = _bck_resolution; // Save current non-fullscreen window size as it will be overwritten by ShowWindow.
928 ShowWindow(hwnd, SW_RESTORE);
929 _bck_resolution = d;
930 if (video_driver->MinimiseRestoreWithToggleFullscreen()) {
931 video_driver->ToggleFullscreen(true);
932 } else {
933 video_driver->MakeWindow(true);
934 }
935 } else if (!active && !minimized) {
936 /* Minimise the window and restore desktop */
937 if (video_driver->MinimiseRestoreWithToggleFullscreen()) {
938 video_driver->ToggleFullscreen(false);
939 video_driver->fullscreen = true;
940 }
941 ShowWindow(hwnd, SW_MINIMIZE);
942 if (!video_driver->MinimiseRestoreWithToggleFullscreen()) ChangeDisplaySettings(nullptr, 0);
943 }
944 }
945 break;
946 }
947 }
948
949 return DefWindowProc(hwnd, msg, wParam, lParam);
950}
951
952static void RegisterWndClass()
953{
954 static bool registered = false;
955
956 if (registered) return;
957
958 HINSTANCE hinst = GetModuleHandle(nullptr);
959 WNDCLASS wnd = {
960 CS_OWNDC,
961 WndProcGdi,
962 0,
963 0,
964 hinst,
965 LoadIcon(hinst, MAKEINTRESOURCE(100)),
966 LoadCursor(nullptr, IDC_ARROW),
967 0,
968 0,
969 L"OTTD"
970 };
971
972 registered = true;
973 if (!RegisterClass(&wnd)) UserError("RegisterClass failed");
974}
975
976static const Dimension default_resolutions[] = {
977 { 640, 480 },
978 { 800, 600 },
979 { 1024, 768 },
980 { 1152, 864 },
981 { 1280, 800 },
982 { 1280, 960 },
983 { 1280, 1024 },
984 { 1400, 1050 },
985 { 1600, 1200 },
986 { 1680, 1050 },
987 { 1920, 1200 }
988};
989
990static void FindResolutions(uint8_t bpp)
991{
992 _resolutions.clear();
993
994 DEVMODE dm;
995 for (uint i = 0; EnumDisplaySettings(nullptr, i, &dm) != 0; i++) {
996 if (dm.dmBitsPerPel != bpp || dm.dmPelsWidth < 640 || dm.dmPelsHeight < 480) continue;
997 if (std::ranges::find(_resolutions, Dimension(dm.dmPelsWidth, dm.dmPelsHeight)) != _resolutions.end()) continue;
998 _resolutions.emplace_back(dm.dmPelsWidth, dm.dmPelsHeight);
999 }
1000
1001 /* We have found no resolutions, show the default list */
1002 if (_resolutions.empty()) {
1003 _resolutions.assign(std::begin(default_resolutions), std::end(default_resolutions));
1004 }
1005
1006 SortResolutions();
1007}
1008
1009std::optional<std::string_view> VideoDriver_Win32Base::Initialize()
1010{
1011 /* Initialize COM */
1012 if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) return "COM initialization failed";
1013
1014 this->UpdateAutoResolution();
1015
1016 RegisterWndClass();
1018
1019 /* fullscreen uses those */
1020 this->width = this->width_org = _cur_resolution.width;
1021 this->height = this->height_org = _cur_resolution.height;
1022
1024 return std::nullopt;
1025}
1026
1028{
1029 DestroyWindow(this->main_wnd);
1030
1031 if (this->fullscreen && MinimiseRestoreWithToggleFullscreen()) ChangeDisplaySettings(nullptr, 0);
1032 MyShowCursor(true);
1033}
1034void VideoDriver_Win32Base::MakeDirty(int left, int top, int width, int height)
1035{
1036 Rect r = {left, top, left + width, top + height};
1037 this->dirty_rect = BoundingRect(this->dirty_rect, r);
1038}
1039
1041{
1042 if (!CopyPalette(this->local_palette)) return;
1043 this->MakeDirty(0, 0, _screen.width, _screen.height);
1044}
1045
1047{
1048 bool old_ctrl_pressed = IsCtrlPressed();
1049
1050 _input_pressed.Set(ControlInput::Ctrl, this->has_focus && GetAsyncKeyState(VK_CONTROL) < 0);
1051 _input_pressed.Set(ControlInput::Shift, this->has_focus && GetAsyncKeyState(VK_SHIFT) < 0);
1052
1053 /* Speedup when pressing tab, except when using ALT+TAB
1054 * to switch to another application. */
1055 this->fast_forward_key_pressed = this->has_focus && GetAsyncKeyState(VK_TAB) < 0 && GetAsyncKeyState(VK_MENU) >= 0;
1056
1057 /* Determine which directional keys are down. */
1058 if (this->has_focus) {
1059 _dirkeys.Set(DirectionKey::Left, GetAsyncKeyState(VK_LEFT));
1060 _dirkeys.Set(DirectionKey::Up, GetAsyncKeyState(VK_UP));
1061 _dirkeys.Set(DirectionKey::Right, GetAsyncKeyState(VK_RIGHT));
1062 _dirkeys.Set(DirectionKey::Down, GetAsyncKeyState(VK_DOWN));
1063 } else {
1064 _dirkeys.Reset();
1065 }
1066
1067 if (old_ctrl_pressed != IsCtrlPressed()) HandleCtrlChanged();
1068}
1069
1071{
1072 MSG mesg;
1073
1074 if (!PeekMessage(&mesg, nullptr, 0, 0, PM_REMOVE)) return false;
1075
1076 /* Convert key messages to char messages if we want text input. */
1077 if (EditBoxInGlobalFocus()) TranslateMessage(&mesg);
1078 DispatchMessage(&mesg);
1079
1080 return true;
1081}
1082
1084{
1085 this->StartGameThread();
1086
1087 for (;;) {
1088 if (_exit_game) break;
1089
1090 this->Tick();
1091 this->SleepTillNextTick();
1092 }
1093
1094 this->StopGameThread();
1095}
1096
1103void VideoDriver_Win32Base::ClientSizeChanged(int w, int h, bool force)
1104{
1105 /* Allocate backing store of the new size. */
1106 if (this->AllocateBackingStore(w, h, force)) {
1107 CopyPalette(this->local_palette, true);
1108
1110
1112 }
1113}
1114
1116{
1117 if (_window_maximize) ShowWindow(this->main_wnd, SW_SHOWNORMAL);
1118
1119 this->width = this->width_org = w;
1120 this->height = this->height_org = h;
1121
1122 return this->MakeWindow(_fullscreen); // _wnd.fullscreen screws up ingame resolution switching
1123}
1124
1126{
1127 bool res = this->MakeWindow(full_screen);
1128
1129 InvalidateWindowClassesData(WindowClass::GameOptions, 3);
1130 return res;
1131}
1132
1139
1140static BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM data)
1141{
1142 auto &list = *reinterpret_cast<std::vector<int>*>(data);
1143
1144 MONITORINFOEX monitorInfo = {};
1145 monitorInfo.cbSize = sizeof(MONITORINFOEX);
1146 GetMonitorInfo(hMonitor, &monitorInfo);
1147
1148 DEVMODE devMode = {};
1149 devMode.dmSize = sizeof(DEVMODE);
1150 devMode.dmDriverExtra = 0;
1151 EnumDisplaySettings(monitorInfo.szDevice, ENUM_CURRENT_SETTINGS, &devMode);
1152
1153 if (devMode.dmDisplayFrequency != 0) list.push_back(devMode.dmDisplayFrequency);
1154 return true;
1155}
1156
1158{
1159 std::vector<int> rates = {};
1160 EnumDisplayMonitors(nullptr, nullptr, MonitorEnumProc, reinterpret_cast<LPARAM>(&rates));
1161 return rates;
1162}
1163
1165{
1166 return { static_cast<uint>(GetSystemMetrics(SM_CXSCREEN)), static_cast<uint>(GetSystemMetrics(SM_CYSCREEN)) };
1167}
1168
1170{
1171 if (this->buffer_locked) return false;
1172 this->buffer_locked = true;
1173
1174 _screen.dst_ptr = this->GetVideoPointer();
1175 assert(_screen.dst_ptr != nullptr);
1176
1177 return true;
1178}
1179
1181{
1182 assert(_screen.dst_ptr != nullptr);
1183 if (_screen.dst_ptr != nullptr) {
1184 /* Hand video buffer back to the drawing backend. */
1185 this->ReleaseVideoPointer();
1186 _screen.dst_ptr = nullptr;
1187 }
1188
1189 this->buffer_locked = false;
1190}
1191
1192
1193static FVideoDriver_Win32GDI iFVideoDriver_Win32GDI;
1194
1195std::optional<std::string_view> VideoDriver_Win32GDI::Start(const StringList &param)
1196{
1197 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
1198
1199 auto err = this->Initialize();
1200 if (err) return err;
1201
1202 this->MakePalette();
1204 this->MakeWindow(_fullscreen);
1205
1207
1208 this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
1209
1210 return std::nullopt;
1211}
1212
1214{
1215 DeleteObject(this->gdi_palette);
1216 DeleteObject(this->dib_sect);
1217
1219}
1220
1222{
1224
1225 w = std::max(w, 64);
1226 h = std::max(h, 64);
1227
1228 if (!force && w == _screen.width && h == _screen.height) return false;
1229
1230 BITMAPINFO *bi = (BITMAPINFO *)new char[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256]();
1231 bi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1232
1233 bi->bmiHeader.biWidth = this->width = w;
1234 bi->bmiHeader.biHeight = -(this->height = h);
1235
1236 bi->bmiHeader.biPlanes = 1;
1237 bi->bmiHeader.biBitCount = bpp;
1238 bi->bmiHeader.biCompression = BI_RGB;
1239
1240 if (this->dib_sect) DeleteObject(this->dib_sect);
1241
1242 HDC dc = GetDC(0);
1243 this->dib_sect = CreateDIBSection(dc, bi, DIB_RGB_COLORS, (VOID **)&this->buffer_bits, nullptr, 0);
1244 if (this->dib_sect == nullptr) {
1245 delete[] bi;
1246 UserError("CreateDIBSection failed");
1247 }
1248 ReleaseDC(0, dc);
1249
1250 _screen.width = w;
1251 _screen.pitch = (bpp == 8) ? Align(w, 4) : w;
1252 _screen.height = h;
1253 _screen.dst_ptr = this->GetVideoPointer();
1254
1255 delete[] bi;
1256 return true;
1257}
1258
1260{
1261 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
1262 return this->AllocateBackingStore(_screen.width, _screen.height, true) && this->MakeWindow(_fullscreen, false);
1263}
1264
1265void VideoDriver_Win32GDI::MakePalette()
1266{
1267 CopyPalette(this->local_palette, true);
1268
1269 LOGPALETTE *pal = (LOGPALETTE *)new char[sizeof(LOGPALETTE) + (256 - 1) * sizeof(PALETTEENTRY)]();
1270
1271 pal->palVersion = 0x300;
1272 pal->palNumEntries = 256;
1273
1274 for (uint i = 0; i != 256; i++) {
1275 pal->palPalEntry[i].peRed = this->local_palette.palette[i].r;
1276 pal->palPalEntry[i].peGreen = this->local_palette.palette[i].g;
1277 pal->palPalEntry[i].peBlue = this->local_palette.palette[i].b;
1278 pal->palPalEntry[i].peFlags = 0;
1279
1280 }
1281 this->gdi_palette = CreatePalette(pal);
1282 delete[] pal;
1283 if (this->gdi_palette == nullptr) UserError("CreatePalette failed!\n");
1284}
1285
1286void VideoDriver_Win32GDI::UpdatePalette(HDC dc, uint start, uint count)
1287{
1288 RGBQUAD rgb[256];
1289
1290 for (uint i = 0; i != count; i++) {
1291 rgb[i].rgbRed = this->local_palette.palette[start + i].r;
1292 rgb[i].rgbGreen = this->local_palette.palette[start + i].g;
1293 rgb[i].rgbBlue = this->local_palette.palette[start + i].b;
1294 rgb[i].rgbReserved = 0;
1295 }
1296
1297 SetDIBColorTable(dc, start, count, rgb);
1298}
1299
1301{
1302 HDC hDC = GetWindowDC(hWnd);
1303 HPALETTE hOldPalette = SelectPalette(hDC, this->gdi_palette, FALSE);
1304 UINT nChanged = RealizePalette(hDC);
1305
1306 SelectPalette(hDC, hOldPalette, TRUE);
1307 ReleaseDC(hWnd, hDC);
1308 if (nChanged != 0) this->MakeDirty(0, 0, _screen.width, _screen.height);
1309}
1310
1312{
1314
1315 if (IsEmptyRect(this->dirty_rect)) return;
1316
1317 HDC dc = GetDC(this->main_wnd);
1318 HDC dc2 = CreateCompatibleDC(dc);
1319
1320 HBITMAP old_bmp = (HBITMAP)SelectObject(dc2, this->dib_sect);
1321 HPALETTE old_palette = SelectPalette(dc, this->gdi_palette, FALSE);
1322
1323 if (this->local_palette.count_dirty != 0) {
1325
1326 switch (blitter->UsePaletteAnimation()) {
1328 this->UpdatePalette(dc2, this->local_palette.first_dirty, this->local_palette.count_dirty);
1329 break;
1330
1332 blitter->PaletteAnimate(this->local_palette);
1333 break;
1334 }
1335
1337 break;
1338
1339 default:
1340 NOT_REACHED();
1341 }
1342 this->local_palette.count_dirty = 0;
1343 }
1344
1345 BitBlt(dc, 0, 0, this->width, this->height, dc2, 0, 0, SRCCOPY);
1346 SelectPalette(dc, old_palette, TRUE);
1347 SelectObject(dc2, old_bmp);
1348 DeleteDC(dc2);
1349
1350 ReleaseDC(this->main_wnd, dc);
1351
1352 this->dirty_rect = {};
1353}
1354
1355#ifdef _DEBUG
1356/* Keep this function here..
1357 * It allows you to redraw the screen from within the MSVC debugger */
1358/* static */ int VideoDriver_Win32GDI::RedrawScreenDebug()
1359{
1360 static int _fooctr;
1361
1363
1364 _screen.dst_ptr = drv->GetVideoPointer();
1365 UpdateWindows();
1366
1367 drv->Paint();
1368 GdiFlush();
1369
1370 return _fooctr++;
1371}
1372#endif
1373
1374#ifdef WITH_OPENGL
1375
1376#ifndef PFD_SUPPORT_COMPOSITION
1377# define PFD_SUPPORT_COMPOSITION 0x00008000
1378#endif
1379
1380static PFNWGLCREATECONTEXTATTRIBSARBPROC _wglCreateContextAttribsARB = nullptr;
1381static PFNWGLSWAPINTERVALEXTPROC _wglSwapIntervalEXT = nullptr;
1382static bool _hasWGLARBCreateContextProfile = false;
1383
1389static OGLProc GetOGLProcAddressCallback(const char *proc)
1390{
1391 OGLProc ret = reinterpret_cast<OGLProc>(wglGetProcAddress(proc));
1392 if (ret == nullptr) {
1393 /* Non-extension GL function? Try normal loading. */
1394 ret = reinterpret_cast<OGLProc>(GetProcAddress(GetModuleHandle(L"opengl32"), proc));
1395 }
1396 return ret;
1397}
1398
1404static std::optional<std::string_view> SelectPixelFormat(HDC dc)
1405{
1406 PIXELFORMATDESCRIPTOR pfd = {
1407 sizeof(PIXELFORMATDESCRIPTOR), // Size of this struct.
1408 1, // Version of this struct.
1409 PFD_DRAW_TO_WINDOW | // Require window support.
1410 PFD_SUPPORT_OPENGL | // Require OpenGL support.
1411 PFD_DOUBLEBUFFER | // Use double buffering.
1412 PFD_DEPTH_DONTCARE,
1413 PFD_TYPE_RGBA, // Request RGBA format.
1414 24, // 24 bpp (excluding alpha).
1415 0, 0, 0, 0, 0, 0, 0, 0, // Colour bits and shift ignored.
1416 0, 0, 0, 0, 0, // No accumulation buffer.
1417 0, 0, // No depth/stencil buffer.
1418 0, // No aux buffers.
1419 PFD_MAIN_PLANE, // Main layer.
1420 0, 0, 0, 0 // Ignored/reserved.
1421 };
1422
1423 pfd.dwFlags |= PFD_SUPPORT_COMPOSITION; // Make OpenTTD compatible with Aero.
1424
1425 /* Choose a suitable pixel format. */
1426 int format = ChoosePixelFormat(dc, &pfd);
1427 if (format == 0) return "No suitable pixel format found";
1428 if (!SetPixelFormat(dc, format, &pfd)) return "Can't set pixel format";
1429
1430 return std::nullopt;
1431}
1432
1434static void LoadWGLExtensions()
1435{
1436 /* Querying the supported WGL extensions and loading the matching
1437 * functions requires a valid context, even for the extensions
1438 * regarding context creation. To get around this, we create
1439 * a dummy window with a dummy context. The extension functions
1440 * remain valid even after this context is destroyed. */
1441 HWND wnd = CreateWindow(L"STATIC", L"dummy", WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, nullptr, nullptr, GetModuleHandle(nullptr), nullptr);
1442 HDC dc = GetDC(wnd);
1443
1444 /* Set pixel format of the window. */
1445 if (SelectPixelFormat(dc) == std::nullopt) {
1446 /* Create rendering context. */
1447 HGLRC rc = wglCreateContext(dc);
1448 if (rc != nullptr) {
1449 wglMakeCurrent(dc, rc);
1450
1451#ifdef __MINGW32__
1452 /* GCC doesn't understand the expected usage of wglGetProcAddress(). */
1453#pragma GCC diagnostic push
1454#pragma GCC diagnostic ignored "-Wcast-function-type"
1455#endif /* __MINGW32__ */
1456
1457 /* Get list of WGL extensions. */
1458 PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
1459 if (wglGetExtensionsStringARB != nullptr) {
1460 std::string_view wgl_exts = wglGetExtensionsStringARB(dc);
1461 /* Bind supported functions. */
1462 if (HasStringInExtensionList(wgl_exts, "WGL_ARB_create_context")) {
1463 _wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
1464 }
1465 _hasWGLARBCreateContextProfile = HasStringInExtensionList(wgl_exts, "WGL_ARB_create_context_profile");
1466 if (HasStringInExtensionList(wgl_exts, "WGL_EXT_swap_control")) {
1467 _wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
1468 }
1469 }
1470
1471#ifdef __MINGW32__
1472#pragma GCC diagnostic pop
1473#endif
1474 wglMakeCurrent(nullptr, nullptr);
1475 wglDeleteContext(rc);
1476 }
1477 }
1478
1479 ReleaseDC(wnd, dc);
1480 DestroyWindow(wnd);
1481}
1482
1483static FVideoDriver_Win32OpenGL iFVideoDriver_Win32OpenGL;
1484
1485std::optional<std::string_view> VideoDriver_Win32OpenGL::Start(const StringList &param)
1486{
1487 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
1488
1489 Dimension old_res = _cur_resolution; // Save current screen resolution in case of errors, as MakeWindow invalidates it.
1490
1491 LoadWGLExtensions();
1492
1493 auto err = this->Initialize();
1494 if (err) {
1495 this->Stop();
1496 _cur_resolution = old_res;
1497 return err;
1498 }
1499 this->MakeWindow(_fullscreen);
1500
1501 /* Create and initialize OpenGL context. */
1502 err = this->AllocateContext();
1503 if (err) {
1504 this->Stop();
1505 _cur_resolution = old_res;
1506 return err;
1507 }
1508
1509 this->driver_info = GetName();
1510 this->driver_info += " (";
1511 this->driver_info += OpenGLBackend::Get()->GetDriverName();
1512 this->driver_info += ")";
1513
1514 this->ClientSizeChanged(this->width, this->height, true);
1515 /* We should have a valid screen buffer now. If not, something went wrong and we should abort. */
1516 if (_screen.dst_ptr == nullptr) {
1517 this->Stop();
1518 _cur_resolution = old_res;
1519 return "Can't get pointer to screen buffer";
1520 }
1521 /* Main loop expects to start with the buffer unmapped. */
1522 this->ReleaseVideoPointer();
1523
1525
1526 this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
1527
1528 return std::nullopt;
1529}
1530
1531void VideoDriver_Win32OpenGL::Stop()
1532{
1533 this->DestroyContext();
1535}
1536
1537void VideoDriver_Win32OpenGL::DestroyContext()
1538{
1540
1541 wglMakeCurrent(nullptr, nullptr);
1542 if (this->gl_rc != nullptr) {
1543 wglDeleteContext(this->gl_rc);
1544 this->gl_rc = nullptr;
1545 }
1546 if (this->dc != nullptr) {
1547 ReleaseDC(this->main_wnd, this->dc);
1548 this->dc = nullptr;
1549 }
1550}
1551
1552void VideoDriver_Win32OpenGL::ToggleVsync(bool vsync)
1553{
1554 if (_wglSwapIntervalEXT != nullptr) {
1555 _wglSwapIntervalEXT(vsync);
1556 } else if (vsync) {
1557 Debug(Facility::Driver, Severity::Critical, "OpenGL: Vsync requested, but not supported by driver");
1558 }
1559}
1560
1561std::optional<std::string_view> VideoDriver_Win32OpenGL::AllocateContext()
1562{
1563 this->dc = GetDC(this->main_wnd);
1564
1565 auto err = SelectPixelFormat(this->dc);
1566 if (err) return err;
1567
1568 HGLRC rc = nullptr;
1569
1570 /* Create OpenGL device context. Try to get an 3.2+ context if possible. */
1571 if (_wglCreateContextAttribsARB != nullptr) {
1572 /* Try for OpenGL 4.5 first. */
1573 int attribs[] = {
1574 WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
1575 WGL_CONTEXT_MINOR_VERSION_ARB, 5,
1576 WGL_CONTEXT_FLAGS_ARB, IsVisibleSeverity(Facility::Driver, Severity::Trace2) ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
1577 _hasWGLARBCreateContextProfile ? WGL_CONTEXT_PROFILE_MASK_ARB : 0, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, // Terminate list if WGL_ARB_create_context_profile isn't supported.
1578 0
1579 };
1580 rc = _wglCreateContextAttribsARB(this->dc, nullptr, attribs);
1581
1582 if (rc == nullptr) {
1583 /* Try again for a 3.2 context. */
1584 attribs[1] = 3;
1585 attribs[3] = 2;
1586 rc = _wglCreateContextAttribsARB(this->dc, nullptr, attribs);
1587 }
1588 }
1589
1590 if (rc == nullptr) {
1591 /* Old OpenGL or old driver, let's hope for the best. */
1592 rc = wglCreateContext(this->dc);
1593 if (rc == nullptr) return "Can't create OpenGL context";
1594 }
1595 if (!wglMakeCurrent(this->dc, rc)) return "Can't activate GL context";
1596
1597 this->ToggleVsync(_video_vsync);
1598
1599 this->gl_rc = rc;
1600 return OpenGLBackend::Create(&GetOGLProcAddressCallback, this->GetScreenSize());
1601}
1602
1603bool VideoDriver_Win32OpenGL::ToggleFullscreen(bool full_screen)
1604{
1605 if (_screen.dst_ptr != nullptr) this->ReleaseVideoPointer();
1606 this->DestroyContext();
1607 bool res = this->VideoDriver_Win32Base::ToggleFullscreen(full_screen);
1608 res &= this->AllocateContext() == std::nullopt;
1609 this->ClientSizeChanged(this->width, this->height, true);
1610 return res;
1611}
1612
1613bool VideoDriver_Win32OpenGL::AfterBlitterChange()
1614{
1615 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
1616 this->ClientSizeChanged(this->width, this->height, true);
1617 return true;
1618}
1619
1620void VideoDriver_Win32OpenGL::PopulateSystemSprites()
1621{
1622 OpenGLBackend::Get()->PopulateCursorCache();
1623}
1624
1625void VideoDriver_Win32OpenGL::ClearSystemSprites()
1626{
1628}
1629
1630bool VideoDriver_Win32OpenGL::AllocateBackingStore(int w, int h, bool force)
1631{
1632 if (!force && w == _screen.width && h == _screen.height) return false;
1633
1634 this->width = w = std::max(w, 64);
1635 this->height = h = std::max(h, 64);
1636
1637 if (this->gl_rc == nullptr) return false;
1638
1639 if (_screen.dst_ptr != nullptr) this->ReleaseVideoPointer();
1640
1641 this->dirty_rect = {};
1642 bool res = OpenGLBackend::Get()->Resize(w, h, force);
1643 SwapBuffers(this->dc);
1644 _screen.dst_ptr = this->GetVideoPointer();
1645
1646 return res;
1647}
1648
1649void *VideoDriver_Win32OpenGL::GetVideoPointer()
1650{
1651 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
1652 this->anim_buffer = OpenGLBackend::Get()->GetAnimBuffer();
1653 this->anim_pitch = _screen.pitch;
1654 }
1656}
1657
1658void VideoDriver_Win32OpenGL::ReleaseVideoPointer()
1659{
1660 if (this->anim_buffer != nullptr) OpenGLBackend::Get()->ReleaseAnimBuffer(this->dirty_rect);
1661 OpenGLBackend::Get()->ReleaseVideoBuffer(this->dirty_rect);
1662 this->dirty_rect = {};
1663 _screen.dst_ptr = nullptr;
1664 this->anim_buffer = nullptr;
1665 this->anim_pitch = 0;
1666}
1667
1668void VideoDriver_Win32OpenGL::Paint()
1669{
1671
1672 if (this->local_palette.count_dirty != 0) {
1674
1675 /* Always push a changed palette to OpenGL. */
1676 OpenGLBackend::Get()->UpdatePalette(this->local_palette.palette, this->local_palette.first_dirty, this->local_palette.count_dirty);
1678 blitter->PaletteAnimate(this->local_palette);
1679 }
1680
1681 this->local_palette.count_dirty = 0;
1682 }
1683
1686
1687 SwapBuffers(this->dc);
1688}
1689
1690#endif /* WITH_OPENGL */
#define AS(ap_name, size_x, size_y, min_year, max_year, catchment, noise, maint_cost, ttdpatch_type, class_id, name, preview)
AirportSpec definition for airports with at least one depot.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:139
How all blitters should look like.
Definition base.hpp:28
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
virtual Blitter::PaletteAnimation UsePaletteAnimation()=0
Check if the blitter uses palette animation at all.
virtual void PaletteAnimate(const Palette &palette)=0
Called when the 8bpp palette is changed; you should redraw all pixels on the screen that are equal to...
@ None
No palette animation.
Definition base.hpp:50
@ Blitter
The blitter takes care of the palette animation.
Definition base.hpp:52
@ VideoBackend
Palette animation should be done by video backend (8bpp only!).
Definition base.hpp:51
virtual void PostResize()
Post resize event.
Definition base.hpp:210
The factory for Windows' video driver.
Definition win32_v.h:133
void Paint()
Render video buffer to the screen.
Definition opengl.cpp:1066
uint8_t * GetAnimBuffer()
Get a pointer to the memory for the separate animation buffer.
Definition opengl.cpp:1197
void * GetVideoBuffer()
Get a pointer to the memory for the video driver to draw to.
Definition opengl.cpp:1175
bool Resize(int w, int h, bool force=false)
Change the size of the drawing window and allocate matching resources.
Definition opengl.cpp:940
static std::optional< std::string_view > Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res)
Create and initialize the singleton back-end class.
Definition opengl.cpp:491
void UpdatePalette(const Colour *pal, uint first, uint length)
Update the stored palette.
Definition opengl.cpp:1052
void ReleaseAnimBuffer(const Rect &update_rect)
Update animation buffer texture after the animation buffer was filled.
Definition opengl.cpp:1258
void ClearCursorCache()
Queue a request for cursor cache clear.
Definition opengl.cpp:1162
static OpenGLBackend * Get()
Get singleton instance of this class.
Definition opengl.h:86
void DrawMouseCursor()
Draw mouse cursor on screen.
Definition opengl.cpp:1098
void ReleaseVideoBuffer(const Rect &update_rect)
Update video buffer texture after the video buffer was filled.
Definition opengl.cpp:1220
static void Destroy()
Free resources and destroy singleton back-end class.
Definition opengl.cpp:504
RAII class for measuring simple elements of performance.
Constant span of UTF-8 encoded data.
Definition utf8.hpp:28
Base class for Windows video drivers.
Definition win32_v.h:17
int height
Height in pixels of our display surface.
Definition win32_v.h:49
bool has_focus
Does our window have system focus?
Definition win32_v.h:46
void EditBoxLostFocus() override
An edit box lost the input focus.
Definition win32_v.cpp:1133
void CheckPaletteAnim() override
Process any pending palette animation.
Definition win32_v.cpp:1040
void Stop() override
Stop this driver.
Definition win32_v.cpp:1027
int height_org
Original monitor resolution height, before we changed it.
Definition win32_v.h:51
HWND main_wnd
Handle to system window.
Definition win32_v.h:44
bool fullscreen
Whether to use (true) fullscreen mode.
Definition win32_v.h:45
int width_org
Original monitor resolution width, before we changed it.
Definition win32_v.h:50
bool MakeWindow(bool full_screen, bool resize=true)
Instantiate a new window.
Definition win32_v.cpp:150
bool buffer_locked
Video buffer was locked by the main thread.
Definition win32_v.h:53
virtual void * GetVideoPointer()=0
Get a pointer to the video buffer.
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
Definition win32_v.cpp:1034
bool PollEvent() override
Process a single system event.
Definition win32_v.cpp:1070
virtual void PaletteChanged(HWND hWnd)=0
Palette of the window has changed.
bool LockVideoBuffer() override
Make sure the video buffer is ready for drawing.
Definition win32_v.cpp:1169
std::vector< int > GetListOfMonitorRefreshRates() override
Get a list of refresh rates of each available monitor.
Definition win32_v.cpp:1157
virtual bool AllocateBackingStore(int w, int h, bool force=false)=0
(Re-)create the backing store.
int width
Width in pixels of our display surface.
Definition win32_v.h:48
void InputLoop() override
Handle input logic, is CTRL pressed, should we fast-forward, etc.
Definition win32_v.cpp:1046
virtual uint8_t GetFullscreenBpp()
Colour depth to use for fullscreen display modes.
Definition win32_v.cpp:138
Dimension GetScreenSize() const override
Get the resolution of the main screen.
Definition win32_v.cpp:1164
virtual void ReleaseVideoPointer()
Hand video buffer back to the painting backend.
Definition win32_v.h:85
Palette local_palette
Current palette to use for drawing.
Definition win32_v.h:54
void UnlockVideoBuffer() override
Unlock a previously locked video buffer.
Definition win32_v.cpp:1180
virtual bool MinimiseRestoreWithToggleFullscreen() const
Whether minimising and restoring fullscreen windows uses ToggleFullscreen.
Definition win32_v.h:97
void ClientSizeChanged(int w, int h, bool force=false)
Indicate to the driver the client-size might have changed.
Definition win32_v.cpp:1103
void MainLoop() override
Perform the actual drawing.
Definition win32_v.cpp:1083
void ClaimMousePointer() override
Claim the exclusive rights for the mouse pointer.
Definition win32_v.cpp:62
Rect dirty_rect
Region of the screen that needs redrawing.
Definition win32_v.h:47
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
Definition win32_v.cpp:1125
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
Definition win32_v.cpp:1115
The GDI video driver for windows.
Definition win32_v.h:103
void * buffer_bits
Internal rendering buffer.
Definition win32_v.h:116
HBITMAP dib_sect
System bitmap object referencing our rendering buffer.
Definition win32_v.h:114
void PaletteChanged(HWND hWnd) override
Palette of the window has changed.
Definition win32_v.cpp:1300
std::optional< std::string_view > Start(const StringList &param) override
Start this driver.
Definition win32_v.cpp:1195
void * GetVideoPointer() override
Get a pointer to the video buffer.
Definition win32_v.h:119
HPALETTE gdi_palette
Palette object for 8bpp blitter.
Definition win32_v.h:115
bool AllocateBackingStore(int w, int h, bool force=false) override
(Re-)create the backing store.
Definition win32_v.cpp:1221
void Paint() override
Paint the window.
Definition win32_v.cpp:1311
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
Definition win32_v.cpp:1259
void Stop() override
Stop this driver.
Definition win32_v.cpp:1213
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.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
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 OGLProc GetOGLProcAddressCallback(const char *proc)
Platform-specific callback to get an OpenGL function pointer.
Definition cocoa_ogl.mm:49
bool _window_maximize
Declared in win32_v.cpp.
Definition win32_v.cpp:58
bool IsVisibleSeverity(Facility facility, Severity severity)
Test if debug severity is visible for the given facility.
Definition debug.h:24
#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
@ Trace2
Trace information #2.
Definition debug_type.h:23
@ Error
Error, but we are recovering.
Definition debug_type.h:16
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
Error reporting related functions.
Factory to 'query' all available blitters.
fluid_settings_t * settings
FluidSynth settings handle.
Types for recording game performance data.
@ Video
Speed of painting drawn video buffer.
Rect BoundingRect(const Rect &r1, const Rect &r2)
Compute the bounding rectangle around two rectangles.
Geometry functions.
bool IsEmptyRect(const Rect &r)
Check if a rectangle is empty.
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
Support8bpp _support8bpp
State of the support for 8bpp graphics.
Definition gfx.cpp:38
DirectionKeys _dirkeys
Pressed direction keys.
Definition gfx.cpp:36
bool AdjustGUIZoom(bool automatic)
Resolve GUI zoom level and adjust GUI to new zoom, if auto-suggestion is requested.
Definition gfx.cpp:1859
Functions related to the gfx engine.
void HandleCtrlChanged()
State of CONTROL key has changed.
Definition window.cpp:2771
void UpdateWindows()
Update the continuously changing contents of the windows, such as the viewports.
Definition window.cpp:3203
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
@ Hardware
Full 8bpp support by OS and hardware.
Definition gfx_type.h:430
@ 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
@ 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
@ Stop
Stop button.
Definition goal_type.h:36
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
Functions/types related to loading libraries dynamically.
#define Point
Macro that prevents name conflicts between included headers.
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 Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition math_func.hpp:37
bool HasStringInExtensionList(std::string_view string, std::string_view substring)
Find a substring in a string made of space delimited elements.
Definition opengl.cpp:151
OpenGL video driver support.
Some generic types.
void GetKeyboardLayout()
Retrieve keyboard layout from language string or (if set) config file.
Definition osk_gui.cpp:357
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.
Pseudo random number generator.
A number of safeguards to prevent using unsafe methods.
static void FindResolutions()
Find and store all possible resolutions into _resolutions.
Definition sdl3_v.cpp:104
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.
char32_t Utf16DecodeSurrogate(uint lead, uint trail)
Convert an UTF-16 surrogate pair to the corresponding Unicode character.
Definition string_func.h:82
bool Utf16IsLeadSurrogate(uint c)
Is the given character a lead surrogate code point?
Definition string_func.h:61
bool Utf16IsTrailSurrogate(uint c)
Is the given character a lead surrogate code point?
Definition string_func.h:71
std::vector< std::string > StringList
Type for a list of strings.
Definition string_type.h:61
T y
Y coordinate.
T x
X coordinate.
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
Colour palette[256]
Current palette. Entry 0 has to be always fully transparent!
Definition gfx_type.h:421
Specification of a rectangle with absolute coordinates of all edges.
Functions related to text effects.
Base of all threads.
Handling of UTF-8 encoded data.
bool _video_vsync
Whether we should use vsync (only if active video driver supports HW acceleration).
std::string_view convert_from_fs(const std::wstring_view src, std::span< char > dst_buf)
Convert to OpenTTD's encoding from that of the environment in UNICODE.
Definition win32.cpp:407
std::wstring OTTD2FS(std::string_view name)
Convert from OpenTTD's encoding to a wide string.
Definition win32.cpp:389
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.
Definition win32.cpp:373
Declarations of functions for MS windows systems.
static LRESULT HandleCharMsg(uint keycode, char32_t charcode)
Forward key presses to the window system.
Definition win32_v.cpp:257
static bool DrawIMECompositionString()
Should we draw the composition string ourself, i.e is this a normal IME?
Definition win32_v.cpp:287
static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
Handle WM_IME_COMPOSITION messages.
Definition win32_v.cpp:361
static void SetCandidatePos(HWND hwnd)
Set the position of the candidate window.
Definition win32_v.cpp:321
static void CancelIMEComposition(HWND hwnd)
Clear the current composition string.
Definition win32_v.cpp:426
static void SetCompositionPos(HWND hwnd)
Set position of the composition window to the caret position.
Definition win32_v.cpp:296
Base of the Windows video driver.
Window * _focused_window
Window that currently has focus.
Definition window.cpp:80
void ReInitAllWindows(bool zoom_changed)
Re-initialize all windows.
Definition window.cpp:3494
bool EditBoxInGlobalFocus()
Check if an edit box is in global focus.
Definition window.cpp:456
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.
Functions, definitions and such used only by the GUI.