RmlUi_Backend_SDL_GL3.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  131. // GLES 3.0 (WebGL 2.0)
  132. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
  133. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
  134. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  135. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  136. #else
  137. // GL 3.3 Core
  138. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
  139. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  140. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  141. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
  142. #endif
  143. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  144. #if SDL_MAJOR_VERSION >= 3
  145. const float window_size_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay());
  146. SDL_PropertiesID props = SDL_CreateProperties();
  147. SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, window_name);
  148. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, SDL_WINDOWPOS_CENTERED);
  149. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, SDL_WINDOWPOS_CENTERED);
  150. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, int(width * window_size_scale));
  151. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, int(height * window_size_scale));
  152. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, true);
  153. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, allow_resize);
  154. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true);
  155. SDL_Window* window = SDL_CreateWindowWithProperties(props);
  156. SDL_DestroyProperties(props);
  157. #else
  158. const Uint32 window_flags = (SDL_WINDOW_OPENGL | (allow_resize ? SDL_WINDOW_RESIZABLE : 0));
  159. SDL_Window* window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  160. // 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.
  161. SDL_StopTextInput();
  162. #endif
  163. if (!window)
  164. {
  165. Rml::Log::Message(Rml::Log::LT_ERROR, "SDL error on create window: %s", SDL_GetError());
  166. return false;
  167. }
  168. SDL_GLContext glcontext = SDL_GL_CreateContext(window);
  169. SDL_GL_MakeCurrent(window, glcontext);
  170. SDL_GL_SetSwapInterval(1);
  171. if (!RmlGL3::Initialize())
  172. {
  173. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize OpenGL renderer");
  174. return false;
  175. }
  176. data = Rml::MakeUnique<BackendData>();
  177. if (!data->render_interface)
  178. {
  179. data.reset();
  180. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize OpenGL3 render interface");
  181. return false;
  182. }
  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 defined RMLUI_PLATFORM_EMSCRIPTEN
  215. // Ideally we would hand over control of the main loop to emscripten:
  216. //
  217. // // Hand over control of the main loop to the WebAssembly runtime.
  218. // emscripten_set_main_loop_arg(EventLoopIteration, (void*)user_data_handle, 0, true);
  219. //
  220. // 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
  221. // Asyncify to yield by sleeping.
  222. // Important: Must be linked with option -sASYNCIFY
  223. emscripten_sleep(1);
  224. #endif
  225. #if SDL_MAJOR_VERSION >= 3
  226. #define RMLSDL_WINDOW_EVENTS_BEGIN
  227. #define RMLSDL_WINDOW_EVENTS_END
  228. auto GetKey = [](const SDL_Event& event) { return event.key.key; };
  229. auto GetDisplayScale = []() { return SDL_GetWindowDisplayScale(data->window); };
  230. constexpr auto event_quit = SDL_EVENT_QUIT;
  231. constexpr auto event_key_down = SDL_EVENT_KEY_DOWN;
  232. constexpr auto event_window_size_changed = SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED;
  233. bool has_event = false;
  234. #else
  235. #define RMLSDL_WINDOW_EVENTS_BEGIN \
  236. case SDL_WINDOWEVENT: \
  237. { \
  238. switch (ev.window.event) \
  239. {
  240. #define RMLSDL_WINDOW_EVENTS_END \
  241. } \
  242. } \
  243. break;
  244. auto GetKey = [](const SDL_Event& event) { return event.key.keysym.sym; };
  245. auto GetDisplayScale = []() { return 1.f; };
  246. constexpr auto event_quit = SDL_QUIT;
  247. constexpr auto event_key_down = SDL_KEYDOWN;
  248. constexpr auto event_window_size_changed = SDL_WINDOWEVENT_SIZE_CHANGED;
  249. int has_event = 0;
  250. #endif
  251. bool result = data->running;
  252. data->running = true;
  253. SDL_Event ev;
  254. if (power_save)
  255. has_event = SDL_WaitEventTimeout(&ev, static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000));
  256. else
  257. has_event = SDL_PollEvent(&ev);
  258. while (has_event)
  259. {
  260. bool propagate_event = true;
  261. switch (ev.type)
  262. {
  263. case event_quit:
  264. {
  265. propagate_event = false;
  266. result = false;
  267. }
  268. break;
  269. case event_key_down:
  270. {
  271. propagate_event = false;
  272. const Rml::Input::KeyIdentifier key = RmlSDL::ConvertKey(GetKey(ev));
  273. const int key_modifier = RmlSDL::GetKeyModifierState();
  274. const float native_dp_ratio = GetDisplayScale();
  275. // See if we have any global shortcuts that take priority over the context.
  276. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  277. break;
  278. // Otherwise, hand the event over to the context by calling the input handler as normal.
  279. if (!RmlSDL::InputEventHandler(context, data->window, ev))
  280. break;
  281. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  282. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  283. break;
  284. }
  285. break;
  286. RMLSDL_WINDOW_EVENTS_BEGIN
  287. case event_window_size_changed:
  288. {
  289. Rml::Vector2i dimensions = {ev.window.data1, ev.window.data2};
  290. data->render_interface.SetViewport(dimensions.x, dimensions.y);
  291. }
  292. break;
  293. RMLSDL_WINDOW_EVENTS_END
  294. default: break;
  295. }
  296. if (propagate_event)
  297. RmlSDL::InputEventHandler(context, data->window, ev);
  298. has_event = SDL_PollEvent(&ev);
  299. }
  300. return result;
  301. }
  302. void Backend::RequestExit()
  303. {
  304. RMLUI_ASSERT(data);
  305. data->running = false;
  306. }
  307. void Backend::BeginFrame()
  308. {
  309. RMLUI_ASSERT(data);
  310. data->render_interface.Clear();
  311. data->render_interface.BeginFrame();
  312. }
  313. void Backend::PresentFrame()
  314. {
  315. RMLUI_ASSERT(data);
  316. data->render_interface.EndFrame();
  317. SDL_GL_SwapWindow(data->window);
  318. // Optional, used to mark frames during performance profiling.
  319. RMLUI_FrameMark;
  320. }