ScreenHandler.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. #ifdef VCMI_MOBILE
  299. // to help with performance - only if player explicitly enabled xbrz
  300. return EUpscalingFilter::NONE;
  301. #else
  302. Point outputResolution = getRenderResolution();
  303. Point logicalResolution = getPreferredLogicalResolution();
  304. float scaleX = static_cast<float>(outputResolution.x) / logicalResolution.x;
  305. float scaleY = static_cast<float>(outputResolution.x) / logicalResolution.x;
  306. float scaling = std::min(scaleX, scaleY);
  307. if (scaling <= 1.001f)
  308. return EUpscalingFilter::NONE; // running at original resolution or even lower than that - no need for xbrz
  309. else
  310. return EUpscalingFilter::XBRZ_2;
  311. #endif
  312. #if 0
  313. // Old version, most optimal, but rather performance-heavy
  314. if (scaling <= 1.001f)
  315. return EUpscalingFilter::NONE; // running at original resolution or even lower than that - no need for xbrz
  316. if (scaling <= 2.001f)
  317. return EUpscalingFilter::XBRZ_2; // resolutions below 1200p (including 1080p / FullHD)
  318. if (scaling <= 3.001f)
  319. return EUpscalingFilter::XBRZ_3; // resolutions below 2400p (including 1440p and 2160p / 4K)
  320. return EUpscalingFilter::XBRZ_4; // Only for massive displays, e.g. 8K
  321. #endif
  322. }
  323. void ScreenHandler::selectUpscalingFilter()
  324. {
  325. upscalingFilter = loadUpscalingFilter();
  326. logGlobal->debug("Selected upscaling filter %d", static_cast<int>(upscalingFilter));
  327. }
  328. void ScreenHandler::selectDownscalingFilter()
  329. {
  330. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, settings["video"]["downscalingFilter"].String().c_str());
  331. logGlobal->debug("Selected downscaling filter %s", settings["video"]["downscalingFilter"].String());
  332. }
  333. void ScreenHandler::initializeScreenBuffers()
  334. {
  335. #ifdef VCMI_ENDIAN_BIG
  336. int bmask = 0xff000000;
  337. int gmask = 0x00ff0000;
  338. int rmask = 0x0000ff00;
  339. int amask = 0x000000ff;
  340. #else
  341. int bmask = 0x000000ff;
  342. int gmask = 0x0000ff00;
  343. int rmask = 0x00ff0000;
  344. int amask = 0xFF000000;
  345. #endif
  346. auto logicalSize = getPreferredLogicalResolution() * getScalingFactor();
  347. SDL_RenderSetLogicalSize(mainRenderer, logicalSize.x, logicalSize.y);
  348. screen = SDL_CreateRGBSurface(0, logicalSize.x, logicalSize.y, 32, rmask, gmask, bmask, amask);
  349. if(nullptr == screen)
  350. {
  351. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", logicalSize.x, logicalSize.y, 32, SDL_GetError());
  352. throw std::runtime_error("Unable to create surface");
  353. }
  354. //No blending for screen itself. Required for proper cursor rendering.
  355. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  356. screenTexture = SDL_CreateTexture(mainRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, logicalSize.x, logicalSize.y);
  357. if(nullptr == screenTexture)
  358. {
  359. logGlobal->error("Unable to create screen texture");
  360. logGlobal->error(SDL_GetError());
  361. throw std::runtime_error("Unable to create screen texture");
  362. }
  363. screen2 = CSDL_Ext::copySurface(screen);
  364. if(nullptr == screen2)
  365. {
  366. throw std::runtime_error("Unable to copy surface\n");
  367. }
  368. if (GH.windows().count() > 1)
  369. screenBuf = screen2;
  370. else
  371. screenBuf = screen;
  372. clearScreen();
  373. }
  374. SDL_Window * ScreenHandler::createWindowImpl(Point dimensions, int flags, bool center)
  375. {
  376. int displayIndex = getPreferredDisplayIndex();
  377. int positionFlags = center ? SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex) : SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex);
  378. return SDL_CreateWindow(NAME.c_str(), positionFlags, positionFlags, dimensions.x, dimensions.y, flags);
  379. }
  380. SDL_Window * ScreenHandler::createWindow()
  381. {
  382. #ifndef VCMI_MOBILE
  383. Point dimensions = getPreferredWindowResolution();
  384. switch(getPreferredWindowMode())
  385. {
  386. case EWindowMode::FULLSCREEN_EXCLUSIVE:
  387. return createWindowImpl(dimensions, SDL_WINDOW_FULLSCREEN, false);
  388. case EWindowMode::FULLSCREEN_BORDERLESS_WINDOWED:
  389. return createWindowImpl(Point(), SDL_WINDOW_FULLSCREEN_DESKTOP, false);
  390. case EWindowMode::WINDOWED:
  391. return createWindowImpl(dimensions, SDL_WINDOW_RESIZABLE, true);
  392. default:
  393. return nullptr;
  394. };
  395. #endif
  396. #ifdef VCMI_IOS
  397. SDL_SetHint(SDL_HINT_IOS_HIDE_HOME_INDICATOR, "1");
  398. SDL_SetHint(SDL_HINT_RETURN_KEY_HIDES_IME, "1");
  399. uint32_t windowFlags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI;
  400. SDL_Window * result = createWindowImpl(Point(), windowFlags | SDL_WINDOW_METAL, false);
  401. if(result != nullptr)
  402. return result;
  403. logGlobal->warn("Metal unavailable, using OpenGLES");
  404. return createWindowImpl(Point(), windowFlags, false);
  405. #endif
  406. #ifdef VCMI_ANDROID
  407. return createWindowImpl(Point(), SDL_WINDOW_RESIZABLE, false);
  408. #endif
  409. }
  410. void ScreenHandler::onScreenResize()
  411. {
  412. recreateWindowAndScreenBuffers();
  413. }
  414. void ScreenHandler::validateSettings()
  415. {
  416. #ifndef VCMI_MOBILE
  417. {
  418. int displayIndex = settings["video"]["displayIndex"].Integer();
  419. int displaysCount = SDL_GetNumVideoDisplays();
  420. if (displayIndex >= displaysCount)
  421. {
  422. Settings writer = settings.write["video"]["displayIndex"];
  423. writer->Float() = 0;
  424. }
  425. }
  426. if (getPreferredWindowMode() == EWindowMode::WINDOWED)
  427. {
  428. //we only check that our desired window size fits on screen
  429. int displayIndex = getPreferredDisplayIndex();
  430. Point resolution = getPreferredWindowResolution();
  431. SDL_DisplayMode mode;
  432. if (SDL_GetDesktopDisplayMode(displayIndex, &mode) == 0)
  433. {
  434. if(resolution.x > mode.w || resolution.y > mode.h)
  435. {
  436. Settings writer = settings.write["video"]["resolution"];
  437. writer["width"].Float() = mode.w;
  438. writer["height"].Float() = mode.h;
  439. }
  440. }
  441. }
  442. if (getPreferredWindowMode() == EWindowMode::FULLSCREEN_EXCLUSIVE)
  443. {
  444. auto legalOptions = getSupportedResolutions();
  445. Point selectedResolution = getPreferredWindowResolution();
  446. if(!vstd::contains(legalOptions, selectedResolution))
  447. {
  448. // resolution selected for fullscreen mode is not supported by display
  449. // try to find current display resolution and use it instead as "reasonable default"
  450. SDL_DisplayMode mode;
  451. if (SDL_GetDesktopDisplayMode(getPreferredDisplayIndex(), &mode) == 0)
  452. {
  453. Settings writer = settings.write["video"]["resolution"];
  454. writer["width"].Float() = mode.w;
  455. writer["height"].Float() = mode.h;
  456. }
  457. }
  458. }
  459. #endif
  460. }
  461. int ScreenHandler::getPreferredRenderingDriver() const
  462. {
  463. int result = -1;
  464. const JsonNode & video = settings["video"];
  465. int driversCount = SDL_GetNumRenderDrivers();
  466. std::string preferredDriverName = video["driver"].String();
  467. logGlobal->info("Found %d render drivers", driversCount);
  468. for(int it = 0; it < driversCount; it++)
  469. {
  470. SDL_RendererInfo info;
  471. if (SDL_GetRenderDriverInfo(it, &info) == 0)
  472. {
  473. std::string driverName(info.name);
  474. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  475. {
  476. result = it;
  477. logGlobal->info("\t%s (active)", driverName);
  478. }
  479. else
  480. logGlobal->info("\t%s", driverName);
  481. }
  482. else
  483. logGlobal->info("\t(error)");
  484. }
  485. return result;
  486. }
  487. void ScreenHandler::destroyScreenBuffers()
  488. {
  489. // screenBuf is not a separate surface, but points to either screen or screen2 - just set to null
  490. screenBuf = nullptr;
  491. if(nullptr != screen2)
  492. {
  493. SDL_FreeSurface(screen2);
  494. screen2 = nullptr;
  495. }
  496. if(nullptr != screen)
  497. {
  498. SDL_FreeSurface(screen);
  499. screen = nullptr;
  500. }
  501. if(nullptr != screenTexture)
  502. {
  503. SDL_DestroyTexture(screenTexture);
  504. screenTexture = nullptr;
  505. }
  506. }
  507. void ScreenHandler::destroyWindow()
  508. {
  509. if(nullptr != mainRenderer)
  510. {
  511. SDL_DestroyRenderer(mainRenderer);
  512. mainRenderer = nullptr;
  513. }
  514. if(nullptr != mainWindow)
  515. {
  516. SDL_DestroyWindow(mainWindow);
  517. mainWindow = nullptr;
  518. }
  519. }
  520. void ScreenHandler::close()
  521. {
  522. if(settings["general"]["notifications"].Bool())
  523. NotificationHandler::destroy();
  524. destroyScreenBuffers();
  525. destroyWindow();
  526. SDL_Quit();
  527. }
  528. void ScreenHandler::clearScreen()
  529. {
  530. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  531. SDL_RenderClear(mainRenderer);
  532. SDL_RenderPresent(mainRenderer);
  533. }
  534. std::vector<Point> ScreenHandler::getSupportedResolutions() const
  535. {
  536. int displayID = getPreferredDisplayIndex();
  537. return getSupportedResolutions(displayID);
  538. }
  539. std::vector<Point> ScreenHandler::getSupportedResolutions( int displayIndex) const
  540. {
  541. //NOTE: this method is never called on Android/iOS, only on desktop systems
  542. std::vector<Point> result;
  543. int modesCount = SDL_GetNumDisplayModes(displayIndex);
  544. for (int i =0; i < modesCount; ++i)
  545. {
  546. SDL_DisplayMode mode;
  547. if (SDL_GetDisplayMode(displayIndex, i, &mode) == 0)
  548. {
  549. Point resolution(mode.w, mode.h);
  550. result.push_back(resolution);
  551. }
  552. }
  553. boost::range::sort(result, [](const auto & left, const auto & right)
  554. {
  555. return left.x * left.y < right.x * right.y;
  556. });
  557. // erase potential duplicates, e.g. resolutions with different framerate / bits per pixel
  558. result.erase(boost::unique(result).end(), result.end());
  559. return result;
  560. }
  561. bool ScreenHandler::hasFocus()
  562. {
  563. ui32 flags = SDL_GetWindowFlags(mainWindow);
  564. return flags & SDL_WINDOW_INPUT_FOCUS;
  565. }