Again and again, correct timestepping?!

Hareball is right, see if the spikes disappear when you force the game into a real fullscreen mode (not just a window that is the same size as the desktop). The network activity icon or other system tray icons can force a display refresh at the GDI level and cause bad spikes.
Oh, I though hareball was referring to his in-game UI updating, not external applications. Anyhow, I tried multiple combination of flags, fullscreen, double buffering, hardware/software surfaces, with/without sdl timer, debug/release. Nothing is visibly influencing the final result.. And no, fullscreen isn't just a borderless window that is the same size as the desktop.

If I use a variable timestep (calculated with the same timer), everything look ultra-smooth. As I said, the exact same thing happened in my previous 3D engine. Before integrating a physic engine, the games are smooth with variable timestep . After trying to implement fixed timestep for the physic engine to function properly (using the same code copy/pasted between the two engines, the very same one that is in my first post of this thread), the exact same behavior happens to the two places. This can't be a coincidence.

I would be grateful for a up-to-date sample code like the one I posted before, but that is proven to be functional, for handling a main loop with events, physics and rendering, and which is not using a third party library like glut to do so. Maybe mine have a stupid round-up or variable cast error somewhere, even though it don't look like it.
If someone comes up with a working demo of fixed time stepping, please contribute it.
I use fixed timestep and interpolation as described in the Gaffer article.

Gaffer does make it sound a bit more complicated than I believe it needs to be though. I just store the previous position and current position of each object, then interpolate between them when I render, using the blend value Gaffer describes. When I first read Gaffer, I got the impression I needed to interpolate forces as well, which is not the case.

The basic approach I use is:

Code:
void object::prestep()
{
    last_pos=pos;
}

void object::poststep()
{
    pos=body->getPosition();
}

void object::render(float delta)
{
    vector p=interpolate(pos,last_pos,blend);
   
    draw_me_at(p);
}


It is also worth interpolating previous and current values for things like screen fade or any other visual effect that changes over time.
Sorry for the late response, I haven't had much time to try this in the past few days.

Thanks Paul, but this is not what I was looking for. In your code, I have to deduce that "delta" is actually unused, blend is "accumulator / timeStep" and interpolate just do something like
return (last_pos * blend + pos * (1 - blend)); ? We already previously mentioned that interpolating is quite useless since most monitors won't render these frames anyway. I tried to do it in my engine anyway, for the second time, just in case I would be wrong about this, but no, it won't help. It seems pretty much the same with or without interpolation, and I still have a laggy refresh movement, maybe even a bit worse.

I got a lot of good hypothesis up to now, but nothing fixing my problem. I'm pretty sure it have to do with either the timer precision, some double variable instability, maybe the way I handle the sdl events. I though printf was influencing so I removed them and used a full WinMain instead of a _tmain so I have no console behind, no help.

Can someone confirm me that the integrate()/state thing in the Gaffer article is the part actually handled by the Box2D Step() function? I don't have to do integration by myself does I?

Also thanks Erin Catto for asking for a working demo, but I doubt someone will do a complete example just for me, that's why I was only asking for the main loop since I know my error is probably there.
Still can't believe it, how does every game programmer out there actually get past that stupid problem?

edit: Here's an executable so you can see what I mean, the lag is pretty bad. But play for a few seconds, it will get smooth, than come back bad. And this is with interpolation. It ask for a monitor capable of 1680x1050x32 @ 60hz. Don't worry, file is virus clean.
http://rapidshare.com/files/385006600/Game.rar.html
Hi Dunge,

From the look of your code, you've only implemented up to the third code snippet in Gaffer's article.

You need to go all the way and implement the fourth. This adds interpolation and will remove the stutter you are seeing.

I.e. you need to calculate the alpha

Code:
const float alpha = accumulator / dt;


In your integration loop, you'd do something like:

Code:
            while (accumulator>=timeStep)
            {
                accumulator -= timeStep;
                world->Step(timeStep, velocityIterations, positionIterations);
                world->ClearForces();
                // NOTE: Moved the update to here, after the step has been calculated
                ((CVMWidget*)m_pRootObject)->UpdatePhysPos(); // Call to ApplyForce() and such on bodies depending on previous events variables
            }

             // Calculate the alpha for use when passing into the Paint() function
             const float alpha = accumulator / dt;


And in your UpdatePhysPos you'd do something like:

