我的射线三角形交点代码是否正确?

问题描述 投票:1回答:1

我在这里问是否有人可以检查我的Ray-Triangle相交代码是否正确,或者我在其中有一些错误,因为它似乎无法正常工作。

Vector3f:

struct Vector3f
{
    Vector3f(): x(0), y(0), z(0) { }
    Vector3f(GLfloat a, GLfloat b, GLfloat c): x(a), y(b), z(c) { }

    GLfloat x, y, z;
};

交叉产品和内部产品:

Vector3f CMath::CrossProduct(Vector3f a, Vector3f b)
{
    Vector3f result;

    result.x = (a.y * b.z) - (a.z * b.y);
    result.y = (a.z * b.x) - (a.x * b.z);
    result.z = (a.x * b.y) - (a.y * b.x);

    return result;
}
GLfloat CMath::InnerProduct(Vector3f a, Vector3f b)
{
    return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
}

射线三角相交检查:

bool CMath::RayIntersectsTriangle(Vector3f p, Vector3f d, Vector3f v0, Vector3f v1, Vector3f v2, Vector3f &hitLocation)
{
    Vector3f e1, e2, h, s, q;
    GLfloat a, f, u, v, t;

    e1.x = v1.x - v0.x;
    e1.y = v1.y - v0.y;
    e1.z = v1.z - v0.z;

    e2.x = v2.x - v0.x;
    e2.y = v2.y - v0.y;
    e2.z = v2.z - v0.z;

    h = CrossProduct(d,e2);
    a = InnerProduct(e1,h);
    if(a > -0.00001 && a < 0.00001)
        return false;

    f = 1 / a;
    s.x = p.x - v0.x;
    s.y = p.y - v0.y;
    s.z = p.z - v0.z;
    u = f * InnerProduct(s,h);
    if(u < 0.0 || u > 1.0)
        return false;

    q = CrossProduct(s,e1);
    v = f * InnerProduct(d,q);
    if(v < 0.0 || u + v > 1.0)
        return false;

    t = f * InnerProduct(e2,d);
    if(t > 0.00001)
    {
        hitLocation.x = p.x + t * d.x;
        hitLocation.y = p.y + t * d.y;
        hitLocation.z = p.z + t * d.z;

        return true;
    }
    else
        return false;
}

只需检查这些功能是否有问题,以了解我的问题是否在其他地方。预先感谢您的帮助。

c++ math opengl intersection
1个回答
0
投票

首先,我建议将InnerProduct重命名为DotProduct(请参见Dot product

您有一个由3个点v0v1v2定义的平面以及由点p和方向d定义的光线。在伪代码中,平面图与射线的交点为:

n = cross(v1-v0, v2-v0)        // normal vector of the plane
t = dot(v0 - p, n) / dot(d, n) // t: scale d to the distance along d between p and the plane 
hitLocation = p + d * t

另请参阅Intersect a ray with a triangle in GLSL C++

将其应用于您的代码时意味着

Vector3f n = CrossProduct(e1, e2);

注意,由于sp - v0(而不是v0 - p),因此距离必须反转:

t = - InnerProduct(s, n) / InnerProduct(d, n)
© www.soinside.com 2019 - 2024. All rights reserved.