WindowHandler.cpp 12 KB

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