aboutsummaryrefslogtreecommitdiff
path: root/src/engine.cpp
blob: da28f75b3abf524520bf45e48aaa7b11557f8607 (plain) (blame)
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
#include "config.h"
#include <iostream>

#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <functional>
#include <utility>
#include <iterator>
#include <memory>
#include <utility>
#include <numbers>
#include <optional>

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <vulkan/vk_enum_string_helper.h>

#ifdef ENABLE_NCURSES
#include <ncurses.h>
#endif

#include "fb/chfb.h"
#include "fb/pixfb.h"
#include "o3d/scene.h"
#include "o3d/mesh.h"
#include "o3d/obj3d.h"
#include "o3d/vertex_data.h"
#include "o3d/tri.h"
#include "o3d/camera.h"
#include "math/vector.h"
#include "math/mat4.h"
#include "math/quat.h"
#include "math/tform.h"
#include "ctrl/keyboard.h"
#include "ctrl/mouse.h"
#include "renderer.h"
#include "obj_parser.h"

using
    engine::Renderer,
    engine::fb::CharacterFrameBuffer,
    engine::fb::PixelFrameBuffer,
    engine::o3d::Scene,
    engine::o3d::Mesh,
    engine::o3d::Triangle,
    engine::o3d::Camera,
    engine::o3d::VertexData,
    engine::math::Vector2,
    engine::math::Vector3,
    engine::math::Vector4,
    engine::math::Matrix4,
    engine::math::Quaternion,
    engine::controllers::Keyboard,
    engine::controllers::KeyboardKey,
    engine::controllers::Mouse;

#define FPS 60

#define PI 3.1415926535f

#define MODE_HELP      0
#define MODE_TERM      1
#define MODE_GRAPHICAL 2

#define GAME_PLANE   0
#define GAME_SUZANNE 1
#define GAME_PHYSICS 2

#define GAME GAME_PHYSICS

static void print_usage(std::ostream& output_stream) {
    output_stream << "Usage: ./engine [-htg] [--help] [--term] [--graphical]\n"
                  << "  -h, --help        show usage (this)\n"
                  << "  -t, --term        terminal mode\n"
                  << "  -g, --graphical   graphical mode (default)\n"
                  << std::flush;
}

[[noreturn]]
static void usage_error_exit() {
    print_usage(std::cerr);
    std::exit(EXIT_FAILURE);
}

extern Camera* camera;
Camera* camera;

