aboutsummaryrefslogtreecommitdiff
path: root/src/core/application.cpp
blob: c24e029656465459d4bfa89a572e39963227ae62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#include "application.h"

#include "rendering/render_api.h"    // RendererAPI
#include "settings_manager.h"

#include "platform/opengl/opengl_device.h"
#include "platform/vulkan/vulkan_device.h"

#include <GLFW/glfw3.h>
#include <imgui.h>
#include <glm/glm.hpp>
#include <algorithm>
#include <thread>
#include <chrono>

namespace Donut
{
    Application* Application::s_instance = nullptr;

    // Scroll is delivered through a GLFW callback; accumulate it here and drain it
    // once per frame in update_input (chaining ImGui's own scroll handler).
    static double        g_scroll_accum = 0.0;
    static GLFWscrollfun g_prev_scroll  = nullptr;
    static void donut_scroll_callback(GLFWwindow* w, double x, double y)
    {
        if (g_prev_scroll) g_prev_scroll(w, x, y);
        g_scroll_accum += y;
    }

    Application::Application(const std::string& name, int width, int height)
    {
        s_instance = this;

        // Select the render API before the window is created: the window is built
        // differently for Vulkan (GLFW_NO_API) than for OpenGL.
        Logger::init();
        SettingsManager::initialize();
        {
            const auto& settings = SettingsManager::get_settings_const();
            RendererAPI::set_api(settings.graphics.render_api == "Vulkan"
                                ? RendererAPI::API::Vulkan : RendererAPI::API::OpenGL);
        }

        if (RendererAPI::get_api() == RendererAPI::API::Vulkan)
            RHI::vulkan_prepare_glfw(); // must precede glfwInit() inside the Window ctor

        m_window = create_scope<Window>(name, width, height);
        m_window->set_event_callback([this](Event& event) { on_event(event); });

        on_init();
    }

    Application::~Application()
    {
        on_shutdown();
        s_instance = nullptr;
    }

    auto Application::on_init() -> void
    {
        int w = 0, h = 0;
        glfwGetFramebufferSize((GLFWwindow*)m_window->get_native_window(), &w, &h);

        if (RendererAPI::get_api() == RendererAPI::API::Vulkan)
            m_device = RHI::create_vulkan_device();
        else
            m_device = RHI::create_opengl_device();

        RHI::NativeWindow native{ m_window->get_native_window(), w, h };
        if (!m_device->init(native))
        {
            DONUT_ERROR("RHI device initialization failed");
            return;
        }

        m_scene = create_scope<Scene>();
        m_render_path = create_scope<RenderPath>();
        m_render_path->init(*m_device, m_scene->hdri_path);
        m_ui = create_scope<UILayer>();

        m_device->init_imgui();
        // Load the UI font into the device-created ImGui context (backend-agnostic;
        // the backend rebuilds the atlas on the next frame).
        ImGuiIO& io = ImGui::GetIO();
        if (!io.Fonts->AddFontFromFileTTF("assets/fonts/inter/static/Inter_18pt-Regular.ttf", 16.0f))
            io.Fonts->AddFontDefault();

        g_prev_scroll = glfwSetScrollCallback((GLFWwindow*)m_window->get_native_window(), donut_scroll_callback);

        m_device->set_vsync(SettingsManager::get_v_sync_enabled());   // apply the persisted preference
        glfwGetWindowSize((GLFWwindow*)m_window->get_native_window(), &m_windowed_w, &m_windowed_h);

        m_start_time = glfwGetTime();
        DONUT_INFO("Application ready on {} backend", m_device->device_name());
    }

    auto Application::run() -> void
    {
        while (m_running)
        {
            double frame_start = glfwGetTime();
            glfwPollEvents();
            if (!m_minimized && m_device)
                render_frame();

            // With vsync off, cap to the target FPS (vsync itself paces otherwise).
            if (!SettingsManager::get_v_sync_enabled())
            {
                int fps = SettingsManager::get_target_fps();
                if (fps > 0)
                {
                    double budget  = 1.0 / (double)fps;
                    double elapsed = glfwGetTime() - frame_start;
                    if (elapsed < budget)
                        std::this_thread::sleep_for(std::chrono::duration<double>(budget - elapsed));
                }
            }
        }
    }

    auto Application::set_resolution(int w, int h) -> void
    {
        if (m_window && !is_fullscreen())
            glfwSetWindowSize((GLFWwindow*)m_window->get_native_window(), w, h);
    }

    auto Application::set_fullscreen(bool on) -> void
    {
        if (!m_window) return;
        GLFWwindow* win = (GLFWwindow*)m_window->get_native_window();
        if (on == is_fullscreen()) return;
        if (on)
        {
            glfwGetWindowPos(win, &m_windowed_x, &m_windowed_y);
            glfwGetWindowSize(win, &m_windowed_w, &m_windowed_h);
            GLFWmonitor* mon = glfwGetPrimaryMonitor();
            const GLFWvidmode* mode = glfwGetVideoMode(mon);
            glfwSetWindowMonitor(win, mon, 0, 0, mode->width, mode->height, mode->refreshRate);
        }
        else
        {
            glfwSetWindowMonitor(win, nullptr, m_windowed_x, m_windowed_y, m_windowed_w, m_windowed_h, 0);
        }
    }

