• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
SonicD007

Fixed Time Step Game loop

16 posts in this topic

I've been trying to understand fixed time step game loops for about 3 weeks and I'm still having trouble understanding it.  I've read http://lspiroengine.com/?p=378 http://gafferongames.com/game-physics/fix-your-timestep/ and http://www.koonsolo.com/news/dewitters-gameloop/ multiple times and I still can't wrap my head around it exactly.  I understand that we want to render as fast as possible as well as updating the game logic at regular intervals.  What I don't understand is why the interpolation value is used in the rendering function instead of the update logic function.  Also, what would be the time that I would use to do my actual logic updates?  Would it be the dt time (interpolation time) or what?  If someone can do a mock up in paint to help me visually see how everything connects I would GREATLY appreciate it.  I'm driving myself crazy trying to get this under my belt.  Another problem I was having was my timer integer was "overflowing".  

 

(I had a tough time understanding gafferon's tutorial.  deWitter and Spiro I understood better)

1

Share this post


Link to post
Share on other sites

Hmm.  I think I understood all that.  So the drawing portion of the fixed time step is almost like lag compensation of networked games except these predictions are pretty much 100% accurate right?  

 

while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) {
update_game();

next_game_tick += SKIP_TICKS;
loops++;
}

 

How do I prevent my next_game_tick variable from overflowing and why do we add the SKIP_TICKS to it?  Also, loops < MAX_FRAMESKIP is to prevent the "spiral of death" correct?

0

Share this post


Link to post
Share on other sites

Show your implementation of GetTickCount().  Depending on what it is doing it could be a problem.

 

Prevent things from over-flowing by starting your timers at 0 every time your game is run.  Search my article for the text, “Updating your timers has its own nuances”.

The section of my article just after that explains why you add SKIP_TICKS rather than just setting the current time etc.

 

 

L. Spiro

2

Share this post


Link to post
Share on other sites
It's not really lag compensation, although it may help with that. Here's how I think of it:

You keep the update logic to fixed time step so that it is consistent. Variable time steps have all sorts of problems. Just try and make it so that when you jump that you reach the same height every time and you'll see what I mean!

The drawing is interpolated because otherwise everything you see is capped at the update rate you set. I.e. imagine that your update logic was running at 6 times a second, but you were getting 60fps. Assuming you hold the mouse still and just move straight forwards only, you would get 10 frames the same, then another 10 frames the same etc. It would look like 6fps!
But if all the frames interpolate everything then it looks like smooth 60fps again.
0

Share this post


Link to post
Share on other sites

For GetTickCount() I'm using gameTime.getElapsedTime().asMilliseconds() where gameTime is an sf::Clock  (using SFML).  It's the next_game_tick that overflows since it's always having a number get added to it (SKIP_TICKS) but nothing gets subtracted from it.

 

 
const int TICKS_PER_SECOND = 25;
    const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
    const int MAX_FRAMESKIP = 5;
    sf::Clock gameTime;
    //First tick is at 0.0 next tick is at 
    long int next_game_tick = 0;
    int loops;
    float interpolation;
 
    bool game_is_running = true;
    while( game_is_running ) {
 
        loops = 0;
        while( gameTime.getElapsedTime().asMilliseconds() > next_game_tick && loops < MAX_FRAMESKIP) {
            std::cout << "Updating" << std::endl;
 
            next_game_tick += SKIP_TICKS;
            loops++;
        }
 
        interpolation = float( gameTime.getElapsedTime().asMilliseconds() + SKIP_TICKS - next_game_tick )
                        / float( SKIP_TICKS );
        std::cout << interpolation << std::endl;
    }
0

Share this post


Link to post
Share on other sites

#1: You can’t be requesting the current time every time you need a time value. Think about how it affects your inner loop when your time function returns a different value every time it is called. My article gives one example of the problems this can cause, as quoted.
#2: As I mentioned before, clock() is forbidden as a game timer. Use QueryPerformanceCounter() and friend.
#3: Notice that GetRealTime() is called only once per frame. The time since the last update is then calculated and all the timer counters are adjusted by that much. Never get the real time more than once per frame. It’s changing, and nothing related to time should be changing until your next update (actually this is not quite true but I won’t confuse you with the details for now, especially not until you have made a game-suitable time class which is instance-based—never work with global time objects).

 

#1 and 3: I understand the reasoning for this and I will be changing that in my code.  I liked the example you gave on your website about this. (Didn't implement it at the time of writing that code because I didn't think it would impact my testing so much, I was just trying to get the loop going)


 

#2: I looked up sf::Clock (well more like asked on the sfml forums) and it seems sf::Clock does use QueryPerformanceCounter() on windows and the equivalents on mac and linux platforms (so it's a cross platform clock).  That being said, I should be able to use it just fine then as long as I getelapsedmilliseconds once and store it to a variable per frame correct?


 