Code:
    void CVMWidget::UpdatePhysPos()
    {
        if(GetParent() && m_pBody)
        {
            b2Transform trans = m_pBody->GetTransform();
            // Store the last frame's position
            m_sRelXPrev = m_sRelX;
            m_sRelYPrev = m_sRelY;
            // And update our current position
            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();
    }


Now in your Paint function you'd do something like (I'm guessing code here, as you didn't show it anywhere):

Code:
    void CVMWidget::Paint(float alpha)
    {
        if(GetParent() && m_pBody)
        {
            float paintX = m_sRelX*alpha + m_sRelXPrev*(1.0f-alpha);
            float paintY = m_sRelY*alpha + m_sRelYPrev*(1.0f-alpha);

            // However you draw, you use the calculated value from above ^
            PaintHere(paintX, paintY);
        }

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


And then finally, just pass the alpha into your paint function:

Code:
            ((CVMWidget*)m_pRootObject)->Paint(alpha);


That should pretty much be it and it'll remove the stutter for you.

Cliff 🙂
edit:

Ok, I got it!! Sorry everyone for the wasted time, it was really the interpolation. I had a small difference, I was keeping the difference between the normal position and the interpolated position to re-add it up later on, and of course did it wrong so it wasn't helping at all. With a correct implementation, it fix all shuttering, and without it, it shutter, so the interpolation IS needed, contrary as what I read in others forum.

I even made a clean small condensed complete game demo example using Box2D, SDL and a fixed timestep. Couldn't be simpler. Here is it, might make a good starting base for others:

Code:
#include <stdio.h>
#include <tchar.h>
#include <time.h>
#include <Windows.h>
#include <SDL.h>
#include <Box2D.h>

#ifdef _DEBUG
    int _tmain(int argc, _TCHAR* argv[])
#else
    INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR lpCmdLine, int )
#endif
{
    // SDL Init
    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
#ifdef _DEBUG
    SDL_Surface* pFrameBuffer = SDL_SetVideoMode(1024, 768, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
#else
    SDL_Surface* pFrameBuffer = SDL_SetVideoMode(1024, 768, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN);
#endif

    // Box2D Init
    b2World world(b2Vec2(0.0f, 0.0f), true);

    // Square, I decided 1meter = 100pixels
    double posX = 0, posY = 0, oldPosX = 0, oldPosY = 0, forceX = 0, forceY = 0;

    SDL_Surface* pSquare = SDL_CreateRGBSurface(SDL_HWSURFACE, 100, 100, 32, 0, 0, 0, 0);
    SDL_FillRect(pSquare, NULL, SDL_MapRGB(pSquare->format, 155, 0, 0));
    b2BodyDef squareBodyDef;
    squareBodyDef.type = b2_dynamicBody;
    squareBodyDef.position = b2Vec2((float32)posX, (float32)posY);
    b2Body* pSquareBody = world.CreateBody(&squareBodyDef);
    b2PolygonShape pSquareShape;
    b2FixtureDef pSquareFixtureDef;
    pSquareShape.SetAsBox(0.5, 0.5);
    pSquareFixtureDef.shape = &pSquareShape;
    pSquareFixtureDef.density = 1.0f;
    pSquareFixtureDef.friction = 0.3f;
    pSquareBody->CreateFixture(&pSquareFixtureDef);

    // Main Loop
    LARGE_INTEGER frequency;
    LARGE_INTEGER startTime;
    LARGE_INTEGER lastFrame;
    LARGE_INTEGER currentTime;
    double deltaT=0;
    double accumulator = 0;
    const double timeStep = 1.0/60.0;
    const int velocityIterations = 10;
    const int positionIterations = 8;
#ifdef _DEBUG
    double second=0;
    UINT PhysicframePerSecond=0;
    UINT RenderframePerSecond=0;
    UINT lastPhysicFramePerSecond=0;
    UINT lastRenderFramePerSecond=0;
#endif

    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) / (double)frequency.QuadPart;

#ifdef _DEBUG
        second += deltaT;
        if(second>=1.0)
        {
            second-=1.0;
            lastPhysicFramePerSecond=PhysicframePerSecond;
            lastRenderFramePerSecond=RenderframePerSecond;
            PhysicframePerSecond=0;
            RenderframePerSecond=0;
            printf("RenderFPS:%d, PhysFPS:%d\n", lastRenderFramePerSecond, lastPhysicFramePerSecond);
        }
        RenderframePerSecond++;
#endif

        if (deltaT>0.25)
            deltaT = 0.25;

        accumulator += deltaT;

        // Event Handling
        while(SDL_PollEvent(&event))
        {
            if(event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE))   
                bRun = false;
            else if(event.type == SDL_KEYDOWN)
            {
                if(event.key.keysym.sym == SDLK_UP)
                    forceY--;
                else if(event.key.keysym.sym == SDLK_DOWN)
                    forceY++;
                else if(event.key.keysym.sym == SDLK_LEFT)
                    forceX--;
                else if(event.key.keysym.sym == SDLK_RIGHT)
                    forceX++;
            }
            else if(event.type == SDL_KEYUP)
            {
                if(event.key.keysym.sym == SDLK_UP)
                    forceY++;
                else if(event.key.keysym.sym == SDLK_DOWN)
                    forceY--;
                else if(event.key.keysym.sym == SDLK_LEFT)
                    forceX++;
                else if(event.key.keysym.sym == SDLK_RIGHT)
                    forceX--;
            }
        }

        // Physic update
        while(accumulator>timeStep)
        {
            accumulator -= timeStep;

            pSquareBody->ApplyForce(b2Vec2((float32)forceX * pSquareBody->GetMass() * 10.f, (float32)forceY * pSquareBody->GetMass() * 10.f), pSquareBody->GetWorldCenter());

            oldPosX = posX; oldPosY = posY;

            world.Step((float)timeStep, velocityIterations, positionIterations);
            world.ClearForces();

            b2Vec2 physPos = pSquareBody->GetPosition();
            posX = physPos.x; posY = physPos.y;

#ifdef _DEBUG
            PhysicframePerSecond++;
#endif
        }

        // Render
        double alpha = accumulator / timeStep;
        SDL_Rect rect;
        rect.x = (Sint16)((posX * alpha + oldPosX * (1 - alpha)) * 100); // Meters to Pixels
        rect.y = (Sint16)((posY * alpha + oldPosY * (1 - alpha)) * 100); // Meters to Pixels
        rect.w = pSquare->w;
        rect.h = pSquare->h;
        SDL_FillRect(pFrameBuffer, NULL, SDL_MapRGB(pFrameBuffer->format, 0, 0, 0)); // Clear screen
        SDL_BlitSurface(pSquare, NULL, pFrameBuffer, &rect); // Blit Square
        SDL_Flip(pFrameBuffer); // Flip

        lastFrame = currentTime;
    }

    // Cleanup
    world.DestroyBody(pSquareBody);
    SDL_FreeSurface(pSquare);
    SDL_FreeSurface(pFrameBuffer);

    SDL_Quit();
   
   return 0;
}

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