Jump to content

  • Log In with Google      Sign In   
  • Create Account


Proper framerate-independent game loop


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
11 replies to this topic

#1 d k h   Members   -  Reputation: 435

Like
0Likes
Like

Posted 14 August 2012 - 07:55 AM

Hello there!

I'm working on a game where I use this basic game loop design:

[source lang="cpp"]int main ( int argc, char* argv[] )// main entry point{ Load ( ); while ( window->IsActive ( ) ) // game loop { // update the ticks for this and the last frame last_frame_tick = this_frame_tick; this_frame_tick = SDL_GetTicks ( ); // update the scene depending on how long // it has been since we last updated Update ( this_frame_tick - last_frame_tick ); // render the scene Render ( ); } Destroy ( ); return 0;}[/source]

So I update and render the scene as much as possible (with VSYNC off). SDL_GetTicks ( ) is an API function that returns the number of milliseconds that have passed since the API (ie. the game) started. In my Update ( float time ) function, I then multiply every speed (that is, a bullet moving forward for example, but also a character turning their head to one side) by that time.

In theory, this should give me a framerate independent gaming experience - if we're running on an older machine, we might just get 20 fps so the time it takes to render each frame is 50 ms, on a modern machine we could get 200 fps (5 ms per frame). A bullet moving forward at an original speed of 2.5 units per frame will move at 2.5 * 50 = 125 units per frame on the slow machine and 2.5 * 5 = 12.5 units per frame on the fast one. In 1 second, on the slow machine (since it renders 20 fps) the bullet will have moved 125 * 20 = 2500 units total, on the fast one (at 200 fps) 12.5 * 200 = 2500 as well. No matter what speed the computer can run the game at, all the action will always be going on at the same rate, it's just going to look and feel a lot smoother on a better system for obvious reasons.

This is the (very basic) theory from what I understand reading tutorials such as this one. But for some reason, this doesn't work for my games, when I set everything up as explained, my bullets (etc.) will still move a lot faster with a higher framerate!

[source lang="cpp"]// in Update ( float time ):// GetForward ( ) returns a normalized forward vector for the projectilebullet->SetPosition ( bullet->GetPosition ( ) + bullet->GetForward ( ) * 2.5f * time );[/source]

