Ray-Triangle Intersection Issue in java

22 Views Asked by At

Hi Stack Overflow community,

I'm currently working on a project involving ray-tracing, and I'm encountering difficulties with the intersection between rays and triangles in java it is like instead of achieving the desired shape, I observe an unusual shape.

I would appreciate any guidance or suggestions. enter image description here

@Override
public Hit intersect(boolean fromOutside, Ray ray, float tmin, float tmax) {
    final Point3f R = ray.getStartingPoint();
    final Vector3f v = ray.getDirection();
    final float cc = -v.dot(g);

    if ((fromOutside ? cc > 0 : cc < 0)) {
        final Vector3f AR = new Vector3f();
        AR.sub(R, A.getPoint());
        final float bb = AR.dot(g);
        if ((fromOutside ? bb > 0 : bb < 0)) {
            final float alpha = bb / cc;
           
                final Vector3f AB = new Vector3f(B.getPoint());
                AB.sub(A.getPoint());
                final Vector3f AC = new Vector3f(C.getPoint());
                AC.sub(A.getPoint());
                if ((signum(tmin - alpha) <= 0) && (signum(alpha - tmax) <= 0)) {
                    
                final float a_det = AB.dot(AB);
                final float b_det = AB.dot(AC);
                final float c_det = AC.dot(AC);
                final float det = a_det * c_det - b_det * b_det;
                final float beta = (c_det * (AR.dot(AC)) - b_det * (AR.dot(AC))) / det;
                
                if ((signum(beta) >= 0) && (signum(beta - 1) <= 0)) {
                    final float gamma = (a_det * (AR.dot(AC)) - b_det * (AR.dot(AB))) / det;
               
                if ((beta >= 0) && (beta <= 1) && (gamma >= 0) && (gamma <= 1) && (beta + gamma <= 1)) {
                        Vector3f smoothNormal = getSmoothedNormal(fromOutside, alpha, beta, gamma);
                       
                        return new Hit(alpha, new Point3f(R), smoothNormal);
                } 
                }
                }
        }
    }
    return Hit.NOHIT;
}



  private Vector3f getSmoothedNormal (final boolean fromOutside,
                                      final float aa, final float bb, final float cc) {
    Vector3f smoothedNormal = new Vector3f();

    if (fromOutside) {
        Vector3f nA = A.getNormal();
        Vector3f nB = B.getNormal();
        Vector3f nC = C.getNormal();

        smoothedNormal.scale(aa, nA);

        Vector3f scaledNB = new Vector3f();
        scaledNB.scale(bb, nB);
        smoothedNormal.add(scaledNB);

        Vector3f scaledNC = new Vector3f();
        scaledNC.scale(cc, nC);
        smoothedNormal.add(scaledNC);

        smoothedNormal.normalize();
    }

    return smoothedNormal;
}
  
0

There are 0 best solutions below