ScreenHandler.cpp 19 KB

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