Again and again, correct timestepping?!

There's tons of thread about it, and no real clear solution. I tried everything, and it's always jerky.

First to clarify some things:
-I use Win32/SDL on fast computers, one thread for both physics and rendering.
-I try to use fixed timestep to keep a coherent simulation. I render at what I can. With logs, I'm certain that my physics actually simulate 60 times per second, and rendering get about 180 frames per seconds.
-I use LARGE_INTEGER and QueryPerformanceCounter() for maximum precision.
-I don't think interpolating between rendering frames when physic didn't change do anything, the monitor don't refresh faster than the timestep anyway, so I guess always rendering at the last position is OK.
-Gaffer article is ok, but there's some things missing like events input and I get lost when he begin to talk about mathematical integration there.

Here is the code I have working the best until now, but sometime there's a strange big jerkiness happening. Seems to happens on certain framerate multiples. I actually used the same code for a DirectX10/PhysX engine and the same thing happened, I though it was something else but now that the exact same thing happens on my very different 2D SDL engine, I'm certain it's because of this timestepping problem.

Code:
bool CApplication::EventLoop(b2World* world)
{
        LARGE_INTEGER frequency;
        LARGE_INTEGER startTime;
        LARGE_INTEGER lastFrame;
        LARGE_INTEGER currentTime;
        float deltaT=0;
        float second=0;
        UINT framePerSecond=0;
        UINT lastFramePerSecond=0;
        float accumulator = 0.f;
        const float timeStep = 1.f/60.f;
        const int velocityIterations = 10;
        const int positionIterations = 8;

        srand((unsigned)time(0));
        QueryPerformanceFrequency(&frequency);
        QueryPerformanceCounter(&startTime);
        lastFrame = startTime;

   SDL_Event event;
   bool bRun = true;
   while(bRun)
   {
            QueryPerformanceCounter(&currentTime);
            deltaT = (currentTime.QuadPart - lastFrame.QuadPart) / (float)frequency.QuadPart;
            second += deltaT ;

            if(second>=1.f)
            {
                second-=1.f;
                lastFramePerSecond=framePerSecond;
                framePerSecond=0;
            }
            framePerSecond++;

            if (deltaT>0.25f)
                deltaT = 0.25f;

            accumulator += deltaT;

            while(SDL_PollEvent(&event))
            {
                if(event.type == SDL_QUIT)   
                    bRun = false;
                else if(event.type == SDL_USEREVENT)
                    ((UserEventFnct)event.user.data1)(event.user.data2);
                else
                    CheckEventLoop((CVMWidget*)m_pRootObject, event); // Handle KeyPress/MouseMove, don't apply force there, simply change variables
            }

            while (accumulator>=timeStep)
            {
                accumulator -= timeStep;
                ((CVMWidget*)m_pRootObject)->Update(); // Call to ApplyForce() and such on bodies depending on previous events variables
                world->Step(timeStep, velocityIterations, positionIterations);
                world->ClearForces();
            }

            ((CVMWidget*)m_pRootObject)->UpdatePhysPos(); // Use GetTransform() on bodies for the renderer to know the new position
            ((CVMWidget*)m_pRootObject)->Paint();
            ((CVMWidget*)m_pRootObject)->Flip();
            printf("%d\n", lastFramePerSecond);
            lastFrame = currentTime;
   }
   return false;
}


