c# - 如何跨多个网格计算边界框/球体 (C#)

标签 c# directx mesh bounding-box vertex-buffer

我从不同网格变量中的 .x 文件加载多个网格。 现在我想计算我加载的所有网格(以及正在显示的网格)的包围球 请指导我如何实现这一目标。 可以将 VertexBuffers 附加到一个变量中并使用它计算 boundingSphere 吗? (如果是的话,它们是如何将 vertexBuffers 添加到一起的) 否则你会建议什么替代方案!? 谢谢

最佳答案

做到这一点非常容易:

首先,您需要对所有顶点进行平均。这为您提供了中心位置。

这是在 C++ 中按如下方式完成的(抱歉,我的 C# 很生疏,但它应该给你一个想法):

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++;
}

现在您需要遍历每个顶点并找出离中心点最远的顶点。

像这样的东西会起作用(在 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 );

现在您有了中心位置 (avgPos) 和半径 (radius),因此,您拥有了定义边界球体所需的所有信息。

关于c# - 如何跨多个网格计算边界框/球体 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3044912/

相关文章:

c# - 是否可以将 CancellationToken 与 ExecuteReader 一起使用?

c# - Ajax 更新面板不允许 javascript 在服务器端工作?

c++ - 在 Dll 中使用 DirectX

mesh - 从使用点云库通过泊松重建构建的网格中去除水密性属性

javascript - Three.js:重新连接骨骼后如何重新绑定(bind)/重新连接网格骨架?

c# - 添加没有命名空间的带前缀的起始元素

c# - 逆变?协方差?这种通用架构有什么问题......?

ffmpeg - DirectX 与 FFmpeg

c# - 获取绘制在窗口上的图像

javascript - 在 WebGL 中只绘制网格的一部分