RmlUi_Backend_SDL_GL2.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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_GL2.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 >= 3
  36. #include <SDL3_image/SDL_image.h>
  37. #else
  38. #include <SDL_image.h>
  39. #endif
  40. #if SDL_MAJOR_VERSION == 2 && !(SDL_VIDEO_RENDER_OGL)
  41. #error "Only the OpenGL SDL backend is supported."
  42. #endif
  43. /**
  44. Custom render interface example for the SDL/GL2 backend.
  45. Overloads the OpenGL2 render interface to load textures through SDL_image's built-in texture loading functionality.
  46. */
  47. class RenderInterface_GL2_SDL : public RenderInterface_GL2 {
  48. public:
  49. Rml::TextureHandle LoadTexture(Rml::Vector2i& texture_dimensions, const Rml::String& source) override
  50. {
  51. Rml::FileInterface* file_interface = Rml::GetFileInterface();
  52. Rml::FileHandle file_handle = file_interface->Open(source);
  53. if (!file_handle)
  54. return {};
  55. file_interface->Seek(file_handle, 0, SEEK_END);
  56. const size_t buffer_size = file_interface->Tell(file_handle);
  57. file_interface->Seek(file_handle, 0, SEEK_SET);
  58. using Rml::byte;
  59. Rml::UniquePtr<byte[]> buffer(new byte[buffer_size]);
  60. file_interface->Read(buffer.get(), buffer_size, file_handle);
  61. file_interface->Close(file_handle);
  62. const size_t i_ext = source.rfind('.');
  63. Rml::String extension = (i_ext == Rml::String::npos ? Rml::String() : source.substr(i_ext + 1));
  64. #if SDL_MAJOR_VERSION >= 3
  65. auto CreateSurface = [&]() { return IMG_LoadTyped_IO(SDL_IOFromMem(buffer.get(), int(buffer_size)), 1, extension.c_str()); };
  66. auto GetSurfaceFormat = [](SDL_Surface* surface) { return surface->format; };
  67. auto ConvertSurface = [](SDL_Surface* surface, SDL_PixelFormat format) { return SDL_ConvertSurface(surface, format); };
  68. auto DestroySurface = [](SDL_Surface* surface) { SDL_DestroySurface(surface); };
  69. #else
  70. auto CreateSurface = [&]() { return IMG_LoadTyped_RW(SDL_RWFromMem(buffer.get(), int(buffer_size)), 1, extension.c_str()); };
  71. auto GetSurfaceFormat = [](SDL_Surface* surface) { return surface->format->format; };
  72. auto ConvertSurface = [](SDL_Surface* surface, Uint32 format) { return SDL_ConvertSurfaceFormat(surface, format, 0); };
  73. auto DestroySurface = [](SDL_Surface* surface) { SDL_FreeSurface(surface); };
  74. #endif
  75. SDL_Surface* surface = CreateSurface();
  76. if (!surface)
  77. return {};
  78. texture_dimensions = {surface->w, surface->h};
  79. if (GetSurfaceFormat(surface) != SDL_PIXELFORMAT_RGBA32)
  80. {
  81. // Ensure correct format for premultiplied alpha conversion and GenerateTexture below.
  82. SDL_Surface* converted_surface = ConvertSurface(surface, SDL_PIXELFORMAT_RGBA32);
  83. DestroySurface(surface);
  84. if (!converted_surface)
  85. return {};
  86. surface = converted_surface;
  87. }
  88. // Convert colors to premultiplied alpha, which is necessary for correct alpha compositing.
  89. const size_t pixels_byte_size = surface->w * surface->h * 4;
  90. byte* pixels = static_cast<byte*>(surface->pixels);
  91. for (size_t i = 0; i < pixels_byte_size; i += 4)
  92. {
  93. const byte alpha = pixels[i + 3];
  94. for (size_t j = 0; j < 3; ++j)
  95. pixels[i + j] = byte(int(pixels[i + j]) * int(alpha) / 255);
  96. }
  97. Rml::TextureHandle texture_handle = RenderInterface_GL2::GenerateTexture({pixels, pixels_byte_size}, texture_dimensions);
  98. DestroySurface(surface);
  99. return texture_handle;
  100. }
  101. };
  102. /**
  103. Global data used by this backend.
  104. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  105. */
  106. struct BackendData {
  107. SystemInterface_SDL system_interface;
  108. RenderInterface_GL2_SDL render_interface;
  109. SDL_Window* window = nullptr;
  110. SDL_GLContext glcontext = nullptr;
  111. bool running = true;
  112. };
  113. static Rml::UniquePtr<BackendData> data;
  114. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  115. {
  116. RMLUI_ASSERT(!data);
  117. #if SDL_MAJOR_VERSION >= 3
  118. if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS))
  119. return false;
  120. #else
  121. if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
  122. return false;
  123. #endif
  124. // Submit click events when focusing the window.
  125. SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
  126. // Request stencil buffer of at least 8-bit size to supporting clipping on transformed elements.
  127. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  128. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  129. // Enable MSAA for better-looking visuals, especially when transforms are applied.
  130. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  131. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);
  132. #if SDL_MAJOR_VERSION >= 3
  133. auto CreateWindow = [&]() {
  134. const float window_size_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay());
  135. SDL_PropertiesID props = SDL_CreateProperties();
  136. SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, window_name);
  137. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, SDL_WINDOWPOS_CENTERED);
  138. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, SDL_WINDOWPOS_CENTERED);
  139. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, int(width * window_size_scale));
  140. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, int(height * window_size_scale));
  141. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, true);
  142. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, allow_resize);
  143. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true);
  144. SDL_Window* window = SDL_CreateWindowWithProperties(props);
  145. SDL_DestroyProperties(props);
  146. return window;
  147. };
  148. #else
  149. auto CreateWindow = [&]() {
  150. const Uint32 window_flags = (SDL_WINDOW_OPENGL | (allow_resize ? SDL_WINDOW_RESIZABLE : 0));
  151. SDL_Window* window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  152. // 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
  153. // field.
  154. SDL_StopTextInput();
  155. return window;
  156. };
  157. // Enable linear filtering, SDL 3 already defaults to it.
  158. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
  159. #endif
  160. SDL_Window* window = CreateWindow();
  161. if (!window)
  162. {
  163. // Try again on low-quality settings.
  164. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  165. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  166. window = CreateWindow();
  167. if (!window)
  168. {
  169. Rml::Log::Message(Rml::Log::LT_ERROR, "SDL error on create window: %s", SDL_GetError());
  170. return false;
  171. }
  172. }
  173. SDL_GLContext glcontext = SDL_GL_CreateContext(window);
  174. SDL_GL_MakeCurrent(window, glcontext);
  175. SDL_GL_SetSwapInterval(1);
  176. data = Rml::MakeUnique<BackendData>();
  177. data->window = window;
  178. data->glcontext = glcontext;
  179. data->system_interface.SetWindow(window);
  180. data->render_interface.SetViewport(width, height);
  181. return true;
  182. }
  183. void Backend::Shutdown()
  184. {
  185. RMLUI_ASSERT(data);
  186. #if SDL_MAJOR_VERSION >= 3
  187. SDL_GL_DestroyContext(data->glcontext);
  188. #else
  189. SDL_GL_DeleteContext(data->glcontext);
  190. #endif
  191. SDL_DestroyWindow(data->window);
  192. data.reset();
  193. SDL_Quit();
  194. }
  195. Rml::SystemInterface* Backend::GetSystemInterface()
  196. {
  197. RMLUI_ASSERT(data);
  198. return &data->system_interface;
  199. }
  200. Rml::RenderInterface* Backend::GetRenderInterface()
  201. {
  202. RMLUI_ASSERT(data);
  203. return &data->render_interface;
  204. }
  205. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  206. {
  207. RMLUI_ASSERT(data && context);
  208. #if SDL_MAJOR_VERSION >= 3
  209. #define RMLSDL_WINDOW_EVENTS_BEGIN
  210. #define RMLSDL_WINDOW_EVENTS_END
  211. auto GetKey = [](const SDL_Event& event) { return event.key.key; };
  212. auto GetDisplayScale = []() { return SDL_GetWindowDisplayScale(data->window); };
  213. constexpr auto event_quit = SDL_EVENT_QUIT;
  214. constexpr auto event_key_down = SDL_EVENT_KEY_DOWN;
  215. constexpr auto event_window_size_changed = SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED;
  216. bool has_event = false;
  217. #else
  218. #define RMLSDL_WINDOW_EVENTS_BEGIN \
  219. case SDL_WINDOWEVENT: \
  220. { \
  221. switch (ev.window.event) \
  222. {
  223. #define RMLSDL_WINDOW_EVENTS_END \
  224. } \
  225. } \
  226. break;
  227. auto GetKey = [](const SDL_Event& event) { return event.key.keysym.sym; };
  228. auto GetDisplayScale = []() { return 1.f; };
  229. constexpr auto event_quit = SDL_QUIT;
  230. constexpr auto event_key_down = SDL_KEYDOWN;
  231. constexpr auto event_window_size_changed = SDL_WINDOWEVENT_SIZE_CHANGED;
  232. int has_event = 0;
  233. #endif
  234. bool result = data->running;
  235. data->running = true;
  236. SDL_Event ev;
  237. if (power_save)
  238. has_event = SDL_WaitEventTimeout(&ev, static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000));
  239. else
  240. has_event = SDL_PollEvent(&ev);
  241. while (has_event)
  242. {
  243. bool propagate_event = true;
  244. switch (ev.type)
  245. {
  246. case event_quit:
  247. {
  248. propagate_event = false;
  249. result = false;
  250. }
  251. break;
  252. case event_key_down:
  253. {
  254. propagate_event = false;
  255. const Rml::Input::KeyIdentifier key = RmlSDL::ConvertKey(GetKey(ev));
  256. const int key_modifier = RmlSDL::GetKeyModifierState();
  257. const float native_dp_ratio = GetDisplayScale();
  258. // See if we have any global shortcuts that take priority over the context.
  259. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  260. break;
  261. // Otherwise, hand the event over to the context by calling the input handler as normal.
  262. if (!RmlSDL::InputEventHandler(context, data->window, ev))
  263. break;
  264. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  265. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  266. break;
  267. }
  268. break;
  269. RMLSDL_WINDOW_EVENTS_BEGIN
  270. case event_window_size_changed:
  271. {
  272. Rml::Vector2i dimensions = {ev.window.data1, ev.window.data2};
  273. data->render_interface.SetViewport(dimensions.x, dimensions.y);
  274. }
  275. break;
  276. RMLSDL_WINDOW_EVENTS_END
  277. default: break;
  278. }
  279. if (propagate_event)
  280. RmlSDL::InputEventHandler(context, data->window, ev);
  281. has_event = SDL_PollEvent(&ev);
  282. }
  283. return result;
  284. }
  285. void Backend::RequestExit()
  286. {
  287. RMLUI_ASSERT(data);
  288. data->running = false;
  289. }
  290. void Backend::BeginFrame()
  291. {
  292. RMLUI_ASSERT(data);
  293. data->render_interface.Clear();
  294. data->render_interface.BeginFrame();
  295. }
  296. void Backend::PresentFrame()
  297. {
  298. RMLUI_ASSERT(data);
  299. data->render_interface.EndFrame();
  300. SDL_GL_SwapWindow(data->window);
  301. }