ScreenHandler.cpp 21 KB

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