Synchronizing frame rate with step time (that old chestnut)

Hi folks,

I'm having the old jitter-bug problem trying to sync my game frame-rate with the physics step(s).

I have read these posts:

viewtopic.php?f=4&t=3973
viewtopic.php?f=4&t=3027

And read Glenn Fiedler's article (http://gafferongames.com/game-physics/f ... -timestep/) but I'm obviously missing something because I'm not understanding how this solves the problem.

I am developing for Android, and as such I have VERY limited [hardware] resources. Rendering is done in hardware (opengl) and hence I kind of NEED to process physics steps in a separate thread (hence CPU for phys, GPU for render.. more or less).

So this creates the problem with a variable frame-rate. I am synchronizing the step(s) of box2d with the render so I have a stable physics state while rendering, but the variable frame-rate means one of two things:

1. I fix a set number of steps in physics land, and the game runs at wildly different speeds depending on the framerate... no good.
2. I bind the number of fixed-time steps to the time taken for the previous render. This gives a constant-time game, but also gives a very jittery experience as one render frame will involve a variable number of physics steps.

What I can't get my head around is how this is solvable. Glenn Fiedler states:
Quote:
The solution is to interpolate between the previous physics state and the current state based on how much time is left in the accumulator.

Excuse my noobness, but I have absolutely no idea what this means in a box2d context. I assume it means stepping with a constant time for a given number of steps, then stepping with a smaller time for the "remainder" which together with the cumulative time taken for the fixed steps matches with the previous frame render time.

Reading the above-mentioned posts, the assumption seems to be that rendering and physics are done in the same thread. This just won't work for me because an average render is usually closer to 32ms anyway so adding the time taken to process box2d would destroy the framerate.

The second (viewtopic.php?f=4&t=3027) post also seems to indicate the solution is:
Code:
  double max = _dt*2.0;
  while (deltasec>=max && !_quit)
  {
    m_world->Step((float)_dt, _iters);
    deltasec -= _dt;
  }
  m_world->Step((float)deltasec, _iters); //This syncs up the physics engine to the current frame


But this is the same solution I currently have, and means that every render frame is not guaranteed to have the same number of physics steps. Which means bodies will appear to "jump" forward every so often as the accumulated time reaches one "step-worth".

I'm hoping (assuming) there is someone out there considerably less nooby than I clearly am to help shed some light on this.

Thanks!
Here is how I see it. I did not implement interpolation yet, but I think it still could help you.
Exaggerating to makes it more obvious: suppose you run one box2d step every second, and you redraw your graphics 40 times per second.

If you always draw the "current" positions, taken from the box2d world, 40 consecutive frames will be rendered the same (position wise), before the world is stepped and things move, and then the next 40 will also be identical ... etc.