    auto Application::set_vsync(bool on) -> void       { if (m_device) m_device->set_vsync(on); }
    auto Application::set_ui_scale(float scale) -> void { ImGui::GetIO().FontGlobalScale = scale; }
    auto Application::export_frame(const ExportConfig& cfg) -> int
    { return (m_render_path && m_scene) ? m_render_path->export_frame(*m_scene, cfg) : 0; }
    auto Application::is_fullscreen() const -> bool
    { return m_window && glfwGetWindowMonitor((GLFWwindow*)m_window->get_native_window()) != nullptr; }
    auto Application::get_window_size(int& w, int& h) const -> void
    { w = 0; h = 0; if (m_window) glfwGetWindowSize((GLFWwindow*)m_window->get_native_window(), &w, &h); }

    auto Application::render_frame() -> void
    {
        RHI::CommandList* cmd = m_device->begin_frame(glm::vec4(0.05f, 0.06f, 0.10f, 1.0f));
        if (!cmd) return;   // frame skipped (e.g. swapchain recreation)

        m_device->imgui_new_frame();

        // Keep the scene camera's projection current before the UI builds, so the
        // scene-tab gizmo and the render agree on the same matrices this frame.
        int w = 0, h = 0;
        glfwGetFramebufferSize((GLFWwindow*)m_window->get_native_window(), &w, &h);
        m_scene->scene_camera.set_projection(45.0f, (float)w / (float)std::max(h, 1), 0.1f, 1000.0f);

        View view = m_ui->draw(UIContext{ *m_scene, m_device->device_name(), *this });
        update_input(view);
        m_render_path->sync_hdri(m_scene->hdri_path);

        float time = (float)(glfwGetTime() - m_start_time);
        m_render_path->render(*cmd, *m_scene, view, w, h, m_user_moving, time);

        m_device->end_frame();
    }

    auto Application::update_input(View view) -> void
    {
        GLFWwindow* window = (GLFWwindow*)m_window->get_native_window();
        bool over_ui = ImGui::GetCurrentContext() && ImGui::GetIO().WantCaptureMouse;

        double now = glfwGetTime();
        float dt = m_last_frame_time > 0.0 ? (float)(now - m_last_frame_time) : 0.0f;
        m_last_frame_time = now;

        double mx = 0, my = 0;
        glfwGetCursorPos(window, &mx, &my);
        bool left_down = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;

        // Tabs without a live viewport (Setup / Export) have no camera to drive.
        if (view == View::None)
        {
            m_left_was_down = left_down;   // keep the drag-edge state coherent
            g_scroll_accum = 0.0;          // discard scroll over inert tabs
            m_user_moving = false;
            return;
        }

        const bool scene_view = view == View::Scene;

        if (!scene_view && m_scene->sim_camera.get_camera_mode() == CameraMode::FPS)
        {
            Camera& cam = m_scene->sim_camera;
            if (left_down && !m_left_was_down) { m_fps_last_x = mx; m_fps_last_y = my; }
            if (left_down && !over_ui)
                cam.on_mouse_move(float(mx - m_fps_last_x), float(m_fps_last_y - my));
            m_fps_last_x = mx; m_fps_last_y = my;
            m_left_was_down = left_down;

            bool over_kb = ImGui::GetCurrentContext() && ImGui::GetIO().WantCaptureKeyboard;
            bool moved = false;
            if (!over_kb && dt > 0.0f)
            {
                float mdt = dt * (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS ? 4.0f : 1.0f);
                if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { cam.move_forward(mdt);  moved = true; }
                if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { cam.move_backward(mdt); moved = true; }
                if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { cam.move_left(mdt);     moved = true; }
                if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { cam.move_right(mdt);    moved = true; }
                if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) { cam.move_up(mdt);       moved = true; }
                if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) { cam.move_down(mdt);     moved = true; }
            }
            g_scroll_accum = 0.0;
            m_user_moving = moved || (left_down && !over_ui);
        }
        else
        {
            Camera& cam = scene_view ? m_scene->scene_camera : m_scene->sim_camera;
            if (left_down && !m_left_was_down && !over_ui)
                cam.process_orbital_mouse_button(GLFW_MOUSE_BUTTON_LEFT, GLFW_PRESS, 0);
            else if (!left_down && m_left_was_down)
                cam.process_orbital_mouse_button(GLFW_MOUSE_BUTTON_LEFT, GLFW_RELEASE, 0);
            m_left_was_down = left_down;

            cam.process_orbital_mouse_move(mx, my);

            double scroll = g_scroll_accum; g_scroll_accum = 0.0;
            if (scroll != 0.0 && !over_ui)
                cam.process_orbital_scroll(0.0, scroll);

            m_user_moving = cam.is_dragging() || cam.is_panning();
        }
    }

    auto Application::close() -> void
    {
        m_running = false;
    }

    auto Application::on_event(Event& event) -> void
    {
        EventDispatcher dispatcher(event);
        dispatcher.dispatch<WindowCloseEvent>([this, &event](WindowCloseEvent& e)
        {
            m_running = false;
            event.handled = true;
            return true;
        });

        dispatcher.dispatch<WindowResizeEvent>([this, &event](WindowResizeEvent& e)
        {
            m_minimized = (e.get_width() == 0 || e.get_height() == 0);
            if (m_device) m_device->resize(e.get_width(), e.get_height());
            event.handled = true;
            return true;
        });
    }

    auto Application::on_shutdown() -> void
    {
        if (m_device)
        {
            m_device->wait_idle();
            if (m_render_path) m_render_path->shutdown();
            m_render_path.reset();
            m_ui.reset();
            m_scene.reset();
            m_device->shutdown();
            m_device.reset();
        }
        SettingsManager::shutdown();
        Logger::shutdown();
    }
}