LCOV - code coverage report
Current view: top level - source/ps - VideoMode.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 65 445 14.6 %
Date: 2026-12-03 01:19:39 Functions: 13 38 34.2 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "VideoMode.h"
      21             : 
      22             : #include "graphics/Camera.h"
      23             : #include "graphics/GameView.h"
      24             : #include "graphics/ShaderDefines.h"
      25             : #include "graphics/ShaderProgram.h"
      26             : #include "gui/GUIManager.h"
      27             : #include "lib/config2.h"
      28             : #include "lib/debug.h"
      29             : #include "lib/file/vfs/vfs.h"
      30             : #include "lib/path.h"
      31             : #include "lib/status.h"
      32             : #include "lib/sysdep/os.h"
      33             : #include "lib/tex/tex.h"
      34             : #include "ps/CConsole.h"
      35             : #include "ps/CLogger.h"
      36             : #include "ps/CStr.h"
      37             : #include "ps/ConfigDB.h"
      38             : #include "ps/Filesystem.h"
      39             : #include "ps/Game.h"
      40             : #include "ps/GameSetup/Config.h"
      41             : #include "ps/Hotkey.h"
      42             : #include "ps/Pyrogenesis.h"
      43             : #include "renderer/Renderer.h"
      44             : #include "renderer/backend/IDevice.h"
      45             : #include "renderer/backend/ISwapChain.h"
      46             : #include "renderer/backend/dummy/DeviceForward.h"
      47             : #include "renderer/backend/gl/DeviceForward.h"
      48             : #include "renderer/backend/vulkan/DeviceForward.h"
      49             : #include "scriptinterface/Interface.h"
      50             : 
      51             : #include <SDL.h>
      52             : #include <SDL_error.h>
      53             : #include <SDL_events.h>
      54             : #include <SDL_mouse.h>
      55             : #include <SDL_pixels.h>
      56             : #include <SDL_stdinc.h>
      57             : #include <SDL_surface.h>
      58             : #include <SDL_version.h>
      59             : #include <SDL_video.h>
      60             : #include <algorithm>
      61             : #include <cstdlib>
      62             : #include <sstream>
      63             : #include <string>
      64             : #include <string_view>
      65             : 
      66             : #if OS_MACOSX && SDL_VERSION_ATLEAST(2, 0, 6)
      67             : #include "ps/DllLoader.h"
      68             : 
      69             : #include <SDL_vulkan.h>
      70             : #endif
      71             : 
      72             : using namespace std::literals;
      73             : 
      74             : namespace
      75             : {
      76             : 
      77             : int DEFAULT_WINDOW_W = 1024;
      78             : int DEFAULT_WINDOW_H = 768;
      79             : 
      80             : int DEFAULT_FULLSCREEN_W = 1024;
      81             : int DEFAULT_FULLSCREEN_H = 768;
      82             : 
      83             : const wchar_t DEFAULT_CURSOR_NAME[] = L"default-arrow";
      84             : 
      85           0 : Renderer::Backend::Backend GetFallbackBackend(const Renderer::Backend::Backend backend)
      86             : {
      87           0 :     Renderer::Backend::Backend fallback = Renderer::Backend::Backend::DUMMY;
      88             :     // We use a switch instead of a list to have compile-time checks for missed
      89             :     // values and because a linear priority list doesn't work for general case.
      90           0 :     switch (backend)
      91             :     {
      92             :     case Renderer::Backend::Backend::GL:
      93             :         fallback = Renderer::Backend::Backend::DUMMY;
      94             :         break;
      95             :     case Renderer::Backend::Backend::DUMMY:
      96             :         break;
      97           0 :     case Renderer::Backend::Backend::VULKAN:
      98           0 :         fallback = Renderer::Backend::Backend::GL;
      99           0 :         break;
     100             :     }
     101           0 :     return fallback;
     102             : }
     103             : 
     104           0 : std::string_view GetBackendName(const Renderer::Backend::Backend backend)
     105             : {
     106           0 :     std::string_view name{"Unknown"};
     107           0 :     switch (backend)
     108             :     {
     109           0 :     case Renderer::Backend::Backend::GL:
     110           0 :         name = "GL";
     111           0 :         break;
     112           0 :     case Renderer::Backend::Backend::DUMMY:
     113           0 :         name = "Dummy";
     114           0 :         break;
     115           0 :     case Renderer::Backend::Backend::VULKAN:
     116           0 :         name = "Vulkan";
     117           0 :         break;
     118             :     }
     119           0 :     return name;
     120             : }
     121             : 
     122             : } // anonymous namespace
     123             : 
     124             : #if OS_WIN
     125             : // We can't include wutil directly because GL headers conflict with Windows
     126             : // until we use a proper GL loader.
     127             : extern void wutil_SetAppWindow(SDL_Window* window);
     128             : 
     129             : // After a proper HiDPI integration we should switch to manifest until
     130             : // SDL has an implemented HiDPI on Windows.
     131             : extern void wutil_EnableHiDPIOnWindows();
     132             : #endif
     133             : 
     134             : CVideoMode g_VideoMode;
     135             : 
     136             : class CVideoMode::CCursor
     137             : {
     138             : public:
     139             :     enum class CursorBackend
     140             :     {
     141             :         SDL,
     142             :         SYSTEM
     143             :     };
     144             : 
     145             :     CCursor();
     146             :     ~CCursor();
     147             : 
     148             :     void SetCursor(const CStrW& name);
     149             :     void ResetCursor();
     150             : 
     151             : private:
     152             :     CursorBackend m_CursorBackend = CursorBackend::SYSTEM;
     153             :     SDL_Surface* m_CursorSurface = nullptr;
     154             :     SDL_Cursor* m_Cursor = nullptr;
     155             :     CStrW m_CursorName;
     156             : };
     157             : 
     158           0 : CVideoMode::CCursor::CCursor()
     159             : {
     160           0 :     if (g_ConfigDB.Get("cursorbackend", std::string{}) == "sdl")
     161           0 :         m_CursorBackend = CursorBackend::SDL;
     162             :     else
     163           0 :         m_CursorBackend = CursorBackend::SYSTEM;
     164             : 
     165           0 :     ResetCursor();
     166           0 : }
     167             : 
     168           0 : CVideoMode::CCursor::~CCursor()
     169             : {
     170           0 :     if (m_Cursor)
     171           0 :         SDL_FreeCursor(m_Cursor);
     172           0 :     if (m_CursorSurface)
     173           0 :         SDL_FreeSurface(m_CursorSurface);
     174           0 : }
     175             : 
     176           0 : void CVideoMode::CCursor::SetCursor(const CStrW& name)
     177             : {
     178           0 :     if (m_CursorBackend == CursorBackend::SYSTEM || m_CursorName == name)
     179           0 :         return;
     180           0 :     m_CursorName = name;
     181             : 
     182           0 :     if (m_Cursor)
     183           0 :         SDL_FreeCursor(m_Cursor);
     184           0 :     if (m_CursorSurface)
     185           0 :         SDL_FreeSurface(m_CursorSurface);
     186             : 
     187           0 :     if (name.empty())
     188             :     {
     189           0 :         SDL_ShowCursor(SDL_DISABLE);
     190           0 :         return;
     191             :     }
     192             : 
     193           0 :     const VfsPath pathBaseName(VfsPath(L"art/textures/cursors") / name);
     194             : 
     195             :     // Read pixel offset of the cursor's hotspot [the bit of it that's
     196             :     // drawn at (g_mouse_x,g_mouse_y)] from file.
     197           0 :     int hotspotX = 0, hotspotY = 0;
     198           0 :     {
     199           0 :         const VfsPath pathHotspotName = pathBaseName.ChangeExtension(L".txt");
     200           0 :         std::unique_ptr<std::uint8_t[], AlignedDeleter> buffer;
     201           0 :         size_t size;
     202           0 :         if (g_VFS->LoadFile(pathHotspotName, buffer, size) != INFO::OK)
     203             :         {
     204           0 :             LOGERROR("Can't load hotspot for cursor: {}", pathHotspotName.string8());
     205           0 :             return;
     206             :         }
     207           0 :         std::wstringstream s(std::wstring(reinterpret_cast<const wchar_t*>(buffer.get()), size));
     208           0 :         s >> hotspotX >> hotspotY;
     209           0 :     }
     210             : 
     211           0 :     const VfsPath pathImageName = pathBaseName.ChangeExtension(L".png");
     212             : 
     213           0 :     std::shared_ptr<std::uint8_t> file;
     214           0 :     size_t fileSize;
     215           0 :     if (g_VFS->LoadFile(pathImageName, file, fileSize) != INFO::OK)
     216             :     {
     217           0 :         LOGERROR("Can't load image for cursor: {}", pathImageName.string8());
     218           0 :         return;
     219             :     }
     220             : 
     221           0 :     Tex t;
     222           0 :     if (t.decode(file, fileSize) != INFO::OK)
     223             :     {
     224           0 :         LOGERROR("Can't decode image for cursor");
     225           0 :         return;
     226             :     }
     227             : 
     228             :     // Convert to required BGRA format.
     229           0 :     const size_t flags = (t.m_Flags | TEX_BGR) & ~TEX_DXT;
     230           0 :     if (t.transform_to(flags) != INFO::OK)
     231             :     {
     232           0 :         LOGERROR("Can't transform image for cursor");
     233           0 :         return;
     234             :     }
     235           0 :     void* imageBGRA = t.get_data();
     236           0 :     if (!imageBGRA)
     237             :     {
     238           0 :         LOGERROR("Transformed image is empty for cursor");
     239           0 :         return;
     240             :     }
     241             : 
     242           0 :     m_CursorSurface = SDL_CreateRGBSurfaceFrom(imageBGRA,
     243           0 :         static_cast<int>(t.m_Width), static_cast<int>(t.m_Height), 32,
     244           0 :         static_cast<int>(t.m_Width * 4),
     245             :         0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
     246           0 :     if (!m_CursorSurface)
     247             :     {
     248           0 :         LOGERROR("Can't create surface for cursor: {}", SDL_GetError());
     249           0 :         return;
     250             :     }
     251           0 :     const float scale = g_VideoMode.GetScale();
     252           0 :     if (scale != 1.0)
     253             :     {
     254           0 :         SDL_Surface* scaledSurface = SDL_CreateRGBSurface(0,
     255           0 :             m_CursorSurface->w * scale,
     256           0 :             m_CursorSurface->h * scale, 32,
     257             :             0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
     258           0 :         if (!scaledSurface)
     259             :         {
     260           0 :             LOGERROR("Can't create scaled surface forcursor: {}", SDL_GetError());
     261           0 :             return;
     262             :         }
     263           0 :         if (SDL_BlitScaled(m_CursorSurface, nullptr, scaledSurface, nullptr))
     264             :             return;
     265           0 :         SDL_FreeSurface(m_CursorSurface);
     266           0 :         m_CursorSurface = scaledSurface;
     267             :     }
     268           0 :     m_Cursor = SDL_CreateColorCursor(m_CursorSurface, hotspotX, hotspotY);
     269           0 :     if (!m_Cursor)
     270             :     {
     271           0 :         LOGERROR("Can't create cursor: {}", SDL_GetError());
     272           0 :         return;
     273             :     }
     274             : 
     275           0 :     SDL_SetCursor(m_Cursor);
     276           0 : }
     277             : 
     278           0 : void CVideoMode::CCursor::ResetCursor()
     279             : {
     280           0 :     SetCursor(DEFAULT_CURSOR_NAME);
     281           0 : }
     282             : 
     283           7 : Input::Reaction CVideoMode::InputHandler::operator()(const SDL_Event& ev)
     284             : {
     285           7 :     if (ev.type == SDL_HOTKEYPRESS)
     286             :     {
     287           1 :         if (static_cast<const char*>(ev.user.data1) == "mousegrabtoggle"sv)
     288             :         {
     289           0 :             SDL_Window* const window{videoMode.GetWindow()};
     290           0 :             const SDL_bool willGrabMouse{SDL_GetWindowGrab(window) ? SDL_FALSE : SDL_TRUE};
     291           0 :             SDL_SetWindowGrab(window, willGrabMouse);
     292           0 :             return Input::Reaction::HANDLED;
     293             :         }
     294             :     }
     295           7 :     if (ev.type == SDL_WINDOWEVENT)
     296             :     {
     297           0 :         switch (ev.window.event)
     298             :         {
     299           0 :         case SDL_WINDOWEVENT_RESIZED:
     300           0 :             videoMode.m_ResizedW = ev.window.data1;
     301           0 :             videoMode.m_ResizedH = ev.window.data2;
     302           0 :             break;
     303           0 :         case SDL_WINDOWEVENT_MOVED:
     304           0 :             if (!videoMode.IsInFullscreen())
     305             :             {
     306           0 :                 videoMode.m_WindowedX = ev.window.data1;
     307           0 :                 videoMode.m_WindowedY = ev.window.data2;
     308             :             }
     309             :             break;
     310             :         }
     311             :     }
     312             : 
     313             :     return Input::Reaction::PASS;
     314             : }
     315             : 
     316           1 : CVideoMode::CVideoMode() :
     317           1 :     m_WindowedW(DEFAULT_WINDOW_W), m_WindowedH(DEFAULT_WINDOW_H), m_WindowedX(0), m_WindowedY(0)
     318             : {
     319           1 : }
     320             : 
     321           1 : CVideoMode::~CVideoMode() = default;
     322             : 
     323          10 : void CVideoMode::ReadConfig()
     324             : {
     325          10 :     m_ConfigFullscreen = !g_ConfigDB.Get("windowed", !m_ConfigFullscreen);
     326             : 
     327          10 :     m_Scale = g_ConfigDB.Get("gui.scale", m_Scale);
     328             : 
     329          10 :     m_ConfigW = g_ConfigDB.Get("xres", m_ConfigW);
     330          10 :     m_ConfigH = g_ConfigDB.Get("yres", m_ConfigH);
     331          10 :     m_ConfigBPP = g_ConfigDB.Get("bpp", m_ConfigBPP);
     332          10 :     m_ConfigDisplay = g_ConfigDB.Get("display", m_ConfigDisplay);
     333          10 :     m_ConfigEnableHiDPI = g_ConfigDB.Get("hidpi", m_ConfigEnableHiDPI);
     334          10 :     m_ConfigVSync = g_ConfigDB.Get("vsync", m_ConfigVSync);
     335             : 
     336          20 :     const std::string rendererBackend{g_ConfigDB.Get("rendererbackend", std::string{})};
     337          10 :     if (rendererBackend == "dummy")
     338          10 :         m_Backend = Renderer::Backend::Backend::DUMMY;
     339           0 :     else if (rendererBackend == "vulkan")
     340           0 :         m_Backend = Renderer::Backend::Backend::VULKAN;
     341             :     else
     342           0 :         m_Backend = Renderer::Backend::Backend::GL;
     343             : 
     344             : #if OS_WIN
     345             :     if (m_ConfigEnableHiDPI)
     346             :         wutil_EnableHiDPIOnWindows();
     347             : #endif
     348          10 : }
     349             : 
     350           0 : bool CVideoMode::SetVideoMode(int w, int h, int bpp, bool fullscreen)
     351             : {
     352           0 :     Uint32 flags = 0;
     353           0 :     if (fullscreen)
     354             :     {
     355           0 :         flags |= g_ConfigDB.Get("borderless.fullscreen", true) ? SDL_WINDOW_FULLSCREEN_DESKTOP :
     356             :             SDL_WINDOW_FULLSCREEN;
     357             :     }
     358           0 :     else if (g_ConfigDB.Get("borderless.window", false))
     359           0 :         flags |= SDL_WINDOW_BORDERLESS;
     360             : 
     361           0 :     if (!m_Window)
     362             :     {
     363           0 :         const bool isGLBackend{m_Backend == Renderer::Backend::Backend::GL};
     364           0 :         if (isGLBackend)
     365             :         {
     366           0 :             SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
     367           0 :             SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
     368           0 :             SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
     369           0 :             SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
     370             : 
     371           0 :             if (g_ConfigDB.Get("renderer.backend.debugcontext", false))
     372           0 :                 SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
     373             : 
     374           0 :             if (g_ConfigDB.Get("forceglversion", false))
     375             :             {
     376           0 :                 const std::string forceGLProfile{g_ConfigDB.Get("forceglprofile", "compatibility"s)};
     377           0 :                 const int forceGLMajorVersion{g_ConfigDB.Get("forceglmajorversion", 3)};
     378           0 :                 const int forceGLMinorVersion{g_ConfigDB.Get("forceglminorversion", 0)};
     379             : 
     380           0 :                 int profile = SDL_GL_CONTEXT_PROFILE_COMPATIBILITY;
     381           0 :                 if (forceGLProfile == "es")
     382             :                     profile = SDL_GL_CONTEXT_PROFILE_ES;
     383           0 :                 else if (forceGLProfile == "core")
     384             :                     profile = SDL_GL_CONTEXT_PROFILE_CORE;
     385           0 :                 else if (forceGLProfile != "compatibility")
     386             :                 {
     387           0 :                     LOGWARNING("Unknown force GL profile '{}', compatibility profile is used",
     388             :                         forceGLProfile);
     389             :                 }
     390             : 
     391           0 :                 if (forceGLMajorVersion < 1 || forceGLMinorVersion < 0)
     392             :                 {
     393           0 :                     LOGERROR("Unsupported force GL version: {}.{}", forceGLMajorVersion,
     394             :                         forceGLMinorVersion);
     395           0 :                 }
     396             :                 else
     397             :                 {
     398           0 :                     SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profile);
     399           0 :                     SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, forceGLMajorVersion);
     400           0 :                     SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, forceGLMinorVersion);
     401             :                 }
     402           0 :             }
     403             :             else
     404             :             {
     405             : #if CONFIG2_GLES
     406             :                 // Require GLES 2.0
     407             :                 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
     408             :                 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
     409             :                 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
     410             : #else
     411             :                 // Some macOS and MESA drivers might not create a context even if they can
     412             :                 // with the core profile. So disable it for a while until we can guarantee
     413             :                 // its creation.
     414             : #if OS_WIN
     415             :                 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
     416             : #endif
     417           0 :                 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
     418           0 :                 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
     419             : #endif
     420             :             }
     421             :         }
     422             : 
     423             :         // Note: these flags only take affect in SDL_CreateWindow
     424           0 :         flags |= SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE;
     425           0 :         if (m_ConfigEnableHiDPI)
     426           0 :             flags |= SDL_WINDOW_ALLOW_HIGHDPI;
     427           0 :         if (isGLBackend)
     428           0 :             flags |= SDL_WINDOW_OPENGL;
     429           0 :         else if (m_Backend == Renderer::Backend::Backend::VULKAN)
     430           0 :             flags |= SDL_WINDOW_VULKAN;
     431           0 :         m_WindowedX = m_WindowedY = SDL_WINDOWPOS_CENTERED_DISPLAY(m_ConfigDisplay);
     432             : 
     433             : #if OS_MACOSX && SDL_VERSION_ATLEAST(2, 0, 6)
     434             :         if (m_Backend == Renderer::Backend::Backend::VULKAN)
     435             :         {
     436             :             // MoltenVK - enable full component swizzling support.
     437             :             setenv("MVK_CONFIG_FULL_IMAGE_VIEW_SWIZZLE", "1", 1);
     438             :             setenv("MVK_CONFIG_USE_METAL_ARGUMENT_BUFFERS", "0", 1);
     439             :             CStr fullPathToVulkanLibrary = DllLoader::GenerateFilename("MoltenVK", "", ".dylib");
     440             :             // MoltenVK - only print warnings and errors.
     441             :             setenv("MVK_CONFIG_LOG_LEVEL", "2", 1);
     442             :             if (SDL_Vulkan_LoadLibrary(fullPathToVulkanLibrary.c_str()) != 0)
     443             :             {
     444             :                 LOGWARNING("Failed to load {}.", fullPathToVulkanLibrary);
     445             :                 DowngradeBackendSettingAfterCreationFailure();
     446             :                 return SetVideoMode(w, h, bpp, fullscreen);
     447             :             }
     448             :             else
     449             :                 LOGMESSAGE("Loaded {}.", fullPathToVulkanLibrary);
     450             :         }
     451             : #endif
     452             : 
     453           0 :         m_Window = SDL_CreateWindow(main_window_name, m_WindowedX, m_WindowedY, w, h, flags);
     454           0 :         if (!m_Window)
     455             :         {
     456             :             // SDL might fail to create a window in case of missing a Vulkan driver.
     457           0 :             if (m_Backend == Renderer::Backend::Backend::VULKAN)
     458             :             {
     459           0 :                 LOGWARNING("Failed to create a Vulkan window: {}", SDL_GetError());
     460           0 :                 DowngradeBackendSettingAfterCreationFailure();
     461           0 :                 return SetVideoMode(w, h, bpp, fullscreen);
     462             :             }
     463             : 
     464             :             // If fullscreen fails, try windowed mode
     465           0 :             if (fullscreen)
     466             :             {
     467           0 :                 LOGWARNING("Failed to set the video mode to fullscreen for the chosen resolution "
     468             :                     "{}x{}:{} (\"{}\"), falling back to windowed mode",
     469             :                     w, h, bpp, SDL_GetError());
     470             :                 // Using default size for the window for now, as the attempted setting
     471             :                 // could be as large, or larger than the screen size.
     472           0 :                 return SetVideoMode(DEFAULT_WINDOW_W, DEFAULT_WINDOW_H, bpp, false);
     473             :             }
     474             :             else
     475             :             {
     476           0 :                 if (isGLBackend)
     477             :                 {
     478           0 :                     int depthSize = 24;
     479           0 :                     SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &depthSize);
     480           0 :                     if (depthSize > 16)
     481             :                     {
     482             :                         // Fall back to a smaller depth buffer
     483             :                         // (The rendering may be ugly but this helps when running in VMware)
     484           0 :                         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
     485             : 
     486           0 :                         return SetVideoMode(w, h, bpp, fullscreen);
     487             :                     }
     488             :                 }
     489             : 
     490           0 :                 LOGERROR("SetVideoMode failed in SDL_CreateWindow: {}x{}:{} {} (\"{}\")", w, h,
     491             :                     bpp, fullscreen ? 1 : 0, SDL_GetError());
     492           0 :                 return false;
     493             :             }
     494             :         }
     495             : 
     496           0 :         if (SDL_SetWindowDisplayMode(m_Window, NULL) < 0)
     497             :         {
     498           0 :             LOGERROR("SetVideoMode failed in SDL_SetWindowDisplayMode: {}x{}:{} {} (\"{}\")", w, h,
     499             :                 bpp, fullscreen, SDL_GetError());
     500           0 :             return false;
     501             :         }
     502             : 
     503             : #if OS_WIN
     504             :         // We need to set the window for an error dialog.
     505             :         wutil_SetAppWindow(m_Window);
     506             : #endif
     507             : 
     508           0 :         if (!TryCreateBackendDevice(m_Window))
     509             :         {
     510           0 :             DowngradeBackendSettingAfterCreationFailure();
     511           0 :             SDL_DestroyWindow(m_Window);
     512           0 :             m_Window = nullptr;
     513           0 :             return SetVideoMode(w, h, bpp, fullscreen);
     514             :         }
     515             :     }
     516             :     else
     517             :     {
     518           0 :         if (IsInFullscreen() != fullscreen)
     519             :         {
     520           0 :             if (!fullscreen)
     521             :             {
     522             :                 // For some reason, when switching from fullscreen to windowed mode,
     523             :                 // we have to set the window size and position before and after switching
     524           0 :                 SDL_SetWindowSize(m_Window, w, h);
     525           0 :                 SDL_SetWindowPosition(m_Window, m_WindowedX, m_WindowedY);
     526             :             }
     527             : 
     528           0 :             if (SDL_SetWindowFullscreen(m_Window, flags) < 0)
     529             :             {
     530           0 :                 LOGERROR("SetVideoMode failed in SDL_SetWindowFullscreen: {}x{}:{} {} (\"{}\")", w,
     531             :                     h, bpp, fullscreen, SDL_GetError());
     532           0 :                 return false;
     533             :             }
     534             :         }
     535             : 
     536           0 :         if (!fullscreen)
     537             :         {
     538           0 :             SDL_SetWindowSize(m_Window, w, h);
     539           0 :             SDL_SetWindowPosition(m_Window, m_WindowedX, m_WindowedY);
     540             :         }
     541             :     }
     542             : 
     543             :     // Grab the current video settings
     544           0 :     SDL_GetWindowSize(m_Window, &m_CurrentW, &m_CurrentH);
     545           0 :     m_CurrentBPP = bpp;
     546             : 
     547             :     // #545: we need to constrain the window in fullscreen mode to avoid mouse
     548             :     // "falling out" of the window in case of multiple displays.
     549           0 :     if (fullscreen ? g_ConfigDB.Get("window.mousegrabinfullscreen", true) :
     550           0 :         g_ConfigDB.Get("window.mousegrabinwindowmode", false))
     551             :     {
     552           0 :         SDL_SetWindowGrab(m_Window, SDL_TRUE);
     553             :     }
     554             :     else
     555           0 :         SDL_SetWindowGrab(m_Window, SDL_FALSE);
     556             : 
     557             :     return true;
     558             : }
     559             : 
     560           0 : bool CVideoMode::InitSDL()
     561             : {
     562           0 :     ENSURE(!m_IsInitialised);
     563             : 
     564           0 :     ReadConfig();
     565             : 
     566             :     // preferred video mode = current desktop settings
     567             :     // (command line params may override these)
     568             :     // TODO: handle multi-screen and HiDPI properly.
     569           0 :     SDL_DisplayMode mode;
     570           0 :     if (SDL_GetDesktopDisplayMode(0, &mode) == 0)
     571             :     {
     572           0 :         m_PreferredW = mode.w;
     573           0 :         m_PreferredH = mode.h;
     574           0 :         m_PreferredBPP = SDL_BITSPERPIXEL(mode.format);
     575           0 :         m_PreferredFreq = mode.refresh_rate;
     576             :     }
     577             : 
     578           0 :     int w = m_ConfigW;
     579           0 :     int h = m_ConfigH;
     580             : 
     581           0 :     if (m_ConfigFullscreen)
     582             :     {
     583             :         // If fullscreen and no explicit size set, default to the desktop resolution
     584           0 :         if (w == 0 || h == 0)
     585             :         {
     586           0 :             w = m_PreferredW;
     587           0 :             h = m_PreferredH;
     588             :         }
     589             :     }
     590             : 
     591             :     // If no size determined, default to something sensible
     592           0 :     if (w == 0 || h == 0)
     593             :     {
     594           0 :         w = DEFAULT_WINDOW_W;
     595           0 :         h = DEFAULT_WINDOW_H;
     596             :     }
     597             : 
     598           0 :     if (!m_ConfigFullscreen)
     599             :     {
     600             :         // Limit the window to the screen size (if known)
     601           0 :         if (m_PreferredW)
     602           0 :             w = std::min(w, m_PreferredW);
     603           0 :         if (m_PreferredH)
     604           0 :             h = std::min(h, m_PreferredH);
     605             :     }
     606             : 
     607           0 :     const int bpp = GetBestBPP();
     608           0 :     if (!SetVideoMode(w, h, bpp, m_ConfigFullscreen))
     609             :         return false;
     610             : 
     611             :     // Work around a bug in the proprietary Linux ATI driver (at least versions 8.16.20 and 8.14.13).
     612             :     // The driver appears to register its own atexit hook on context creation.
     613             :     // If this atexit hook is called before SDL_Quit destroys the OpenGL context,
     614             :     // some kind of double-free problem causes a crash and lockup in the driver.
     615             :     // Calling SDL_Quit twice appears to be harmless, though, and avoids the problem
     616             :     // by destroying the context *before* the driver's atexit hook is called.
     617             :     // (Note that atexit hooks are guaranteed to be called in reverse order of their registration.)
     618           0 :     if (m_Backend == Renderer::Backend::Backend::GL)
     619           0 :         atexit(SDL_Quit);
     620             :     // End work around.
     621             : 
     622           0 :     m_IsInitialised = true;
     623             : 
     624           0 :     if (!m_ConfigFullscreen)
     625             :     {
     626           0 :         m_WindowedW = w;
     627           0 :         m_WindowedH = h;
     628             :     }
     629             : 
     630           0 :     SetWindowIcon();
     631             : 
     632           0 :     m_Cursor = std::make_unique<CCursor>();
     633             : 
     634           0 :     return true;
     635             : }
     636             : 
     637          10 : bool CVideoMode::InitNonSDL()
     638             : {
     639          10 :     ENSURE(!m_IsInitialised);
     640             : 
     641          10 :     ReadConfig();
     642             : 
     643          10 :     m_IsInitialised = true;
     644             : 
     645          10 :     return true;
     646             : }
     647             : 
     648          10 : void CVideoMode::Shutdown()
     649             : {
     650          10 :     ENSURE(m_IsInitialised);
     651             : 
     652          10 :     m_Cursor.reset();
     653             : 
     654          10 :     m_IsInitialised = false;
     655             : 
     656          10 :     if (m_BackendDevice)
     657             :     {
     658             :         // We need to wait before we can destroy the device.
     659          10 :         m_BackendDevice->WaitUntilIdle();
     660             :     }
     661             : 
     662          10 :     m_SwapChain.reset();
     663          10 :     m_BackendDevice.reset();
     664          10 :     if (m_Window)
     665             :     {
     666           0 :         SDL_DestroyWindow(m_Window);
     667           0 :         m_Window = nullptr;
     668             :     }
     669          10 : }
     670             : 
     671          10 : bool CVideoMode::CreateBackendDevice(const bool createSDLContext)
     672             : {
     673          10 :     if (!createSDLContext && m_Backend == Renderer::Backend::Backend::VULKAN)
     674           0 :         m_Backend = Renderer::Backend::Backend::GL;
     675           0 :     SDL_Window* window = createSDLContext ? m_Window : nullptr;
     676          10 :     while (m_Backend != Renderer::Backend::Backend::DUMMY)
     677             :     {
     678           0 :         if (TryCreateBackendDevice(window))
     679             :             return true;
     680           0 :         DowngradeBackendSettingAfterCreationFailure();
     681             :     }
     682          10 :     return TryCreateBackendDevice(window);
     683             : }
     684             : 
     685          10 : bool CVideoMode::TryCreateBackendDevice(SDL_Window* window)
     686             : {
     687          10 :     switch (m_Backend)
     688             :     {
     689           0 :     case Renderer::Backend::Backend::GL:
     690           0 :         m_BackendDevice = Renderer::Backend::GL::CreateDevice(window);
     691           0 :         break;
     692          10 :     case Renderer::Backend::Backend::DUMMY:
     693          10 :         m_BackendDevice = Renderer::Backend::Dummy::CreateDevice(window);
     694          10 :         ENSURE(m_BackendDevice);
     695             :         break;
     696           0 :     case Renderer::Backend::Backend::VULKAN:
     697           0 :         m_BackendDevice = Renderer::Backend::Vulkan::CreateDevice(window);
     698             :         // HACK: the repository doesn't have prebuilt SPIR-V shaders. So some
     699             :         // users might get an error in case of missing shaders.
     700           0 :         if (m_BackendDevice)
     701             :         {
     702             :             // We must not use CShaderManager here to avoid caching.
     703           0 :             std::unique_ptr<Renderer::Backend::IShaderProgram> shaderProgram =
     704           0 :                 m_BackendDevice->CreateShaderProgram("spirv/canvas2d", CShaderDefines{});
     705           0 :             if (!shaderProgram)
     706             :             {
     707           0 :                 m_BackendDevice.reset();
     708             :             }
     709           0 :         }
     710             :         break;
     711             :     }
     712             :     // We don't need to wait because we don't have any swapchain in use.
     713          10 :     RecreateSwapChain();
     714          10 :     if (m_BackendDevice && (!m_SwapChain || !m_SwapChain->IsValid()))
     715             :     {
     716             :         // Currently we assume that we should have a valid swapchain on the device
     717             :         // creation.
     718           0 :         m_BackendDevice.reset();
     719             :     }
     720          10 :     return static_cast<bool>(m_BackendDevice);
     721             : }
     722             : 
     723           0 : void CVideoMode::DowngradeBackendSettingAfterCreationFailure()
     724             : {
     725           0 :     const Renderer::Backend::Backend fallback = GetFallbackBackend(m_Backend);
     726           0 :     LOGERROR("Unable to create device for {} backend, switching to {}.", GetBackendName(m_Backend),
     727             :         GetBackendName(fallback));
     728           0 :     m_Backend = fallback;
     729           0 : }
     730             : 
     731          10 : void CVideoMode::RecreateSwapChain()
     732             : {
     733          10 :     if (m_BackendDevice)
     734             :     {
     735          10 :         char nameBuffer[64];
     736          10 :         snprintf(nameBuffer, std::size(nameBuffer), "SwapChain: %dx%d", m_CurrentW, m_CurrentH);
     737          20 :         m_SwapChain = m_BackendDevice->CreateSwapChain(
     738          10 :             nameBuffer, m_Window, m_CurrentW, m_CurrentH, m_ConfigVSync, std::move(m_SwapChain));
     739             :     }
     740          10 : }
     741             : 
     742           0 : Renderer::Backend::ISwapChain* CVideoMode::GetOrCreateSwapChain()
     743             : {
     744             : #if !OS_MACOSX
     745           0 :     const bool vsync{g_ConfigDB.Get("vsync", false)};
     746           0 :     const bool vsyncChanged{m_ConfigVSync != vsync};
     747           0 :     if (vsyncChanged)
     748           0 :         m_ConfigVSync = vsync;
     749             : #else
     750             :     // Currently there is a bug in MoltenVK which doesn't allow to recreate
     751             :     // a swapchain with the same size (it makes it 1x1):
     752             :     //  https://github.com/KhronosGroup/MoltenVK/pull/2722
     753             :     const bool vsyncChanged{false};
     754             : #endif
     755           0 :     const bool shouldRecreate{
     756           0 :         !m_SwapChain || !m_SwapChain->IsValid() || vsyncChanged};
     757           0 :     if (shouldRecreate)
     758             :     {
     759           0 :         if (m_SwapChain)
     760             :         {
     761             :             // We need to wait until we can destroy the swapchain because it
     762             :             // might be in use.
     763           0 :             m_BackendDevice->WaitUntilIdle();
     764             :         }
     765           0 :         RecreateSwapChain();
     766             :     }
     767           0 :     return m_SwapChain.get();
     768             : }
     769             : 
     770           0 : bool CVideoMode::OnceAFrameWork()
     771             : {
     772           0 :     ENSURE(m_IsInitialised);
     773             : 
     774             :     // Ignore if the size hasn't changed
     775           0 :     if ((m_ResizedH == 0 && m_ResizedW == 0) || (m_ResizedW == m_CurrentW && m_ResizedH == m_CurrentH))
     776             :         return true;
     777             : 
     778           0 :     const int w{m_ResizedW};
     779           0 :     const int h{m_ResizedH};
     780           0 :     m_ResizedW = m_ResizedH = 0;
     781             : 
     782             :     // The size was changed externally (by the user or the compositor).
     783           0 :     if (!IsInFullscreen())
     784             :     {
     785           0 :         m_WindowedW = w;
     786           0 :         m_WindowedH = h;
     787             :     }
     788             : 
     789           0 :     UpdateRenderer(w, h);
     790             : 
     791           0 :     return true;
     792             : }
     793             : 
     794           0 : void CVideoMode::Rescale(float scale)
     795             : {
     796           0 :     ENSURE(m_IsInitialised);
     797           0 :     m_Scale = scale;
     798           0 :     UpdateRenderer(m_CurrentW, m_CurrentH);
     799           0 : }
     800             : 
     801           4 : float CVideoMode::GetScale() const
     802             : {
     803           0 :     return m_Scale;
     804             : }
     805             : 
     806           0 : bool CVideoMode::SetFullscreen(bool fullscreen)
     807             : {
     808             :     // This might get called before initialisation by psDisplayError;
     809             :     // if so then silently fail
     810           0 :     if (!m_IsInitialised)
     811             :         return false;
     812             : 
     813             :     // Check whether this is actually a change
     814           0 :     if (fullscreen == IsInFullscreen())
     815             :         return true;
     816             : 
     817           0 :     if (!IsInFullscreen())
     818             :     {
     819             :         // Windowed -> fullscreen:
     820             : 
     821           0 :         int w = 0, h = 0;
     822             : 
     823             :         // If a fullscreen size was configured, use that; else use the desktop size; else use a default
     824           0 :         if (m_ConfigFullscreen)
     825             :         {
     826           0 :             w = m_ConfigW;
     827           0 :             h = m_ConfigH;
     828             :         }
     829           0 :         if (w == 0 || h == 0)
     830             :         {
     831           0 :             w = m_PreferredW;
     832           0 :             h = m_PreferredH;
     833             :         }
     834           0 :         if (w == 0 || h == 0)
     835             :         {
     836           0 :             w = DEFAULT_FULLSCREEN_W;
     837           0 :             h = DEFAULT_FULLSCREEN_H;
     838             :         }
     839             : 
     840           0 :         int bpp = GetBestBPP();
     841             : 
     842           0 :         if (!SetVideoMode(w, h, bpp, fullscreen))
     843             :             return false;
     844             : 
     845           0 :         UpdateRenderer(m_CurrentW, m_CurrentH);
     846             : 
     847           0 :         return true;
     848             :     }
     849             :     else
     850             :     {
     851             :         // Fullscreen -> windowed:
     852             : 
     853             :         // Go back to whatever the previous window size was
     854           0 :         int w = m_WindowedW, h = m_WindowedH;
     855             : 
     856           0 :         int bpp = GetBestBPP();
     857             : 
     858           0 :         if (!SetVideoMode(w, h, bpp, fullscreen))
     859             :             return false;
     860             : 
     861           0 :         UpdateRenderer(w, h);
     862             : 
     863           0 :         return true;
     864             :     }
     865             : }
     866             : 
     867           0 : bool CVideoMode::ToggleFullscreen()
     868             : {
     869           0 :     return SetFullscreen(!IsInFullscreen());
     870             : }
     871             : 
     872           0 : bool CVideoMode::IsInFullscreen() const
     873             : {
     874           0 :     return SDL_GetWindowFlags(m_Window) & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_FULLSCREEN_DESKTOP);
     875             : }
     876             : 
     877           0 : void CVideoMode::UpdateRenderer(int w, int h)
     878             : {
     879           0 :     if (w < 2) w = 2; // avoid GL errors caused by invalid sizes
     880           0 :     if (h < 2) h = 2;
     881             : 
     882           0 :     m_CurrentW = w;
     883           0 :     m_CurrentH = h;
     884             : 
     885           0 :     SViewPort vp = { 0, 0, w, h };
     886             : 
     887             :     // We need to separate destroy and create of objects to be able to flush
     888             :     // all queued to destroy resources during WaitUntilIdle.
     889           0 :     if (CRenderer::IsInitialised())
     890           0 :         g_Renderer.DestroyViewSizeDependentObjects();
     891             : 
     892           0 :     if (g_VideoMode.m_BackendDevice)
     893             :     {
     894             :         // We need to wait until we can destroy the swapchain because it
     895             :         // might be in use.
     896           0 :         g_VideoMode.m_BackendDevice->WaitUntilIdle();
     897             : 
     898           0 :         g_VideoMode.RecreateSwapChain();
     899             :     }
     900             : 
     901           0 :     if (CRenderer::IsInitialised())
     902           0 :         g_Renderer.CreateViewSizeDependentObjects(w, h);
     903             : 
     904           0 :     if (g_GUI)
     905           0 :         g_GUI->UpdateResolution();
     906             : 
     907           0 :     if (g_Console)
     908           0 :         g_Console->UpdateScreenSize(w, h);
     909             : 
     910           0 :     if (g_Game)
     911           0 :         g_Game->GetView()->SetViewport(vp);
     912           0 : }
     913             : 
     914           0 : int CVideoMode::GetBestBPP()
     915             : {
     916           0 :     if (m_ConfigBPP)
     917             :         return m_ConfigBPP;
     918           0 :     if (m_PreferredBPP)
     919           0 :         return m_PreferredBPP;
     920             :     return 32;
     921             : }
     922             : 
     923          12 : int CVideoMode::GetWindowWidth() const
     924             : {
     925          12 :     ENSURE(m_IsInitialised);
     926          12 :     return m_CurrentW;
     927             : }
     928             : 
     929          12 : int CVideoMode::GetWindowHeight() const
     930             : {
     931          12 :     ENSURE(m_IsInitialised);
     932          12 :     return m_CurrentH;
     933             : }
     934             : 
     935           0 : int CVideoMode::GetBPP() const
     936             : {
     937           0 :     ENSURE(m_IsInitialised);
     938           0 :     return m_CurrentBPP;
     939             : }
     940             : 
     941           0 : bool CVideoMode::IsVSyncEnabled() const
     942             : {
     943           0 :     ENSURE(m_IsInitialised);
     944           0 :     return m_ConfigVSync;
     945             : }
     946             : 
     947           0 : int CVideoMode::GetDesktopXRes() const
     948             : {
     949           0 :     ENSURE(m_IsInitialised);
     950           0 :     return m_PreferredW;
     951             : }
     952             : 
     953           0 : int CVideoMode::GetDesktopYRes() const
     954             : {
     955           0 :     ENSURE(m_IsInitialised);
     956           0 :     return m_PreferredH;
     957             : }
     958             : 
     959           0 : int CVideoMode::GetDesktopBPP() const
     960             : {
     961           0 :     ENSURE(m_IsInitialised);
     962           0 :     return m_PreferredBPP;
     963             : }
     964             : 
     965           0 : int CVideoMode::GetDesktopFreq() const
     966             : {
     967           0 :     ENSURE(m_IsInitialised);
     968           0 :     return m_PreferredFreq;
     969             : }
     970             : 
     971           0 : SDL_Window* CVideoMode::GetWindow()
     972             : {
     973           0 :     ENSURE(m_IsInitialised);
     974           0 :     return m_Window;
     975             : }
     976             : 
     977           0 : bool CVideoMode::IsInitialized() const
     978             : {
     979           0 :     return m_IsInitialised;
     980             : }
     981             : 
     982           0 : void CVideoMode::SetWindowIcon()
     983             : {
     984             :     // The window icon should be kept outside of art/textures/, or else it will be converted
     985             :     // to DDS by the archive builder and will become unusable here. Using DDS makes BGRA
     986             :     // conversion needlessly complicated.
     987           0 :     std::shared_ptr<std::uint8_t> iconFile;
     988           0 :     size_t iconFileSize;
     989           0 :     if (g_VFS->LoadFile("art/icons/window.png", iconFile, iconFileSize) != INFO::OK)
     990             :     {
     991           0 :         LOGWARNING("Window icon not found.");
     992           0 :         return;
     993             :     }
     994             : 
     995           0 :     Tex iconTexture;
     996           0 :     if (iconTexture.decode(iconFile, iconFileSize) != INFO::OK)
     997             :         return;
     998             : 
     999             :     // Convert to required BGRA format.
    1000           0 :     const size_t iconFlags = (iconTexture.m_Flags | TEX_BGR) & ~TEX_DXT;
    1001           0 :     if (iconTexture.transform_to(iconFlags) != INFO::OK)
    1002             :         return;
    1003             : 
    1004           0 :     void* bgra_img = iconTexture.get_data();
    1005           0 :     if (!bgra_img)
    1006             :         return;
    1007             : 
    1008           0 :     SDL_Surface *iconSurface = SDL_CreateRGBSurfaceFrom(bgra_img,
    1009           0 :         iconTexture.m_Width, iconTexture.m_Height, 32, iconTexture.m_Width * 4,
    1010             :         0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
    1011           0 :     if (!iconSurface)
    1012             :         return;
    1013             : 
    1014           0 :     SDL_SetWindowIcon(m_Window, iconSurface);
    1015           0 :     SDL_FreeSurface(iconSurface);
    1016           0 : }
    1017             : 
    1018           0 : void CVideoMode::SetCursor(const CStrW& name)
    1019             : {
    1020           0 :     if (m_Cursor)
    1021           0 :         m_Cursor->SetCursor(name);
    1022           0 : }
    1023             : 
    1024          18 : void CVideoMode::ResetCursor()
    1025             : {
    1026          18 :     if (m_Cursor)
    1027           0 :         m_Cursor->ResetCursor();
    1028          18 : }

Generated by: LCOV version 1.16