WindowHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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, SDL_WINDOW_RESIZABLE, 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. uint32_t windowFlags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI;
  255. SDL_Window * result = createWindowImpl(Point(), windowFlags | SDL_WINDOW_METAL, false);
  256. if(result != nullptr)
  257. return result;
  258. logGlobal->warn("Metal unavailable, using OpenGLES");
  259. return createWindowImpl(Point(), windowFlags, false);
  260. #endif
  261. #ifdef VCMI_ANDROID
  262. return createWindowImpl(Point(), SDL_WINDOW_FULLSCREEN, false);
  263. #endif
  264. }
  265. void WindowHandler::onScreenResize()
  266. {
  267. if(!recreateWindow())
  268. {
  269. //will return false and report error if video mode is not supported
  270. return;
  271. }
  272. GH.onScreenResize();
  273. }
  274. void WindowHandler::validateSettings()
  275. {
  276. #if !defined(VCMI_MOBILE)
  277. {
  278. int displayIndex = settings["video"]["displayIndex"].Integer();
  279. int displaysCount = SDL_GetNumVideoDisplays();
  280. if (displayIndex >= displaysCount)
  281. {
  282. Settings writer = settings.write["video"]["displayIndex"];
  283. writer->Float() = 0;
  284. }
  285. }
  286. if (getPreferredWindowMode() == EWindowMode::WINDOWED)
  287. {
  288. //we only check that our desired window size fits on screen
  289. int displayIndex = getPreferredDisplayIndex();
  290. Point resolution = getPreferredRenderingResolution();
  291. SDL_DisplayMode mode;
  292. if (SDL_GetDesktopDisplayMode(displayIndex, &mode) == 0)
  293. {
  294. if(resolution.x > mode.w || resolution.y > mode.h)
  295. {
  296. Settings writer = settings.write["video"]["resolution"];
  297. writer["width"].Float() = mode.w;
  298. writer["height"].Float() = mode.h;
  299. }
  300. }
  301. }
  302. if (getPreferredWindowMode() == EWindowMode::FULLSCREEN_TRUE)
  303. {
  304. // TODO: check that display supports selected resolution
  305. }
  306. #endif
  307. }
  308. int WindowHandler::getPreferredRenderingDriver() const
  309. {
  310. int result = -1;
  311. const JsonNode & video = settings["video"];
  312. int driversCount = SDL_GetNumRenderDrivers();
  313. std::string preferredDriverName = video["driver"].String();
  314. logGlobal->info("Found %d render drivers", driversCount);
  315. for(int it = 0; it < driversCount; it++)
  316. {
  317. SDL_RendererInfo info;
  318. SDL_GetRenderDriverInfo(it, &info);
  319. std::string driverName(info.name);
  320. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  321. {
  322. result = it;
  323. logGlobal->info("\t%s (active)", driverName);
  324. }
  325. else
  326. logGlobal->info("\t%s", driverName);
  327. }
  328. return result;
  329. }
  330. void WindowHandler::destroyScreen()
  331. {
  332. screenBuf = nullptr; //it`s a link - just nullify
  333. if(nullptr != screen2)
  334. {
  335. SDL_FreeSurface(screen2);
  336. screen2 = nullptr;
  337. }
  338. if(nullptr != screen)
  339. {
  340. SDL_FreeSurface(screen);
  341. screen = nullptr;
  342. }
  343. if(nullptr != screenTexture)
  344. {
  345. SDL_DestroyTexture(screenTexture);
  346. screenTexture = nullptr;
  347. }
  348. }
  349. void WindowHandler::destroyWindow()
  350. {
  351. if(nullptr != mainRenderer)
  352. {
  353. SDL_DestroyRenderer(mainRenderer);
  354. mainRenderer = nullptr;
  355. }
  356. if(nullptr != mainWindow)
  357. {
  358. SDL_DestroyWindow(mainWindow);
  359. mainWindow = nullptr;
  360. }
  361. }
  362. void WindowHandler::close()
  363. {
  364. if(settings["general"]["notifications"].Bool())
  365. NotificationHandler::destroy();
  366. destroyScreen();
  367. destroyWindow();
  368. SDL_Quit();
  369. }
  370. void WindowHandler::clearScreen()
  371. {
  372. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  373. SDL_RenderClear(mainRenderer);
  374. SDL_RenderPresent(mainRenderer);
  375. }
  376. std::vector<Point> WindowHandler::getSupportedResolutions() const
  377. {
  378. int displayID = SDL_GetWindowDisplayIndex(mainWindow);
  379. return getSupportedResolutions(displayID);
  380. }
  381. std::vector<Point> WindowHandler::getSupportedResolutions( int displayIndex) const
  382. {
  383. //TODO: check this method on iOS / Android
  384. std::vector<Point> result;
  385. int modesCount = SDL_GetNumDisplayModes(displayIndex);
  386. for (int i =0; i < modesCount; ++i)
  387. {
  388. SDL_DisplayMode mode;
  389. if (SDL_GetDisplayMode(displayIndex, i, &mode) != 0)
  390. continue;
  391. Point resolution(mode.w, mode.h);
  392. result.push_back(resolution);
  393. }
  394. boost::range::sort(result, [](const auto & left, const auto & right)
  395. {
  396. return left.x * left.y < right.x * right.y;
  397. });
  398. result.erase(boost::unique(result).end(), result.end());
  399. return result;
  400. }