RmlUi_Backend_SDL_GL3.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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_GL3.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. #include <RmlUi/Core/Profiling.h>
  36. #if SDL_MAJOR_VERSION >= 3
  37. #include <SDL3_image/SDL_image.h>
  38. #else
  39. #include <SDL_image.h>
  40. #endif
  41. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  42. #include <emscripten.h>
  43. #elif SDL_MAJOR_VERSION == 2 && !(SDL_VIDEO_RENDER_OGL)
  44. #error "Only the OpenGL SDL backend is supported."
  45. #endif
  46. /**
  47. Custom render interface example for the SDL/GL3 backend.
  48. Overloads the OpenGL3 render interface to load textures through SDL_image's built-in texture loading functionality.
  49. */
  50. class RenderInterface_GL3_SDL : public RenderInterface_GL3 {
  51. public:
  52. RenderInterface_GL3_SDL() {}
  53. Rml::TextureHandle LoadTexture(Rml::Vector2i& texture_dimensions, const Rml::String& source) override
  54. {
  55. Rml::FileInterface* file_interface = Rml::GetFileInterface();
  56. Rml::FileHandle file_handle = file_interface->Open(source);
  57. if (!file_handle)
  58. return {};
  59. file_interface->Seek(file_handle, 0, SEEK_END);
  60. const size_t buffer_size = file_interface->Tell(file_handle);
  61. file_interface->Seek(file_handle, 0, SEEK_SET);
  62. using Rml::byte;
  63. Rml::UniquePtr<byte[]> buffer(new byte[buffer_size]);
  64. file_interface->Read(buffer.get(), buffer_size, file_handle);
  65. file_interface->Close(file_handle);
  66. const size_t i_ext = source.rfind('.');
  67. Rml::String extension = (i_ext == Rml::String::npos ? Rml::String() : source.substr(i_ext + 1));
  68. #if SDL_MAJOR_VERSION >= 3
  69. auto CreateSurface = [&]() { return IMG_LoadTyped_IO(SDL_IOFromMem(buffer.get(), int(buffer_size)), 1, extension.c_str()); };
  70. auto GetSurfaceFormat = [](SDL_Surface* surface) { return surface->format; };
  71. auto ConvertSurface = [](SDL_Surface* surface, SDL_PixelFormat format) { return SDL_ConvertSurface(surface, format); };
  72. auto DestroySurface = [](SDL_Surface* surface) { SDL_DestroySurface(surface); };
  73. #else
  74. auto CreateSurface = [&]() { return IMG_LoadTyped_RW(SDL_RWFromMem(buffer.get(), int(buffer_size)), 1, extension.c_str()); };
  75. auto GetSurfaceFormat = [](SDL_Surface* surface) { return surface->format->format; };
  76. auto ConvertSurface = [](SDL_Surface* surface, Uint32 format) { return SDL_ConvertSurfaceFormat(surface, format, 0); };
  77. auto DestroySurface = [](SDL_Surface* surface) { SDL_FreeSurface(surface); };
  78. #endif
  79. SDL_Surface* surface = CreateSurface();
  80. if (!surface)
  81. return {};
  82. texture_dimensions = {surface->w, surface->h};
  83. if (GetSurfaceFormat(surface) != SDL_PIXELFORMAT_RGBA32)
  84. {
  85. // Ensure correct format for premultiplied alpha conversion and GenerateTexture below.
  86. SDL_Surface* converted_surface = ConvertSurface(surface, SDL_PIXELFORMAT_RGBA32);
  87. DestroySurface(surface);
  88. if (!converted_surface)
  89. return {};
  90. surface = converted_surface;
  91. }
  92. // Convert colors to premultiplied alpha, which is necessary for correct alpha compositing.
  93. const size_t pixels_byte_size = surface->w * surface->h * 4;
  94. byte* pixels = static_cast<byte*>(surface->pixels);
  95. for (size_t i = 0; i < pixels_byte_size; i += 4)
  96. {
  97. const byte alpha = pixels[i + 3];
  98. for (size_t j = 0; j < 3; ++j)
  99. pixels[i + j] = byte(int(pixels[i + j]) * int(alpha) / 255);
  100. }
  101. Rml::TextureHandle texture_handle = RenderInterface_GL3::GenerateTexture({pixels, pixels_byte_size}, texture_dimensions);
  102. DestroySurface(surface);
  103. return texture_handle;
  104. }
  105. };
  106. /**
  107. Global data used by this backend.
  108. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  109. */
  110. struct BackendData {
  111. SystemInterface_SDL system_interface;
  112. RenderInterface_GL3_SDL render_interface;
  113. SDL_Window* window = nullptr;
  114. SDL_GLContext glcontext = nullptr;
  115. bool running = true;
  116. };
  117. static Rml::UniquePtr<BackendData> data;
  118. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  119. {
  120. RMLUI_ASSERT(!data);
  121. #if SDL_MAJOR_VERSION >= 3
  122. if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS))
  123. return false;
  124. #else
  125. if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
  126. return false;
  127. #endif
  128. // Submit click events when focusing the window.
  129. SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
  130. // Touch events are handled natively, no need to generate synthetic mouse events for touch devices.
  131. SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
  132. #if defined RMLUI_BACKEND_SIMULATE_TOUCH
  133. // Simulate touch events from mouse events for testing touch behavior on a desktop machine.
  134. SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "1");
  135. #endif
  136. #if defined(RMLUI_PLATFORM_EMSCRIPTEN)
  137. // GLES 3.0 (WebGL 2.0)
  138. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
  139. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
  140. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  141. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  142. #elif defined(__ANDROID__)
  143. // GLES 3.2 on Android
  144. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
  145. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
  146. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  147. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
  148. #else
  149. // GL 3.3 Core
  150. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
  151. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  152. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  153. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
  154. #endif
  155. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  156. #if SDL_MAJOR_VERSION >= 3
  157. const float window_size_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay());
  158. SDL_PropertiesID props = SDL_CreateProperties();
  159. SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, window_name);
  160. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, SDL_WINDOWPOS_CENTERED);
  161. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, SDL_WINDOWPOS_CENTERED);
  162. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, int(width * window_size_scale));
  163. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, int(height * window_size_scale));
  164. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, true);
  165. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, allow_resize);
  166. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true);
  167. SDL_Window* window = SDL_CreateWindowWithProperties(props);
  168. SDL_DestroyProperties(props);
  169. #else
  170. const Uint32 window_flags = (SDL_WINDOW_OPENGL | (allow_resize ? SDL_WINDOW_RESIZABLE : 0));
  171. SDL_Window* window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  172. // 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.
  173. SDL_StopTextInput();
  174. #endif
  175. if (!window)
  176. {
  177. Rml::Log::Message(Rml::Log::LT_ERROR, "SDL error on create window: %s", SDL_GetError());
  178. return false;
  179. }
  180. SDL_GLContext glcontext = SDL_GL_CreateContext(window);
  181. SDL_GL_MakeCurrent(window, glcontext);
  182. SDL_GL_SetSwapInterval(1);
  183. if (!RmlGL3::Initialize())
  184. {
  185. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize OpenGL renderer");
  186. return false;
  187. }
  188. data = Rml::MakeUnique<BackendData>();
  189. if (!data->render_interface)
  190. {
  191. data.reset();
  192. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize OpenGL3 render interface");
  193. return false;
  194. }
  195. data->window = window;
  196. data->glcontext = glcontext;
  197. data->system_interface.SetWindow(window);
  198. data->render_interface.SetViewport(width, height);
  199. return true;
  200. }
  201. void Backend::Shutdown()
  202. {
  203. RMLUI_ASSERT(data);
  204. #if SDL_MAJOR_VERSION >= 3
  205. SDL_GL_DestroyContext(data->glcontext);
  206. #else
  207. SDL_GL_DeleteContext(data->glcontext);
  208. #endif
  209. SDL_DestroyWindow(data->window);
  210. data.reset();
  211. SDL_Quit();
  212. }
  213. Rml::SystemInterface* Backend::GetSystemInterface()
  214. {
  215. RMLUI_ASSERT(data);
  216. return &data->system_interface;
  217. }
  218. Rml::RenderInterface* Backend::GetRenderInterface()
  219. {
  220. RMLUI_ASSERT(data);
  221. return &data->render_interface;
  222. }
  223. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  224. {
  225. RMLUI_ASSERT(data && context);
  226. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  227. // Ideally we would hand over control of the main loop to emscripten:
  228. //
  229. // // Hand over control of the main loop to the WebAssembly runtime.
  230. // emscripten_set_main_loop_arg(EventLoopIteration, (void*)user_data_handle, 0, true);
  231. //
  232. // The above is the recommended approach. However, as we don't control the main loop here we have to make due with another approach. Instead, use
  233. // Asyncify to yield by sleeping.
  234. // Important: Must be linked with option -sASYNCIFY
  235. emscripten_sleep(1);
  236. #endif
  237. #if SDL_MAJOR_VERSION >= 3
  238. #define RMLSDL_WINDOW_EVENTS_BEGIN
  239. #define RMLSDL_WINDOW_EVENTS_END
  240. auto GetKey = [](const SDL_Event& event) { return event.key.key; };
  241. auto GetDisplayScale = []() { return SDL_GetWindowDisplayScale(data->window); };
  242. constexpr auto event_quit = SDL_EVENT_QUIT;
  243. constexpr auto event_key_down = SDL_EVENT_KEY_DOWN;
  244. constexpr auto event_window_size_changed = SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED;
  245. bool has_event = false;
  246. #else
  247. #define RMLSDL_WINDOW_EVENTS_BEGIN \
  248. case SDL_WINDOWEVENT: \
  249. { \
  250. switch (ev.window.event) \
  251. {
  252. #define RMLSDL_WINDOW_EVENTS_END \
  253. } \
  254. } \
  255. break;
  256. auto GetKey = [](const SDL_Event& event) { return event.key.keysym.sym; };
  257. auto GetDisplayScale = []() { return 1.f; };
  258. constexpr auto event_quit = SDL_QUIT;
  259. constexpr auto event_key_down = SDL_KEYDOWN;
  260. constexpr auto event_window_size_changed = SDL_WINDOWEVENT_SIZE_CHANGED;
  261. int has_event = 0;
  262. #endif
  263. bool result = data->running;
  264. data->running = true;
  265. SDL_Event ev;
  266. if (power_save)
  267. has_event = SDL_WaitEventTimeout(&ev, static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000));
  268. else
  269. has_event = SDL_PollEvent(&ev);
  270. while (has_event)
  271. {
  272. bool propagate_event = true;
  273. switch (ev.type)
  274. {
  275. case event_quit:
  276. {
  277. propagate_event = false;
  278. result = false;
  279. }
  280. break;
  281. case event_key_down:
  282. {
  283. propagate_event = false;
  284. const Rml::Input::KeyIdentifier key = RmlSDL::ConvertKey(GetKey(ev));
  285. const int key_modifier = RmlSDL::GetKeyModifierState();
  286. const float native_dp_ratio = GetDisplayScale();
  287. // See if we have any global shortcuts that take priority over the context.
  288. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  289. break;
  290. // Otherwise, hand the event over to the context by calling the input handler as normal.
  291. if (!RmlSDL::InputEventHandler(context, data->window, ev))
  292. break;
  293. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  294. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  295. break;
  296. }
  297. break;
  298. RMLSDL_WINDOW_EVENTS_BEGIN
  299. case event_window_size_changed:
  300. {
  301. Rml::Vector2i dimensions = {ev.window.data1, ev.window.data2};
  302. data->render_interface.SetViewport(dimensions.x, dimensions.y);
  303. }
  304. break;
  305. RMLSDL_WINDOW_EVENTS_END
  306. default: break;
  307. }
  308. if (propagate_event)
  309. RmlSDL::InputEventHandler(context, data->window, ev);
  310. has_event = SDL_PollEvent(&ev);
  311. }
  312. return result;
  313. }
  314. void Backend::RequestExit()
  315. {
  316. RMLUI_ASSERT(data);
  317. data->running = false;
  318. }
  319. void Backend::BeginFrame()
  320. {
  321. RMLUI_ASSERT(data);
  322. data->render_interface.Clear();
  323. data->render_interface.BeginFrame();
  324. }
  325. void Backend::PresentFrame()
  326. {
  327. RMLUI_ASSERT(data);
  328. data->render_interface.EndFrame();
  329. SDL_GL_SwapWindow(data->window);
  330. // Optional, used to mark frames during performance profiling.
  331. RMLUI_FrameMark;
  332. }