To prevent this, you do an interpolation, which aims at rendering objects in positions where they are supposed to be between 2 world steps. You don't know how they moved between those 2 steps, but assuming a straight line trajectory is already good.
For this you have to store 2 positions for every object: the one before the step, and the one after the step (this one is in box2d so you might not need to store it yourself). Then, you draw objects at their interpolated positions between those 2, depending on the rank of your frame inside this series of 40 (that's what is handled by the "accumulator").

I hope that helps.
Unfortunately, I am not less nooby than you with Box2d (downloaded it a week ago), but this is something I've been tinkering with myself.

Just by my own discoveries, the code snippet you found as your solution works the best for me also. I haven't really noticed the jumpiness that's described by gaffer or others yet, but my tests are very limited.

I've been trying to visualize a BOX2D solution to the problem of interpolation as Gaffer describes. Gaffer's example uses states, which in his source code is just the x,y position of the object he's moving, however, box2d is slightly more complicated.

If box2d internally kept a previous step state data (which is far more complicated than x and y positions), this would be a non-issue. Though, it doesn't -- so as far as I can tell, to do the interpolation step "like you're supposed to," you'd have to track these yourself. Er, I mean, ourselves.

Frustrating for me, because I'm an old-school time-based movement person. Which means the game is scaled to run at the delta speed of each game loop. For real physics though, that's a problem.

At least we can share this problem together!

So At this point I'll probably wrap my box2d bodies around a class that snapshots their important states before a step, then loop through the list and interpolate myself.

If there's not a more automated approach, that is... ? Anyone know?
So.. I am only running in emulator, so maybe the frame rate varies more under this scenario.

After reading your post, and re-reading the article I came to the same conclusion. Because I am rendering in Java (well.. opengl, but the api is java), I need a representation of the box2d objects in java land (which I already have). It struck me that all I'm representing is position, rotation and velocity, so it would be a simple matter to interpolate two states in the way described.

Now all I need to do is work out how I interpolate a collision. If we alter the state of the "real world" elements to match the frame rate, we will also be potentially disregarding collision information and I'm worried I'll start seeing collision event that "haven't occurred yet". Eg if box2d says object A touches object B, and my game code is supposed to play a sound when this happens, then I interpolate the state and the effect is to move the body to a slightly "historical" location, I'll end up with a sound playing before the bodies "appear" to collide in the game.

It may be that this is not noticeable (as the collision is only a frame away) so hopefully it won't make a difference.

Otherwise I could hold onto the collision event until the next frame, but then you may have the opposite effect... and the sound may play after the collision.

I guess the best compromise is to look at the "alpha" value Mr Fiedler describes [0..1] and assume if < 0.5 then "process events now", else "process next frame". The worst case is an alpha of 0.5 which would mean you miss the collision entirely and either process the collision event completely before, or after the "actual" event.

Not ideal, but I'm guessing (hoping) this will be a lot less noticeable than the visual effect of frame/physics mismatch.

Thanks for your post, you actually helped solidify my understanding.

Cheers,

Jason.
snowcrash wrote:
Now all I need to do is work out how I interpolate a collision. If we alter the state of the "real world" elements to match the frame rate, we will also be potentially disregarding collision information and I'm worried I'll start seeing collision event that "haven't occurred yet". Eg if box2d says object A touches object B, and my game code is supposed to play a sound when this happens, then I interpolate the state and the effect is to move the body to a slightly "historical" location, I'll end up with a sound playing before the bodies "appear" to collide in the game.

It may be that this is not noticeable (as the collision is only a frame away) so hopefully it won't make a difference.


Remember, you're interpolating between two known positions, the previous and the current. You'd probably just play the sound "now" and I don't think you'll notice any oddities in collision... the physics are still running, you're just doing some smoothing for the viewer.

Quote:
I guess the best compromise is to look at the "alpha" value Mr Fiedler describes [0..1] and assume if < 0.5 then "process events now", else "process next frame". The worst case is an alpha of 0.5 which would mean you miss the collision entirely and either process the collision event completely before, or after the "actual" event.


I suppose. I'm thinking you won't really notice it though.

Best way to find out is to try... 🙂

I'm on my interpolation step now, so I'll be trying soon as well.
Two things that I've learned:

1. Make sure that you use the correct scale for your physics. If the physics is scaled down too much, you'll see excessive jitter since there are minimum values that are used for various corrections, and if your physics is too large, it will be floaty feeling and not crisp, or will be jittery when you increase gravity and other forces too high in order to try to bring it into crispness. For my last two games, the main character had a width of .5 meters and 2 meters respectively, not .001 meters or 100 meters.

2. I run Box2D on a fixed 60Hz timestep, and I notice considerable jitter when running it at 30Hz, particularly with joints affecting the player (he ropes like in worms).

If you need to improve the performance of Box2D, here are some tips:

1. Keep your world as small as possible. (have a cache of objects and a fast algorithm for inserting and removing objects from box2D's world)
2. Normalize your world around the origin and go with the fixed point implementation.
3. Replace b2DynamicTree with spatial hashing. I did a similar conversion for the Farseer engine and can vouch for the massive speed increase. (note: this conversion is not worth doing unless your game has many bodies)

On my Flash and iPhone games, the profiler almost always steers me away from Box2D as the culpret after I've implemented a naive algorithm for keeping offscreen objects inactive. Optimizing rendering seems to have the biggest payoff, but you can't know until you profile.

So what's slowing you down?
Hi all.. I'm back!

So I got caught up in another area of the app, but I'm back at synchronization of phys and render, and am still having big problems.

I have implemented the Fiedler approach, but I'm still getting really jerky simulations, and here (I think) is why:

I have two threads, one rendering as fast as it can, the other processing the physics simulation. On Android the graphics is (can be) hardware accelerated (opengl) so having a separate thread for graphics processing makes sense. However, in my test simulations I don't have very many bodies defined in box2d so the physics thread routinely out-performs the rendering.

Now it must be said that I am only running in the emulator at present (so no "real" hardware processing) and the render is very slow as a result. More importantly, I get wildly different render times so the frame rate is all over the place.

The problem is that the approach Fiedler suggests appears to assume you will only ever have between 1 and 2 physics frames per render (interpolating the state only between the previous step and the current one). I am seeing way more than this (usually 6-7, but fluctuating all the way to 9 or 10 and down to 1). This means at every render, I can "squeeze in" anywhere between 1 and 10 box2d steps (stepping box2d at 60 Htz, or ~16ms intervals).

The result is that within each frame, bodies in box2d land are being simulated to a wildly different degree. Meaning they are moving in a very jerky fashion. The only way I can get a smooth simulation is if I step box2d the EXACT same number of times for each render.. but of course this means that the speed of the simulation will change with faster/slower frame rates.. back to square one.

Maybe if I could guarantee a semi-stable frame rate it wouldn't be a problem, and maybe because the emulator runs so slowly I am getting unrealistic conditions, but it worries me that I can't seem to create a scenario where, regardless of frame rate, I get a smooth consistent simulation.

Anyone else have any experience/guidance in this regard? Maybe I'm still not understanding the approach.

Cheers.
Please checkout my post here: viewtopic.php?f=3&t=4907

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