method to fix the timestep (beginner)

Hi,
i'm a beginner with Box2d, i'm reading a book and i'm a bit confused about this example and the "fixed timestep implementation" :

Code:
-(void)update:(ccTime)dt {   
//    int32 velocityIterations = 3;
//    int32 positionIterations = 2;
//    world->Step(dt, velocityIterations, positionIterations);
   
    static double UPDATE_INTERVAL = 1.0f/60.0f;
    static double MAX_CYCLES_PER_FRAME = 5;
    static double timeAccumulator = 0;
   
    timeAccumulator += dt;   
    if (timeAccumulator > (MAX_CYCLES_PER_FRAME * UPDATE_INTERVAL)) {
        timeAccumulator = UPDATE_INTERVAL;
    }   
   
    int32 velocityIterations = 3;
    int32 positionIterations = 2;
    while (timeAccumulator >= UPDATE_INTERVAL) {       
        timeAccumulator -= UPDATE_INTERVAL;       
        world->Step(UPDATE_INTERVAL,
                    velocityIterations, positionIterations);       
    }


i tried to find some more informations on the internet, one website explained it with this example :

Code:
   void integrate(State &state, float t, float dt)
    {
         Derivative a = evaluate(state, t, 0.0f, Derivative());
         Derivative b = evaluate(state, t, dt*0.5f, a);
         Derivative c = evaluate(state, t, dt*0.5f, b);
         Derivative d = evaluate(state, t, dt, c);

         const float dxdt = 1.0f/6.0f * (a.dx + 2.0f*(b.dx + c.dx) + d.dx);
         const float dvdt = 1.0f/6.0f * (a.dv + 2.0f*(b.dv + c.dv) + d.dv)

         state.x = state.x + dxdt * dt;
         state.v = state.v + dvdt * dt;
    }
   
   
    double t = 0.0;
    double dt = 1 / 60.0;

    double currentTime = hires_time_in_seconds();

    while ( !quit )
    {
         double newTime = hires_time_in_seconds();
         double frameTime = newTime - currentTime;
         currentTime = newTime;

         while ( frameTime > 0.0 )
         {
             const float deltaTime = min( frameTime, dt );
             integrate( state, t, deltaTime );
             frameTime -= deltaTime;
             t += deltaTime;
         }

         render( state );
    }


but i'm a bit confused. Could someone explain me the logic of this? when i searched some explanations, i finally ended up on the wikipedia's page of RK4, or "numerical integration", but it did not really help me as it was too complicated for me 😮 😀 )

Thanks for your help
The idea is that you shouldn't have a variable timestep for the Box2D engine (or a lot of physics engines that I know of) because having a variable timestep makes the physics unpredictable and sometimes unstable (because of how some engines optimize processing time, and a large timestep (i.e. a drop in the framerate) will cause some undesirable effects). A fixed timestep is a must if you want stable, predictable physics.

But, how do you have a fixed physics timestep when the rest of your program is doing its own thing with its own timestep? One solution, if the rest of the program is almost guaranteed to be faster than the physics timestep with the occasional drop in framerate, is to have the physics update only when it's at its timestep interval. To determine when it's at the timestep interval, you use an accumulator and add the amount of time passed from the start of the previous frame (delta time) and check if the accumulator is more than or equal to the interval. But an accumulator alone is dangerous, as there is the danger of the physics update taking longer, thus increasing the delta time for the next frame, which will add more to the accumulator, which will make the physics update more times in an attempt to catch up, which increases the delta time, etc. etc. (the spiral of death). A certain minimum frame rate (or in this case, max (physics update) cycles per frame) will stop that spiral of death.

This is if you want the physics to be synchronized with real time. If that is the case, you want the physics to update when it's 1/60 seconds since start, 2/60 seconds, 3/60, and so-forth, and not in between (or else the physics will be going faster than the intended speed and not sync up with real time). So, the accumulator solution is good for some cases.

However, the accumulator solution may cause some visual "jumps" in physics because the accumulator has accumulated enough odd delta time values for two updates. The idea of the physics updating multiple times in order to catch up for the lag the rest of the program (or the computer) may have caused is a good idea, but the accumulator solution can cause an occasional visual "jump" in physics if nothing done is to fix that graphically.

