Saturday, November 12, 2011

Havok: Setting mesh color in the Visual Debugger, Part 2

In part 1 of this series I showed you how to colorize your physics meshes in the Havok Visual Debugger (HVD). However as you may have noticed, this only works for colorizing meshes that are already loaded in the HVD, so if you connect the HVD to the game after those colors have been set you will not see that information. Here's a simple way to get around that problem.

You program is likely directly using an hkVisualDebugger, what you will need to do is derived a new class from hkVisualDebugger. The hkVisualDebugger class has an m_clients variable, but it's access is protected, and there is no accessor to its information in hkVisualDebugger so unless you have the actual source code for Havok, you're going to need to derive your own class from hkVisualDebugger so you can create an accessor to the data that you need.

Create a new header file in your project, name it 'PhysicsVisualDebugger' or whatever class name you would like to use. The code below is the entire class, no .cpp file is needed.

#pragma once

#ifndef __PhysicsVisualDebugger_h_
#define __PhysicsVisualDebugger_h_

#include <common\visualize\hkvisualdebugger.h>

class PhysicsVisualDebugger : public hkVisualDebugger
{
public:
    PhysicsVisualDebugger(const hkArray<hkProcessContext*>,
                          const class hkVtableClassRegistry* classReg = HK_NULL)
         : hkVisualDebugger(contexts, classReg)
    {}

    virtual ~PhysicsVisualDebugger() {};

    unsigned int GetNumClients() const { return m_clients.getSize(); }
};

#endif //__PhysicsVisualDebugger_h_


Make sure any place you were using an 'hkVisualDebugger' that you're not using your new class you've just made.
The goal we're aiming for is to know when somebody connects the HVD to your program. The GetNumClients() above will return to you the number of current clients connected, if you call it at the appropriate time you can compare it to check if that number has just increased.

In my example below, 'm_pDebugger' is a pointer to a 'PhysicsVisualDebugger'. Put this code wherever you're currently stepping the HVD.

unsigned int numConnections = m_pDebugger->GetNumClients();

// Update the debuggers (which also checks for new clients)
m_pDebugger->step(m_fStepLength);

// If there are now more connections than before the update
if ( m_pDebugger->GetNumClients() > numConnections )
{
    // This is where you will want to go through all physics
    // objects and have to re-send their color info to the
    // debugger.
    UpdateDebuggerInfoForAllEntities();
}

Notice we query the number of connections before stepping the debugger, store that number, and then after stepping the debugger we query for number of connections again. If the number of clients has increased, then you should find a way of having all of your objects resend their color information to the HVD. In my case whenever I add an object to the Havok world, I keep track of its pointer in a list so I can call a function on everything in that list at any time to have them refresh their information for the HVD.

Why Gamebryo was "fun"

If you didn't catch it in the title, there was some sarcasm in there. Gamebryo (the game engine used to make LEGO Universe as well as other titles such as Fallout 3, Oblivion, Epic Mickey, and more) had some very annoying quirks that made my life a little bit more difficult, as well as some of my coworkers'.

Both the Matrix and the Quaternion classes had multiple ways to create rotations, and naturally Gamebryo used no naming convention between these two classes.

Create a Rotation from the X axis and an angle?
Matrix function: MakeXRotation(float angle)
Quaternion function: FromAngleAxisX(float angle)

Gamebryo included a lot of functionality in either the Matrix or Quaternion classes, but not both. It's like a cruel joke.

Want to make your matrix an identity matrix? Call 'MakeIdentity( )'. Want to do that with a Quaternion? Do it yourself, there is no function.

Want to lerp (linearly interpolate) a Quaternion? Go for it. Want to lerp a Matrix? Sorry, convert it to a Quaternion, lerp it, then convert it back to a matrix. On top of that, the Slerp (spherical linear interpolation) did not even work properly with Gamebryo, often causing objects to rotate 350 degrees to get to the target, rather than 10 degrees. We ended up discontinuing the use of Gamebryo's Slerp method altogether and calling to Havok to have it do the rotations for us. Alternatively we could have just rolled our own Slerp code or altered Gamebryo's version to use ours, but Gamebryo made calls internally to its Slerp method so we didn't want to break something by fixing something.

Gamebryo also thought it would be cute to use opposite rotation directions for matrices vs. quaternions. Those two rotation functions I listed earlier, if you want to represent the same rotation with a matrix as well as a quaternion you pass a positive angle into one, and a negative angle into the other. It's always fun to try and remember which way you need to rotate which type depending on the case you were using it in. Gamebryo likes to make sure the programmer is paying attention I guess.

Here's another little chestnut that Gamebryo left me to deal with. Their camera coordinate system has a 'forward' vector of X, rather than Z. Seriously? What game has EVER done that? For those new to game programming, about 90% of games use the X-axis as a 'right' vector, and Z as a 'forward', the other 10% use the Y-axis as the forward and the Z-axis as the 'up'. But I had never seen an X-axis be used for a 'forward' before. There was no way we were going to use the X-axis as the forward for LEGO Universe, so we ended up having to deal with Gamebryo's wacky camera coordinate system. It was always a fun task when trying to do something that involved aligning the camera based on a rotation that was in another system, you'll set them to the same rotations and then rotate the camera 90 degrees to line it up.

