RmlUi_Backend_SDL_GL3.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. SDL_PropertiesID props = SDL_CreateProperties();
  146. SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, window_name);
  147. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, SDL_WINDOWPOS_CENTERED);
  148. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, SDL_WINDOWPOS_CENTERED);
  149. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, width);
  150. SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, height);
  151. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_OPENGL_BOOLEAN, true);
  152. SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, allow_resize);
  153. SDL_Window* window = SDL_CreateWindowWithProperties(props);
  154. SDL_DestroyProperties(props);
  155. #else
  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 field.
  159. SDL_StopTextInput();
  160. #endif
  161. if (!window)
  162. {
  163. Rml::Log::Message(Rml::Log::LT_ERROR, "SDL error on create window: %s", SDL_GetError());
  164. return false;
  165. }
  166. SDL_GLContext glcontext = SDL_GL_CreateContext(window);
  167. SDL_GL_MakeCurrent(window, glcontext);
  168. SDL_GL_SetSwapInterval(1);
  169. if (!RmlGL3::Initialize())
  170. {
  171. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize OpenGL renderer");
  172. return false;
  173. }
  174. data = Rml::MakeUnique<BackendData>();
  175. if (!data->render_interface)
  176. {
  177. data.reset();
  178. Rml::Log::Message(Rml::Log::LT_ERROR, "Failed to initialize OpenGL3 render interface");
  179. return false;
  180. }
  181. data->window = window;
  182. data->glcontext = glcontext;
  183. data->system_interface.SetWindow(window);
  184. data->render_interface.SetViewport(width, height);
  185. return true;
  186. }
  187. void Backend::Shutdown()
  188. {
  189. RMLUI_ASSERT(data);
  190. #if SDL_MAJOR_VERSION >= 3
  191. SDL_GL_DestroyContext(data->glcontext);
  192. #else
  193. SDL_GL_DeleteContext(data->glcontext);
  194. #endif
  195. SDL_DestroyWindow(data->window);
  196. data.reset();
  197. SDL_Quit();
  198. }
  199. Rml::SystemInterface* Backend::GetSystemInterface()
  200. {
  201. RMLUI_ASSERT(data);
  202. return &data->system_interface;
  203. }
  204. Rml::RenderInterface* Backend::GetRenderInterface()
  205. {
  206. RMLUI_ASSERT(data);
  207. return &data->render_interface;
  208. }
  209. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  210. {
  211. RMLUI_ASSERT(data && context);
  212. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  213. // Ideally we would hand over control of the main loop to emscripten:
  214. //
  215. // // Hand over control of the main loop to the WebAssembly runtime.
  216. // emscripten_set_main_loop_arg(EventLoopIteration, (void*)user_data_handle, 0, true);
  217. //
  218. // 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
  219. // Asyncify to yield by sleeping.
  220. // Important: Must be linked with option -sASYNCIFY
  221. emscripten_sleep(1);
  222. #endif
  223. #if SDL_MAJOR_VERSION >= 3
  224. #define RMLSDL_WINDOW_EVENTS_BEGIN
  225. #define RMLSDL_WINDOW_EVENTS_END
  226. auto GetKey = [](const SDL_Event& event) { return event.key.key; };
  227. constexpr auto event_quit = SDL_EVENT_QUIT;
  228. constexpr auto event_key_down = SDL_EVENT_KEY_DOWN;
  229. constexpr auto event_window_size_changed = SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED;
  230. bool has_event = false;
  231. #else
  232. #define RMLSDL_WINDOW_EVENTS_BEGIN \
  233. case SDL_WINDOWEVENT: \
  234. { \
  235. switch (ev.window.event) \
  236. {
  237. #define RMLSDL_WINDOW_EVENTS_END \
  238. } \
  239. } \
  240. break;
  241. auto GetKey = [](const SDL_Event& event) { return event.key.keysym.sym; };
  242. constexpr auto event_quit = SDL_QUIT;
  243. constexpr auto event_key_down = SDL_KEYDOWN;
  244. constexpr auto event_window_size_changed = SDL_WINDOWEVENT_SIZE_CHANGED;
  245. int has_event = 0;
  246. #endif
  247. bool result = data->running;
  248. data->running = true;
  249. SDL_Event ev;
  250. if (power_save)
  251. has_event = SDL_WaitEventTimeout(&ev, static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000));
  252. else
  253. has_event = SDL_PollEvent(&ev);
  254. while (has_event)
  255. {
  256. bool propagate_event = true;
  257. switch (ev.type)
  258. {
  259. case event_quit:
  260. {
  261. propagate_event = false;
  262. result = false;
  263. }
  264. break;
  265. case event_key_down:
  266. {
  267. propagate_event = false;
  268. const Rml::Input::KeyIdentifier key = RmlSDL::ConvertKey(GetKey(ev));
  269. const int key_modifier = RmlSDL::GetKeyModifierState();
  270. const float native_dp_ratio = 1.f;
  271. // See if we have any global shortcuts that take priority over the context.
  272. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  273. break;
  274. // Otherwise, hand the event over to the context by calling the input handler as normal.
  275. if (!RmlSDL::InputEventHandler(context, ev))
  276. break;
  277. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  278. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  279. break;
  280. }
  281. break;
  282. RMLSDL_WINDOW_EVENTS_BEGIN
  283. case event_window_size_changed:
  284. {
  285. Rml::Vector2i dimensions = {ev.window.data1, ev.window.data2};
  286. data->render_interface.SetViewport(dimensions.x, dimensions.y);
  287. }
  288. break;
  289. RMLSDL_WINDOW_EVENTS_END
  290. default: break;
  291. }
  292. if (propagate_event)
  293. RmlSDL::InputEventHandler(context, ev);
  294. has_event = SDL_PollEvent(&ev);
  295. }
  296. return result;
  297. }
  298. void Backend::RequestExit()
  299. {
  300. RMLUI_ASSERT(data);
  301. data->running = false;
  302. }
  303. void Backend::BeginFrame()
  304. {
  305. RMLUI_ASSERT(data);
  306. data->render_interface.Clear();
  307. data->render_interface.BeginFrame();
  308. }
  309. void Backend::PresentFrame()
  310. {
  311. RMLUI_ASSERT(data);
  312. data->render_interface.EndFrame();
  313. SDL_GL_SwapWindow(data->window);
  314. // Optional, used to mark frames during performance profiling.
  315. RMLUI_FrameMark;
  316. }