template<typename FrameBuffer, typename UpdateFrameFn>
static void scene_main(Renderer<FrameBuffer>& renderer, const Matrix4& final_transform_mat, UpdateFrameFn update_frame) {
    bool cont = true;
    Scene scene{
        {90.f * PI / 180.f, {{0.f, 1.8f, 7.f}, Quaternion::one(), {1.f, 1.f, 1.f}}},
        {
#if GAME == GAME_PLANE
            {
                Mesh::plane(2.f, 2.f),
                {
                    Vector3(0.f, 0.f, 0.f),
                    Quaternion::one(),
                    Vector3(1.f, 1.f, 1.f),
                }
            },
#elif GAME == GAME_SUZANNE
            {
                engine::parse_object("../assets/suzanne.obj"),
                {
                    Vector3(0.f, 0.f, 0.f),
                    Quaternion::one(),
                    Vector3(1.f, 1.f, 1.f),
                }
            },
#elif GAME == GAME_PHYSICS
            {
                Mesh::plane(10.f, 10.f),
                {
                    Vector3(0.f, 0.f, 0.f),
                    Quaternion::one(),
                    Vector3(1.f, 1.f, 1.f),
                }
            },
            {
                engine::parse_object("../assets/suzanne.obj"),
                {
                    Vector3(0.f, 1.f, 0.f),
                    Quaternion::one(),
                    Vector3(1.f, 1.f, 1.f),
                }
            },
#endif
        }
    };

    float rx = 0.f, ry = 0.f;
    Keyboard kb{[&](KeyboardKey key) {
        (void) key;
    }, [&](KeyboardKey key) {
        (void) key;
    }};
    Mouse mouse{[&](Vector2 rel) {
        rx += -rel.y;
        ry += -rel.x;
        if (rx < -PI / 2.f) rx = -PI / 2.f;
        if (rx >  PI / 2.f) rx =  PI / 2.f;
        scene.camera.transform.rot = Quaternion::euler_zxy(rx, ry, 0.f);
    }};

    camera = &scene.camera;

    while (cont) {
        renderer.clear();
        auto pre_final_mat = final_transform_mat
            * scene.camera.to_mat4(static_cast<float>(renderer.height()) / static_cast<float>(renderer.width()), .5f, 12.f);
        for (const auto& obj : scene.objs) {
            auto obj_mat = obj.transform.to_mat4();
            auto final_mat = pre_final_mat * obj_mat;
            const auto& mesh = obj.mesh;
            std::vector<Vector4> vertices;
            std::vector<VertexData> vertices_data;
            for (const auto& vertex : mesh.vertices) {
                vertices.push_back(final_mat * vertex);
                vertices_data.push_back(VertexData((obj_mat * vertex).xyz()));
            }
            for (const auto& triangle_indices : mesh.indices) {
                [&]<std::size_t... j>(std::integer_sequence<std::size_t, j...>) {
                    renderer.draw_triangle({{vertices[triangle_indices[j][0]], mesh.normals[triangle_indices[j][1]], vertices_data[triangle_indices[j][0]]}...});
                }(std::make_integer_sequence<std::size_t, 3>());
            }
        }
        cont = update_frame(scene, kb, mouse);

        Vector3 movement(0.f, 0.f, 0.f);
        if (kb.is_down(KeyboardKey::fw))        movement.z += -1.f;
        if (kb.is_down(KeyboardKey::key_left))  movement.x += -1.f;
        if (kb.is_down(KeyboardKey::bw))        movement.z += +1.f;
        if (kb.is_down(KeyboardKey::key_right)) movement.x += +1.f;
        if (kb.is_down(KeyboardKey::fw) || kb.is_down(KeyboardKey::key_left)
            || kb.is_down(KeyboardKey::bw) || kb.is_down(KeyboardKey::key_right)) movement.normalize();
        scene.camera.transform.loc += movement.rot(Quaternion::rot_y(ry)) * .05f;
        scene.camera.fov = (kb.is_down(KeyboardKey::zoom) ? 40.f : 80.f) * PI / 180.f;
    }
}

#ifdef ENABLE_NCURSES
#define MKEY_ESC 27

static int main_term() {
    // init
    std::setlocale(LC_ALL, "");
    initscr();
    cbreak();
    noecho();
    intrflush(stdscr, FALSE);
    keypad(stdscr, TRUE);
    set_escdelay(0);
    curs_set(0);

    int w, h;
    getmaxyx(stdscr, h, w);
    Renderer<CharacterFrameBuffer> renderer{CharacterFrameBuffer{static_cast<unsigned int>(w), static_cast<unsigned int>(h)}};

    scene_main(renderer, Matrix4::scale(Vector3(2.f, 1.f, 1.f)),
        [&](Scene& scene, auto& kb, auto& mouse) {
            (void) scene;
            mvaddnstr(0, 0, renderer.fb.chars(), renderer.width() * renderer.height());

            bool cont = true;
            std::optional<KeyboardKey> key;
            std::optional<Vector2> rel;
            //timeout(1000 / FPS);
            timeout(10);
            int c = getch();

            switch (c) {
            case 'z':
                key = KeyboardKey::fw;
                break;
            case 'q':
                key = KeyboardKey::key_left;
                break;
            case 's':
                key = KeyboardKey::bw;
                break;
            case 'd':
                key = KeyboardKey::key_right;
                break;
            case 'p':
                key = KeyboardKey::zoom;
                break;
            case KEY_UP:
                rel = Vector2(0.f, -.1f);
                break;
            case KEY_LEFT:
                rel = Vector2(-.1f, 0.f);
                break;
            case KEY_DOWN:
                rel = Vector2(0.f, +.1f);
                break;
            case KEY_RIGHT:
                rel = Vector2(+.1f, 0.f);
                break;
            case MKEY_ESC:
                return false;
            }

            if (key && *key == KeyboardKey::fw) {
                if (!kb.is_down(KeyboardKey::fw)) kb.key_down_event(KeyboardKey::fw);
            } else {
                if (kb.is_down(KeyboardKey::fw)) kb.key_up_event(KeyboardKey::fw);
            }
            if (key && *key == KeyboardKey::key_left) {
                if (!kb.is_down(KeyboardKey::key_left)) kb.key_down_event(KeyboardKey::key_left);
            } else {
                if (kb.is_down(KeyboardKey::key_left)) kb.key_up_event(KeyboardKey::key_left);
            }
            if (key && *key == KeyboardKey::bw) {
                if (!kb.is_down(KeyboardKey::bw)) kb.key_down_event(KeyboardKey::bw);
            } else {
                if (kb.is_down(KeyboardKey::bw)) kb.key_up_event(KeyboardKey::bw);
            }
            if (key && *key == KeyboardKey::key_right) {
                if (!kb.is_down(KeyboardKey::key_right)) kb.key_down_event(KeyboardKey::key_right);
            } else {
                if (kb.is_down(KeyboardKey::key_right)) kb.key_up_event(KeyboardKey::key_right);
            }

            if (key && *key == KeyboardKey::zoom) {
                if (kb.is_down(KeyboardKey::zoom)) kb.key_up_event(KeyboardKey::zoom);
                else kb.key_down_event(KeyboardKey::zoom);
            }

            if (rel)
                mouse.mouse_motion_event(*rel);

            getmaxyx(stdscr, h, w);
            renderer.resize(static_cast<unsigned int>(w), static_cast<unsigned int>(h));

            return cont;
        }
    );

    // terminate
    endwin();

    return EXIT_SUCCESS;
}
#endif

