A 3D game engine from scratch.
1// (c) 2020 Vlad-Stefan Harbuz <vlad@vladh.net>
2
3#pragma once
4
5#include <chrono>
6namespace chrono = std::chrono;
7#include "types.hpp"
8#include "entities.hpp"
9#include "lights.hpp"
10#include "behavior.hpp"
11#include "physics.hpp"
12#include "models.hpp"
13#include "renderer.hpp"
14#include "mats.hpp"
15#include "core.hpp"
16#include "cameras.hpp"
17
18
19static constexpr u32 DT_HIST_LENGTH = 512;
20
21
22class engine {
23public:
24 struct TimingInfo {
25 chrono::steady_clock::time_point frame_start;
26 chrono::steady_clock::time_point last_frame_start;
27 chrono::nanoseconds frame_duration;
28 chrono::steady_clock::time_point time_frame_should_end;
29
30 chrono::steady_clock::time_point second_start;
31 u32 n_frames_this_second;
32 u32 n_frames_since_start;
33 };
34
35 struct PerfCounters {
36 f64 dt_average;
37 f64 dt_hist[DT_HIST_LENGTH];
38 u32 dt_hist_idx;
39 u32 last_fps;
40 };
41
42 struct State {
43 bool is_manual_frame_advance_enabled;
44 bool should_manually_advance_to_next_frame;
45 bool should_stop;
46 bool should_pause;
47 bool should_limit_fps;
48 bool should_enable_text_input;
49 char current_scene_name[MAX_COMMON_NAME_LENGTH];
50 // NOTE: `t` and `dt` will not change when gameplay is paused.
51 f64 t; // us
52 f64 dt; // us
53 f64 timescale_diff;
54 PerfCounters perf_counters;
55 u32 n_valid_model_loaders;
56 u32 n_valid_entity_loaders;
57 bool is_world_loaded;
58 bool was_world_ever_loaded;
59 Array<models::ModelLoader> model_loaders;
60 Array<models::EntityLoader> entity_loaders;
61 TimingInfo timing_info;
62 };
63
64 static engine::State * debug_get_engine_state();
65 static models::EntityLoader * get_entity_loader(entities::Handle entity_handle);
66 static models::ModelLoader * push_model_loader();
67 static f64 get_t();
68 static f64 get_dt();
69 static u32 get_frame_number();
70 static void run_main_loop(GLFWwindow *window);
71 static void init(engine::State *engine_state, memory::Pool *asset_memory_pool);
72
73private:
74 static engine::State *state;
75 static void destroy_model_loaders();
76 static void destroy_scene();
77 static bool load_scene(const char *scene_name);
78 static void handle_console_command();
79 static void update_light_position(f32 amount);
80 static void process_input(GLFWwindow *window);
81 static bool check_all_entities_loaded();
82 static void update();
83 static TimingInfo init_timing_info(u32 target_fps);
84 static void update_timing_info(u32 *last_fps);
85 static void update_dt_and_perf_counters();
86};