RmlUi_Backend_SFML_GL2.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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_SFML.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/Profiling.h>
  35. #include <RmlUi/Debugger/Debugger.h>
  36. #include <SFML/Graphics.hpp>
  37. #include <SFML/Window.hpp>
  38. /**
  39. Custom render interface example for the SFML/GL2 backend.
  40. Overloads the OpenGL2 render interface to load textures through SFML's built-in texture loading functionality.
  41. */
  42. class RenderInterface_GL2_SFML : public RenderInterface_GL2 {
  43. public:
  44. // -- Inherited from Rml::RenderInterface --
  45. void RenderCompiledGeometry(Rml::CompiledGeometryHandle handle, const Rml::Vector2f& translation, Rml::TextureHandle texture) override
  46. {
  47. if (texture)
  48. {
  49. sf::Texture::bind((sf::Texture*)texture);
  50. texture = RenderInterface_GL2::TextureEnableWithoutBinding;
  51. }
  52. RenderInterface_GL2::RenderCompiledGeometry(handle, translation, texture);
  53. }
  54. bool LoadTexture(Rml::TextureHandle& texture_handle, Rml::Vector2i& texture_dimensions, const Rml::String& source) override
  55. {
  56. Rml::FileInterface* file_interface = Rml::GetFileInterface();
  57. Rml::FileHandle file_handle = file_interface->Open(source);
  58. if (!file_handle)
  59. return false;
  60. file_interface->Seek(file_handle, 0, SEEK_END);
  61. size_t buffer_size = file_interface->Tell(file_handle);
  62. file_interface->Seek(file_handle, 0, SEEK_SET);
  63. using Rml::byte;
  64. Rml::UniquePtr<byte[]> buffer(new byte[buffer_size]);
  65. file_interface->Read(buffer.get(), buffer_size, file_handle);
  66. file_interface->Close(file_handle);
  67. sf::Image image;
  68. if (!image.loadFromMemory(buffer.get(), buffer_size))
  69. return false;
  70. // Convert colors to premultiplied alpha, which is necessary for correct alpha compositing.
  71. for (unsigned int x = 0; x < image.getSize().x; x++)
  72. {
  73. for (unsigned int y = 0; y < image.getSize().y; y++)
  74. {
  75. sf::Color color = image.getPixel(x, y);
  76. color.r = (sf::Uint8)((color.r * color.a) / 255);
  77. color.g = (sf::Uint8)((color.g * color.a) / 255);
  78. color.b = (sf::Uint8)((color.b * color.a) / 255);
  79. image.setPixel(x, y, color);
  80. }
  81. }
  82. sf::Texture* texture = new sf::Texture();
  83. texture->setSmooth(true);
  84. if (!texture->loadFromImage(image))
  85. {
  86. delete texture;
  87. return false;
  88. }
  89. texture_handle = (Rml::TextureHandle)texture;
  90. texture_dimensions = Rml::Vector2i(texture->getSize().x, texture->getSize().y);
  91. return true;
  92. }
  93. bool GenerateTexture(Rml::TextureHandle& texture_handle, const Rml::byte* source, const Rml::Vector2i& source_dimensions) override
  94. {
  95. sf::Texture* texture = new sf::Texture();
  96. texture->setSmooth(true);
  97. if (!texture->create(source_dimensions.x, source_dimensions.y))
  98. {
  99. delete texture;
  100. return false;
  101. }
  102. texture->update(source, source_dimensions.x, source_dimensions.y, 0, 0);
  103. texture_handle = (Rml::TextureHandle)texture;
  104. return true;
  105. }
  106. void ReleaseTexture(Rml::TextureHandle texture_handle) override { delete (sf::Texture*)texture_handle; }
  107. };
  108. // Updates the viewport and context dimensions, should be called whenever the window size changes.
  109. static void UpdateWindowDimensions(sf::RenderWindow& window, RenderInterface_GL2_SFML& render_interface, Rml::Context* context)
  110. {
  111. const int width = (int)window.getSize().x;
  112. const int height = (int)window.getSize().y;
  113. if (context)
  114. context->SetDimensions(Rml::Vector2i(width, height));
  115. sf::View view(sf::FloatRect(0.f, 0.f, (float)width, (float)height));
  116. window.setView(view);
  117. render_interface.SetViewport(width, height);
  118. }
  119. /**
  120. Global data used by this backend.
  121. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  122. */
  123. struct BackendData {
  124. SystemInterface_SFML system_interface;
  125. RenderInterface_GL2_SFML render_interface;
  126. sf::RenderWindow window;
  127. bool running = true;
  128. };
  129. static Rml::UniquePtr<BackendData> data;
  130. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  131. {
  132. RMLUI_ASSERT(!data);
  133. data = Rml::MakeUnique<BackendData>();
  134. // Create the window.
  135. sf::RenderWindow out_window;
  136. sf::ContextSettings context_settings;
  137. context_settings.stencilBits = 8;
  138. context_settings.antialiasingLevel = 2;
  139. const sf::Uint32 style = (allow_resize ? sf::Style::Default : (sf::Style::Titlebar | sf::Style::Close));
  140. data->window.create(sf::VideoMode(width, height), window_name, style, context_settings);
  141. data->window.setVerticalSyncEnabled(true);
  142. if (!data->window.isOpen())
  143. {
  144. data.reset();
  145. return false;
  146. }
  147. // Optionally apply the SFML window to the system interface so that it can change its mouse cursor.
  148. data->system_interface.SetWindow(&data->window);
  149. UpdateWindowDimensions(data->window, data->render_interface, nullptr);
  150. return true;
  151. }
  152. void Backend::Shutdown()
  153. {
  154. data.reset();
  155. }
  156. Rml::SystemInterface* Backend::GetSystemInterface()
  157. {
  158. RMLUI_ASSERT(data);
  159. return &data->system_interface;
  160. }
  161. Rml::RenderInterface* Backend::GetRenderInterface()
  162. {
  163. RMLUI_ASSERT(data);
  164. return &data->render_interface;
  165. }
  166. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  167. {
  168. RMLUI_ASSERT(data && context);
  169. // SFML does not seem to provide a way to wait for events with a timeout.
  170. (void)power_save;
  171. // The contents of this function is intended to be copied directly into your main loop.
  172. bool result = data->running;
  173. data->running = true;
  174. sf::Event ev;
  175. while (data->window.pollEvent(ev))
  176. {
  177. switch (ev.type)
  178. {
  179. case sf::Event::Resized: UpdateWindowDimensions(data->window, data->render_interface, context); break;
  180. case sf::Event::KeyPressed:
  181. {
  182. const Rml::Input::KeyIdentifier key = RmlSFML::ConvertKey(ev.key.code);
  183. const int key_modifier = RmlSFML::GetKeyModifierState();
  184. const float native_dp_ratio = 1.f;
  185. // See if we have any global shortcuts that take priority over the context.
  186. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, true))
  187. break;
  188. // Otherwise, hand the event over to the context by calling the input handler as normal.
  189. if (!RmlSFML::InputHandler(context, ev))
  190. break;
  191. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  192. if (key_down_callback && !key_down_callback(context, key, key_modifier, native_dp_ratio, false))
  193. break;
  194. }
  195. break;
  196. case sf::Event::Closed: result = false; break;
  197. default: RmlSFML::InputHandler(context, ev); break;
  198. }
  199. }
  200. return result;
  201. }
  202. void Backend::RequestExit()
  203. {
  204. RMLUI_ASSERT(data);
  205. data->running = false;
  206. }
  207. void Backend::BeginFrame()
  208. {
  209. RMLUI_ASSERT(data);
  210. sf::RenderWindow& window = data->window;
  211. window.resetGLStates();
  212. window.clear();
  213. data->render_interface.BeginFrame();
  214. #if 0
  215. // Draw a simple shape with SFML for demonstration purposes. Make sure to push and pop GL states as appropriate.
  216. sf::Vector2f circle_position(100.f, 100.f);
  217. window.pushGLStates();
  218. sf::CircleShape circle(50.f);
  219. circle.setPosition(circle_position);
  220. circle.setFillColor(sf::Color::Blue);
  221. circle.setOutlineColor(sf::Color::Red);
  222. circle.setOutlineThickness(10.f);
  223. window.draw(circle);
  224. window.popGLStates();
  225. #endif
  226. }
  227. void Backend::PresentFrame()
  228. {
  229. RMLUI_ASSERT(data);
  230. data->render_interface.EndFrame();
  231. data->window.display();
  232. // Optional, used to mark frames during performance profiling.
  233. RMLUI_FrameMark;
  234. }