I am brand new to HLSL and I am trying to code a simple ray tracer in Unity. I've just started on it and am currently just trying to set the pixels to red if the ray intersects with a sphere.
Here is my code:
void CSMain (uint3 id : SV_DispatchThreadID)
{
float x = id.x / Resolution;
float y = id.y / Resolution;
Ray ray;
Sphere sphere;
sphere.color = float3(1, 0, 0);
sphere.radius = 2.0;
sphere.position = float3(0, 0, 4);
ray.direction = CalculateDirection(float2 (id.x, id.y), Resolution, float3 (0, 0, 0));
float t = 0.0;
bool intersects = Intersects(ray, sphere, t);
float4 color;
if (intersects == true) {
// If the ray intersects the sphere, set the color to the sphere color
color = float4(1.0, 0.0, 0.0, 0.0);
}
else {
// If the ray does not intersect the sphere, set the color to the background color
color = float4(0.0, 0.0, 0.0, 0.0);
}
Result[id.xy] = color;
}
All of it works fine except for the line where I set Result[id.xy] = color; For some reason I cannot seem to set Result to anything that comes from the intersect function. I can set it just fine to another color or color resulting from a function but this one seems to be giving issues. The intersect function itself works just fine.
Here is the intersect function:
bool Intersects(Ray ray, Sphere sphere, out float t) {
float3 m = ray.origin - sphere.position;
float b = dot(m, ray.direction);
float c = dot(m, m) - sphere.radius * sphere.radius;
// Exit if r's origin outside s (c > 0) and r pointing away from s (b > 0)
if (c > 0.0f && b > 0.0f) {
t = 0.0f;
return false;
}
float discr = b * b - c;
// A negative discriminant corresponds to ray missing sphere
if (discr < 0.0f) {
t = 0.0f;
return false;
}
// Ray now found to intersect sphere, compute smallest t value of intersection
t = -b - sqrt(discr);
// If t is negative, ray started inside sphere so clamp t to zero
if (t < 0.0f) {
t = 0.0f;
}
return true;
}
I tried removing the color variable and just setting the color of Result directly in the if statement to Result[id.xy] = float4(1.0, 0.0, 0.0, 0.0); This gave me an error. I moved it outside the if statement and the error stopped and the screen successfully turned red. I tried getting rid of the intersects variable and putting the function directly as the parameter of the if statement.
Here is my exact error message from Unity: ComputeTest.compute: Kernel at index (0) is invalid UnityEngine.StackTraceUtility:ExtractStackTrace () ComputeShaderTest:OnRenderImage (UnityEngine.RenderTexture,UnityEngine.RenderTexture) (at Assets/ComputeShaderTest.cs:36) UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)