Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to cap sdl2 fps just like pygame

Tags:

c++

c

sdl-2

When I write my SDL2 OpenGL program somewhat like this (using VSync):

SDL_GL_SetSwapInterval(1);
while(isRunning)
{
    while(SDL_PollEvent(&e))
    {
        if(e.type == SDL_Quit)
        {
            isRunning = false;
        }
    }
    SDL_GL_SwapWindow(window);
}

my CPU usage goes as high as 39%-50% for this single program which actually does nothing

whereas when I pass sleep time after calculating time difference to SDL_Delay() makes my programming to freeze completely with a 'not responding'.

I do not want to use SDL_WaitEvent() because my program will show animation which will run regardless of input events.

is there any equivalent to pygame's which neither blocks input nor the video thread

fpsClock = pygame.time.Clock()
while(True):
    pygame.display.update()
    fpsClock.tick(60)
like image 915
Thomas Avatar asked Oct 30 '22 01:10

Thomas


1 Answers

Have you checked that call to SDL_GL_SetSwapInterval(1) was successful? Your FPS should be capped at your refresh rate if your call was successful.

Did you properly initialized your OpenGL in SDL for double buffering? Like this for exmaple:

SDL_Window *window;
SDL_GLContext context;

SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

window = SDL_CreateWindow("OpenGL Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_OPENGL);
if (!window) {
    fprintf(stderr, "Couldn't create window: %s\n", SDL_GetError());
    return;
}

context = SDL_GL_CreateContext(window);
if (!context) {
    fprintf(stderr, "Couldn't create context: %s\n", SDL_GetError());
    return;
}

int r, g, b;
SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &r);
SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &g);
SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &b);

printf("Red size: %d, Green size: %d, Blue size: %d\n", r, g, b);

SDL is not a framework, there is no such high level functions as framerate control. However you should have framerate cap with VSync. If there is no capping then it's probably means VSync is not working.

Please consider to check more in depth tutorials on how to setup OpenGL apps in SDL, this for example, see also.

like image 189
Petr Abdulin Avatar answered Nov 14 '22 07:11

Petr Abdulin