c++ - 是什么导致这个简单的 SDL 渲染循环中的帧速率卡顿?

标签 c++ windows-7 sdl

我编写了一个非常基本的测试来查看 SDL 是否可以在我的系统上正常工作。我原以为它会运行得非常流畅,因为绘图代码非常简单,但它一点也不流畅,而且根据我指定的帧速率,它以不同的方式看起来很糟糕。

我希望我做了一些傻事。我担心的是代码没问题,但我的 Windows 7 机器不能很好地使用 SDL。我已经过度修补和谷歌搜索,但我无法弄清楚发生了什么。知识渊博的人可以看到问题吗?代码如下:

#include "SDL.h"

static int g_width = 1024;
static int g_height = 768;

static int g_frameWaitInterval = 20;   // 50fps
static int g_lastFrameTime = 0;

static int g_ballx = 200;
static int g_bally = 200;
static int g_ballSize = 20;
static int g_ballxVelocity = 5;

void Step();
void Draw();

// Main application loop
void Run(){        
    while(true){
        if(SDL_GetTicks() - g_lastFrameTime >= g_frameWaitInterval){
            g_lastFrameTime = SDL_GetTicks();
            Step();
            Draw();
        }
    }
}

// Bounces the ball back and forth across the screen
void Step(){
    g_ballx += g_ballxVelocity;
    if(g_ballx+g_ballSize>=g_width){
        g_ballx = g_width - (g_ballSize+1);
        g_ballxVelocity = -g_ballxVelocity;
    }
    if(g_ballx<0){
        g_ballx = 0;
        g_ballxVelocity = -g_ballxVelocity;
    }
}

// Draws the ball as a square
void Draw(){
    SDL_Surface* p_screen = SDL_GetVideoSurface();
    SDL_FillRect(p_screen, NULL, 0xff000000);

    SDL_Rect rect;
    rect.x = g_ballx; rect.y = g_bally;
    rect.w = rect.h = g_ballSize;
    SDL_FillRect(SDL_GetVideoSurface(), &rect, 0xffff00ff);

    SDL_UpdateRect(p_screen,0,0,0,0);
}

// Initialises SDL, etc (checking removed for brevity)
int main(int argc, char *argv[]){
    SDL_Init(SDL_INIT_VIDEO);
    SDL_SetVideoMode(g_width, g_height, 0, SDL_SWSURFACE);
    Run();
    return 0;
}

编辑:我在 10 秒的过程中运行了帧速率测试并得到 49.76,这非常接近我预期的 50fps。我还打印出了大量单独的帧时序,发现每一帧都像预期的那样花费了 20 毫秒。这向我表明问题出在配置的某些方面,而不是我的渲染循环。

最佳答案

您可能只需要设置双缓冲。没有它,即使在简单的程序中,您也会有一点闪烁。

关于c++ - 是什么导致这个简单的 SDL 渲染循环中的帧速率卡顿?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7773747/

相关文章:

c++ - 命名空间中的 unordered_map 不是 "saving"它跨源文件的数据

c++ - 以 FLOPS 估算 GPU 的效率(CUDA SAMPLES)

C++11 直接列表初始化语法

linux - 从 Windows 7 上的 Linux 虚拟框访问文件

SDL 创建透明表面

c++ - 是否有用于 C++ 的 Python StringIO/StringIO 之类的东西?

php - UTF-8、PHP、Win7 - 现在有解决方案可以使用 php 在 Win 7 上保存 UTF-8 文件名吗?

c++ windows - 在子进程中禁用崩溃对话框

c++ - 不循环检测连接请求

c++ - 程序死机,找不到解决办法。 SDL 和 C++