开发者

How to compute bounding box/sphere across multiple meshes (C#)

I load multiple meshs from .x files in different mesh variables. Now I would like to calculate the bounding sphere across all the meshes I have loaded (and which are being displayed) Please guide me how this could be achieved. Can VertexBuffers be appended togather in one variable and the boundingSphere be computed using that? (if yes how are they vertexBuffers added togath开发者_如何学编程er) Otherwise what alternative would you suggest!? Thankx


Its surprisingly easy to do this:

You need to, firstly, average all your vertices. This gives you the center position.

This is done as follows in C++ (Sorry my C# is pretty rusty but it should give ya an idea):

D3DXVECTOR3 avgPos;

const rcpNum  = 1.0f / (float)numVerts; // Do this here as divides are far more epxensive than multiplies.
int count = 0;
while( count < numVerts )
{
    // Instead of adding everything up and then dividing by the number (which could lead 
    // to overflows) I'll divide by the number as I go along.  The result is the same.
    avgPos.x += vert[count].pos.x * rcpNum;
    avgPos.y += vert[count].pos.y * rcpNum;
    avgPos.z += vert[count].pos.z * rcpNum;
    count++;
}

Now you need to go through every vert and work out which vert is the furthest away from the center point.

Something like this would work (in C++):

float maxSqDist      = 0.0f;

int count = 0;
while( count < numVerts )
{
    D3DXVECTOR3 diff = avgPos - vert[count].pos;

    // Note we may as well use the square length as the sqrt is very expensive and the 
    // maximum square length will ALSO be the maximum length and yet we only need to
    // do one sqrt this way :)
    const float sqDist = D3DXVec3LengthSq( diff ); 
    if ( sqDist > maxSqDist )
    {
        maxSqDist = sqDist;
    }
    count++;
}

const float radius = sqrtf( maxSqDist );

And you now have your center position (avgPos) and your radius (radius) and, thus, all the info you need to define a bounding sphere.


I have an idea, what I would do is that I would determine the center of every single mesh object, and then determine the center of the collection of mesh objects by using the aforementioned information ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