RmlUi_Backend_GLFW_VK.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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/Config/Config.h"
  29. #include "RmlUi_Backend.h"
  30. #include "RmlUi_Renderer_VK.h"
  31. // This space is intentional to prevent autoformat from reordering RmlUi_Renderer_VK behind RmlUi_Platform_GLFW
  32. #include "RmlUi_Platform_GLFW.h"
  33. #include <RmlUi/Core/Context.h>
  34. #include <RmlUi/Core/Core.h>
  35. #include <RmlUi/Core/FileInterface.h>
  36. #include <GLFW/glfw3.h>
  37. #include <stdint.h>
  38. #include <thread>
  39. static void SetupCallbacks(GLFWwindow* window);
  40. static void LogErrorFromGLFW(int error, const char* description)
  41. {
  42. Rml::Log::Message(Rml::Log::LT_ERROR, "GLFW error (0x%x): %s", error, description);
  43. }
  44. /**
  45. Global data used by this backend.
  46. Lifetime governed by the calls to Backend::Initialize() and Backend::Shutdown().
  47. */
  48. struct BackendData {
  49. SystemInterface_GLFW system_interface;
  50. RenderInterface_VK render_interface;
  51. GLFWwindow* window = nullptr;
  52. Rml::Context* context = nullptr;
  53. KeyDownCallback key_down_callback = nullptr;
  54. int glfw_active_modifiers = 0;
  55. bool running = true;
  56. bool context_dimensions_dirty = true;
  57. };
  58. static Rml::UniquePtr<BackendData> data;
  59. bool Backend::Initialize(const char* window_name, int width, int height, bool allow_resize)
  60. {
  61. RMLUI_ASSERT(!data);
  62. glfwSetErrorCallback(LogErrorFromGLFW);
  63. if (!glfwInit())
  64. {
  65. glfwTerminate();
  66. return false;
  67. }
  68. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
  69. glfwWindowHint(GLFW_RESIZABLE, allow_resize ? GLFW_TRUE : GLFW_FALSE);
  70. glfwWindowHint(GLFW_SCALE_TO_MONITOR, GLFW_TRUE);
  71. GLFWwindow* window = glfwCreateWindow(width, height, window_name, nullptr, nullptr);
  72. if (!window)
  73. {
  74. fprintf(stderr, "[GLFW] error can't create window!");
  75. return false;
  76. }
  77. data = Rml::MakeUnique<BackendData>();
  78. data->window = window;
  79. uint32_t count;
  80. const char** extensions = glfwGetRequiredInstanceExtensions(&count);
  81. RMLUI_VK_ASSERTMSG(extensions != nullptr, "Failed to query glfw vulkan extensions");
  82. if (!data->render_interface.Initialize(Rml::Vector<const char*>(extensions, extensions + count),
  83. [](VkInstance instance, VkSurfaceKHR* out_surface) {
  84. return glfwCreateWindowSurface(instance, data->window, nullptr, out_surface) == VkResult::VK_SUCCESS;
  85. ;
  86. }))
  87. {
  88. data.reset();
  89. fprintf(stderr, "Could not initialize Vulkan render interface.");
  90. return false;
  91. }
  92. data->system_interface.SetWindow(window);
  93. data->render_interface.SetViewport(width, height);
  94. // Receive num lock and caps lock modifiers for proper handling of numpad inputs in text fields.
  95. glfwSetInputMode(window, GLFW_LOCK_KEY_MODS, GLFW_TRUE);
  96. SetupCallbacks(window);
  97. return true;
  98. }
  99. void Backend::Shutdown()
  100. {
  101. RMLUI_ASSERT(data);
  102. data->render_interface.Shutdown();
  103. glfwDestroyWindow(data->window);
  104. data.reset();
  105. glfwTerminate();
  106. }
  107. Rml::SystemInterface* Backend::GetSystemInterface()
  108. {
  109. RMLUI_ASSERT(data);
  110. return &data->system_interface;
  111. }
  112. Rml::RenderInterface* Backend::GetRenderInterface()
  113. {
  114. RMLUI_ASSERT(data);
  115. return &data->render_interface;
  116. }
  117. static bool WaitForValidSwapchain()
  118. {
  119. bool result = true;
  120. // In some situations the swapchain may become invalid, such as when the window is minimized. In this state the renderer cannot accept any render
  121. // calls. Since we don't have full control over the main loop here we may risk calls to Context::Render if we were to return. Instead, we keep the
  122. // application inside this loop until we are able to recreate the swapchain and render again.
  123. while (!data->render_interface.IsSwapchainValid())
  124. {
  125. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  126. if (glfwWindowShouldClose(data->window))
  127. {
  128. glfwRestoreWindow(data->window);
  129. result = false;
  130. }
  131. glfwPollEvents();
  132. data->render_interface.RecreateSwapchain();
  133. }
  134. return result;
  135. }
  136. bool Backend::ProcessEvents(Rml::Context* context, KeyDownCallback key_down_callback, bool power_save)
  137. {
  138. RMLUI_ASSERT(data && context);
  139. bool result = data->running;
  140. if (data->context_dimensions_dirty)
  141. {
  142. data->context_dimensions_dirty = false;
  143. Rml::Vector2i window_size;
  144. float dp_ratio = 1.f;
  145. glfwGetFramebufferSize(data->window, &window_size.x, &window_size.y);
  146. glfwGetWindowContentScale(data->window, &dp_ratio, nullptr);
  147. context->SetDimensions(window_size);
  148. context->SetDensityIndependentPixelRatio(dp_ratio);
  149. }
  150. data->context = context;
  151. data->key_down_callback = key_down_callback;
  152. if (power_save)
  153. glfwWaitEventsTimeout(Rml::Math::Min(context->GetNextUpdateDelay(), 10.0));
  154. else
  155. glfwPollEvents();
  156. if (!WaitForValidSwapchain())
  157. result = false;
  158. data->context = nullptr;
  159. data->key_down_callback = nullptr;
  160. result = !glfwWindowShouldClose(data->window);
  161. glfwSetWindowShouldClose(data->window, GLFW_FALSE);
  162. return result;
  163. }
  164. void Backend::RequestExit()
  165. {
  166. RMLUI_ASSERT(data);
  167. data->running = false;
  168. glfwSetWindowShouldClose(data->window, GLFW_TRUE);
  169. }
  170. void Backend::BeginFrame()
  171. {
  172. RMLUI_ASSERT(data);
  173. data->render_interface.BeginFrame();
  174. }
  175. void Backend::PresentFrame()
  176. {
  177. RMLUI_ASSERT(data);
  178. data->render_interface.EndFrame();
  179. }
  180. static void SetupCallbacks(GLFWwindow* window)
  181. {
  182. RMLUI_ASSERT(data);
  183. // Key input
  184. glfwSetKeyCallback(window, [](GLFWwindow* /*window*/, int glfw_key, int /*scancode*/, int glfw_action, int glfw_mods) {
  185. if (!data->context)
  186. return;
  187. // Store the active modifiers for later because GLFW doesn't provide them in the callbacks to the mouse input events.
  188. data->glfw_active_modifiers = glfw_mods;
  189. // Override the default key event callback to add global shortcuts for the samples.
  190. Rml::Context* context = data->context;
  191. KeyDownCallback key_down_callback = data->key_down_callback;
  192. switch (glfw_action)
  193. {
  194. case GLFW_PRESS:
  195. case GLFW_REPEAT:
  196. {
  197. const Rml::Input::KeyIdentifier key = RmlGLFW::ConvertKey(glfw_key);
  198. const int key_modifier = RmlGLFW::ConvertKeyModifiers(glfw_mods);
  199. float dp_ratio = 1.f;
  200. glfwGetWindowContentScale(data->window, &dp_ratio, nullptr);
  201. // See if we have any global shortcuts that take priority over the context.
  202. if (key_down_callback && !key_down_callback(context, key, key_modifier, dp_ratio, true))
  203. break;
  204. // Otherwise, hand the event over to the context by calling the input handler as normal.
  205. if (!RmlGLFW::ProcessKeyCallback(context, glfw_key, glfw_action, glfw_mods))
  206. break;
  207. // The key was not consumed by the context either, try keyboard shortcuts of lower priority.
  208. if (key_down_callback && !key_down_callback(context, key, key_modifier, dp_ratio, false))
  209. break;
  210. }
  211. break;
  212. case GLFW_RELEASE: RmlGLFW::ProcessKeyCallback(context, glfw_key, glfw_action, glfw_mods); break;
  213. }
  214. });
  215. glfwSetCharCallback(window, [](GLFWwindow* /*window*/, unsigned int codepoint) { RmlGLFW::ProcessCharCallback(data->context, codepoint); });
  216. glfwSetCursorEnterCallback(window, [](GLFWwindow* /*window*/, int entered) { RmlGLFW::ProcessCursorEnterCallback(data->context, entered); });
  217. // Mouse input
  218. glfwSetCursorPosCallback(window, [](GLFWwindow* window, double xpos, double ypos) {
  219. RmlGLFW::ProcessCursorPosCallback(data->context, window, xpos, ypos, data->glfw_active_modifiers);
  220. });
  221. glfwSetMouseButtonCallback(window, [](GLFWwindow* /*window*/, int button, int action, int mods) {
  222. data->glfw_active_modifiers = mods;
  223. RmlGLFW::ProcessMouseButtonCallback(data->context, button, action, mods);
  224. });
  225. glfwSetScrollCallback(window, [](GLFWwindow* /*window*/, double /*xoffset*/, double yoffset) {
  226. RmlGLFW::ProcessScrollCallback(data->context, yoffset, data->glfw_active_modifiers);
  227. });
  228. // Window events
  229. glfwSetFramebufferSizeCallback(window, [](GLFWwindow* /*window*/, int width, int height) {
  230. data->render_interface.SetViewport(width, height);
  231. RmlGLFW::ProcessFramebufferSizeCallback(data->context, width, height);
  232. });
  233. glfwSetWindowContentScaleCallback(window,
  234. [](GLFWwindow* /*window*/, float xscale, float /*yscale*/) { RmlGLFW::ProcessContentScaleCallback(data->context, xscale); });
  235. }