#define SCREEN_WIDTH  640
#define SCREEN_HEIGHT 480

const std::vector<const char*> validation_layers = {
    "VK_LAYER_KHRONOS_validation"
};

#ifdef NDEBUG
const bool enable_validation_layers = false;
#else
const bool enable_validation_layers = true;
#endif

static bool check_validation_layer_support() {
    uint32_t layer_count;
    vkEnumerateInstanceLayerProperties(&layer_count, nullptr);

    std::vector<VkLayerProperties> available_layers(layer_count);
    vkEnumerateInstanceLayerProperties(&layer_count, available_layers.data());

    for (const char* layer_name : validation_layers) {
        bool layer_found = false;

        for (const auto& layer_properties : available_layers) {
            if (strcmp(layer_name, layer_properties.layerName) == 0) {
                layer_found = true;
                break;
            }
        }

        if (!layer_found) {
            return false;
        }
    }

    return true;
}

static VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback(
        VkDebugUtilsMessageSeverityFlagBitsEXT message_severity,
        VkDebugUtilsMessageTypeFlagsEXT message_type,
        const VkDebugUtilsMessengerCallbackDataEXT* callback_data,
        void* user_data) {
    std::cerr << "validation layer: " << callback_data->pMessage << std::endl;
    return VK_FALSE;
}

static void populate_msger_create_info(VkDebugUtilsMessengerCreateInfoEXT& msger_create_info) {
    msger_create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
    msger_create_info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT
        | VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT
        | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT
        | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
    msger_create_info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT
        | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT
        | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
    msger_create_info.pfnUserCallback = debug_callback;
    msger_create_info.pUserData = nullptr;
}

