1#include "window_system.h"
2#include "taichi/rhi/impl_support.h"
3
4#include <mutex>
5#include <array>
6#include <iostream>
7
8namespace taichi::lang::window_system {
9
10#ifdef TI_WITH_GLFW
11struct GLFWState {
12 std::mutex mutex;
13 int glfw_ref_count = 0;
14};
15
16static GLFWState glfw_state;
17
18static void glfw_error_callback(int code, const char *description) {
19 std::array<char, 1024> buf;
20 snprintf(buf.data(), buf.size(), "GLFW Error %d: %s", code, description);
21 RHI_LOG_ERROR(buf.data());
22}
23
24bool glfw_context_acquire() {
25 std::lock_guard lg(glfw_state.mutex);
26 if (glfw_state.glfw_ref_count == 0) {
27 auto res = glfwInit();
28 if (res != GLFW_TRUE) {
29 return false;
30 }
31
32 glfwSetErrorCallback(glfw_error_callback);
33 }
34 glfw_state.glfw_ref_count++;
35 return true;
36}
37
38void glfw_context_release() {
39 std::lock_guard lg(glfw_state.mutex);
40 glfw_state.glfw_ref_count--;
41 if (glfw_state.glfw_ref_count == 0) {
42 glfwTerminate();
43 } else if (glfw_state.glfw_ref_count < 0) {
44 assert(false && "GLFW context double release?");
45 }
46}
47
48#else
49
50bool glfw_context_acquire() {
51 return false;
52}
53
54void glfw_context_release() {
55 return;
56}
57
58#endif // TI_WITH_GLFW
59
60} // namespace taichi::lang::window_system
61