Now, to prevent this particular visual jump (while keeping the fixed timestep), there is interpolation solution. This is mostly for visual purposes and fixes the odd "jump" in a multiple physics update caused by an odd accumulation. If you've looked online on how to implement a fixed physics timestep without affecting the frame rate of your application, you've probably come across an article that mentioned the idea of "do a physics update, and have the graphics renderer take up however much time there is left until the next physics update".

Of course, you don't want the graphics renderer to render the location of the physics bodies exactly the same for all X amount of times; that's not any better than the odd visual "jump". What interpolation does is to "fill in" the spots between the physics timesteps, and have the renderer use these in-between time spots to render the positions and angles of stuff so the motions are visually fluid. These are also known as motion states (hence, the use of the word "state" in that second block of code you posted). Figure out what point in between of the physics timestep (the motion state) to render, then send that data to the renderer.

The whole "numerical integration" deal is simply a way to use the point of time given between the physics timesteps to calculate and generate the values for the interpolation thing to calculate the midway positions and angles of the physics bodies.

Physics interpolation and motion states are entire fields of study, so don't feel bad about not knowing any of this, nor should you feel obligated to know everything. I don't know how interpolation is done (in the same way I cannot really understand the deep calculations of Box2D); I only know the gist of what's going on.
Thanks Jayther, i really appreciate your help and your explanations! Can i ask you some questions?
Quote:
when the rest of your program is doing its own thing with its own timestep?

what does it mean? isn't there one world per game, with one timestep set at the beginning of the game?

Quote:
you want the physics to update when it's 1/60 seconds since start, 2/60 seconds, 3/60, and so-forth

What does contain "dt" actually? Is "dt" the time from the start, as dt = 1/60 the first time, then it is 2/60 etc. ? (does it mean 1 frame per second, then 2 frames per second? Can it go until 60/60 etc. ?)

In the second code, i'm not sure to understand why we're calculating the four points from a to d, it's a bit mysterious to me right now ... 🙂

Thanks again
Soloraze wrote:
Quote:
when the rest of your program is doing its own thing with its own timestep?

what does it mean? isn't there one world per game, with one timestep set at the beginning of the game?
What I meant is the processing of the rest of the program that's not physics, i.e. graphics rendering and game logic. The idea is that the physics should only update once every 1/60th seconds (60 frames per second), but some parts of the rest of the program (like graphics rendering) can probably do things multiple times between each physics timestep safely.

Soloraze wrote:
What does contain "dt" actually? Is "dt" the time from the start, as dt = 1/60 the first time, then it is 2/60 etc. ? (does it mean 1 frame per second, then 2 frames per second? Can it go until 60/60 etc. ?)
"dt" is delta time, the amount of time between the current frame and the previous frame. What I meant with 1/60 seconds since start, then 2/60 seconds, etc. is the interval of 1/60th of a second since the beginning of the game. If you want the physics to be synchronized with real time, you want the physics to update only at 0.016667 seconds (1/60 seconds) since the start of the game, then 0.033333 seconds (2/60 seconds) since the start of the game, etc.. You don't want it to update between those intervals because that would mean the physics will not be synchronized with real time. Essentially, only update the physics when it's time to update the physics.

