ScreenHandler.cpp 16 KB

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