2
$\begingroup$

I started a ray tracing project in Python. I made a CUDA kernel and a trace() function for each pixel. It works perfectly when calculating intersections, shadows and lambert shading, however when I introduce a reflection from the surface of a sphere I get a 'band' around the edge of the projected sphere disk and I cannot figure out why.

Image results: https://imgur.com/a/LoXOyl5


My reflection algorithm:

  1. Find point P of the intersection.
  2. Find normal vector N at the intersection with C being the sphere center:
    N = P - C
    N = N / norm(N)
  1. Find reflection vector R using (where D is the original ray direction:
    R = D - 2 * (D * N ) * N
    R = R / norm(R)
  1. Shift point P along R a little bit (to avoid reflection acne, adding this didn't solve the problem)
    P = P + 1e-4 * R
  1. Call the ray trace function (only one more time) again as:
    color_refl = trace(ray_origin=P, ray_direction=R) 
  1. Add the reflected color using:
    color = color + color_refl * reflect_intensity

Notes:

  • Between step 2 and step 3 I calculate the Lambert shading which works quite well.
  • Reflections that bounce off a plane work perfectly.
  • I use a CUDA kernel which does not support recursive function calls, so I made another trace function with a different name that doesn't calculate reflections. (that's why there is only one reflection call)

Here is the source code for the trace and reflection trace functions: https://github.com/Speterius/ray_tracing/blob/master/cuda_ray_tracing.py

$\endgroup$
4
$\begingroup$

The issue was caused by an incorrect calculation of the reflection direction vector. With D ray direction and N the normal vector:

R = D - 2 * dot(D, N) * N

The issue was caused by calculating the components of R as follows:

R[i] = D[i] - 2 * (D[i] * N[i]) * N[i]

It took me a while to find the mistake because this produced a correct reflection with the horizontal plane.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.