static int main_graphical() {
    // init window
    glfwInit();
    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
    GLFWwindow* window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Engine", nullptr, nullptr);

    // init Vulkan
    // init Vulkan - create instance
    if (enable_validation_layers && !check_validation_layer_support()) {
        std::cerr << "validation layers requested, but not available!" << std::endl;
        std::exit(EXIT_FAILURE);
    }

    VkApplicationInfo app_info{};
    app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
    app_info.pApplicationName = "engine - test";
    app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
    app_info.pEngineName = "engine";
    app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0);
    app_info.apiVersion = VK_API_VERSION_1_0;

    std::vector<const char*> extensions;

    {
        uint32_t glfw_extension_count;
        const char** glfw_extensions;
        glfw_extensions = glfwGetRequiredInstanceExtensions(&glfw_extension_count);
        extensions.insert(extensions.end(), glfw_extensions, glfw_extensions + glfw_extension_count);
    }

    if (enable_validation_layers) {
        extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
    }

    uint32_t extension_count;
    vkEnumerateInstanceExtensionProperties(nullptr, &extension_count, nullptr);
    std::vector<VkExtensionProperties> available_extensions(extension_count);
    vkEnumerateInstanceExtensionProperties(nullptr, &extension_count, available_extensions.data());

    std::cout << "vulkan extensions:\n";
    for (const auto& extension : available_extensions)
        std::cout << "   " << extension.extensionName << "\n";

    std::cout << "\n";

    std::cout << "required extensions:\n";
    for (const auto& extension_name : extensions)
        std::cout << "   " << extension_name << "\n";

    VkInstanceCreateInfo create_info{};
    create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
    create_info.pApplicationInfo = &app_info;

    create_info.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
    create_info.ppEnabledExtensionNames = extensions.data();

    VkDebugUtilsMessengerCreateInfoEXT inst_msger_create_info{};
    if (enable_validation_layers) {
        create_info.enabledLayerCount = static_cast<uint32_t>(validation_layers.size());
        create_info.ppEnabledLayerNames = validation_layers.data();

        populate_msger_create_info(inst_msger_create_info);
        create_info.pNext = (VkDebugUtilsMessengerCreateInfoEXT*) &inst_msger_create_info;
    } else {
        create_info.enabledLayerCount = 0;
        create_info.pNext = nullptr;
    }

    VkInstance instance;
    if (VkResult res = vkCreateInstance(&create_info, nullptr, &instance); res != VK_SUCCESS) {
        std::cerr << "failed to create instance, error code: " << string_VkResult(res) << std::endl;
        std::exit(EXIT_FAILURE);
    }

    VkDebugUtilsMessengerEXT debug_messenger;
    if (enable_validation_layers) {
        VkDebugUtilsMessengerCreateInfoEXT msger_create_info{};
        populate_msger_create_info(msger_create_info);

        auto create_debug_messenger = (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
        if (!create_debug_messenger) {
            std::cerr << "failed to set up debug messenger!" << std::endl;
            std::exit(EXIT_FAILURE);
        }
        create_debug_messenger(instance, &msger_create_info, nullptr, &debug_messenger);
    }

    // main loop
    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
    }

    // cleanup
    if (enable_validation_layers) {
        auto destroy_debug_messenger = (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
        if (!destroy_debug_messenger) {
            std::cerr << "failed to destroy debug messenger!" << std::endl;
            std::exit(EXIT_FAILURE);
        }
        destroy_debug_messenger(instance, debug_messenger, nullptr);
    }

    vkDestroyInstance(instance, nullptr);
    glfwDestroyWindow(window);
    glfwTerminate();

    return EXIT_SUCCESS;
}

static std::vector<std::string_view> convert_args(int argc, char *argv[]) {
    std::vector<std::string_view> args(argc);
    for (int i = 0; i < argc; i++)
        args[i] = argv[i];
    return args;
}

static void parse_args(const std::vector<std::string_view>& args, int& mode) {
    for (auto args_iter = std::next(args.begin()); args_iter != args.end(); args_iter++) {
        const auto& arg = *args_iter;
        if (arg.size() >= 1 && arg[0] == '-') {
            if (arg.size() >= 2 && arg[1] == '-') {
                auto long_opt = arg.substr(2);
                if (long_opt == "help") {
                    mode = MODE_HELP;
                } else if (long_opt == "term") {
                    mode = MODE_TERM;
                } else if (long_opt == "graphical") {
                    mode = MODE_GRAPHICAL;
                } else {
                    std::cerr << "Error: Unexpected option `--" << long_opt << "'." << std::endl;
                    usage_error_exit();
                }
            } else {
                std::size_t arg_len = arg.size();
                if (arg_len == 1) {
                    std::cerr << "Error: Unexpected argument `-'." << std::endl;
                    usage_error_exit();
                }
                for (auto arg_iter = std::next(arg.begin()); arg_iter != arg.end(); arg_iter++) {
                    const auto& opt = *arg_iter;
                    switch (opt) {
                    case 'h':
                        mode = MODE_HELP;
                        break;
                    case 't':
                        mode = MODE_TERM;
                        break;
                    case 'g':
                        mode = MODE_GRAPHICAL;
                        break;
                    default:
                        std::cerr << "Error: Unexpected option `-" << opt << "'." << std::endl;
                        usage_error_exit();
                    }
                }
            }
        } else {
            std::cerr << "Error: Unexpected argument `" << arg << "'." << std::endl;
            usage_error_exit();
        }
    }
}

int main(int argc, char *argv[]) {
    int mode = MODE_GRAPHICAL;
    parse_args(convert_args(argc, argv), mode);
    switch (mode) {
    case MODE_HELP:
        print_usage(std::cout);
        return EXIT_SUCCESS;
    case MODE_TERM:
#ifdef ENABLE_NCURSES
        return main_term();
#else
        std::cerr << "Error: ncurses was not enabled during compilation." << std::endl;
        return EXIT_FAILURE;
#endif
    case MODE_GRAPHICAL:
        return main_graphical();
    default:
        std::unreachable();
    }
}