ScreenHandler.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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 "../renderSDL/SDL_Extensions.h"
  20. #include "../../lib/CConfigHandler.h"
  21. #include "../../lib/constants/StringConstants.h"
  22. #ifdef VCMI_ANDROID
  23. #include "../lib/CAndroidVMHelper.h"
  24. #endif
  25. #ifdef VCMI_IOS
  26. # include "ios/utils.h"
  27. #endif
  28. #include <SDL.h>
  29. // TODO: should be made into a private members of ScreenHandler
  30. static SDL_Window * mainWindow = nullptr;
  31. SDL_Renderer * mainRenderer = nullptr;
  32. SDL_Texture * screenTexture = nullptr;
  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(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER))
  176. {
  177. logGlobal->error("Something was wrong: %s", SDL_GetError());
  178. exit(-1);
  179. }
  180. const auto & logCallback = [](void * userdata, int category, SDL_LogPriority priority, const char * message)
  181. {
  182. logGlobal->debug("SDL(category %d; priority %d) %s", category, priority, message);
  183. };
  184. SDL_LogSetOutputFunction(logCallback, nullptr);
  185. #ifdef VCMI_ANDROID
  186. // manually setting egl pixel format, as a possible solution for sdl2<->android problem
  187. // https://bugzilla.libsdl.org/show_bug.cgi?id=2291
  188. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
  189. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
  190. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
  191. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  192. #endif // VCMI_ANDROID
  193. validateSettings();
  194. recreateWindowAndScreenBuffers();
  195. }
  196. void ScreenHandler::recreateWindowAndScreenBuffers()
  197. {
  198. destroyScreenBuffers();
  199. if(mainWindow == nullptr)
  200. initializeWindow();
  201. else
  202. updateWindowState();
  203. initializeScreenBuffers();
  204. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  205. {
  206. NotificationHandler::init(mainWindow);
  207. }
  208. }
  209. void ScreenHandler::updateWindowState()
  210. {
  211. #ifndef VCMI_MOBILE
  212. int displayIndex = getPreferredDisplayIndex();
  213. switch(getPreferredWindowMode())
  214. {
  215. case EWindowMode::FULLSCREEN_EXCLUSIVE:
  216. {
  217. // for some reason, VCMI fails to switch from FULLSCREEN_BORDERLESS_WINDOWED to FULLSCREEN_EXCLUSIVE directly
  218. // Switch to windowed mode first to avoid this bug
  219. SDL_SetWindowFullscreen(mainWindow, 0);
  220. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN);
  221. SDL_DisplayMode mode;
  222. SDL_GetDesktopDisplayMode(displayIndex, &mode);
  223. Point resolution = getPreferredWindowResolution();
  224. mode.w = resolution.x;
  225. mode.h = resolution.y;
  226. SDL_SetWindowDisplayMode(mainWindow, &mode);
  227. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  228. return;
  229. }
  230. case EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED:
  231. {
  232. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
  233. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  234. return;
  235. }
  236. case EWindowMode::WINDOWED:
  237. {
  238. Point resolution = getPreferredWindowResolution();
  239. SDL_SetWindowFullscreen(mainWindow, 0);
  240. SDL_SetWindowSize(mainWindow, resolution.x, resolution.y);
  241. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex));
  242. return;
  243. }
  244. }
  245. #endif
  246. }
  247. void ScreenHandler::initializeWindow()
  248. {
  249. mainWindow = createWindow();
  250. if(mainWindow == nullptr)
  251. {
  252. const char * error = SDL_GetError();
  253. Point dimensions = getPreferredWindowResolution();
  254. std::string messagePattern = "Failed to create SDL Window of size %d x %d. Reason: %s";
  255. std::string message = boost::str(boost::format(messagePattern) % dimensions.x % dimensions.y % error);
  256. handleFatalError(message, true);
  257. }
  258. // create first available renderer if no preferred one is set
  259. // use no SDL_RENDERER_SOFTWARE or SDL_RENDERER_ACCELERATED flag, so HW accelerated will be preferred but SW renderer will also be possible
  260. uint32_t rendererFlags = 0;
  261. if(settings["video"]["vsync"].Bool())
  262. {
  263. rendererFlags |= SDL_RENDERER_PRESENTVSYNC;
  264. }
  265. mainRenderer = SDL_CreateRenderer(mainWindow, getPreferredRenderingDriver(), rendererFlags);
  266. if(mainRenderer == nullptr)
  267. {
  268. const char * error = SDL_GetError();
  269. std::string messagePattern = "Failed to create SDL renderer. Reason: %s";
  270. std::string message = boost::str(boost::format(messagePattern) % error);
  271. handleFatalError(message, true);
  272. }
  273. selectUpscalingFilter();
  274. selectDownscalingFilter();
  275. SDL_RendererInfo info;
  276. SDL_GetRendererInfo(mainRenderer, &info);
  277. logGlobal->info("Created renderer %s", info.name);
  278. }
  279. EUpscalingFilter ScreenHandler::loadUpscalingFilter() const
  280. {
  281. static const std::map<std::string, EUpscalingFilter> upscalingFilterTypes =
  282. {
  283. {"auto", EUpscalingFilter::AUTO },
  284. {"none", EUpscalingFilter::NONE },
  285. {"xbrz2", EUpscalingFilter::XBRZ_2 },
  286. {"xbrz3", EUpscalingFilter::XBRZ_3 },
  287. {"xbrz4", EUpscalingFilter::XBRZ_4 }
  288. };
  289. auto filterName = settings["video"]["upscalingFilter"].String();
  290. auto filter = upscalingFilterTypes.count(filterName) ? upscalingFilterTypes.at(filterName) : EUpscalingFilter::AUTO;
  291. if (filter != EUpscalingFilter::AUTO)
  292. return filter;
  293. // else - autoselect
  294. #ifdef VCMI_MOBILE
  295. // to help with performance - only if player explicitly enabled xbrz
  296. return EUpscalingFilter::NONE;
  297. #else
  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. if (scaling <= 1.001f)
  304. return EUpscalingFilter::NONE; // running at original resolution or even lower than that - no need for xbrz
  305. else
  306. return EUpscalingFilter::XBRZ_2;
  307. #endif
  308. #if 0
  309. // Old version, most optimal, but rather performance-heavy
  310. if (scaling <= 1.001f)
  311. return EUpscalingFilter::NONE; // running at original resolution or even lower than that - no need for xbrz
  312. if (scaling <= 2.001f)
  313. return EUpscalingFilter::XBRZ_2; // resolutions below 1200p (including 1080p / FullHD)
  314. if (scaling <= 3.001f)
  315. return EUpscalingFilter::XBRZ_3; // resolutions below 2400p (including 1440p and 2160p / 4K)
  316. return EUpscalingFilter::XBRZ_4; // Only for massive displays, e.g. 8K
  317. #endif
  318. }
  319. void ScreenHandler::selectUpscalingFilter()
  320. {
  321. upscalingFilter = loadUpscalingFilter();
  322. logGlobal->debug("Selected upscaling filter %d", static_cast<int>(upscalingFilter));
  323. }
  324. void ScreenHandler::selectDownscalingFilter()
  325. {
  326. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, settings["video"]["downscalingFilter"].String().c_str());
  327. logGlobal->debug("Selected downscaling filter %s", settings["video"]["downscalingFilter"].String());
  328. }
  329. void ScreenHandler::initializeScreenBuffers()
  330. {
  331. #ifdef VCMI_ENDIAN_BIG
  332. int bmask = 0xff000000;
  333. int gmask = 0x00ff0000;
  334. int rmask = 0x0000ff00;
  335. int amask = 0x000000ff;
  336. #else
  337. int bmask = 0x000000ff;
  338. int gmask = 0x0000ff00;
  339. int rmask = 0x00ff0000;
  340. int amask = 0xFF000000;
  341. #endif
  342. auto logicalSize = getPreferredLogicalResolution() * getScalingFactor();
  343. SDL_RenderSetLogicalSize(mainRenderer, logicalSize.x, logicalSize.y);
  344. screen = SDL_CreateRGBSurface(0, logicalSize.x, logicalSize.y, 32, rmask, gmask, bmask, amask);
  345. if(nullptr == screen)
  346. {
  347. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", logicalSize.x, logicalSize.y, 32, SDL_GetError());
  348. throw std::runtime_error("Unable to create surface");
  349. }
  350. //No blending for screen itself. Required for proper cursor rendering.
  351. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  352. screenTexture = SDL_CreateTexture(mainRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, logicalSize.x, logicalSize.y);
  353. if(nullptr == screenTexture)
  354. {
  355. logGlobal->error("Unable to create screen texture");
  356. logGlobal->error(SDL_GetError());
  357. throw std::runtime_error("Unable to create screen texture");
  358. }
  359. clearScreen();
  360. }
  361. SDL_Window * ScreenHandler::createWindowImpl(Point dimensions, int flags, bool center)
  362. {
  363. int displayIndex = getPreferredDisplayIndex();
  364. int positionFlags = center ? SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex) : SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex);
  365. return SDL_CreateWindow(NAME.c_str(), positionFlags, positionFlags, dimensions.x, dimensions.y, flags);
  366. }
  367. SDL_Window * ScreenHandler::createWindow()
  368. {
  369. #ifndef VCMI_MOBILE
  370. Point dimensions = getPreferredWindowResolution();
  371. switch(getPreferredWindowMode())
  372. {
  373. case EWindowMode::FULLSCREEN_EXCLUSIVE:
  374. return createWindowImpl(dimensions, SDL_WINDOW_FULLSCREEN, false);
  375. case EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED:
  376. return createWindowImpl(Point(), SDL_WINDOW_FULLSCREEN_DESKTOP, false);
  377. case EWindowMode::WINDOWED:
  378. return createWindowImpl(dimensions, SDL_WINDOW_RESIZABLE, true);
  379. default:
  380. return nullptr;
  381. };
  382. #endif
  383. #ifdef VCMI_IOS
  384. SDL_SetHint(SDL_HINT_IOS_HIDE_HOME_INDICATOR, "1");
  385. SDL_SetHint(SDL_HINT_RETURN_KEY_HIDES_IME, "1");
  386. uint32_t windowFlags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI;
  387. SDL_Window * result = createWindowImpl(Point(), windowFlags | SDL_WINDOW_METAL, false);
  388. if(result != nullptr)
  389. return result;
  390. logGlobal->warn("Metal unavailable, using OpenGLES");
  391. return createWindowImpl(Point(), windowFlags, false);
  392. #endif
  393. #ifdef VCMI_ANDROID
  394. return createWindowImpl(Point(), SDL_WINDOW_FULLSCREEN, false);
  395. #endif
  396. }
  397. void ScreenHandler::onScreenResize()
  398. {
  399. recreateWindowAndScreenBuffers();
  400. }
  401. void ScreenHandler::validateSettings()
  402. {
  403. #ifndef VCMI_MOBILE
  404. {
  405. int displayIndex = settings["video"]["displayIndex"].Integer();
  406. int displaysCount = SDL_GetNumVideoDisplays();
  407. if (displayIndex >= displaysCount)
  408. {
  409. Settings writer = settings.write["video"]["displayIndex"];
  410. writer->Float() = 0;
  411. }
  412. }
  413. if (getPreferredWindowMode() == EWindowMode::WINDOWED)
  414. {
  415. //we only check that our desired window size fits on screen
  416. int displayIndex = getPreferredDisplayIndex();
  417. Point resolution = getPreferredWindowResolution();
  418. SDL_DisplayMode mode;
  419. if (SDL_GetDesktopDisplayMode(displayIndex, &mode) == 0)
  420. {
  421. if(resolution.x > mode.w || resolution.y > mode.h)
  422. {
  423. Settings writer = settings.write["video"]["resolution"];
  424. writer["width"].Float() = mode.w;
  425. writer["height"].Float() = mode.h;
  426. }
  427. }
  428. }
  429. if (getPreferredWindowMode() == EWindowMode::FULLSCREEN_EXCLUSIVE)
  430. {
  431. auto legalOptions = getSupportedResolutions();
  432. Point selectedResolution = getPreferredWindowResolution();
  433. if(!vstd::contains(legalOptions, selectedResolution))
  434. {
  435. // resolution selected for fullscreen mode is not supported by display
  436. // try to find current display resolution and use it instead as "reasonable default"
  437. SDL_DisplayMode mode;
  438. if (SDL_GetDesktopDisplayMode(getPreferredDisplayIndex(), &mode) == 0)
  439. {
  440. Settings writer = settings.write["video"]["resolution"];
  441. writer["width"].Float() = mode.w;
  442. writer["height"].Float() = mode.h;
  443. }
  444. }
  445. }
  446. #endif
  447. }
  448. int ScreenHandler::getPreferredRenderingDriver() const
  449. {
  450. int result = -1;
  451. const JsonNode & video = settings["video"];
  452. int driversCount = SDL_GetNumRenderDrivers();
  453. std::string preferredDriverName = video["driver"].String();
  454. logGlobal->info("Found %d render drivers", driversCount);
  455. for(int it = 0; it < driversCount; it++)
  456. {
  457. SDL_RendererInfo info;
  458. if (SDL_GetRenderDriverInfo(it, &info) == 0)
  459. {
  460. std::string driverName(info.name);
  461. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  462. {
  463. result = it;
  464. logGlobal->info("\t%s (active)", driverName);
  465. }
  466. else
  467. logGlobal->info("\t%s", driverName);
  468. }
  469. else
  470. logGlobal->info("\t(error)");
  471. }
  472. return result;
  473. }
  474. void ScreenHandler::destroyScreenBuffers()
  475. {
  476. if(nullptr != screen)
  477. {
  478. SDL_FreeSurface(screen);
  479. screen = nullptr;
  480. }
  481. if(nullptr != screenTexture)
  482. {
  483. SDL_DestroyTexture(screenTexture);
  484. screenTexture = nullptr;
  485. }
  486. }
  487. void ScreenHandler::destroyWindow()
  488. {
  489. if(nullptr != mainRenderer)
  490. {
  491. SDL_DestroyRenderer(mainRenderer);
  492. mainRenderer = nullptr;
  493. }
  494. if(nullptr != mainWindow)
  495. {
  496. SDL_DestroyWindow(mainWindow);
  497. mainWindow = nullptr;
  498. }
  499. }
  500. void ScreenHandler::close()
  501. {
  502. if(settings["general"]["notifications"].Bool())
  503. NotificationHandler::destroy();
  504. destroyScreenBuffers();
  505. destroyWindow();
  506. SDL_Quit();
  507. }
  508. void ScreenHandler::clearScreen()
  509. {
  510. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  511. SDL_RenderClear(mainRenderer);
  512. SDL_RenderPresent(mainRenderer);
  513. }
  514. Canvas ScreenHandler::getScreenCanvas() const
  515. {
  516. return Canvas::createFromSurface(screen, CanvasScalingPolicy::AUTO);
  517. }
  518. void ScreenHandler::updateScreenTexture()
  519. {
  520. SDL_UpdateTexture(screenTexture, nullptr, screen->pixels, screen->pitch);
  521. }
  522. void ScreenHandler::presetScreenTexture()
  523. {
  524. SDL_RenderClear(mainRenderer);
  525. SDL_RenderCopy(mainRenderer, screenTexture, nullptr, nullptr);
  526. CCS->curh->render();
  527. SDL_RenderPresent(mainRenderer);
  528. }
  529. std::vector<Point> ScreenHandler::getSupportedResolutions() const
  530. {
  531. int displayID = getPreferredDisplayIndex();
  532. return getSupportedResolutions(displayID);
  533. }
  534. std::vector<Point> ScreenHandler::getSupportedResolutions( int displayIndex) const
  535. {
  536. //NOTE: this method is never called on Android/iOS, only on desktop systems
  537. std::vector<Point> result;
  538. int modesCount = SDL_GetNumDisplayModes(displayIndex);
  539. for (int i =0; i < modesCount; ++i)
  540. {
  541. SDL_DisplayMode mode;
  542. if (SDL_GetDisplayMode(displayIndex, i, &mode) == 0)
  543. {
  544. Point resolution(mode.w, mode.h);
  545. result.push_back(resolution);
  546. }
  547. }
  548. boost::range::sort(result, [](const auto & left, const auto & right)
  549. {
  550. return left.x * left.y < right.x * right.y;
  551. });
  552. // erase potential duplicates, e.g. resolutions with different framerate / bits per pixel
  553. result.erase(boost::unique(result).end(), result.end());
  554. return result;
  555. }
  556. bool ScreenHandler::hasFocus()
  557. {
  558. ui32 flags = SDL_GetWindowFlags(mainWindow);
  559. return flags & SDL_WINDOW_INPUT_FOCUS;
  560. }