RmlUi_Backend_SDL_GL2.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 RenderGeometry(Rml::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rml::TextureHandle texture,
  50. const Rml::Vector2f& translation) 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(vertices, num_vertices, indices, num_indices, texture, translation);
  59. if (sdl_texture)
  60. SDL_GL_UnbindTexture(sdl_texture);
  61. }
  62. bool LoadTexture(Rml::TextureHandle& texture_handle, 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 false;
  68. file_interface->Seek(file_handle, 0, SEEK_END);
  69. size_t buffer_size = file_interface->Tell(file_handle);
  70. file_interface->Seek(file_handle, 0, SEEK_SET);
  71. Rml::UniquePtr<char[]> buffer(new char[buffer_size]);
  72. file_interface->Read(buffer.get(), buffer_size, file_handle);
  73. file_interface->Close(file_handle);
  74. const size_t i = source.rfind('.');
  75. Rml::String extension = (i == Rml::String::npos ? Rml::String() : source.substr(i + 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->Amask == 0)
  80. {
  81. // Fix for rendering images with no alpha channel, see https://github.com/mikke89/RmlUi/issues/239
  82. SDL_Surface* converted_surface = SDL_ConvertSurfaceFormat(surface, SDL_PixelFormatEnum::SDL_PIXELFORMAT_RGBA32, 0);
  83. SDL_FreeSurface(surface);
  84. if (!converted_surface)
  85. return false;
  86. surface = converted_surface;
  87. }
  88. SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
  89. if (texture)
  90. {
  91. texture_handle = (Rml::TextureHandle)texture;
  92. texture_dimensions = Rml::Vector2i(surface->w, surface->h);
  93. }
  94. SDL_FreeSurface(surface);
  95. return true;
  96. }
  97. bool GenerateTexture(Rml::TextureHandle& texture_handle, const Rml::byte* source, const Rml::Vector2i& source_dimensions) override
  98. {
  99. #if SDL_BYTEORDER == SDL_BIG_ENDIAN
  100. Uint32 rmask = 0xff000000;
  101. Uint32 gmask = 0x00ff0000;
  102. Uint32 bmask = 0x0000ff00;
  103. Uint32 amask = 0x000000ff;
  104. #else
  105. Uint32 rmask = 0x000000ff;
  106. Uint32 gmask = 0x0000ff00;
  107. Uint32 bmask = 0x00ff0000;
  108. Uint32 amask = 0xff000000;
  109. #endif
  110. SDL_Surface* surface = SDL_CreateRGBSurfaceFrom((void*)source, source_dimensions.x, source_dimensions.y, 32, source_dimensions.x * 4, rmask,
  111. gmask, bmask, amask);
  112. SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
  113. SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
  114. SDL_FreeSurface(surface);
  115. texture_handle = (Rml::TextureHandle)texture;
  116. return true;
  117. }
  118. void ReleaseTexture(Rml::TextureHandle texture_handle) override { SDL_DestroyTexture((SDL_Texture*)texture_handle); }
  119. };
  120. /**
  121. Global data used by this backend.
  122. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  123. */
  124. struct BackendData {
  125. BackendData(SDL_Renderer* renderer) : render_interface(renderer) {}
  126. SystemInterface_SDL system_interface;
  127. RenderInterface_GL2_SDL render_interface;
  128. SDL_Window* window = nullptr;
  129. SDL_Renderer* renderer = nullptr;
  130. SDL_GLContext glcontext = nullptr;
  131. bool running = true;
  132. };
  133. static Rml::UniquePtr<BackendData> data;
  134. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  135. {
  136. RMLUI_ASSERT(!data);
  137. if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) != 0)
  138. return false;
  139. // Submit click events when focusing the window.
  140. SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
  141. // Request stencil buffer of at least 8-bit size to supporting clipping on transformed elements.
  142. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  143. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  144. // Enable linear filtering and MSAA for better-looking visuals, especially when transforms are applied.
  145. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
  146. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  147. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);
  148. const Uint32 window_flags = (SDL_WINDOW_OPENGL | (allow_resize ? SDL_WINDOW_RESIZABLE : 0));
  149. SDL_Window* window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  150. if (!window)
  151. {
  152. // Try again on low-quality settings.
  153. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest");
  154. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  155. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  156. window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  157. if (!window)
  158. {
  159. fprintf(stderr, "SDL error on create window: %s\n", SDL_GetError());
  160. return false;
  161. }
  162. }
  163. SDL_GLContext glcontext = SDL_GL_CreateContext(window);
  164. int opengl_renderer_index = -1;
  165. int num_render_drivers = SDL_GetNumRenderDrivers();
  166. for (int i = 0; i < num_render_drivers; i++)
  167. {
  168. SDL_RendererInfo info;
  169. if (SDL_GetRenderDriverInfo(i, &info) == 0)
  170. {
  171. if (strcmp(info.name, "opengl") == 0)
  172. opengl_renderer_index = i;
  173. }
  174. }
  175. SDL_Renderer* renderer = SDL_CreateRenderer(window, opengl_renderer_index, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  176. if (!renderer)
  177. return false;
  178. GLenum err = glewInit();
  179. if (err != GLEW_OK)
  180. {
  181. fprintf(stderr, "GLEW error: %s\n", glewGetErrorString(err));
  182. return false;
  183. }
  184. data = Rml::MakeUnique<BackendData>(renderer);
  185. data->window = window;
  186. data->glcontext = glcontext;
  187. data->renderer = renderer;
  188. data->system_interface.SetWindow(window);
  189. data->render_interface.SetViewport(width, height);
  190. return true;
  191. }
  192. void Backend::Shutdown()
  193. {
  194. RMLUI_ASSERT(data);
  195. SDL_DestroyRenderer(data->renderer);
  196. SDL_GL_DeleteContext(data->glcontext);
  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. bool result = data->running;
  215. data->running = true;
  216. SDL_Event ev;
  217. int has_event = 0;
  218. if (power_save)
  219. has_event = SDL_WaitEventTimeout(&ev, static_cast<int>(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0) * 1000));
  220. else
  221. has_event = SDL_PollEvent(&ev);
  222. while (has_event)
  223. {
  224. switch (ev.type)
  225. {
  226. case SDL_QUIT:
  227. {
  228. result = false;
  229. }
  230. break;
  231. case SDL_KEYDOWN:
  232. {
  233. const Rml::Input::KeyIdentifier key = RmlSDL::ConvertKey(ev.key.keysym.sym);
  234. const int key_modifier = RmlSDL::GetKeyModifierState();
  235. const float native_dp_ratio = 1.f;
  236. // See if we have any global shortcuts that take priority over the context.
  237. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  238. break;
  239. // Otherwise, hand the event over to the context by calling the input handler as normal.
  240. if (!RmlSDL::InputEventHandler(context, ev))
  241. break;
  242. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  243. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  244. break;
  245. }
  246. break;
  247. case SDL_WINDOWEVENT:
  248. {
  249. switch (ev.window.event)
  250. {
  251. case SDL_WINDOWEVENT_SIZE_CHANGED:
  252. {
  253. Rml::Vector2i dimensions(ev.window.data1, ev.window.data2);
  254. data->render_interface.SetViewport(dimensions.x, dimensions.y);
  255. }
  256. break;
  257. }
  258. RmlSDL::InputEventHandler(context, ev);
  259. }
  260. break;
  261. default:
  262. {
  263. RmlSDL::InputEventHandler(context, ev);
  264. }
  265. break;
  266. }
  267. has_event = SDL_PollEvent(&ev);
  268. }
  269. return result;
  270. }
  271. void Backend::RequestExit()
  272. {
  273. RMLUI_ASSERT(data);
  274. data->running = false;
  275. }
  276. void Backend::BeginFrame()
  277. {
  278. RMLUI_ASSERT(data);
  279. SDL_SetRenderDrawColor(data->renderer, 0, 0, 0, 0);
  280. SDL_RenderClear(data->renderer);
  281. // SDL uses shaders that we need to disable here.
  282. glUseProgramObjectARB(0);
  283. glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  284. data->render_interface.BeginFrame();
  285. }
  286. void Backend::PresentFrame()
  287. {
  288. RMLUI_ASSERT(data);
  289. data->render_interface.EndFrame();
  290. // 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.
  291. SDL_SetRenderDrawBlendMode(data->renderer, SDL_BLENDMODE_NONE);
  292. SDL_RenderDrawPoint(data->renderer, -1, -1);
  293. SDL_RenderPresent(data->renderer);
  294. }