How would I fix the overflow of next_game_tick?  I would think I'd have to reset it somehow so it doesn't overflow but keep it in a way that it's still correctly getting the next game tick which brings me to another question.  Wouldn't gameTime.getElapsedTime().asMilliseconds() eventually wrap around as well?  (I think I understand the fixed time step and how it works, now it's just these 2 questions and I think I'll have it working.)

 

I appreciate your time everyone, I'm almost there >.<
 

EDIT: 

So this is how the new loop looks

 
const int TICKS_PER_SECOND = 25;
    const int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
    const int MAX_FRAMESKIP = 5;
    sf::Clock gameTime;
    //First tick is at 0.0 next tick is at 
    long int next_game_tick = 0;
    int loops;
    float interpolation;
 
    bool game_is_running = true;
    while( game_is_running ) {
        sf::Time curTime = gameTime.getElapsedTime();
        loops = 0;
        while( curTime.asMicroseconds() > next_game_tick && loops < MAX_FRAMESKIP) {
            std::cout << "Updating" << std::endl;
 
            next_game_tick += SKIP_TICKS;
            loops++;
        }
 
        interpolation = float( curTime.asMicroseconds() + SKIP_TICKS - next_game_tick )
                        / float( SKIP_TICKS );
        std::cout << interpolation << std::endl;
    }
    return 0;
Edited by SonicD007
0

Share this post


Link to post
Share on other sites

#2: I looked up sf::Clock (well more like asked on the sfml forums) and it seems sf::Clock does use QueryPerformanceCounter() on windows and the equivalents on mac and linux platforms (so it's a cross platform clock).  That being said, I should be able to use it just fine then as long as I getelapsedmilliseconds once and store it to a variable per frame correct?

Yes.

How would I fix the overflow of next_game_tick?

Firstly, don’t make signed what can never be negative. You lose an entire bit of positive precision.
Making it an unsigned 64-bit integer is a start.

Secondly, if it is an unsigned 64-bit integer, starts at 0, and counts in microseconds since the game has started, it would take 584,542.046091 years (not accounting for the slowing of Earth’s rotation) to overflow. You don’t need to worry about it unless you are not following all 3 of the above conditions.

Wouldn't gameTime.getElapsedTime().asMilliseconds() eventually wrap around as well?

I think you mean gameTime.getElapsedTime().asMicroseconds().
If it is starting from 0 and counting microseconds since the game started, no, it will not overflow within your lifetime.
If it is returning the real time in microseconds since epoch, no, it will not overflow within your lifetime.
If it is only used in a subtraction operation to determine how much time has passed since the last time it was called, overflow will be handled automatically by the laws of computer science.


L. Spiro
0

Share this post


Link to post
Share on other sites

Thank you so much everyone!  L. Spiro, thank you for clearing things up for me, that's two blogs you've made that've helped me out so far :)

1

Share this post


Link to post
Share on other sites

Sorry to bring this topic up, but i can't get this to work correctly.

I have made a minimal example (win32/dx9) cpp that shows the problem. I have read and follow L. Spiro tutorial but for me objects are moving at different speeds if vsync is on and off.

Please if can someone could try it and tell me where is my mistake?

 

http://pastebin.com/mmDUVELE

 

Thank you for your time.

0

Share this post


Link to post
Share on other sites

Does not look like you ever call gTimer.update, and gTimer.get just returns a variable, which is initialised to 0 and updated via gTimer.update. So looks like gTimer.get is always zero. This leaves you with "while((0 - 0) > 33333)" which never runs.

 

Also you are moving stuff in onPreUpdate which is not part of your fixed step loop anyway ("vSprites[i]->moveRandom();"), it will be the rendering frame rate.

1

Share this post


Link to post
Share on other sites

laugh.png  OMG, forgat to update the timer, ok i fixed that now but again the moving speed is different.

 

Also you are moving stuff in onPreUpdate which is not part of your fixed step loop anyway ("vSprites[i]->moveRandom();"), it will be the rendering frame rate.

 

 

Imagine that onPreUpdate is using input from keyboard to move objects, i cannot call that in "fixed-step" loop, can i?

I though i just need to interpolate positions in that loop.

 

Thank you for your time.

0

Share this post


Link to post
Share on other sites

If your moving objects outside the fixed step loop, it is not fixed step. For key pressed / released events you can possibly get away with it, but your not doing that there, you are moving the objects regardless by some amount that doesnt look like it even tries to account for the loop rate.

 

Your input needs to be using events (so when the user presses a key you do one thing once, not every loop), or if your polling (e.g. do something as long as a key is pressed) it really should be in the fixed step section.

Edited by SyncViews
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0