ps_2_0
// intersect a sphere
// line origin in tex0, direction in tex1
// sphere position in t2.xyz, square of radius in t2.w
// {render mask in tex3}
// index of sphere in v0 (color value) - max 255 !!
// outputs index of sphere in blue component
// outputs distance in green component
// output buffer format should be A32R32G32B32F
def c5,4,2,-2,10000
def c6,0.01,1,0,0
def c7,-128,-128,-128,0
def c8,256,256,256,256
def c9,0,0.01,1.0,0
def c10,-1,0,0,0
dcl t0
dcl t1
dcl t2
dcl v0
dcl_2d s0
dcl_2d s1
dcl_2d s3
//texld r0,t0,s3
//mul r0,r0,c10.x
//texkill r0            // rendering mask
texld r0,t0,s0
texld r1,t1,s1
sub r2,r0,t2       // orig2 = ray.orig - sphere.orig
dp3 r3.x,r1,r2     // da = dot(ray.dir, orig2)
dp3 r3.y,r1,r1     // dd = dot(ray.dir, ray.dir)
dp3 r3.z,r2,r2     // dot(orig2,orig2)
sub r3.z,r3.z,t2.w  // - sqr(sphere.radius)
mul r3.z,r3.z,r3.y  // * dd
mul r3.z,r3.z,c5.x  // * 4
mul r3.w,r3.x,r3.x  // | da*da
mul r3.w,r3.w,c5.x  // *4
sub r3.w,r3.w,r3.z  // discriminant of quadratic equation = 4*da*da - 4*dd*(orig2 * orig2 - r*r);
abs r4.x,r3.w       // make it positive, we will eliminate result later if disc is negative
rsq r4.x,r4.x
rcp r4.x,r4.x       // sqrt(disc)
mul r4.y,r3.y,c5.y
rcp r4.y,r4.y       // 1 / (2 * dd)
mul r4.z,r3.x,c5.z  // -2*da
sub r5.x,r4.z,r4.x
mul r5.x,r5.x,r4.y  // t1 = (-2da - sqrt(disc))/(2dd)
sub r5.z,r5.x,c6.y
cmp r5.x,r5.z,r5.x,c5.w
add r5.y,r4.z,r4.x
mul r5.y,r5.y,r4.y  // t2 = (-2da + sqrt(disc))/(2dd)
sub r5.z,r5.y,c6.y
cmp r5.y,r5.z,r5.y,c5.w
sub r5.z,r5.x,r5.y
cmp r5.w,r5.z,r5.y,r5.x   // choose the smaller distance
cmp r5.w,r3.w,r5.w,c5.w   // return a great distance if discrimiant was negative
mul r5.w,r5.w,c6.x
mov oDepth,r5.w
mov r0.b,v0.b
mov r0.g,r5.w
mov oC0,r0
//mov oDepth,c6.x
//mov oC0,r1
//mov oC0,r0
