Ray-tracer sphere-ray intersection is incorrect

Started by
1 comment, last by nullsquared 14 years, 5 months ago
That is essentially my problem. The colour is equal to the distance along the ray that is needed to reach the surface of the sphere. Other than that white spot in the center, it looks correct to me. However, I cannot figure out what that white spot is. Here is my intersection code:

         float sphere::intersect(const ray &r)
         {
            // ray(t) = o + t * d
            // sphere(p): dot(p - c, p - c) = r^2

            // substitute and solve for t and we get a quadratic:
            // a = dot(d, d)
            // b = 2 * dot(o - c, d)
            // c = dot(o - c, o - c) - r^2

            vec3 dir = r.orig - pos;

            float a = r.dir.sqlength();
            float b = 2.0f * dir.dot(r.dir);
            float c = dir.sqlength() - radius * radius;

            float disc = b * b - 4.0f * a * c;

            // imaginary roots, doesn't intersect the sphere
            if (disc < 0)
                return -1; // the renderer ignores negative distances

            float t = (-b - std::sqrt(disc)) / (2.0f * a);

            return t;
        }
Any ideas? I've tried multiple intersection routines besides my own (above), and they all end up doing the same thing. Here is my ray-generation code:

    vec3 plane(float(x) / WIDTH * 2 - 1, float(y) / HEIGHT * 2 - 1, 0);

    r.orig = vec3(0, 0, 0);
    r.dir = plane + vec3(0, 0, -1);
    r.dir.normalize();
I'm pretty sure that's not the issue, though, since even making some simple orthographic rays yields the same issue.
Advertisement
Your ray-sphere intersection is IMHO correct, but you're rendering wrong colors. Just render fully red sphere (because you're going over value 1.0 while distributing color by-depth, try to re-range your depth color, something like colorBuffer = depth / 100.0f; should do the trick)

I also would like to point that your ray-sphere intersection will behave very slow as compared to faster ones (with early ray termination in algorithm and square root at the end).

My current blog on programming, linux and stuff - http://gameprogrammerdiary.blogspot.com

You're completely right!

I was just taking the float and just dividing by 255 to get it into a byte, without saturating the float into [0..1] first [embarrass]

Many thanks, I wouldn't have thought to look in that part of the code. [smile]

This topic is closed to new replies.

Advertisement