RmlUi_Backend_GLFW_VK.cpp 8.5 KB

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