• API
• FAQ
• Tools
• Trends
• Archive
daily pastebin goal
75%
SHARE
TWEET

# Realtime Ray Caster in HLSL

alaskajohn Nov 5th, 2013 250 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. float4 PixelShaderFunction(float2 texCoord: TEXCOORD0) : COLOR0
2. {
3.         float4 color = tex2D(ScreenS, texCoord);
4.         float4 ambient = {0.0f, 0.05f, 0.0f, 1.0f};
5.
6.         float3 pixelPosition = {texCoord[0]-0.5f, texCoord[1]-0.5f, 0.0f};
7.
8.         //Calculate Ray
9.         float3 ray = cameraPosition - pixelPosition;
10.         float3 origin = cameraPosition;
11.
12.         //Look for intersection of Ray with one of the spheres
13.         for (int i=0; i<5; i++)
14.         {
15.                 float a,b,c;
16.                 a = dot(ray, ray);
17.                 b = dot(2*ray, (origin - spheres[i]));
18.                 c = dot(spheres[i],spheres[i]) + dot(origin, origin) - (2 * dot(spheres[i],origin)) - sphereRadiusSqr;
19.
20.                 float discriminant  = (b * b) - (4 * a * c);
21.                 if (discriminant  > 0)
22.                 {
23.                         color = ambient;
24.
25.                         //Find coordinates of intersection on sphere surface
26.                         float t1 = (-b + sqrt(discriminant)) / 2 * a;
27.                         float3 intersection = origin + (t1 * ray);
28.
29.                         //Calculate light using flat shading (cos() of vectors calculated using dot product)
30.                         color[1] = dot(normalize(intersection - spheres[i]), normalize(spheres[0] - intersection));     //spheres[0] is lightPos
31.                         if (i == 0)     {       color = lightColor;     }                                                                                                               //default light location
32.                 }
33.         }
34.         return color;
35. }
RAW Paste Data
Top