graphics - 路径追踪光线三角形交点

标签 graphics geometry raytracing

我目前正在编写路径追踪器。现在我想实现射线-三角形相交。所以我的三角形由三个点(v0,v1,v2)组成。我查看了有关此主题的其他帖子(Raytracing - Ray/Triangle Intersection)。遗憾的是它无法正常工作,所以我想检查问题是否出在交叉路口一侧。这是我的两个三角形函数:

public float intersect(Ray ray){
    Vector3D e1 = v1.sub(v0);
    Vector3D e2 = v2.sub(v0);
    Vector3D e1e2 = e1.cross(e2).normalize();

    Vector3D p = ray.direction.cross(e2);

    float a = e1.dot(p);
    if(a < 0.0)
        return -1.0f;

    float f = 1.0f / a;
    Vector3D s = ray.origin.sub(v0);
    float u = f*(s.dot(p));
    if(u < 0.0 || u > 1.0)
        return -1.0f; //no hit

    Vector3D q = s.cross(e1);
    float v = f * (ray.direction.dot(q));
    if(v < 0.0 || v > 1.0)
        return -1.0f; //no hit

    float t = f * (e2.dot(q)); //distance
    return t;
}

public Vector3D normal(Vector3D nVec){
    Vector3D e1 = v1.sub(v0);
    Vector3D e2 = v2.sub(v0);
    Vector3D e1e2 = e1.cross(e2).normalize();
    return e1e2;
}

那么这段代码正确吗?

最佳答案

老实说,我发现您的代码很难阅读,因为您没有使用非常具有描述性的名称。 我将向您展示我在伪代码中所做的事情:

//1.Find intersection point of the ray and the infinite Plane created by triangle,
//or find if the ray is parralel to the plane (no intersection Point)
//2.Find out if the intersection point is within the triangle itself

Triangle: Vector A, Vector B, Vector C
ray: Vector rayOrig, Vector rayDir
Intersection: boolean hasHit = false, Vector hitPoint, float t

Vector normal = (B-A)CrossProduct(C-A) //I think you had basically the same with e1e2
float d = (normal)DotProduct(A)
float nd = (normal)DotProduct(rayDir)
if(nd!=0)
{    //The ray hits the triangles plane
    Intersection.t=(d- (normal).DotProduct(rayOrig))/nd
    Intersection.hitPoint=rayOrig+(rayDir*Intersection.t)
    if (pointInTriangle(Intersection.hitPoint, A, B, C))
    {
         Intersection.hasHit = true
    }
}
return Intersection

请注意,在获得与平面的交点后,调用三角形中的函数点,该函数应返回一个 bool 值。我的方法来自:http://www.blackpawn.com/texts/pointinpoly/使用第二个重心坐标,看起来您在这部分中正在做类似的事情

if(u < 0.0 || u > 1.0)
    return -1.0f; //no hit

Vector3D q = s.cross(e1);
float v = f * (ray.direction.dot(q));
if(v < 0.0 || v > 1.0)
    return -1.0f; //no hit

看起来您根本没有在检查光线平面相交,您是在不同的函数中执行此操作吗?如果是这种情况,我认为您实际上不需要光线方向来进行三角形测试。

关于graphics - 路径追踪光线三角形交点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27668837/

相关文章:

javascript - Three.js - 未捕获的类型错误 : Cannot read property 'normal' of undefined

algorithm - 计算地理坐标的边界框

javascript - 如何在复杂场景中快速发现某个点是否被遮挡?

c# - 圆和线段相交检测(Lat Lon Point、Meter Radius 和 Lat Long Line)

ios - 为 iPad Retina 更新 OpenGL ES 触摸检测(光线追踪)?

c - 不一致的 z 缓冲区算法

c# - 在 .Net、WinForms 中查找有关 PixelOffsetMode 枚举的详细信息

javascript - 如何制作具有可点击位置的网页图表

JavaFX 错误报告了我在 Linux 上的屏幕尺寸。这是一个错误吗?

c++ - Qt/C++ : drawing efficiently