RmlUi_Backend_SDL_VK.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "RmlUi_Backend.h"
  29. #include "RmlUi_Platform_SDL.h"
  30. #include "RmlUi_Renderer_VK.h"
  31. #include <RmlUi/Core/Context.h>
  32. #include <RmlUi/Core/Core.h>
  33. #include <RmlUi/Core/FileInterface.h>
  34. #include <RmlUi/Core/Log.h>
  35. #if SDL_MAJOR_VERSION == 2 && !(SDL_VIDEO_VULKAN)
  36. #error "Only the Vulkan SDL backend is supported."
  37. #endif
  38. #if SDL_MAJOR_VERSION >= 3
  39. #include <SDL3/SDL_vulkan.h>
  40. #else
  41. #include <SDL2/SDL_vulkan.h>
  42. #endif
  43. /**
  44. Global data used by this backend.
  45. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  46. */
  47. struct BackendData {
  48. SystemInterface_SDL system_interface;
  49. RenderInterface_VK render_interface;
  50. SDL_Window* window = nullptr;
  51. bool running = true;
  52. };
  53. static Rml::UniquePtr<BackendData> data;
  54. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  55. {
  56. RMLUI_ASSERT(!data);
  57. #if SDL_MAJOR_VERSION >= 3
  58. if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS))
  59. return false;
  60. #else
  61. if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
  62. return false;
  63. #endif
  64. // Submit click events when focusing the window.
  65. SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
  66. #if SDL_MAJOR_VERSION >= 3
  67. SDL_PropertiesID props = SDL_CreateProperties();
  68. SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, window_name);
  69. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, SDL_WINDOWPOS_CENTERED);
  70. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, SDL_WINDOWPOS_CENTERED);
  71. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, width);
  72. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, height);
  73. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_VULKAN_BOOLEAN, true);
  74. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, allow_resize);
  75. SDL_Window* window = SDL_CreateWindowWithProperties(props);
  76. SDL_DestroyProperties(props);
  77. auto CreateSurface = [](VkInstance instance, VkSurfaceKHR* out_surface) {
  78. return SDL_Vulkan_CreateSurface(data->window, instance, nullptr, out_surface);
  79. };
  80. #else
  81. const Uint32 window_flags = (SDL_WINDOW_VULKAN | (allow_resize ? SDL_WINDOW_RESIZABLE : 0));
  82. SDL_Window* window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  83. // SDL2 implicitly activates text input on window creation. Turn it off for now, it will be activated again e.g. when focusing a text input field.
  84. SDL_StopTextInput();
  85. auto CreateSurface = [](VkInstance instance, VkSurfaceKHR* out_surface) {
  86. return (bool)SDL_Vulkan_CreateSurface(data->window, instance, out_surface);
  87. };
  88. #endif
  89. if (!window)
  90. {
  91. Rml::Log::Message(Rml::Log::LT_ERROR, "SDL error on create window: %s", SDL_GetError());
  92. return false;
  93. }
  94. data = Rml::MakeUnique<BackendData>();
  95. data->window = window;
  96. Rml::Vector<const char*> extensions;
  97. {
  98. unsigned int count;
  99. #if SDL_MAJOR_VERSION >= 3
  100. const char* const* extensions_list = SDL_Vulkan_GetInstanceExtensions(&count);
  101. if (!extensions_list)
  102. {
  103. data.reset();
  104. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to get required vulkan extensions");
  105. return false;
  106. }
  107. extensions.resize(count);
  108. for (unsigned int i = 0; i < count; i++)
  109. extensions[i] = extensions_list[i];
  110. #else
  111. if (!SDL_Vulkan_GetInstanceExtensions(window, &count, nullptr))
  112. {
  113. data.reset();
  114. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to get required vulkan extensions");
  115. return false;
  116. }
  117. extensions.resize(count);
  118. if (!SDL_Vulkan_GetInstanceExtensions(window, &count, extensions.data()))
  119. {
  120. data.reset();
  121. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to get required vulkan extensions");
  122. return false;
  123. }
  124. #endif
  125. }
  126. if (!data->render_interface.Initialize(std::move(extensions), CreateSurface))
  127. {
  128. data.reset();
  129. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize Vulkan render interface");
  130. return false;
  131. }
  132. data->system_interface.SetWindow(window);
  133. data->render_interface.SetViewport(width, height);
  134. return true;
  135. }
  136. void Backend::Shutdown()
  137. {
  138. RMLUI_ASSERT(data);
  139. data->render_interface.Shutdown();
  140. SDL_DestroyWindow(data->window);
  141. data.reset();
  142. SDL_Quit();
  143. }
  144. Rml::SystemInterface* Backend::GetSystemInterface()
  145. {
  146. RMLUI_ASSERT(data);
  147. return &data->system_interface;
  148. }
  149. Rml::RenderInterface* Backend::GetRenderInterface()
  150. {
  151. RMLUI_ASSERT(data);
  152. return &data->render_interface;
  153. }
  154. static bool WaitForValidSwapchain()
  155. {
  156. #if SDL_MAJOR_VERSION >= 3
  157. constexpr auto event_quit = SDL_EVENT_QUIT;
  158. #else
  159. constexpr auto event_quit = SDL_QUIT;
  160. #endif
  161. bool result = true;
  162. // In some situations the swapchain may become invalid, such as when the window is minimized. In this state the renderer cannot accept any render
  163. // calls. Since we don't have full control over the main loop here we may risk calls to Context::Render if we were to return. Instead, we keep the
  164. // application inside this loop until we are able to recreate the swapchain and render again.
  165. while (!data->render_interface.IsSwapchainValid())
  166. {
  167. SDL_Event ev;
  168. while (SDL_PollEvent(&ev))
  169. {
  170. if (ev.type == event_quit)
  171. {
  172. // Restore the window so that we can recreate the swapchain, and then properly release all resource and shutdown cleanly.
  173. SDL_RestoreWindow(data->window);
  174. result = false;
  175. }
  176. }
  177. SDL_Delay(10);
  178. data->render_interface.RecreateSwapchain();
  179. }
  180. return result;
  181. }
  182. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  183. {
  184. RMLUI_ASSERT(data && context);
  185. #if SDL_MAJOR_VERSION >= 3
  186. #define RMLSDL_WINDOW_EVENTS_BEGIN
  187. #define RMLSDL_WINDOW_EVENTS_END
  188. auto GetKey = [](const SDL_Event& event) { return event.key.key; };
  189. constexpr auto event_quit = SDL_EVENT_QUIT;
  190. constexpr auto event_key_down = SDL_EVENT_KEY_DOWN;
  191. constexpr auto event_window_size_changed = SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED;
  192. bool has_event = false;
  193. #else
  194. #define RMLSDL_WINDOW_EVENTS_BEGIN \
  195. case SDL_WINDOWEVENT: \
  196. { \
  197. switch (ev.window.event) \
  198. {
  199. #define RMLSDL_WINDOW_EVENTS_END \
  200. } \
  201. } \
  202. break;
  203. auto GetKey = [](const SDL_Event& event) { return event.key.keysym.sym; };
  204. constexpr auto event_quit = SDL_QUIT;
  205. constexpr auto event_key_down = SDL_KEYDOWN;
  206. constexpr auto event_window_size_changed = SDL_WINDOWEVENT_SIZE_CHANGED;
  207. int has_event = 0;
  208. #endif
  209. bool result = data->running;
  210. data->running = true;
  211. SDL_Event ev;
  212. if (power_save)
  213. has_event = SDL_WaitEventTimeout(&ev, static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000));
  214. else
  215. has_event = SDL_PollEvent(&ev);
  216. while (has_event)
  217. {
  218. bool propagate_event = true;
  219. switch (ev.type)
  220. {
  221. case event_quit:
  222. {
  223. propagate_event = false;
  224. result = false;
  225. }
  226. break;
  227. case event_key_down:
  228. {
  229. propagate_event = false;
  230. const Rml::Input::KeyIdentifier key = RmlSDL::ConvertKey(GetKey(ev));
  231. const int key_modifier = RmlSDL::GetKeyModifierState();
  232. const float native_dp_ratio = 1.f;
  233. // See if we have any global shortcuts that take priority over the context.
  234. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  235. break;
  236. // Otherwise, hand the event over to the context by calling the input handler as normal.
  237. if (!RmlSDL::InputEventHandler(context, ev))
  238. break;
  239. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  240. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  241. break;
  242. }
  243. break;
  244. RMLSDL_WINDOW_EVENTS_BEGIN
  245. case event_window_size_changed:
  246. {
  247. Rml::Vector2i dimensions = {ev.window.data1, ev.window.data2};
  248. data->render_interface.SetViewport(dimensions.x, dimensions.y);
  249. }
  250. break;
  251. RMLSDL_WINDOW_EVENTS_END
  252. default: break;
  253. }
  254. if (propagate_event)
  255. RmlSDL::InputEventHandler(context, ev);
  256. has_event = SDL_PollEvent(&ev);
  257. }
  258. if (!WaitForValidSwapchain())
  259. result = false;
  260. return result;
  261. }
  262. void Backend::RequestExit()
  263. {
  264. RMLUI_ASSERT(data);
  265. data->running = false;
  266. }
  267. void Backend::BeginFrame()
  268. {
  269. RMLUI_ASSERT(data);
  270. data->render_interface.BeginFrame();
  271. }
  272. void Backend::PresentFrame()
  273. {
  274. RMLUI_ASSERT(data);
  275. data->render_interface.EndFrame();
  276. }