This is all assuming that the game itself (not just the physics) has an uncapped variable frame rate (or a capped frame rate that's faster than the physics timestep) while keeping the physics timestep fixed and only update the physics at an interval of the timestep. If the entire game is locked at a fixed frame rate and does a sort of automatic delay until the next frame (like what Flash does) and stuck at one thread of processing, most of this does not apply to the game, maybe except the idea of the physics catching up with real time when the game lags a bit (the first block of code you posted).

Soloraze wrote:
In the second code, i'm not sure to understand why we're calculating the four points from a to d, it's a bit mysterious to me right now ... 🙂
It's part of the interpolation thing, an analysis to the time passed to create a smooth curve (if you were to put the time passed in a line graph, the integration function would create smooth curves rather than a simple point-to-point segmented lines). The code edits the "state" variable with two values needed for figuring out what point in the path of the physics bodies to render. The entire integration function in the second block of code sort of creates splines (guided curves) in relation to the time since the start and the delta time. This is all to create smooth motions for physics bodies instead of jumpy motions that the game might get with highly inconsistent frame rates.
Thanks Jayther,
it took me some time to catch up with some basics of physics, i'm finally coming back to this subject.
Can i ask you : when is timeAccumulator greater than 5 (max cycles per frame) ? is it the iphone on which the game is installed, that defines "dt" ? in which case do we have the delta time at 5/60 ? and if "dt" is 5/60, and we launch the world step just one time, what will happen?

Code:
-(void)update:(ccTime)dt {   
   
    static double UPDATE_INTERVAL = 1.0f/60.0f;
    static double MAX_CYCLES_PER_FRAME = 5;
    static double timeAccumulator = 0;
   
    timeAccumulator += dt;   
    if (timeAccumulator > (MAX_CYCLES_PER_FRAME * UPDATE_INTERVAL)) {
        timeAccumulator = UPDATE_INTERVAL;
    }   
   
    int32 velocityIterations = 3;
    int32 positionIterations = 2;
    while (timeAccumulator >= UPDATE_INTERVAL) {       
        timeAccumulator -= UPDATE_INTERVAL;       
        world->Step(UPDATE_INTERVAL,
                    velocityIterations, positionIterations);       
    }


Thanks again
The timeAccumulator is greater than 5 (max cycles per frame) when the game lags on the physics or something else (like game logic), causing it to be stuck in one frame for a little too long, resulting in a large "dt" that will be added to the timeAccumulator.

According to the code you just posted, "dt" seems like it's defined by the Cocos2D engine (ccTime data type ... usually, stuff prefixed with "cc" involves the Cocos2D engine). To get "dt", you subtract the time of the current frame by the time of the previous frame.

When the timeAccumulator is over 5/60 (or "dt" is 5/60, causing timeAccumulator to go over 5/60) and the world step is only done once, the physics will simply be updated only once. So yes, this will result in a visual lag in the game. This is done so the game doesn't end up trying to get the physics up to date when the physics is the one causing the lag (sort of like a dog chasing its tail). It's better to have some lag in the game than a frozen game.
Thanks,
do you mean by "lagging" that the character in the game will suddenly "jump" from one part of the game to another, or does it just slow the game down?
and, even if the device is too slow to catch up with the animations, "dt" will still be incremented?

Thanks again
The timeAccumulator thing with max cycles per frame will allow a little bit of slow down, and will try to update the physics a couple of times to catch up with real time. This sort of thing will result in a subtle "jump" from one part of the game to another (the jumpy kind of lag). This may be noticeable but it's tolerable.

But if the time accumulator exceeds 5/60th of a second, it will just update the physics just one time instead of trying to catch up with real time. This will slow down the game because it only updated the physics once (the slow kind of lag).

If the device is too slow to catch up with the animations, "dt" will still be large ("dt" isn't incremented or increased; it's the time accumulator that gets increased due to "dt").
Thanks a lot, it makes more sense to me now!

One last thing, if i can 😀 When i read again all the messages, i'm not sure to understand your explanation about the method of integration and why we used 4 points (a,b,c,d) and how this gives us a curved line :

Code:
    void integrate(State &state, float t, float dt)
    {
         Derivative a = evaluate(state, t, 0.0f, Derivative());
         Derivative b = evaluate(state, t, dt*0.5f, a);
         Derivative c = evaluate(state, t, dt*0.5f, b);
         Derivative d = evaluate(state, t, dt, c);

         const float dxdt = 1.0f/6.0f * (a.dx + 2.0f*(b.dx + c.dx) + d.dx);
         const float dvdt = 1.0f/6.0f * (a.dv + 2.0f*(b.dv + c.dv) + d.dv)

         state.x = state.x + dxdt * dt;
         state.v = state.v + dvdt * dt;
    }

    Derivative evaluate(const State &initial, float t, float dt, const Derivative &d)
    {
         State state;
         state.x = initial.x + d.dx*dt;
         state.v = initial.v + d.dv*dt;

         Derivative output;
         output.dx = state.v;
         output.dv = acceleration(state, t+dt);
         return output;
    }

    float acceleration(const State &state, float t)
    {
         const float k = 10;
         const float b = 1;
         return -k * state.x - b*state.v;
    }


Thanks again, i really appreciate your help
This article (towards the end of the article, just before the conclusion) explains it well: http://gafferongames.com/game-physics/i ... on-basics/

If that's where you got it, then read it a little more carefully, as he does explain exactly what each thing does.

The four points are used to achieve more accuracy in the curvature (a better fitting curve).

How it forms a curve is based on the acceleration function and how it will "plot" the next point. Instead of forming an imaginary straight line between each point, it forms an imaginary curve. When you plot out the state.x and state.v over time, the best fit line will be a curve, not straight segments.

Original thread: https://box2d.org/forum/viewtopic.php?t=8435