I might go more into some annoyances using Gamebryo later, but for now I'm still bound to an NDA on most subjects.

Calculus: Network prediction, calculating time to travel a distance

In the last post we talked about how we could calculate how far something traveled over a specific amount of time based on its velocity and acceleration. In that post we were left with a problem, we know our origin and destination positions, and how much time has elapsed, and after a certain amount of time we found we had past the destination. What we really need to know now is how long it will take us to get to our destination given our velocity and acceleration, that way we know how much time is left after we got to the destination.


Given the path above, we had calculated that after 1 second we were almost to P2 if we had started at P1. But what if the client's game had stuttered for 2 full seconds? Where would we put them along the way then? Well, to know that we need to know how long it takes to get from P1 to P2.

Here is the formula for calculating how long is takes to travel a specific distance given an initial velocity and a constant acceleration:

't' is time, v(i) is initial velocity, 'a' is acceleration, and 'd' is the distance between the points.

Our initial velocity is 5 meters per second.
Our constant acceleration is 3.591849, which we calculated in the last blog post.
Distance is 8.9796225, which was also calculated in the last blog post.

If we plug the numbers in we get:
Time = ( -5 + √(5² + 2 * 3.591849 * 9.9796225) ) / 3.591849
        = ( -5 + √(25 + 71.690594) ) / 3.591849
        = ( -5 + √96.690594 ) / 3.591849
        = ( -5 + 9.8331375 ) / 3.591849
        = 4.8331375 / 3.591849
Time = 1.3455868 seconds

And here's the code:
float CalcTimeOverDistance( float initVelocity, 
                            float constantAccel,
                            float distance )
{
    if ( distance <= 0.0f )
    {
        return 0.0f;
    }

    // If there is an acceleration present
    if ( constantAccel != 0.0f )
    {
        float initVelSqr = initVelocity * initVelocity;

        return (-initVelocity 
                + sqrt(initVelSqr + (2*constantAccel*distance))
                / constantAccel;
    }
    else  // No acceleration was present
    {
        if ( initVelocity == 0.0f )
        {
            // No velocity or acceleration means infinite
            // time required, just return 0.0f, or whatever
            // value you want to return in this case.
            return 0.0f;
        }
        else
        {
            return ( distance / initVelocity );
        }
    }
}
So now we can see that the platform will reach P2 in only 1.3455868 seconds, and because the client stuttered for 2 seconds that leaves us 0.6544132 seconds we need to predict. The next step is to see how much time it takes to get from P2 to P3, and if that is greater than 0.6544132 seconds than we need know we're not to P3 yet and we can calculate how far we've traveled between P2 and P3. 

Alright, time to figure out some values:
Difference vector between P2 and P3 = (18 - 10, 5 - -3) = (8, 8)
Length of difference vector = √(8² + 8²) = √128 = 11.3137085
Constant accel = (5² - 10²) / (2 * 11.3137085) = (25 - 100) / 22.627417 = -3.3145630

Notice our constant acceleration was negative, that is because we slow down when going from P2 to P3. Now that we have all of our values we can calculate the time it takes to travel distance from P2 to P3 given the initial velocity, and the acceleration we just calculated.

Time = (-10 + √(-10² + 2 * -3.3145630 * 11.3137085) ) / -3.3145630
         = (-10 + √(100 + -75.0) ) / -3.3145630
         = (-10 + 5 ) / -3.3145630
         = -5 / -3.3145630

Time = 1.5084944 seconds

We can clearly see that the time we have remaining (~0.65 seconds) isn't enough to reach P3 (~1.51 seconds), so lets see how far we make it.

Distance = 10 * 0.6544132 + (-3.3145630 * 0.6544132² * 0.5)
               = 6.544132 + (-3.3145630 * 0.4282566 * 0.5)
               = 6.544132 + -0.7097417

Distance = 5.8343903 meters

And now we need to figure out the direction, which we have some of the data for from earlier:

Inverse length of difference vector = 1 / 11.3137085 = 0.08838835
Unitized difference vector from P2 to P3 = (8 * 0.08838835, 8 * 0.08838835)
                                                                 = (0.7071068, 0.7071068)

And now that we have distance and direction, we multiply them and add it to P2 to get our final position after 2 seconds:

Position = P2 + ( distance * direction )            
              = (10, -3) + ( 0.7071068 * 5.8343903, 0.7071068 * 5.8343903 )
              = (10, -3) + ( 6.5414971, 6.5414971 )

Position = ( 16.5414971, 3.5414971 )

And there we have it, we just predicted the position of a platform 2 seconds into the future along a strict path.