What the hell is wrong with that!?
Can you show me the UpdatePhysPos function? I assume this is where you're doing an interpolation?
One other thing, do you have any other code in your update routine that updates based on some sort of time counter? i.e. update GUI every 2 seconds, or something like that?
With interpolation, you mean interpolate the objects positions between two timesteps when the rendering is faster than physics? The last time I tried that I came to conclusion it simply get things worse (because it's always interpolating one frame late) and is really useless because the monitor don't display theses frames anyway (over 60Hz). My symptoms are that sometimes it's smooth, and the it have a refresh lag, can get worse, then comes back smooth and just keep doing that every few seconds. I pretty sure there's nothing else influencing the speed in my code.

The UpdatePhysPos() could be omitted, I just store the top-left position in a variable to blit there later on in Paint(), but to give you an idea:

Code:
    void CVMWidget::UpdatePhysPos()
    {
        if(GetParent() && m_pBody)
        {
            b2Transform trans = m_pBody->GetTransform();
            m_sRelX = trans.position.x - GetWidth()/2;
            m_sRelY = trans.position.y - GetHeight()/2;
        }

        for(std::list<CVMWidget*>::iterator iter=m_Children.begin();iter!=m_Children.end();iter++)
            (*iter)->UpdatePhysPos();
    }


Is my while(SDL_PollEvent(&event)) loop in the correct place?

I don't have anything else time-based currently. I do initialize SDL with the SDL_INIT_TIMER flag, which create an internal timer in another thread to process events, but I don't have any timer active yet. I do plan to use it later though.
Hmm... Yep that is what I meant by interpolation, but if you're not using it then it's not going to cause the problem.

I can't see anything obviously wrong, perhaps your best bet would be to try some graphics debugging software, like perfkit from nvidia, or the useful PIX software from microsoft. I've used PIX before, I would try that first.
Both PIX and PerfHUD are only for Direct3D applications. I use SDL so it's a no go.
Plus, I've used PIX before and it's nice, but it's used mostly to debug draw calls in a frame, nothing related to what we are talking here.

I don't exactly know what would I look for anyway, I don't know where the problem come from. I simply know that every single games ever using physic engine need to do that, so it's strange there's no concise example available online. The problem seems to be a synchronization issue between two things (physics step, buffer flipping or monitor Hz), I just can't pinpoint what.

I would be grateful if someone who know how it really supposed to work could answer.
There are several possibilities, and rest assured that I have seen this before.

1. If your timesteps are too small (unlikely unless they aren't fixed, and you are getting a high FPS on a fast PC), then you can invoke too many underflow floating point operations in a single frame, causing a major slowdown. "Underflow conditions can slow down floating-point operations considerably on HP 9000 systems." from URL: http://docs.hp.com/en/B3906-90006/ch02s03.html

I had to work around this in my game by using a fixed timestep so that fast machines couldn't reduce the timestep down to small enough values to cause significant underflow.

2. It is possible that you need to switch from QueryPerformanceCounter to timeGetTime, there have been issues with this Win32 function for several versions of windows. http://www.virtualdub.org/blog/pivot/entry.php?id=106
Point #1 don't seems to apply since timesteps are fixed at 1/60, which is a commonly used refresh rate.

Thanks for point #2, the virtualdub guy make sense with modern CPU dynamically changing speed, but it's not it.
I tried timeGetTime() and I get the same jerky feeling but 10 times worse. It seems like an outdated Windows function. It actually use a DWORD to store milliseconds, so a timestep of 1/60 (16,66667ms) get rounded down to 16ms. This gives inexact results, my deltaT is 6/7ms and my "physics Step() FPS" switching between 62 and 63.

At least with QueryPerformanceCounter it's smooth most of the time and my "physics Step() FPS" stay at 60 most of the time, even though I saw go to 61, probably at the same time it jerked. Could that mean that even this timer is not accurate enough? Would adding more objects on screen so my rendering function takes longer could help?

Note: I tried to use double instead of float for the timestep/deltaT/accumulator variables and the frequency division. Don't seems to solve anything.

I found out on another thread (http://www.gamedev.net/community/forums ... _id=553890) a logic answer, but no solution:
Quote:
You're going to have jerkiness anytime your game simulation isn't in sync with your rendering. This can happen very easily with a fixed time step where you "catch up" by doing multiple updates for a single render, since for some frames you'll have maybe 0 or 1 updates and then for other frames you might have 2 or 3. The end result is that the game seems to "jump forward" in time, and the flow of time will not appear even. Quite distracting.

For this reason the simple "catch up" game loop isn't too popular. Most games will either use interpolation in their physics to keep things smooth (the big physics packages like PhysX or Havok can do this for you), or they try to keep rendering locked or VSYNC'ed at the rate of their fixed time step (really only doable on consoles where you know the refresh rate is 60Hz). Or of course you can use a variable time step, and just hope that your physics simulation doesn't explode.


I wouldn't mind to vsync my game to 60fps, but it's not standard and does not works. using the nvidia control panel to enable it do nothing (probably because it's SDL, and not D3D/OGL) and calling Paint()/Flip() in the same loop as the physic Step() don't seems to change the results at all. As for the other things he said (the big physics packages like PhysX or Havok can do this for you) it's not really true, since they behave exactly like Box2D and you need to call Step() at the exact same time frame you pass as argument, so you have to handle it yourselves anyway.
Dunge wrote:
Both PIX and PerfHUD are only for Direct3D applications. I use SDL so it's a no go.
Plus, I've used PIX before and it's nice, but it's used mostly to debug draw calls in a frame, nothing related to what we are talking here.


I had a similiar issue... once I profiled it with PIX, I could see that I was skipping every 10th frame or so, because a GUI update I was doing was taking a long time. I have a very similiar main loop to you, so it's probably more related than you think. Anyway, since you can't use those tools on SDL, it's a moot point.
Well that's not it. It's not a slow down every X frames or seconds, it just keeps switching between smooth and laggy every few seconds. I can think of two things, one is that Box2D actually can manage it for me and I'm not digging the good way, or as I saw a few other places, I should do something with numerical integration, but I don't get it. Isn't that the part Box2D handle with the velocityIterations/positionIterations parameters?

Seriously, how do you guys do it in your own games? Do you all do like the testbed sample and let Glut handle it? Or do you use variable timestep and don't care that players sometime move faster/slower than supposed? Or do you use exactly the same code as me and it simply works?

I'm still at the start of game building and it's not too late to change anything. I just want a game with Box2D physics and smooth fluid gameplay and I can't believe this is asking too much, what is going on here?

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