summaryrefslogtreecommitdiff
path: root/platformer/src/main.c
blob: 61972cc07ad2a72167aafee6fd28f69d2ea61380 (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
/*
 * ============================================================
 * FILE:        main.c
 *
 * PURPOSE:     Entry point. Starts every module, runs the game loop, and shuts
 *              everything down. It should read like a table of contents for the
 *              game, with NO gameplay logic of its own.
 *
 * FITS IN:     The top of the dependency graph. Includes window.h, controls.h,
 *              world.h, player.h, camera.h, render.h, config.h.
 *
 * IMPLEMENT:
 *   - Startup (in this order, and if any step fails, clean up what
 *     already started and return 1):
 *       window_init()  ->  controls_init()  ->  world_init()
 *       player_init(&player, world_spawn_point())
 *       camera_init(&camera, player.body.pos)
 *       render_init()
 *
 *   - Game loop with a FIXED TIMESTEP + accumulator (explain it in a comment;
 *     this is the most important idea in the file):
 *
 *       previous = window_time(); accumulator = 0;
 *       while (!window_should_close()):
 *           now = window_time();
 *           frame_time = now - previous; previous = now;
 *           if frame_time > MAX_FRAME_TIME: frame_time = MAX_FRAME_TIME
 *           accumulator += frame_time;
 *
 *           window_poll_events();
 *
 *           while accumulator >= TICK_DT:          // 0, 1 or several ticks
 *               controls_poll(&input);
 *               if input.quit_pressed:  window_request_close();
 *               if input.reset_pressed:
 *                   player_reset(&player, world_spawn_point());
 *                   camera_init(&camera, player.body.pos);   // see WHY below
 *               player_update(&player, &input, camera_yaw(&camera), TICK_DT);
 *               camera_update(&camera, &input, player.body.pos, player.facing_yaw,
 *                             window_aspect(), TICK_DT);
 *               accumulator -= TICK_DT;
 *
 *           render_frame(&camera, &player, window_aspect(), fps);
 *           window_swap();
 *           count the frame toward the FPS reading (below)
 *
 *     WHY the fixed timestep: the game behaves the same (identical jump
 *     height, identical speeds) no matter the monitor's refresh rate or a
 *     dropped frame, which is exactly what you need when tuning movement. SM64
 *     ran logic at 30 Hz; we use TICK_HZ (60).
 *     WHY player before camera: the camera then follows where the player IS,
 *     not where it was a tick ago. SM64 updates Mario before the camera too.
 *     WHY reset the camera too: the camera frames the player by tracking how
 *     far they moved each tick, so a teleport back to spawn would look like a
 *     100 m sprint. Re-initializing gives a clean, centered start instead.
 *
 *   - FPS counter: count rendered frames, and every FPS_UPDATE_INTERVAL
 *     seconds set fps = frames / elapsed time (rounded), then start counting
 *     again. Averaging over a window keeps the number steady enough to read.
 *     fps starts at 0, which render_frame() takes as "not measured yet".
 *
 *   - Debug readout for tuning (a few times per second, not every frame):
 *     window_set_title() with something like
 *       "platformer | RUN | speed 7.42 m/s | y 1.83 | pad | heightened"
 *     using player_state_name(), forward_speed, body.pos.y,
 *     input.using_gamepad, and "| heightened" only while
 *     player.heightened_movement is on. This is our "HUD" until text rendering exists.
 *
 *   - Shutdown in reverse order: render_shutdown() -> window_shutdown().
 *
 * CONVENTIONS: `int main(void)`. Game objects (Player, Camera, Input) are
 *              local variables in main, passed by pointer. No globals.
 *
 * NOT IN SCOPE: Menus, pause, command-line args, state interpolation.
 *
 * DONE WHEN:   `make run` opens the window. The player can run, turn and jump
 *              with a gamepad, the camera orbits and frames them (right stick
 *              click recenters behind them), Back resets, Start quits, and
 *              the title bar shows live state/speed, and the top-right corner
 *              shows the FPS.
 * ============================================================
 */

#include <stdio.h>

#include "camera.h"
#include "config.h"
#include "controls.h"
#include "player.h"
#include "render.h"
#include "window.h"
#include "world.h"

#define TITLE_UPDATE_INTERVAL 0.25   /* seconds between debug title refreshes */
#define FPS_UPDATE_INTERVAL   0.5    /* seconds of frames averaged into each FPS reading */

/* Our "HUD" until text rendering exists: live state in the title bar.
 * Updating a few times per second keeps it readable (and cheap). */
static void update_debug_title(const Player *player, const Input *input)
{
    char title[128];
    snprintf(title, sizeof title, "%s | %s | speed %.2f m/s | y %.2f | %s%s",
             WINDOW_TITLE,
             player_state_name(player->state),
             player->forward_speed,
             player->body.pos.y,
             input->using_gamepad ? "pad" : "keyboard",
             player->heightened_movement ? " | heightened" : "");
    window_set_title(title);
}

int main(void)
{
    if (!window_init())
        return 1;
    controls_init();
    world_init();

    Player player;
    player_init(&player, world_spawn_point());
    Camera camera;
    camera_init(&camera, player.body.pos);

    if (!render_init()) {
        window_shutdown();
        return 1;
    }

    /* FIXED TIMESTEP with an accumulator. Real time comes in uneven chunks
     * (one display frame at a time), but the game logic always advances in
     * exact TICK_DT steps. Each frame adds the elapsed time to the
     * accumulator, then runs as many whole ticks as fit (0, 1 or several);
     * the leftover carries into the next frame. The payoff: identical jump
     * heights and speeds no matter the monitor's refresh rate or a dropped
     * frame, which is exactly what you need when tuning movement. SM64 ran its
     * logic at 30 Hz; we use TICK_HZ. */
    Input  input = { 0 };
    double previous = window_time();
    double accumulator = 0.0;
    double last_title_time = 0.0;
    double fps_start = previous;   /* when the current FPS count began */
    int    fps_frames = 0;         /* frames rendered since fps_start */
    int    fps = 0;                /* last FPS reading; 0 = not measured yet */

    while (!window_should_close()) {
        double now = window_time();
        double frame_time = now - previous;
        previous = now;
        /* After a stall (breakpoint, window drag) don't try to simulate the
         * whole gap at once: that would take even longer and fall further behind. */
        if (frame_time > MAX_FRAME_TIME)
            frame_time = MAX_FRAME_TIME;
        accumulator += frame_time;

        window_poll_events();

        while (accumulator >= TICK_DT) {
            controls_poll(&input);
            if (input.quit_pressed)
                window_request_close();
            if (input.reset_pressed) {
                /* The camera tracks per-tick movement, so a teleport needs a
                 * fresh camera rather than a 100 m "sprint" to follow. */
                player_reset(&player, world_spawn_point());
                camera_init(&camera, player.body.pos);
            }
            /* Player before camera, so the camera follows where the player IS,
             * not where it was a tick ago. SM64 updates Mario before the camera too. */
            player_update(&player, &input, camera_yaw(&camera), TICK_DT);
            camera_update(&camera, &input, player.body.pos, player.facing_yaw,
                          window_aspect(), TICK_DT);
            accumulator -= TICK_DT;
        }

        render_frame(&camera, &player, window_aspect(), fps);
        window_swap();

        /* FPS averaged over FPS_UPDATE_INTERVAL: a per-frame number would
         * flicker too fast to read. */
        fps_frames++;
        if (now - fps_start >= FPS_UPDATE_INTERVAL) {
            fps = (int)(fps_frames / (now - fps_start) + 0.5);
            fps_frames = 0;
            fps_start = now;
        }

        if (now - last_title_time >= TITLE_UPDATE_INTERVAL) {
            update_debug_title(&player, &input);
            last_title_time = now;
        }
    }

    render_shutdown();
    window_shutdown();
    return 0;
}