WindowHandler.cpp 13 KB

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