RmlUi_Backend_SDL_GL2.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. // Touch events are handled natively, no need to generate synthetic mouse events for touch devices.
  127. SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
  128. #if defined RMLUI_BACKEND_SIMULATE_TOUCH
  129. // Simulate touch events from mouse events for testing touch behavior on a desktop machine.
  130. SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "1");
  131. #endif
  132. // Request stencil buffer of at least 8-bit size to supporting clipping on transformed elements.
  133. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  134. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  135. // Enable MSAA for better-looking visuals, especially when transforms are applied.
  136. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  137. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);
  138. #if SDL_MAJOR_VERSION >= 3
  139. auto CreateWindow = [&]() {
  140. const float window_size_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay());
  141. SDL_PropertiesID props = SDL_CreateProperties();
  142. SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, window_name);
  143. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, SDL_WINDOWPOS_CENTERED);
  144. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, SDL_WINDOWPOS_CENTERED);
  145. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, int(width * window_size_scale));
  146. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, int(height * window_size_scale));
  147. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, true);
  148. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, allow_resize);
  149. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true);
  150. SDL_Window* window = SDL_CreateWindowWithProperties(props);
  151. SDL_DestroyProperties(props);
  152. return window;
  153. };
  154. #else
  155. auto CreateWindow = [&]() {
  156. const Uint32 window_flags = (SDL_WINDOW_OPENGL | (allow_resize ? SDL_WINDOW_RESIZABLE : 0));
  157. SDL_Window* window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  158. // 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
  159. // field.
  160. SDL_StopTextInput();
  161. return window;
  162. };
  163. // Enable linear filtering, SDL 3 already defaults to it.
  164. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
  165. #endif
  166. SDL_Window* window = CreateWindow();
  167. if (!window)
  168. {
  169. // Try again on low-quality settings.
  170. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  171. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  172. window = CreateWindow();
  173. if (!window)
  174. {
  175. Rml::Log::Message(Rml::Log::LT_ERROR, "SDL error on create window: %s", SDL_GetError());
  176. return false;
  177. }
  178. }
  179. SDL_GLContext glcontext = SDL_GL_CreateContext(window);
  180. SDL_GL_MakeCurrent(window, glcontext);
  181. SDL_GL_SetSwapInterval(1);
  182. data = Rml::MakeUnique<BackendData>();
  183. data->window = window;
  184. data->glcontext = glcontext;
  185. data->system_interface.SetWindow(window);
  186. data->render_interface.SetViewport(width, height);
  187. return true;
  188. }
  189. void Backend::Shutdown()
  190. {
  191. RMLUI_ASSERT(data);
  192. #if SDL_MAJOR_VERSION >= 3
  193. SDL_GL_DestroyContext(data->glcontext);
  194. #else
  195. SDL_GL_DeleteContext(data->glcontext);
  196. #endif
  197. SDL_DestroyWindow(data->window);
  198. data.reset();
  199. SDL_Quit();
  200. }
  201. Rml::SystemInterface* Backend::GetSystemInterface()
  202. {
  203. RMLUI_ASSERT(data);
  204. return &data->system_interface;
  205. }
  206. Rml::RenderInterface* Backend::GetRenderInterface()
  207. {
  208. RMLUI_ASSERT(data);
  209. return &data->render_interface;
  210. }
  211. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  212. {
  213. RMLUI_ASSERT(data && context);
  214. #if SDL_MAJOR_VERSION >= 3
  215. #define RMLSDL_WINDOW_EVENTS_BEGIN
  216. #define RMLSDL_WINDOW_EVENTS_END
  217. auto GetKey = [](const SDL_Event& event) { return event.key.key; };
  218. auto GetDisplayScale = []() { return SDL_GetWindowDisplayScale(data->window); };
  219. constexpr auto event_quit = SDL_EVENT_QUIT;
  220. constexpr auto event_key_down = SDL_EVENT_KEY_DOWN;
  221. constexpr auto event_window_size_changed = SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED;
  222. bool has_event = false;
  223. #else
  224. #define RMLSDL_WINDOW_EVENTS_BEGIN \
  225. case SDL_WINDOWEVENT: \
  226. { \
  227. switch (ev.window.event) \
  228. {
  229. #define RMLSDL_WINDOW_EVENTS_END \
  230. } \
  231. } \
  232. break;
  233. auto GetKey = [](const SDL_Event& event) { return event.key.keysym.sym; };
  234. auto GetDisplayScale = []() { return 1.f; };
  235. constexpr auto event_quit = SDL_QUIT;
  236. constexpr auto event_key_down = SDL_KEYDOWN;
  237. constexpr auto event_window_size_changed = SDL_WINDOWEVENT_SIZE_CHANGED;
  238. int has_event = 0;
  239. #endif
  240. bool result = data->running;
  241. data->running = true;
  242. SDL_Event ev;
  243. if (power_save)
  244. has_event = SDL_WaitEventTimeout(&ev, static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000));
  245. else
  246. has_event = SDL_PollEvent(&ev);
  247. while (has_event)
  248. {
  249. bool propagate_event = true;
  250. switch (ev.type)
  251. {
  252. case event_quit:
  253. {
  254. propagate_event = false;
  255. result = false;
  256. }
  257. break;
  258. case event_key_down:
  259. {
  260. propagate_event = false;
  261. const Rml::Input::KeyIdentifier key = RmlSDL::ConvertKey(GetKey(ev));
  262. const int key_modifier = RmlSDL::GetKeyModifierState();
  263. const float native_dp_ratio = GetDisplayScale();
  264. // See if we have any global shortcuts that take priority over the context.
  265. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  266. break;
  267. // Otherwise, hand the event over to the context by calling the input handler as normal.
  268. if (!RmlSDL::InputEventHandler(context, data->window, ev))
  269. break;
  270. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  271. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  272. break;
  273. }
  274. break;
  275. RMLSDL_WINDOW_EVENTS_BEGIN
  276. case event_window_size_changed:
  277. {
  278. Rml::Vector2i dimensions = {ev.window.data1, ev.window.data2};
  279. data->render_interface.SetViewport(dimensions.x, dimensions.y);
  280. }
  281. break;
  282. RMLSDL_WINDOW_EVENTS_END
  283. default: break;
  284. }
  285. if (propagate_event)
  286. RmlSDL::InputEventHandler(context, data->window, ev);
  287. has_event = SDL_PollEvent(&ev);
  288. }
  289. return result;
  290. }
  291. void Backend::RequestExit()
  292. {
  293. RMLUI_ASSERT(data);
  294. data->running = false;
  295. }
  296. void Backend::BeginFrame()
  297. {
  298. RMLUI_ASSERT(data);
  299. data->render_interface.Clear();
  300. data->render_interface.BeginFrame();
  301. }
  302. void Backend::PresentFrame()
  303. {
  304. RMLUI_ASSERT(data);
  305. data->render_interface.EndFrame();
  306. SDL_GL_SwapWindow(data->window);
  307. }