feat: fixed timestep game loop + FPS counter
- 60Hz fixed timestep with accumulator - FPS display via engine->fps - Proper delta_time accumulation
This commit is contained in:
1 parent
f85c7e37f1
commit
2947ca3b9d
2 files changed
+28
-5
No files matched your search
+27
-5
@@ -90,6 +90,12 @@ void engine_run(Engine* engine) {
|
||||
return;
|
||||
}
|
||||
|
||||
double fixed_dt = 1.0 / 60.0; // 60Hz 固定时间步
|
||||
double accumulator = 0.0;
|
||||
double fps_timer = 0.0;
|
||||
int fps_frames = 0;
|
||||
int fps_display = 0;
|
||||
|
||||
while (engine->running) {
|
||||
// 处理窗口消息
|
||||
if (!window_process_messages(engine->window)) {
|
||||
@@ -100,18 +106,34 @@ void engine_run(Engine* engine) {
|
||||
// 更新计时
|
||||
timer_tick();
|
||||
engine->delta_time = timer_get_delta();
|
||||
engine->total_time = timer_get_total();
|
||||
engine->total_time += engine->delta_time;
|
||||
engine->frame_count++;
|
||||
|
||||
// 用户更新
|
||||
if (g_update_callback) {
|
||||
g_update_callback(engine, engine->delta_time);
|
||||
// FPS 计算
|
||||
fps_timer += engine->delta_time;
|
||||
fps_frames++;
|
||||
if (fps_timer >= 1.0) {
|
||||
fps_display = fps_frames;
|
||||
fps_frames = 0;
|
||||
fps_timer -= 1.0;
|
||||
}
|
||||
|
||||
// 用户渲染
|
||||
// 固定时间步逻辑更新
|
||||
accumulator += engine->delta_time;
|
||||
while (accumulator >= fixed_dt) {
|
||||
if (g_update_callback) {
|
||||
g_update_callback(engine, fixed_dt);
|
||||
}
|
||||
accumulator -= fixed_dt;
|
||||
}
|
||||
|
||||
// 渲染
|
||||
if (g_render_callback) {
|
||||
g_render_callback(engine);
|
||||
}
|
||||
|
||||
// 存储 FPS 供外部读取
|
||||
engine->fps = fps_display;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ typedef struct {
|
||||
void* renderer;
|
||||
double delta_time;
|
||||
double total_time;
|
||||
int fps;
|
||||
uint64_t frame_count;
|
||||
} Engine;
|
||||
|
||||
|
||||
Reference in new issue
Block a user