RmlUi_Backend_SDL_GL2.cpp 11 KB

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