ScreenHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /*
  2. * ScreenHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "ScreenHandler.h"
  12. #include "../../lib/CConfigHandler.h"
  13. #include "../../lib/constants/StringConstants.h"
  14. #include "../gui/CGuiHandler.h"
  15. #include "../eventsSDL/NotificationHandler.h"
  16. #include "../gui/WindowHandler.h"
  17. #include "CMT.h"
  18. #include "SDL_Extensions.h"
  19. #ifdef VCMI_ANDROID
  20. #include "../lib/CAndroidVMHelper.h"
  21. #endif
  22. #ifdef VCMI_IOS
  23. # include "ios/utils.h"
  24. #endif
  25. #include <SDL.h>
  26. // TODO: should be made into a private members of ScreenHandler
  27. static SDL_Window * mainWindow = nullptr;
  28. SDL_Renderer * mainRenderer = nullptr;
  29. SDL_Texture * screenTexture = nullptr;
  30. SDL_Surface * screen = nullptr; //main screen surface
  31. SDL_Surface * screen2 = nullptr; //and hlp surface (used to store not-active interfaces layer)
  32. SDL_Surface * screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  33. static const std::string NAME_AFFIX = "client";
  34. static const std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  35. std::tuple<int, int> ScreenHandler::getSupportedScalingRange() const
  36. {
  37. // H3 resolution, any resolution smaller than that is not correctly supported
  38. static const Point minResolution = {800, 600};
  39. // arbitrary limit on *downscaling*. Allow some downscaling, if requested by user. Should be generally limited to 100+ for all but few devices
  40. static const double minimalScaling = 50;
  41. Point renderResolution = getRenderResolution();
  42. double reservedAreaWidth = settings["video"]["reservedWidth"].Float();
  43. Point availableResolution = Point(renderResolution.x * (1 - reservedAreaWidth), renderResolution.y);
  44. double maximalScalingWidth = 100.0 * availableResolution.x / minResolution.x;
  45. double maximalScalingHeight = 100.0 * availableResolution.y / minResolution.y;
  46. double maximalScaling = std::min(maximalScalingWidth, maximalScalingHeight);
  47. return { minimalScaling, maximalScaling };
  48. }
  49. Rect ScreenHandler::convertLogicalPointsToWindow(const Rect & input) const
  50. {
  51. Rect result;
  52. // FIXME: use SDL_RenderLogicalToWindow instead? Needs to be tested on ios
  53. float scaleX, scaleY;
  54. SDL_Rect viewport;
  55. SDL_RenderGetScale(mainRenderer, &scaleX, &scaleY);
  56. SDL_RenderGetViewport(mainRenderer, &viewport);
  57. #ifdef VCMI_IOS
  58. // TODO ios: looks like SDL bug actually, try fixing there
  59. const auto nativeScale = iOS_utils::screenScale();
  60. scaleX /= nativeScale;
  61. scaleY /= nativeScale;
  62. #endif
  63. result.x = (viewport.x + input.x) * scaleX;
  64. result.y = (viewport.y + input.y) * scaleY;
  65. result.w = input.w * scaleX;
  66. result.h = input.h * scaleY;
  67. return result;
  68. }
  69. Point ScreenHandler::getPreferredLogicalResolution() const
  70. {
  71. Point renderResolution = getRenderResolution();
  72. double reservedAreaWidth = settings["video"]["reservedWidth"].Float();
  73. Point availableResolution = Point(renderResolution.x * (1 - reservedAreaWidth), renderResolution.y);
  74. auto [minimalScaling, maximalScaling] = getSupportedScalingRange();
  75. int userScaling = settings["video"]["resolution"]["scaling"].Integer();
  76. int scaling = std::clamp(userScaling, minimalScaling, maximalScaling);
  77. Point logicalResolution = availableResolution * 100.0 / scaling;
  78. return logicalResolution;
  79. }
  80. Point ScreenHandler::getRenderResolution() const
  81. {
  82. assert(mainRenderer != nullptr);
  83. Point result;
  84. SDL_GetRendererOutputSize(mainRenderer, &result.x, &result.y);
  85. return result;
  86. }
  87. Point ScreenHandler::getPreferredWindowResolution() const
  88. {
  89. if (getPreferredWindowMode() == EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED)
  90. {
  91. SDL_Rect bounds;
  92. if (SDL_GetDisplayBounds(getPreferredDisplayIndex(), &bounds) == 0)
  93. return Point(bounds.w, bounds.h);
  94. }
  95. const JsonNode & video = settings["video"];
  96. int width = video["resolution"]["width"].Integer();
  97. int height = video["resolution"]["height"].Integer();
  98. return Point(width, height);
  99. }
  100. int ScreenHandler::getPreferredDisplayIndex() const
  101. {
  102. #ifdef VCMI_MOBILE
  103. // Assuming no multiple screens on Android / ios?
  104. return 0;
  105. #else
  106. if (mainWindow != nullptr)
  107. {
  108. int result = SDL_GetWindowDisplayIndex(mainWindow);
  109. if (result >= 0)
  110. return result;
  111. }
  112. return settings["video"]["displayIndex"].Integer();
  113. #endif
  114. }
  115. EWindowMode ScreenHandler::getPreferredWindowMode() const
  116. {
  117. #ifdef VCMI_MOBILE
  118. // On Android / ios game will always render to screen size
  119. return EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED;
  120. #else
  121. const JsonNode & video = settings["video"];
  122. bool fullscreen = video["fullscreen"].Bool();
  123. bool realFullscreen = settings["video"]["realFullscreen"].Bool();
  124. if (!fullscreen)
  125. return EWindowMode::WINDOWED;
  126. if (realFullscreen)
  127. return EWindowMode::FULLSCREEN_EXCLUSIVE;
  128. else
  129. return EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED;
  130. #endif
  131. }
  132. ScreenHandler::ScreenHandler()
  133. {
  134. #ifdef VCMI_WINDOWS
  135. // set VCMI as "per-monitor DPI awareness". This completely disables any DPI-scaling by system.
  136. // Might not be the best solution since VCMI can't automatically adjust to DPI changes (including moving to monitors with different DPI scaling)
  137. // However this fixed unintuitive bug where player selects specific resolution for windowed mode, but ends up with completely different one due to scaling
  138. // NOTE: requires SDL 2.24.
  139. SDL_SetHint(SDL_HINT_WINDOWS_DPI_AWARENESS, "permonitor");
  140. #endif
  141. if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER))
  142. {
  143. logGlobal->error("Something was wrong: %s", SDL_GetError());
  144. exit(-1);
  145. }
  146. const auto & logCallback = [](void * userdata, int category, SDL_LogPriority priority, const char * message)
  147. {
  148. logGlobal->debug("SDL(category %d; priority %d) %s", category, priority, message);
  149. };
  150. SDL_LogSetOutputFunction(logCallback, nullptr);
  151. #ifdef VCMI_ANDROID
  152. // manually setting egl pixel format, as a possible solution for sdl2<->android problem
  153. // https://bugzilla.libsdl.org/show_bug.cgi?id=2291
  154. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
  155. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
  156. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
  157. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  158. #endif // VCMI_ANDROID
  159. validateSettings();
  160. recreateWindowAndScreenBuffers();
  161. }
  162. void ScreenHandler::recreateWindowAndScreenBuffers()
  163. {
  164. destroyScreenBuffers();
  165. if(mainWindow == nullptr)
  166. initializeWindow();
  167. else
  168. updateWindowState();
  169. initializeScreenBuffers();
  170. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  171. {
  172. NotificationHandler::init(mainWindow);
  173. }
  174. }
  175. void ScreenHandler::updateWindowState()
  176. {
  177. #ifndef VCMI_MOBILE
  178. int displayIndex = getPreferredDisplayIndex();
  179. switch(getPreferredWindowMode())
  180. {
  181. case EWindowMode::FULLSCREEN_EXCLUSIVE:
  182. {
  183. // for some reason, VCMI fails to switch from FULLSCREEN_BORDERLESS_WINDOWED to FULLSCREEN_EXCLUSIVE directly
  184. // Switch to windowed mode first to avoid this bug
  185. SDL_SetWindowFullscreen(mainWindow, 0);
  186. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN);
  187. SDL_DisplayMode mode;
  188. SDL_GetDesktopDisplayMode(displayIndex, &mode);
  189. Point resolution = getPreferredWindowResolution();
  190. mode.w = resolution.x;
  191. mode.h = resolution.y;
  192. SDL_SetWindowDisplayMode(mainWindow, &mode);
  193. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  194. return;
  195. }
  196. case EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED:
  197. {
  198. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
  199. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  200. return;
  201. }
  202. case EWindowMode::WINDOWED:
  203. {
  204. Point resolution = getPreferredWindowResolution();
  205. SDL_SetWindowFullscreen(mainWindow, 0);
  206. SDL_SetWindowSize(mainWindow, resolution.x, resolution.y);
  207. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex));
  208. return;
  209. }
  210. }
  211. #endif
  212. }
  213. void ScreenHandler::initializeWindow()
  214. {
  215. mainWindow = createWindow();
  216. if(mainWindow == nullptr)
  217. {
  218. const char * error = SDL_GetError();
  219. Point dimensions = getPreferredWindowResolution();
  220. std::string messagePattern = "Failed to create SDL Window of size %d x %d. Reason: %s";
  221. std::string message = boost::str(boost::format(messagePattern) % dimensions.x % dimensions.y % error);
  222. handleFatalError(message, true);
  223. }
  224. // create first available renderer if no preferred one is set
  225. // use no SDL_RENDERER_SOFTWARE or SDL_RENDERER_ACCELERATED flag, so HW accelerated will be preferred but SW renderer will also be possible
  226. uint32_t rendererFlags = 0;
  227. if(settings["video"]["vsync"].Bool())
  228. {
  229. rendererFlags |= SDL_RENDERER_PRESENTVSYNC;
  230. }
  231. mainRenderer = SDL_CreateRenderer(mainWindow, getPreferredRenderingDriver(), rendererFlags);
  232. if(mainRenderer == nullptr)
  233. {
  234. const char * error = SDL_GetError();
  235. std::string messagePattern = "Failed to create SDL renderer. Reason: %s";
  236. std::string message = boost::str(boost::format(messagePattern) % error);
  237. handleFatalError(message, true);
  238. }
  239. SDL_RendererInfo info;
  240. SDL_GetRendererInfo(mainRenderer, &info);
  241. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, settings["video"]["scalingMode"].String().c_str());
  242. logGlobal->info("Created renderer %s", info.name);
  243. }
  244. void ScreenHandler::initializeScreenBuffers()
  245. {
  246. #ifdef VCMI_ENDIAN_BIG
  247. int bmask = 0xff000000;
  248. int gmask = 0x00ff0000;
  249. int rmask = 0x0000ff00;
  250. int amask = 0x000000ff;
  251. #else
  252. int bmask = 0x000000ff;
  253. int gmask = 0x0000ff00;
  254. int rmask = 0x00ff0000;
  255. int amask = 0xFF000000;
  256. #endif
  257. auto logicalSize = getPreferredLogicalResolution();
  258. SDL_RenderSetLogicalSize(mainRenderer, logicalSize.x, logicalSize.y);
  259. screen = SDL_CreateRGBSurface(0, logicalSize.x, logicalSize.y, 32, rmask, gmask, bmask, amask);
  260. if(nullptr == screen)
  261. {
  262. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", logicalSize.x, logicalSize.y, 32, SDL_GetError());
  263. throw std::runtime_error("Unable to create surface");
  264. }
  265. //No blending for screen itself. Required for proper cursor rendering.
  266. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  267. screenTexture = SDL_CreateTexture(mainRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, logicalSize.x, logicalSize.y);
  268. if(nullptr == screenTexture)
  269. {
  270. logGlobal->error("Unable to create screen texture");
  271. logGlobal->error(SDL_GetError());
  272. throw std::runtime_error("Unable to create screen texture");
  273. }
  274. screen2 = CSDL_Ext::copySurface(screen);
  275. if(nullptr == screen2)
  276. {
  277. throw std::runtime_error("Unable to copy surface\n");
  278. }
  279. if (GH.windows().count() > 1)
  280. screenBuf = screen2;
  281. else
  282. screenBuf = screen;
  283. clearScreen();
  284. }
  285. SDL_Window * ScreenHandler::createWindowImpl(Point dimensions, int flags, bool center)
  286. {
  287. int displayIndex = getPreferredDisplayIndex();
  288. int positionFlags = center ? SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex) : SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex);
  289. return SDL_CreateWindow(NAME.c_str(), positionFlags, positionFlags, dimensions.x, dimensions.y, flags);
  290. }
  291. SDL_Window * ScreenHandler::createWindow()
  292. {
  293. #ifndef VCMI_MOBILE
  294. Point dimensions = getPreferredWindowResolution();
  295. switch(getPreferredWindowMode())
  296. {
  297. case EWindowMode::FULLSCREEN_EXCLUSIVE:
  298. return createWindowImpl(dimensions, SDL_WINDOW_FULLSCREEN, false);
  299. case EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED:
  300. return createWindowImpl(Point(), SDL_WINDOW_FULLSCREEN_DESKTOP, false);
  301. case EWindowMode::WINDOWED:
  302. return createWindowImpl(dimensions, SDL_WINDOW_RESIZABLE, true);
  303. default:
  304. return nullptr;
  305. };
  306. #endif
  307. #ifdef VCMI_IOS
  308. SDL_SetHint(SDL_HINT_IOS_HIDE_HOME_INDICATOR, "1");
  309. SDL_SetHint(SDL_HINT_RETURN_KEY_HIDES_IME, "1");
  310. uint32_t windowFlags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI;
  311. SDL_Window * result = createWindowImpl(Point(), windowFlags | SDL_WINDOW_METAL, false);
  312. if(result != nullptr)
  313. return result;
  314. logGlobal->warn("Metal unavailable, using OpenGLES");
  315. return createWindowImpl(Point(), windowFlags, false);
  316. #endif
  317. #ifdef VCMI_ANDROID
  318. return createWindowImpl(Point(), SDL_WINDOW_FULLSCREEN, false);
  319. #endif
  320. }
  321. void ScreenHandler::onScreenResize()
  322. {
  323. recreateWindowAndScreenBuffers();
  324. }
  325. void ScreenHandler::validateSettings()
  326. {
  327. #ifndef VCMI_MOBILE
  328. {
  329. int displayIndex = settings["video"]["displayIndex"].Integer();
  330. int displaysCount = SDL_GetNumVideoDisplays();
  331. if (displayIndex >= displaysCount)
  332. {
  333. Settings writer = settings.write["video"]["displayIndex"];
  334. writer->Float() = 0;
  335. }
  336. }
  337. if (getPreferredWindowMode() == EWindowMode::WINDOWED)
  338. {
  339. //we only check that our desired window size fits on screen
  340. int displayIndex = getPreferredDisplayIndex();
  341. Point resolution = getPreferredWindowResolution();
  342. SDL_DisplayMode mode;
  343. if (SDL_GetDesktopDisplayMode(displayIndex, &mode) == 0)
  344. {
  345. if(resolution.x > mode.w || resolution.y > mode.h)
  346. {
  347. Settings writer = settings.write["video"]["resolution"];
  348. writer["width"].Float() = mode.w;
  349. writer["height"].Float() = mode.h;
  350. }
  351. }
  352. }
  353. if (getPreferredWindowMode() == EWindowMode::FULLSCREEN_EXCLUSIVE)
  354. {
  355. auto legalOptions = getSupportedResolutions();
  356. Point selectedResolution = getPreferredWindowResolution();
  357. if(!vstd::contains(legalOptions, selectedResolution))
  358. {
  359. // resolution selected for fullscreen mode is not supported by display
  360. // try to find current display resolution and use it instead as "reasonable default"
  361. SDL_DisplayMode mode;
  362. if (SDL_GetDesktopDisplayMode(getPreferredDisplayIndex(), &mode) == 0)
  363. {
  364. Settings writer = settings.write["video"]["resolution"];
  365. writer["width"].Float() = mode.w;
  366. writer["height"].Float() = mode.h;
  367. }
  368. }
  369. }
  370. #endif
  371. }
  372. int ScreenHandler::getPreferredRenderingDriver() const
  373. {
  374. int result = -1;
  375. const JsonNode & video = settings["video"];
  376. int driversCount = SDL_GetNumRenderDrivers();
  377. std::string preferredDriverName = video["driver"].String();
  378. logGlobal->info("Found %d render drivers", driversCount);
  379. for(int it = 0; it < driversCount; it++)
  380. {
  381. SDL_RendererInfo info;
  382. if (SDL_GetRenderDriverInfo(it, &info) == 0)
  383. {
  384. std::string driverName(info.name);
  385. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  386. {
  387. result = it;
  388. logGlobal->info("\t%s (active)", driverName);
  389. }
  390. else
  391. logGlobal->info("\t%s", driverName);
  392. }
  393. else
  394. logGlobal->info("\t(error)");
  395. }
  396. return result;
  397. }
  398. void ScreenHandler::destroyScreenBuffers()
  399. {
  400. // screenBuf is not a separate surface, but points to either screen or screen2 - just set to null
  401. screenBuf = nullptr;
  402. if(nullptr != screen2)
  403. {
  404. SDL_FreeSurface(screen2);
  405. screen2 = nullptr;
  406. }
  407. if(nullptr != screen)
  408. {
  409. SDL_FreeSurface(screen);
  410. screen = nullptr;
  411. }
  412. if(nullptr != screenTexture)
  413. {
  414. SDL_DestroyTexture(screenTexture);
  415. screenTexture = nullptr;
  416. }
  417. }
  418. void ScreenHandler::destroyWindow()
  419. {
  420. if(nullptr != mainRenderer)
  421. {
  422. SDL_DestroyRenderer(mainRenderer);
  423. mainRenderer = nullptr;
  424. }
  425. if(nullptr != mainWindow)
  426. {
  427. SDL_DestroyWindow(mainWindow);
  428. mainWindow = nullptr;
  429. }
  430. }
  431. void ScreenHandler::close()
  432. {
  433. if(settings["general"]["notifications"].Bool())
  434. NotificationHandler::destroy();
  435. destroyScreenBuffers();
  436. destroyWindow();
  437. SDL_Quit();
  438. }
  439. void ScreenHandler::clearScreen()
  440. {
  441. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  442. SDL_RenderClear(mainRenderer);
  443. SDL_RenderPresent(mainRenderer);
  444. }
  445. std::vector<Point> ScreenHandler::getSupportedResolutions() const
  446. {
  447. int displayID = getPreferredDisplayIndex();
  448. return getSupportedResolutions(displayID);
  449. }
  450. std::vector<Point> ScreenHandler::getSupportedResolutions( int displayIndex) const
  451. {
  452. //NOTE: this method is never called on Android/iOS, only on desktop systems
  453. std::vector<Point> result;
  454. int modesCount = SDL_GetNumDisplayModes(displayIndex);
  455. for (int i =0; i < modesCount; ++i)
  456. {
  457. SDL_DisplayMode mode;
  458. if (SDL_GetDisplayMode(displayIndex, i, &mode) == 0)
  459. {
  460. Point resolution(mode.w, mode.h);
  461. result.push_back(resolution);
  462. }
  463. }
  464. boost::range::sort(result, [](const auto & left, const auto & right)
  465. {
  466. return left.x * left.y < right.x * right.y;
  467. });
  468. // erase potential duplicates, e.g. resolutions with different framerate / bits per pixel
  469. result.erase(boost::unique(result).end(), result.end());
  470. return result;
  471. }
  472. bool ScreenHandler::hasFocus()
  473. {
  474. ui32 flags = SDL_GetWindowFlags(mainWindow);
  475. return flags & SDL_WINDOW_INPUT_FOCUS;
  476. }
  477. void ScreenHandler::getRenderScale(float & scaleX, float & scaleY)
  478. {
  479. SDL_RenderGetScale(mainRenderer, &scaleX, &scaleY);
  480. }