RmlUi_Backend_SFML_GL2.cpp 9.8 KB

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