RmlUi_Backend_SDL_GL3.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 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 <SDL.h>
  35. #include <SDL_image.h>
  36. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  37. #include <emscripten.h>
  38. #else
  39. #if !(SDL_VIDEO_RENDER_OGL)
  40. #error "Only the OpenGL SDL backend is supported."
  41. #endif
  42. #endif
  43. /**
  44. Custom render interface example for the SDL/GL3 backend.
  45. Overloads the OpenGL3 render interface to load textures through SDL_image's built-in texture loading functionality.
  46. */
  47. class RenderInterface_GL3_SDL : public RenderInterface_GL3 {
  48. public:
  49. RenderInterface_GL3_SDL() {}
  50. bool LoadTexture(Rml::TextureHandle& texture_handle, Rml::Vector2i& texture_dimensions, const Rml::String& source) override
  51. {
  52. Rml::FileInterface* file_interface = Rml::GetFileInterface();
  53. Rml::FileHandle file_handle = file_interface->Open(source);
  54. if (!file_handle)
  55. return false;
  56. file_interface->Seek(file_handle, 0, SEEK_END);
  57. const size_t buffer_size = file_interface->Tell(file_handle);
  58. file_interface->Seek(file_handle, 0, SEEK_SET);
  59. using Rml::byte;
  60. Rml::UniquePtr<byte[]> buffer(new byte[buffer_size]);
  61. file_interface->Read(buffer.get(), buffer_size, file_handle);
  62. file_interface->Close(file_handle);
  63. const size_t i = source.rfind('.');
  64. Rml::String extension = (i == Rml::String::npos ? Rml::String() : source.substr(i + 1));
  65. SDL_Surface* surface = IMG_LoadTyped_RW(SDL_RWFromMem(buffer.get(), int(buffer_size)), 1, extension.c_str());
  66. bool success = false;
  67. if (surface)
  68. {
  69. texture_dimensions.x = surface->w;
  70. texture_dimensions.y = surface->h;
  71. if (surface->format->format != SDL_PIXELFORMAT_RGBA32)
  72. {
  73. SDL_SetSurfaceAlphaMod(surface, SDL_ALPHA_OPAQUE);
  74. SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_NONE);
  75. SDL_Surface* new_surface = SDL_CreateRGBSurfaceWithFormat(0, surface->w, surface->h, 32, SDL_PIXELFORMAT_RGBA32);
  76. if (!new_surface)
  77. return false;
  78. if (SDL_BlitSurface(surface, 0, new_surface, 0) != 0)
  79. return false;
  80. SDL_FreeSurface(surface);
  81. surface = new_surface;
  82. }
  83. success = RenderInterface_GL3::GenerateTexture(texture_handle, (const Rml::byte*)surface->pixels, texture_dimensions);
  84. SDL_FreeSurface(surface);
  85. }
  86. return success;
  87. }
  88. };
  89. /**
  90. Global data used by this backend.
  91. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  92. */
  93. struct BackendData {
  94. SystemInterface_SDL system_interface;
  95. RenderInterface_GL3_SDL render_interface;
  96. SDL_Window* window = nullptr;
  97. SDL_GLContext glcontext = nullptr;
  98. bool running = true;
  99. };
  100. static Rml::UniquePtr<BackendData> data;
  101. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  102. {
  103. RMLUI_ASSERT(!data);
  104. if (SDL_Init(SDL_INIT_VIDEO) != 0)
  105. return false;
  106. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  107. // GLES 3.0 (WebGL 2.0)
  108. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
  109. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
  110. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  111. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  112. #else
  113. // GL 3.3 Core
  114. SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 0);
  115. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  116. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  117. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
  118. #endif
  119. // Request stencil buffer of at least 8-bit size to supporting clipping on transformed elements.
  120. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  121. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  122. // Enable linear filtering and MSAA for better-looking visuals, especially when transforms are applied.
  123. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
  124. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  125. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 2);
  126. const Uint32 window_flags = (SDL_WINDOW_OPENGL | (allow_resize ? SDL_WINDOW_RESIZABLE : 0));
  127. SDL_Window* window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  128. if (!window)
  129. {
  130. // Try again on low-quality settings.
  131. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest");
  132. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  133. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  134. window = SDL_CreateWindow(window_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, window_flags);
  135. if (!window)
  136. {
  137. fprintf(stderr, "SDL error on create window: %s\n", SDL_GetError());
  138. return false;
  139. }
  140. }
  141. SDL_GLContext glcontext = SDL_GL_CreateContext(window);
  142. SDL_GL_MakeCurrent(window, glcontext);
  143. SDL_GL_SetSwapInterval(1);
  144. if (!RmlGL3::Initialize())
  145. {
  146. fprintf(stderr, "Could not initialize OpenGL");
  147. return false;
  148. }
  149. data = Rml::MakeUnique<BackendData>();
  150. if (!data->render_interface)
  151. {
  152. data.reset();
  153. fprintf(stderr, "Could not initialize OpenGL3 render interface.");
  154. return false;
  155. }
  156. data->window = window;
  157. data->glcontext = glcontext;
  158. data->system_interface.SetWindow(window);
  159. data->render_interface.SetViewport(width, height);
  160. return true;
  161. }
  162. void Backend::Shutdown()
  163. {
  164. RMLUI_ASSERT(data);
  165. SDL_GL_DeleteContext(data->glcontext);
  166. SDL_DestroyWindow(data->window);
  167. data.reset();
  168. SDL_Quit();
  169. }
  170. Rml::SystemInterface* Backend::GetSystemInterface()
  171. {
  172. RMLUI_ASSERT(data);
  173. return &data->system_interface;
  174. }
  175. Rml::RenderInterface* Backend::GetRenderInterface()
  176. {
  177. RMLUI_ASSERT(data);
  178. return &data->render_interface;
  179. }
  180. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback)
  181. {
  182. RMLUI_ASSERT(data && context);
  183. #if defined RMLUI_PLATFORM_EMSCRIPTEN
  184. // Ideally we would hand over control of the main loop to emscripten:
  185. //
  186. // // Hand over control of the main loop to the WebAssembly runtime.
  187. // emscripten_set_main_loop_arg(EventLoopIteration, (void*)user_data_handle, 0, true);
  188. //
  189. // 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
  190. // Asyncify to yield by sleeping.
  191. // Important: Must be linked with option -sASYNCIFY
  192. emscripten_sleep(1);
  193. #endif
  194. bool result = data->running;
  195. SDL_Event ev;
  196. while (SDL_PollEvent(&ev))
  197. {
  198. switch (ev.type)
  199. {
  200. case SDL_QUIT:
  201. {
  202. result = false;
  203. }
  204. break;
  205. case SDL_KEYDOWN:
  206. {
  207. const Rml::Input::KeyIdentifier key = RmlSDL::ConvertKey(ev.key.keysym.sym);
  208. const int key_modifier = RmlSDL::GetKeyModifierState();
  209. const float native_dp_ratio = 1.f;
  210. // See if we have any global shortcuts that take priority over the context.
  211. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  212. break;
  213. // Otherwise, hand the event over to the context by calling the input handler as normal.
  214. if (!RmlSDL::InputEventHandler(context, ev))
  215. break;
  216. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  217. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  218. break;
  219. }
  220. break;
  221. case SDL_WINDOWEVENT:
  222. {
  223. switch (ev.window.event)
  224. {
  225. case SDL_WINDOWEVENT_SIZE_CHANGED:
  226. {
  227. Rml::Vector2i dimensions(ev.window.data1, ev.window.data2);
  228. data->render_interface.SetViewport(dimensions.x, dimensions.y);
  229. }
  230. break;
  231. }
  232. RmlSDL::InputEventHandler(context, ev);
  233. }
  234. break;
  235. default:
  236. {
  237. RmlSDL::InputEventHandler(context, ev);
  238. }
  239. break;
  240. }
  241. }
  242. return result;
  243. }
  244. void Backend::RequestExit()
  245. {
  246. RMLUI_ASSERT(data);
  247. data->running = false;
  248. }
  249. void Backend::BeginFrame()
  250. {
  251. RMLUI_ASSERT(data);
  252. data->render_interface.Clear();
  253. data->render_interface.BeginFrame();
  254. }
  255. void Backend::PresentFrame()
  256. {
  257. RMLUI_ASSERT(data);
  258. data->render_interface.EndFrame();
  259. SDL_GL_SwapWindow(data->window);
  260. }