Quick'n'Dirty Ray Intersect Sphere

6ad5f8c742f1e8ec61000e2b0900fc76
0
davepermen 101 Jul 28, 2003 at 20:41
float intersectRaySphere(Ray ray,Sphere sphere) {
    Vec dst = ray.o - sphere.o;
    Real B = dot(dst,ray.d);
    Real C = dot(dst,dst) - sphere.r2;
    Real D = B*B - C;
    return D > 0 ? - B - sqrt(D) : std::numeric_limits<float>::infinity();
}

i bet there is a typo:D

8 Replies

Please log in or register to post a reply.

6ad5f8c742f1e8ec61000e2b0900fc76
0
davepermen 101 Jul 28, 2003 at 20:46

btw, an ARB_fragment_program version of this function is actually used in raytracegl.jpg this pic

here’s the ARB_fragment_program implementing a ray-sphere test

!!ARBfp1.0 #rayTracer Sphere1 
TEMP origin;
TEMP direction;
PARAM sphere = { 0.0,0.0,2.0,1.0 };
TEX origin, fragment.texcoord[0], texture[0], RECT;
TEX direction, fragment.texcoord[0], texture[1], RECT;
# intersectRaySphere 
TEMP distance;
SUB distance,origin,sphere;
# quadricEquation 
TEMP params;
DP3 params.x,distance,direction;
DP3 params.y,distance,distance;
SUB params.y,params.y,sphere.w;
MAD params.z,params.x,params.x,-params.y;
KIL params.z;
RSQ params.z,params.z;
RCP params.z,params.z;
ADD params.x,-params.x,-params.z;
TEMP point;
MAD point,params.x,direction,origin;
TEMP normal;
SUB normal,point,sphere;
DP3 normal.w,normal,normal;
RSQ normal.w,normal.w;
MUL normal,normal,normal.w;
TEMP diffuse;
DP3 diffuse,normal,state.light[0].position;
PARAM color = { 1.0,0.5,0.25,0 };
MUL result.depth,params.x,0.125;
MUL result.color,color,diffuse;
END
Fdbdc4176840d77fe6a8deca457595ab
0
dk 158 Jul 28, 2003 at 20:49

wow, very nice piece of code. very useful.

E05263ec846eb85da803f56e2917962d
0
Noor 101 Jul 28, 2003 at 20:54

Nice picture. Thank for the Code!

6ad5f8c742f1e8ec61000e2b0900fc76
0
davepermen 101 Jul 28, 2003 at 20:55

just be warned, it does only hit the outer hull (or so.., the near one:D)..

call it glEnable(GL_SPHERE_INSIDE_CULLING_RT); :D

C24eb7e6aaefba78b94c831ddc7b4d0b
0
donBerto 101 Jul 28, 2003 at 21:59

wow… it’s so majestic.

[star wars “the force” theme solo on horn plays in my head]

:yes:

6ad5f8c742f1e8ec61000e2b0900fc76
0
davepermen 101 Jul 28, 2003 at 22:04

hehe, thanks..

the death star never looked that round, did it? :D

0684f9d33f52fa189aad7ac9e8c87510
0
baldurk 101 Jul 29, 2003 at 17:11

could you resize the pic down? it’s painfully large :D.

however, you do appreciate it’s smoothness at this size… :)

6ad5f8c742f1e8ec61000e2b0900fc76
0
davepermen 101 Jul 29, 2003 at 17:14

i could post the software version.. runs at the same speed as the hw version, but on 320x240 :D