5
votes

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)
1
I recommendation seen online would be for you to put the input processing and animation updates in different threads - dvhh
What I am wondering is that SDL_GL_SetSwapInterval(1) being successful, that is, VSync being set, why is my FPS not capping to my monitor refresh rate? My monitor refresh rate is 77Hz, I am on 32bit windows 10. Also I am a beginner and using OpenGL for drawing, I don't know whether OpenGL supports threading or not. - Thomas
this page(OpenGL and multithreading on kronos website) should answer your question about openGL and mutlithreading - dvhh

1 Answers

2
votes

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.