Question

I'm writting a game using C++. I wonder how can I optimize my game loop. For example, we have some game with the main loop looks like this:

while ( gameContinue ) {
    if ( SCENE == HELP_SCENE ) {
        renderHelpScene();
    } else if ( SCENE == SCORE_SCENE ) {
        renderScoreScene();
    } else if ( SCENE == MAIN_GAME_SCENE ) {
        renderMainGameScene();
    } // .... and many others scenes
}

I'm thinking on how to make this code faster and lighter. I think about using callbacks so we will not need many if-cases. Something like this:

typedef void (*callback_function)(void);
callback_function renderFunc; 

void renderMainGameScene() {
    renderFunc = renderScoreScene(); // set to another scene if we need this
}
void renderScoreScene() {
    renderFunc = renderAnyAnotherSceneWeNeedNow();
}

renderFunc = renderMainGameScene();
while ( gameContinue ) {
    renderFunc();
}

What do you think about it? How do you organize your main loops?

Était-ce utile?

La solution

I've personally started using multi-threading. I have a thread for object updates, a thread for objects collision and a thread for drawing. Each thread loops with a while (GetMessage()) and threads send messages from one to another.

At each cycle (frame), my main loop sends a message to each thread to:

  1. Calculate collision for modified objects
  2. Update objects (movement, state etc.)
  3. Draw the updated objects

That's how I do it (at least on my GDI/GDI+ games). Not sure if the best way, but so far it works like a charm :).

Autres conseils

Helpful patterns for this kind of problem are the State Pattern and the Strategy Pattern.
As you can see they are both similar. The Strategy pattern is a bit simpler than the State, but in exchange the State Pattern is more powerful and probably better fitted for a game engine like this. You can also easily create a stack with this for example: game start -> menu -> game run -> menu.
If the parent state of the last menu is game run, the menu would look different (e.g. "Return game" instead of "Start game" in the first menu). The states can be popped and you have a easy navigation.

Using call-backs should be fine. Just be careful not to have any cyclic dependencies in your headers. Notably it's a bad idea to include the header for your controller loop anywhere other than the .cpp for the controller loop.

As for the runtime benefits, they are very small. The if-else method will not noticeably slow down your game. Alternatively, there is also the switch statement, which is preferable to a series of if-else statements in terms of code readability.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top