What am I doing wrong or misunderstanding here? Is the entire game loop design faulty? The article linked makes it sound like this should work (albeit saying that speed prediction methods are better, stuff I'd rather not get into without it being necessary).

Any help would be greatly appreciated, as always! I'm lost! Posted Image

Edited by d k h, 14 August 2012 - 08:05 AM.


Sponsor:

#2 JWBaker   Members   -  Reputation: 235

Like
0Likes
Like

Posted 14 August 2012 - 08:23 AM

http://gafferongames.com/game-physics/fix-your-timestep/

Read this until your understand it.

#3 L. Spiro   Crossbones+   -  Reputation: 12334

Like
1Likes
Like

Posted 14 August 2012 - 08:27 AM

http://gafferongames...-your-timestep/

Read this until your understand it.

He isn’t trying to decouple his logic and rendering, only make logic non-framerate dependent.


Print the values for this_frame_tick, last_frame_tick, and time.
Note that SDL_GetTicks() returns an unsigned integer in milliseconds and you need a proper conversion to float.


L. Spiro
It is amazing how often people try to be unique, and yet they are always trying to make others be like them. - L. Spiro 2011
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
I went to my local Subway once to find some guy yelling at the staff. When someone finally came to take my order and asked, “May I help you?”, I replied, “Yeah, I’ll have one asshole to go.”
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums

#4 d k h   Members   -  Reputation: 435

Like
0Likes
Like

Posted 14 August 2012 - 08:32 AM

Print the values for this_frame_tick, last_frame_tick, and time.


Will do and edit results in in a second.


Note that SDL_GetTicks() returns an unsigned integer in milliseconds and you need a proper conversion to float.


I'm just bruteforcing the conversion as such:

[source lang="cpp"]float time = ( float ) uint_time;[/source]

I didn't consider this a problem, whether the time value is 500 as unsigned int or 500.0f as float? Is this were I'm going wrong?

Thanks for the response!

Edited by d k h, 14 August 2012 - 08:32 AM.


#5 Firestryke31   Members   -  Reputation: 350

Like
3Likes
Like

Posted 14 August 2012 - 08:40 AM

I second reading that link, it's pretty helpful for this situation. The gist of it is

totalTime = 0;

while(notDeadYet)

{

  startUpdate = timestamp();

  while(totalTime >= UPDATE_STEP)

  {

	Update(); // Simulates exactly UPDATE_STEP amount of time each call

  }



  Render(); // Renders the latest tick

  totalTime += timestamp() - startUpdate;

}


This way at 200 FPS you only update the simulation every X frames, but at 20 FPS you update multiple times a frame as needed. Animations are smoother as you're taking snapshots of a guaranteed smooth stepping, and it's easier to ensure physics are accurate as they're no longer framerate-dependant.

#6 d k h   Members   -  Reputation: 435

Like
0Likes
Like

Posted 14 August 2012 - 10:23 AM

I understand the beauty of that game loop design, I'm really just wondering what's wrong with the way I'm trying to do it (where updating and rendering the scene is coupled)! If I can't sort this out, I can always switch to the version with fixed timestep for updating the scene but for now, if possible, I'd prefer to stay with the framerate independent updating and find out what is going wrong. Any further ideas?

EDIT: last_frame_tick, this_frame_tick and time look okay to me. last_frame_tick is 17619 after about 17 seconds, this_frame_tick in the same frame is 17745, time is 127.0f that frame. Next frame, last_frame_tick then is 17745 of course. This looks to be perfectly fine to me!

Edited by d k h, 14 August 2012 - 11:08 AM.


#7 ddlox   Members   -  Reputation: 168

Like
2Likes
Like

Posted 15 August 2012 - 05:03 AM

The problem that you do not realise is that 'you are mixing 2 things into 1 Framerate (FPS) and Rendertime (RT)'.
Looking at your gameloop, I can tell that it is framerate dependent loop. No doubt about that. Why?
- because your update call feeds with the last RT and this RT is produced by an uncapped Framerate. That's why your bullet still travels fast/slow because you are rendering what the last rendertime dictates (rather than what the last update should dictate).

Your framerate should ALWAYS be capped (or fixed) and your rendertime is ALWAYS variable. This last rendertime variance is then broken into steps into your future update calls for the next frame. This is how your loop becomes framerate independent.

Currently, your render call comes immediately after the update call, which is fed with the last render time. This is a typical scenario for framerate dependency. This is why your bullet will still seem to be fast or slow (depending on CPU). To achieve independence you need to do what Firestryke31 or the suggested link said. What he/she posted there is typical scenario for framerate independence.

This method will allow you to cap or fix your framerate (FPS) and allow your render time (RT) to feed into your next update call in steps .
As an example:
you can cap your game loop to always run at 60FPS on slow and fast machines, but your RT will be the one changing. Your updates (logic) will therefore take place in steps as highlighted by Firestryke31 then after those updates you call render.

You cannot achieve framerate independent updates with immediate render call after it, it will never work well across CPUs. You need to break down your updates in steps.

Good luck.

#8 nfactorial   Members   -  Reputation: 721

Like
1Likes
Like

Posted 15 August 2012 - 09:16 AM

First up, you really don't want a framerate independent game loop. Not at all. There are no games out there (okay, benefit of the doubt, less than 1% of games) with a framerate independent game loop. Making your game loop framerate independent puts you at the mercy of floating point inconsistencies and introduces many more problems than benefits.

What you want to do, is choose a framerate for your games update. And ensure your game updates to that time period, whether you choose 30fps update, 60fps update, 120fps update is upto you. This is pretty much as ddlox above me has stated, and how just about every game out there is written. There are implementation differences for sure, but the basic concept is the same.

Whilst that is not the direct answer you requested, the issue you have (looking at the code) is simply doing:

#define MILLISECONDS    1000.0f
float currentTime = 0;

oldTime = timeGetTime();
while ( notDeadYet )
{
    newTime = timeGetTime();
	 timeDelta = newTime - oldTime;

    float t = timeDelta / MILLSECONDS;
    Update( t );
}


I didn't consider this a problem, whether the time value is 500 as unsigned int or 500.0f as float? Is this were I'm going wrong?


The problem is the time is in milliseconds, whereas your float is in seconds. So 500 milliseconds is not 500.0f, dividing by 1000 will not work directly as it is an integer calculation. So the above example uses 1000.0f to force the calculation to use floating point.

I am assuming it is for C/C++, if I made a mistake on that, my apologies.

n!

#9 nfactorial   Members   -  Reputation: 721

Like
0Likes
Like

Posted 15 August 2012 - 09:18 AM

Hmmm, can I not edit a post on here? The sample code is, ofcourse, missing a "oldTime = newTime;".

#10 d k h   Members   -  Reputation: 435

Like
1Likes
Like

Posted 15 August 2012 - 09:29 AM

Ah, got it! That was the missing piece of information. I have gone ahead and changed my game loop, Firestryke31's loop did not work out of the box, using the article I came up with this which seems to work fine and caps my update calls (ie. the game simulation) at 50 times a second (every 20ms)!

[source lang="cpp"]// update the scene every 20ms (50 times a second)const unsigned int UPDATE_STEP = 20;unsigned int total_time = 0;unsigned int current_time = SDL_GetTicks ( );while ( window->IsActive ( ) )// game loop{ unsigned int new_time = SDL_GetTicks ( ); unsigned int frame_time = new_time - current_time; current_time = new_time; total_time += frame_time; while ( total_time >= UPDATE_STEP ) { Update ( ); total_time -= UPDATE_STEP; } Render ( );}[/source]
Does this look better? Works fine from what I can tell! :)

#11 nfactorial   Members   -  Reputation: 721

Like
1Likes
Like

Posted 15 August 2012 - 09:37 AM

Yes, that looks pretty close to most games core loops.

Have fun :)

#12 Firestryke31   Members   -  Reputation: 350

Like
0Likes
Like

Posted 16 August 2012 - 12:19 PM

Sorry, I forgot to mention that my sample was just pseudocode (and apparently I completely forgot to decrement the accumulated time in the loop).

One thing you might possibly consider is, in a separate "game state," stepping one step into the future, and passing the post-looping total_time / UPDATE_STEP to the renderer to interpolate between the current step and the "future" step, giving smoother animations.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS