RmlUi_Backend_SDL_GL2.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. #include <GL/glew.h>
  36. #include <SDL.h>
  37. #include <SDL_image.h>
  38. #if !(SDL_VIDEO_RENDER_OGL)
  39. #error "Only the OpenGL SDL backend is supported."
  40. #endif
  41. /**
  42. Custom render interface example for the SDL/GL2 backend.
  43. Overloads the OpenGL2 render interface to load textures through SDL_image's built-in texture loading functionality.
  44. */
  45. class RenderInterface_GL2_SDL : public RenderInterface_GL2 {
  46. private:
  47. SDL_Renderer* renderer;
  48. public:
  49. RenderInterface_GL2_SDL(SDL_Renderer* renderer) : renderer(renderer) {}
  50. void RenderGeometry(Rml::CompiledGeometryHandle handle, Rml::Vector2f translation, Rml::TextureHandle texture) override
  51. {
  52. SDL_Texture* sdl_texture = (SDL_Texture*)texture;
  53. if (sdl_texture)
  54. {
  55. SDL_GL_BindTexture(sdl_texture, nullptr, nullptr);
  56. texture = RenderInterface_GL2::TextureEnableWithoutBinding;
  57. }
  58. RenderInterface_GL2::RenderGeometry(handle, translation, texture);
  59. if (sdl_texture)
  60. SDL_GL_UnbindTexture(sdl_texture);
  61. }
  62. Rml::TextureHandle LoadTexture(Rml::Vector2i& texture_dimensions, const Rml::String& source) override
  63. {
  64. Rml::FileInterface* file_interface = Rml::GetFileInterface();
  65. Rml::FileHandle file_handle = file_interface->Open(source);
  66. if (!file_handle)
  67. return {};
  68. file_interface->Seek(file_handle, 0, SEEK_END);
  69. const size_t buffer_size = file_interface->Tell(file_handle);
  70. file_interface->Seek(file_handle, 0, SEEK_SET);
  71. using Rml::byte;
  72. Rml::UniquePtr<byte[]> buffer(new byte[buffer_size]);
  73. file_interface->Read(buffer.get(), buffer_size, file_handle);
  74. file_interface->Close(file_handle);
  75. const size_t i_ext = source.rfind('.');
  76. Rml::String extension = (i_ext == Rml::String::npos ? Rml::String() : source.substr(i_ext + 1));
  77. SDL_Surface* surface = IMG_LoadTyped_RW(SDL_RWFromMem(buffer.get(), int(buffer_size)), 1, extension.c_str());
  78. if (!surface)
  79. return {};
  80. texture_dimensions = {surface->w, surface->h};
  81. if (surface->format->format != SDL_PIXELFORMAT_RGBA32 && surface->format->format != SDL_PIXELFORMAT_BGRA32)
  82. {
  83. // Ensure correct format for premultiplied alpha conversion below. Additionally, fix rendering images with
  84. // no alpha channel, see https://github.com/mikke89/RmlUi/issues/239
  85. SDL_Surface* converted_surface = SDL_ConvertSurfaceFormat(surface, SDL_PixelFormatEnum::SDL_PIXELFORMAT_RGBA32, 0);
  86. SDL_FreeSurface(surface);
  87. if (!converted_surface)
  88. return {};
  89. surface = converted_surface;
  90. }
  91. // Convert colors to premultiplied alpha, which is necessary for correct alpha compositing.
  92. byte* pixels = static_cast<byte*>(surface->pixels);
  93. for (int i = 0; i < surface->w * surface->h * 4; i += 4)
  94. {
  95. const byte alpha = pixels[i + 3];
  96. for (int j = 0; j < 3; ++j)
  97. pixels[i + j] = byte(int(pixels[i + j]) * int(alpha) / 255);
  98. }
  99. SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
  100. SDL_FreeSurface(surface);
  101. return (Rml::TextureHandle)texture;
  102. }
  103. Rml::TextureHandle GenerateTexture(Rml::Span<const Rml::byte> source, Rml::Vector2i source_dimensions) override
  104. {
  105. #if SDL_BYTEORDER == SDL_BIG_ENDIAN
  106. Uint32 rmask = 0xff000000;
  107. Uint32 gmask = 0x00ff0000;
  108. Uint32 bmask = 0x0000ff00;
  109. Uint32 amask = 0x000000ff;
  110. #else
  111. Uint32 rmask = 0x000000ff;
  112. Uint32 gmask = 0x0000ff00;
  113. Uint32 bmask = 0x00ff0000;
  114. Uint32 amask = 0xff000000;
  115. #endif
  116. SDL_Surface* surface = SDL_CreateRGBSurfaceFrom((void*)source.data(), source_dimensions.x, source_dimensions.y, 32, source_dimensions.x * 4,
  117. rmask, gmask, bmask, amask);
  118. SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
  119. SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
  120. SDL_FreeSurface(surface);
  121. return (Rml::TextureHandle)texture;
  122. }
  123. void ReleaseTexture(Rml::TextureHandle texture_handle) override { SDL_DestroyTexture((SDL_Texture*)texture_handle); }
  124. };
  125. /**
  126. Global data used by this backend.
  127. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  128. */
  129. struct BackendData {
  130. BackendData(SDL_Renderer* renderer) : render_interface(renderer) {}
  131. SystemInterface_SDL system_interface;
  132. RenderInterface_GL2_SDL render_interface;
  133. SDL_Window* window = nullptr;
  134. SDL_Renderer* renderer = nullptr;
  135. SDL_GLContext glcontext = nullptr;
  136. bool running = true;
  137. };
  138. static Rml::UniquePtr<BackendData> data;
  139. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  140. {
  141. RMLUI_ASSERT(!data);
  142. if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
  143. return false;
  144. // Submit click events when focusing the window.
  145. SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
  146. // Request stencil buffer of at least 8-bit size to supporting clipping on transformed elements.
  147. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  148. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  149. // Enable linear filtering and MSAA for better-looking visuals, especially when transforms are applied.
  150. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
  151. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  152. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);
  153. const Uint32 window_flags = (SDL_WINDOW_OPENGL | (allow_resize ? SDL_WINDOW_RESIZABLE : 0));
  154. SDL_Window* window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  155. if (!window)
  156. {
  157. // Try again on low-quality settings.
  158. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest");
  159. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  160. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  161. window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  162. if (!window)
  163. {
  164. Rml::Log::Message(Rml::Log::LT_ERROR, "SDL error on create window: %s", SDL_GetError());
  165. return false;
  166. }
  167. }
  168. SDL_GLContext glcontext = SDL_GL_CreateContext(window);
  169. int opengl_renderer_index = -1;
  170. int num_render_drivers = SDL_GetNumRenderDrivers();
  171. for (int i = 0; i < num_render_drivers; i++)
  172. {
  173. SDL_RendererInfo info;
  174. if (SDL_GetRenderDriverInfo(i, &info) == 0)
  175. {
  176. if (strcmp(info.name, "opengl") == 0)
  177. opengl_renderer_index = i;
  178. }
  179. }
  180. SDL_Renderer* renderer = SDL_CreateRenderer(window, opengl_renderer_index, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  181. if (!renderer)
  182. return false;
  183. GLenum err = glewInit();
  184. if (err != GLEW_OK)
  185. {
  186. Rml::Log::Message(Rml::Log::LT_ERROR, "GLEW error: %s", glewGetErrorString(err));
  187. return false;
  188. }
  189. data = Rml::MakeUnique<BackendData>(renderer);
  190. data->window = window;
  191. data->glcontext = glcontext;
  192. data->renderer = renderer;
  193. data->system_interface.SetWindow(window);
  194. data->render_interface.SetViewport(width, height);
  195. return true;
  196. }
  197. void Backend::Shutdown()
  198. {
  199. RMLUI_ASSERT(data);
  200. SDL_DestroyRenderer(data->renderer);
  201. SDL_GL_DeleteContext(data->glcontext);
  202. SDL_DestroyWindow(data->window);
  203. data.reset();
  204. SDL_Quit();
  205. }
  206. Rml::SystemInterface* Backend::GetSystemInterface()
  207. {
  208. RMLUI_ASSERT(data);
  209. return &data->system_interface;
  210. }
  211. Rml::RenderInterface* Backend::GetRenderInterface()
  212. {
  213. RMLUI_ASSERT(data);
  214. return &data->render_interface;
  215. }
  216. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  217. {
  218. RMLUI_ASSERT(data && context);
  219. bool result = data->running;
  220. data->running = true;
  221. SDL_Event ev;
  222. int has_event = 0;
  223. if (power_save)
  224. has_event = SDL_WaitEventTimeout(&ev, static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000));
  225. else
  226. has_event = SDL_PollEvent(&ev);
  227. while (has_event)
  228. {
  229. switch (ev.type)
  230. {
  231. case SDL_QUIT:
  232. {
  233. result = false;
  234. }
  235. break;
  236. case SDL_KEYDOWN:
  237. {
  238. const Rml::Input::KeyIdentifier key = RmlSDL::ConvertKey(ev.key.keysym.sym);
  239. const int key_modifier = RmlSDL::GetKeyModifierState();
  240. const float native_dp_ratio = 1.f;
  241. // See if we have any global shortcuts that take priority over the context.
  242. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  243. break;
  244. // Otherwise, hand the event over to the context by calling the input handler as normal.
  245. if (!RmlSDL::InputEventHandler(context, ev))
  246. break;
  247. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  248. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  249. break;
  250. }
  251. break;
  252. case SDL_WINDOWEVENT:
  253. {
  254. switch (ev.window.event)
  255. {
  256. case SDL_WINDOWEVENT_SIZE_CHANGED:
  257. {
  258. Rml::Vector2i dimensions(ev.window.data1, ev.window.data2);
  259. data->render_interface.SetViewport(dimensions.x, dimensions.y);
  260. }
  261. break;
  262. }
  263. RmlSDL::InputEventHandler(context, ev);
  264. }
  265. break;
  266. default:
  267. {
  268. RmlSDL::InputEventHandler(context, ev);
  269. }
  270. break;
  271. }
  272. has_event = SDL_PollEvent(&ev);
  273. }
  274. return result;
  275. }
  276. void Backend::RequestExit()
  277. {
  278. RMLUI_ASSERT(data);
  279. data->running = false;
  280. }
  281. void Backend::BeginFrame()
  282. {
  283. RMLUI_ASSERT(data);
  284. SDL_SetRenderDrawColor(data->renderer, 0, 0, 0, 0);
  285. SDL_RenderClear(data->renderer);
  286. // SDL uses shaders that we need to disable here.
  287. glUseProgramObjectARB(0);
  288. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  289. data->render_interface.BeginFrame();
  290. }
  291. void Backend::PresentFrame()
  292. {
  293. RMLUI_ASSERT(data);
  294. data->render_interface.EndFrame();
  295. // Draw a fake point just outside the screen to let SDL know that it needs to reset its state in case it wants to render a texture next frame.
  296. SDL_SetRenderDrawBlendMode(data->renderer, SDL_BLENDMODE_NONE);
  297. SDL_RenderDrawPoint(data->renderer, -1, -1);
  298. SDL_RenderPresent(data->renderer);
  299. }