如何在 GLFW 窗口中以固定的 FPS 渲染?

How to render at a fixed FPS in a GLFW window?

本文关键字:FPS 渲染 GLFW 窗口      更新时间:2023-10-16

我正在尝试以 60 FPS 的速度渲染,但我的场景渲染速度远高于 60 FPS。

这是我的渲染循环代码,这是以所需的 FPS 渲染的正确方法还是有更好的方法?

double lastTime = glfwGetTime(), timer = lastTime;
double deltaTime = 0, nowTime = 0;
int frames = 0, updates = 0;
while (!glfwWindowShouldClose(window))
{
// input
// -----
processInput(window);
// - Measure time
nowTime = glfwGetTime();
deltaTime += (nowTime - lastTime) / limitFPS;  // limitFPS = 1.0 / 60.0
lastTime = nowTime;
// - Only update at 60 frames / s
while (deltaTime >= 1.0) {
updates++;
deltaTime--;
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT |  GL_STENCIL_BUFFER_BIT);
w.render();  // Render function
frames++; 
}
glfwPollEvents();
// - Reset after one second
if (glfwGetTime() - timer > 1.0) {
timer++;
}
glfwSwapBuffers(window);
}

根据上面评论中的讨论,您希望绘制最多 60 FPS,但您希望逻辑尽可能频繁地更新。正确?

这可以通过一个循环、一个计时器和一个 if 语句来实现:

const double fpsLimit = 1.0 / 60.0;
double lastUpdateTime = 0;  // number of seconds since the last loop
double lastFrameTime = 0;   // number of seconds since the last frame
// This while loop repeats as fast as possible
while (!glfwWindowShouldClose(window))
{
double now = glfwGetTime();
double deltaTime = now - lastUpdateTime;
glfwPollEvents();
// update your application logic here,
// using deltaTime if necessary (for physics, tweening, etc.)
// This if-statement only executes once every 60th of a second
if ((now - lastFrameTime) >= fpsLimit)
{
// draw your frame here
glfwSwapBuffers(window);
// only set lastFrameTime when you actually draw something
lastFrameTime = now;
}
// set lastUpdateTime every iteration
lastUpdateTime = now;
}

要尽可能频繁地执行的所有内容都应位于该while循环的外部,并且要以每秒最多 60 次的速度执行的所有内容都应位于if语句内。

如果循环执行迭代的时间超过 1/60 秒,则您的 FPS 和更新速率将下降到该工作负载/系统可实现的任何速率。