2
0

ScreenHandler.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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 "../eventsSDL/NotificationHandler.h"
  13. #include "../gui/CGuiHandler.h"
  14. #include "../gui/WindowHandler.h"
  15. #include "../renderSDL/SDL_Extensions.h"
  16. #include "CMT.h"
  17. #include "../../lib/CConfigHandler.h"
  18. #include "../../lib/constants/StringConstants.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 = GameConstants::VCMI_VERSION; //application name
  34. static constexpr Point heroes3Resolution = Point(800, 600);
  35. std::tuple<int, int> ScreenHandler::getSupportedScalingRange() const
  36. {
  37. // H3 resolution, any resolution smaller than that is not correctly supported
  38. static constexpr Point minResolution = heroes3Resolution;
  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 constexpr 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. int ScreenHandler::getInterfaceScalingPercentage() const
  70. {
  71. auto [minimalScaling, maximalScaling] = getSupportedScalingRange();
  72. int userScaling = settings["video"]["resolution"]["scaling"].Integer();
  73. if (userScaling == 0) // autodetection
  74. {
  75. #ifdef VCMI_MOBILE
  76. // for mobiles - stay at maximum scaling unless we have large screen
  77. // might be better to check screen DPI / physical dimensions, but way more complex, and may result in different edge cases, e.g. chromebooks / tv's
  78. int preferredMinimalScaling = 200;
  79. #else
  80. // for PC - avoid downscaling if possible
  81. int preferredMinimalScaling = 100;
  82. #endif
  83. // prefer a little below maximum - to give space for extended UI
  84. int preferredMaximalScaling = maximalScaling * 10 / 12;
  85. userScaling = std::max(std::min(maximalScaling, preferredMinimalScaling), preferredMaximalScaling);
  86. }
  87. int scaling = std::clamp(userScaling, minimalScaling, maximalScaling);
  88. return scaling;
  89. }
  90. Point ScreenHandler::getPreferredLogicalResolution() const
  91. {
  92. Point renderResolution = getRenderResolution();
  93. double reservedAreaWidth = settings["video"]["reservedWidth"].Float();
  94. int scaling = getInterfaceScalingPercentage();
  95. Point availableResolution = Point(renderResolution.x * (1 - reservedAreaWidth), renderResolution.y);
  96. Point logicalResolution = availableResolution * 100.0 / scaling;
  97. return logicalResolution;
  98. }
  99. int ScreenHandler::getScalingFactor() const
  100. {
  101. switch (upscalingFilter)
  102. {
  103. case EUpscalingFilter::NONE: return 1;
  104. case EUpscalingFilter::XBRZ_2: return 2;
  105. case EUpscalingFilter::XBRZ_3: return 3;
  106. case EUpscalingFilter::XBRZ_4: return 4;
  107. }
  108. throw std::runtime_error("invalid upscaling filter");
  109. }
  110. Point ScreenHandler::getLogicalResolution() const
  111. {
  112. return Point(screen->w, screen->h) / getScalingFactor();
  113. }
  114. Point ScreenHandler::getRenderResolution() const
  115. {
  116. assert(mainRenderer != nullptr);
  117. Point result;
  118. SDL_GetRendererOutputSize(mainRenderer, &result.x, &result.y);
  119. return result;
  120. }
  121. Point ScreenHandler::getPreferredWindowResolution() const
  122. {
  123. if (getPreferredWindowMode() == EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED)
  124. {
  125. SDL_Rect bounds;
  126. if (SDL_GetDisplayBounds(getPreferredDisplayIndex(), &bounds) == 0)
  127. return Point(bounds.w, bounds.h);
  128. }
  129. const JsonNode & video = settings["video"];
  130. int width = video["resolution"]["width"].Integer();
  131. int height = video["resolution"]["height"].Integer();
  132. return Point(width, height);
  133. }
  134. int ScreenHandler::getPreferredDisplayIndex() const
  135. {
  136. #ifdef VCMI_MOBILE
  137. // Assuming no multiple screens on Android / ios?
  138. return 0;
  139. #else
  140. if (mainWindow != nullptr)
  141. {
  142. int result = SDL_GetWindowDisplayIndex(mainWindow);
  143. if (result >= 0)
  144. return result;
  145. }
  146. return settings["video"]["displayIndex"].Integer();
  147. #endif
  148. }
  149. EWindowMode ScreenHandler::getPreferredWindowMode() const
  150. {
  151. #ifdef VCMI_MOBILE
  152. // On Android / ios game will always render to screen size
  153. return EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED;
  154. #else
  155. const JsonNode & video = settings["video"];
  156. bool fullscreen = video["fullscreen"].Bool();
  157. bool realFullscreen = settings["video"]["realFullscreen"].Bool();
  158. if (!fullscreen)
  159. return EWindowMode::WINDOWED;
  160. if (realFullscreen)
  161. return EWindowMode::FULLSCREEN_EXCLUSIVE;
  162. else
  163. return EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED;
  164. #endif
  165. }
  166. ScreenHandler::ScreenHandler()
  167. {
  168. #ifdef VCMI_WINDOWS
  169. // set VCMI as "per-monitor DPI awareness". This completely disables any DPI-scaling by system.
  170. // Might not be the best solution since VCMI can't automatically adjust to DPI changes (including moving to monitors with different DPI scaling)
  171. // However this fixed unintuitive bug where player selects specific resolution for windowed mode, but ends up with completely different one due to scaling
  172. // NOTE: requires SDL 2.24.
  173. SDL_SetHint(SDL_HINT_WINDOWS_DPI_AWARENESS, "permonitor");
  174. #endif
  175. if(settings["video"]["allowPortrait"].Bool())
  176. SDL_SetHint(SDL_HINT_ORIENTATIONS, "Portrait PortraitUpsideDown LandscapeLeft LandscapeRight");
  177. else
  178. SDL_SetHint(SDL_HINT_ORIENTATIONS, "LandscapeLeft LandscapeRight");
  179. if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER))
  180. {
  181. logGlobal->error("Something was wrong: %s", SDL_GetError());
  182. exit(-1);
  183. }
  184. const auto & logCallback = [](void * userdata, int category, SDL_LogPriority priority, const char * message)
  185. {
  186. logGlobal->debug("SDL(category %d; priority %d) %s", category, priority, message);
  187. };
  188. SDL_LogSetOutputFunction(logCallback, nullptr);
  189. #ifdef VCMI_ANDROID
  190. // manually setting egl pixel format, as a possible solution for sdl2<->android problem
  191. // https://bugzilla.libsdl.org/show_bug.cgi?id=2291
  192. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
  193. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
  194. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
  195. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  196. #endif // VCMI_ANDROID
  197. validateSettings();
  198. recreateWindowAndScreenBuffers();
  199. }
  200. void ScreenHandler::recreateWindowAndScreenBuffers()
  201. {
  202. destroyScreenBuffers();
  203. if(mainWindow == nullptr)
  204. initializeWindow();
  205. else
  206. updateWindowState();
  207. initializeScreenBuffers();
  208. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  209. {
  210. NotificationHandler::init(mainWindow);
  211. }
  212. }
  213. void ScreenHandler::updateWindowState()
  214. {
  215. #ifndef VCMI_MOBILE
  216. int displayIndex = getPreferredDisplayIndex();
  217. switch(getPreferredWindowMode())
  218. {
  219. case EWindowMode::FULLSCREEN_EXCLUSIVE:
  220. {
  221. // for some reason, VCMI fails to switch from FULLSCREEN_BORDERLESS_WINDOWED to FULLSCREEN_EXCLUSIVE directly
  222. // Switch to windowed mode first to avoid this bug
  223. SDL_SetWindowFullscreen(mainWindow, 0);
  224. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN);
  225. SDL_DisplayMode mode;
  226. SDL_GetDesktopDisplayMode(displayIndex, &mode);
  227. Point resolution = getPreferredWindowResolution();
  228. mode.w = resolution.x;
  229. mode.h = resolution.y;
  230. SDL_SetWindowDisplayMode(mainWindow, &mode);
  231. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  232. return;
  233. }
  234. case EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED:
  235. {
  236. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
  237. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  238. return;
  239. }
  240. case EWindowMode::WINDOWED:
  241. {
  242. Point resolution = getPreferredWindowResolution();
  243. SDL_SetWindowFullscreen(mainWindow, 0);
  244. SDL_SetWindowSize(mainWindow, resolution.x, resolution.y);
  245. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex));
  246. return;
  247. }
  248. }
  249. #endif
  250. }
  251. void ScreenHandler::initializeWindow()
  252. {
  253. mainWindow = createWindow();
  254. if(mainWindow == nullptr)
  255. {
  256. const char * error = SDL_GetError();
  257. Point dimensions = getPreferredWindowResolution();
  258. std::string messagePattern = "Failed to create SDL Window of size %d x %d. Reason: %s";
  259. std::string message = boost::str(boost::format(messagePattern) % dimensions.x % dimensions.y % error);
  260. handleFatalError(message, true);
  261. }
  262. // create first available renderer if no preferred one is set
  263. // use no SDL_RENDERER_SOFTWARE or SDL_RENDERER_ACCELERATED flag, so HW accelerated will be preferred but SW renderer will also be possible
  264. uint32_t rendererFlags = 0;
  265. if(settings["video"]["vsync"].Bool())
  266. {
  267. rendererFlags |= SDL_RENDERER_PRESENTVSYNC;
  268. }
  269. mainRenderer = SDL_CreateRenderer(mainWindow, getPreferredRenderingDriver(), rendererFlags);
  270. if(mainRenderer == nullptr)
  271. {
  272. const char * error = SDL_GetError();
  273. std::string messagePattern = "Failed to create SDL renderer. Reason: %s";
  274. std::string message = boost::str(boost::format(messagePattern) % error);
  275. handleFatalError(message, true);
  276. }
  277. selectUpscalingFilter();
  278. selectDownscalingFilter();
  279. SDL_RendererInfo info;
  280. SDL_GetRendererInfo(mainRenderer, &info);
  281. logGlobal->info("Created renderer %s", info.name);
  282. }
  283. EUpscalingFilter ScreenHandler::loadUpscalingFilter() const
  284. {
  285. static const std::map<std::string, EUpscalingFilter> upscalingFilterTypes =
  286. {
  287. {"auto", EUpscalingFilter::AUTO },
  288. {"none", EUpscalingFilter::NONE },
  289. {"xbrz2", EUpscalingFilter::XBRZ_2 },
  290. {"xbrz3", EUpscalingFilter::XBRZ_3 },
  291. {"xbrz4", EUpscalingFilter::XBRZ_4 }
  292. };
  293. auto filterName = settings["video"]["upscalingFilter"].String();
  294. auto filter = upscalingFilterTypes.count(filterName) ? upscalingFilterTypes.at(filterName) : EUpscalingFilter::AUTO;
  295. if (filter != EUpscalingFilter::AUTO)
  296. return filter;
  297. // else - autoselect
  298. Point outputResolution = getRenderResolution();
  299. Point logicalResolution = getPreferredLogicalResolution();
  300. float scaleX = static_cast<float>(outputResolution.x) / logicalResolution.x;
  301. float scaleY = static_cast<float>(outputResolution.x) / logicalResolution.x;
  302. float scaling = std::min(scaleX, scaleY);
  303. int systemMemoryMb = SDL_GetSystemRAM();
  304. if (scaling <= 1.001f)
  305. return EUpscalingFilter::NONE; // running at original resolution or even lower than that - no need for xbrz
  306. if (systemMemoryMb < 2048)
  307. return EUpscalingFilter::NONE; // xbrz2 may use ~1.0 - 1.5 Gb of RAM and has notable CPU cost - avoid on low-spec hardware
  308. // Only using xbrz2 for autoselection.
  309. // Higher options may have high system requirements and should be only selected explicitly by player
  310. return EUpscalingFilter::XBRZ_2;
  311. }
  312. void ScreenHandler::selectUpscalingFilter()
  313. {
  314. upscalingFilter = loadUpscalingFilter();
  315. logGlobal->debug("Selected upscaling filter %d", static_cast<int>(upscalingFilter));
  316. }
  317. void ScreenHandler::selectDownscalingFilter()
  318. {
  319. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, settings["video"]["downscalingFilter"].String().c_str());
  320. logGlobal->debug("Selected downscaling filter %s", settings["video"]["downscalingFilter"].String());
  321. }
  322. void ScreenHandler::initializeScreenBuffers()
  323. {
  324. #ifdef VCMI_ENDIAN_BIG
  325. int bmask = 0xff000000;
  326. int gmask = 0x00ff0000;
  327. int rmask = 0x0000ff00;
  328. int amask = 0x000000ff;
  329. #else
  330. int bmask = 0x000000ff;
  331. int gmask = 0x0000ff00;
  332. int rmask = 0x00ff0000;
  333. int amask = 0xFF000000;
  334. #endif
  335. auto logicalSize = getPreferredLogicalResolution() * getScalingFactor();
  336. SDL_RenderSetLogicalSize(mainRenderer, logicalSize.x, logicalSize.y);
  337. screen = SDL_CreateRGBSurface(0, logicalSize.x, logicalSize.y, 32, rmask, gmask, bmask, amask);
  338. if(nullptr == screen)
  339. {
  340. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", logicalSize.x, logicalSize.y, 32, SDL_GetError());
  341. throw std::runtime_error("Unable to create surface");
  342. }
  343. //No blending for screen itself. Required for proper cursor rendering.
  344. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  345. screenTexture = SDL_CreateTexture(mainRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, logicalSize.x, logicalSize.y);
  346. if(nullptr == screenTexture)
  347. {
  348. logGlobal->error("Unable to create screen texture");
  349. logGlobal->error(SDL_GetError());
  350. throw std::runtime_error("Unable to create screen texture");
  351. }
  352. screen2 = CSDL_Ext::copySurface(screen);
  353. if(nullptr == screen2)
  354. {
  355. throw std::runtime_error("Unable to copy surface\n");
  356. }
  357. if (GH.windows().count() > 1)
  358. screenBuf = screen2;
  359. else
  360. screenBuf = screen;
  361. clearScreen();
  362. }
  363. SDL_Window * ScreenHandler::createWindowImpl(Point dimensions, int flags, bool center)
  364. {
  365. int displayIndex = getPreferredDisplayIndex();
  366. int positionFlags = center ? SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex) : SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex);
  367. return SDL_CreateWindow(NAME.c_str(), positionFlags, positionFlags, dimensions.x, dimensions.y, flags);
  368. }
  369. SDL_Window * ScreenHandler::createWindow()
  370. {
  371. #ifndef VCMI_MOBILE
  372. Point dimensions = getPreferredWindowResolution();
  373. switch(getPreferredWindowMode())
  374. {
  375. case EWindowMode::FULLSCREEN_EXCLUSIVE:
  376. return createWindowImpl(dimensions, SDL_WINDOW_FULLSCREEN, false);
  377. case EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED:
  378. return createWindowImpl(Point(), SDL_WINDOW_FULLSCREEN_DESKTOP, false);
  379. case EWindowMode::WINDOWED:
  380. return createWindowImpl(dimensions, SDL_WINDOW_RESIZABLE, true);
  381. default:
  382. return nullptr;
  383. };
  384. #endif
  385. #ifdef VCMI_IOS
  386. SDL_SetHint(SDL_HINT_IOS_HIDE_HOME_INDICATOR, "1");
  387. SDL_SetHint(SDL_HINT_RETURN_KEY_HIDES_IME, "1");
  388. uint32_t windowFlags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI;
  389. SDL_Window * result = createWindowImpl(Point(), windowFlags | SDL_WINDOW_METAL, false);
  390. if(result != nullptr)
  391. return result;
  392. logGlobal->warn("Metal unavailable, using OpenGLES");
  393. return createWindowImpl(Point(), windowFlags, false);
  394. #endif
  395. #ifdef VCMI_ANDROID
  396. return createWindowImpl(Point(), SDL_WINDOW_RESIZABLE, false);
  397. #endif
  398. }
  399. void ScreenHandler::onScreenResize()
  400. {
  401. recreateWindowAndScreenBuffers();
  402. }
  403. void ScreenHandler::validateSettings()
  404. {
  405. #ifndef VCMI_MOBILE
  406. {
  407. int displayIndex = settings["video"]["displayIndex"].Integer();
  408. int displaysCount = SDL_GetNumVideoDisplays();
  409. if (displayIndex >= displaysCount)
  410. {
  411. Settings writer = settings.write["video"]["displayIndex"];
  412. writer->Float() = 0;
  413. }
  414. }
  415. if (getPreferredWindowMode() == EWindowMode::WINDOWED)
  416. {
  417. //we only check that our desired window size fits on screen
  418. int displayIndex = getPreferredDisplayIndex();
  419. Point resolution = getPreferredWindowResolution();
  420. SDL_DisplayMode mode;
  421. if (SDL_GetDesktopDisplayMode(displayIndex, &mode) == 0)
  422. {
  423. if(resolution.x > mode.w || resolution.y > mode.h)
  424. {
  425. Settings writer = settings.write["video"]["resolution"];
  426. writer["width"].Float() = mode.w;
  427. writer["height"].Float() = mode.h;
  428. }
  429. }
  430. }
  431. if (getPreferredWindowMode() == EWindowMode::FULLSCREEN_EXCLUSIVE)
  432. {
  433. auto legalOptions = getSupportedResolutions();
  434. Point selectedResolution = getPreferredWindowResolution();
  435. if(!vstd::contains(legalOptions, selectedResolution))
  436. {
  437. // resolution selected for fullscreen mode is not supported by display
  438. // try to find current display resolution and use it instead as "reasonable default"
  439. SDL_DisplayMode mode;
  440. if (SDL_GetDesktopDisplayMode(getPreferredDisplayIndex(), &mode) == 0)
  441. {
  442. Settings writer = settings.write["video"]["resolution"];
  443. writer["width"].Float() = mode.w;
  444. writer["height"].Float() = mode.h;
  445. }
  446. }
  447. }
  448. #endif
  449. }
  450. int ScreenHandler::getPreferredRenderingDriver() const
  451. {
  452. int result = -1;
  453. const JsonNode & video = settings["video"];
  454. int driversCount = SDL_GetNumRenderDrivers();
  455. std::string preferredDriverName = video["driver"].String();
  456. logGlobal->info("Found %d render drivers", driversCount);
  457. for(int it = 0; it < driversCount; it++)
  458. {
  459. SDL_RendererInfo info;
  460. if (SDL_GetRenderDriverInfo(it, &info) == 0)
  461. {
  462. std::string driverName(info.name);
  463. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  464. {
  465. result = it;
  466. logGlobal->info("\t%s (active)", driverName);
  467. }
  468. else
  469. logGlobal->info("\t%s", driverName);
  470. }
  471. else
  472. logGlobal->info("\t(error)");
  473. }
  474. return result;
  475. }
  476. void ScreenHandler::destroyScreenBuffers()
  477. {
  478. // screenBuf is not a separate surface, but points to either screen or screen2 - just set to null
  479. screenBuf = nullptr;
  480. if(nullptr != screen2)
  481. {
  482. SDL_FreeSurface(screen2);
  483. screen2 = nullptr;
  484. }
  485. if(nullptr != screen)
  486. {
  487. SDL_FreeSurface(screen);
  488. screen = nullptr;
  489. }
  490. if(nullptr != screenTexture)
  491. {
  492. SDL_DestroyTexture(screenTexture);
  493. screenTexture = nullptr;
  494. }
  495. }
  496. void ScreenHandler::destroyWindow()
  497. {
  498. if(nullptr != mainRenderer)
  499. {
  500. SDL_DestroyRenderer(mainRenderer);
  501. mainRenderer = nullptr;
  502. }
  503. if(nullptr != mainWindow)
  504. {
  505. SDL_DestroyWindow(mainWindow);
  506. mainWindow = nullptr;
  507. }
  508. }
  509. void ScreenHandler::close()
  510. {
  511. if(settings["general"]["notifications"].Bool())
  512. NotificationHandler::destroy();
  513. destroyScreenBuffers();
  514. destroyWindow();
  515. SDL_Quit();
  516. }
  517. void ScreenHandler::clearScreen()
  518. {
  519. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  520. SDL_RenderClear(mainRenderer);
  521. SDL_RenderPresent(mainRenderer);
  522. }
  523. std::vector<Point> ScreenHandler::getSupportedResolutions() const
  524. {
  525. int displayID = getPreferredDisplayIndex();
  526. return getSupportedResolutions(displayID);
  527. }
  528. std::vector<Point> ScreenHandler::getSupportedResolutions( int displayIndex) const
  529. {
  530. //NOTE: this method is never called on Android/iOS, only on desktop systems
  531. std::vector<Point> result;
  532. int modesCount = SDL_GetNumDisplayModes(displayIndex);
  533. for (int i =0; i < modesCount; ++i)
  534. {
  535. SDL_DisplayMode mode;
  536. if (SDL_GetDisplayMode(displayIndex, i, &mode) == 0)
  537. {
  538. Point resolution(mode.w, mode.h);
  539. result.push_back(resolution);
  540. }
  541. }
  542. boost::range::sort(result, [](const auto & left, const auto & right)
  543. {
  544. return left.x * left.y < right.x * right.y;
  545. });
  546. // erase potential duplicates, e.g. resolutions with different framerate / bits per pixel
  547. result.erase(boost::unique(result).end(), result.end());
  548. return result;
  549. }
  550. bool ScreenHandler::hasFocus()
  551. {
  552. ui32 flags = SDL_GetWindowFlags(mainWindow);
  553. return flags & SDL_WINDOW_INPUT_FOCUS;
  554. }