Skip to content

Instantly share code, notes, and snippets.

@Sid911
Created August 23, 2020 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sid911/5c6677e596d1dbd634067023c9f302b3 to your computer and use it in GitHub Desktop.
Save Sid911/5c6677e596d1dbd634067023c9f302b3 to your computer and use it in GitHub Desktop.
// Each #kernel tells which function to compile; you can have many kernels
#pragma kernel CSMain
RWTexture2D<float4> Result;
float4x4 _CameraToWorld;
float4x4 _CameraInverseProjection;
Texture2D<float4> _skyBoxTexture;
SamplerState sampler_skyBoxTexture;
static const float PI = 3.14158265f;
struct Ray{
float3 origin;
float3 direction;
};
struct RayHit
{
float3 position;
float distance;
float3 normal;
};
RayHit CreateRayHit()
{
RayHit hit;
hit.position = float3(0.0f, 0.0f, 0.0f);
hit.distance = 1.#INF;
hit.normal = float3(0.0f, 0.0f, 0.0f);
return hit;
}
void IntersectGroundPlane(Ray ray, inout RayHit bestHit)
{
// Calculate distance along the ray where the ground plane is intersected
float t = -ray.origin.y / ray.direction.y;
if (t > 0 && t < bestHit.distance)
{
bestHit.distance = t;
bestHit.position = ray.origin + t * ray.direction;
bestHit.normal = float3(0.0f, 1.0f, 0.0f);
}
}
RayHit Trace(Ray ray)
{
RayHit bestHit = CreateRayHit();
IntersectGroundPlane(ray, bestHit);
return bestHit;
}
float3 Shade(inout Ray ray, RayHit hit)
{
if(hit.distance < 1.#INF)
{
return hit.normal * 0.5f + 0.5f;
}
else
{
//Sample the skybox and write it
float theta = acos(ray.direction.y)/ -PI;
float phi = atan2(ray.direction.x, -ray.direction.z) / -PI * 0.5f;
return _skyBoxTexture.SampleLevel(sampler_skyBoxTexture, float2(phi, theta),0).xyz;
}
}
Ray CreateRay(float3 origin, float3 direction)
{
Ray ray;
ray.origin = origin;
ray.direction = direction;
return ray;
}
Ray CreateCameraRay(float2 uv){
float3 origin = mul(_CameraToWorld, float4(0.0f, 0.0f, 0.0f, 1.0f)).xyz;
float3 direction = mul(_CameraInverseProjection, float4(uv, 0.0f, 1.0f)).xyz;
direction = mul(_CameraToWorld, float4(direction,0.0f)).xyz;
direction = normalize(direction);
return CreateRay(origin, direction);
}
[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
uint width, height;
Result.GetDimensions(width, height);
float2 uv = float2((id.xy + float2(0.5f, 0.5f)) / float2(width,height) * 2.0f - 1.0f);
Ray ray = CreateCameraRay(uv);
// for showing rainbow color directed in different directions
// Result[id.xy] = float4(ray.direction * 0.5f + 0.5f, 1.0f);
RayHit hit = Trace(ray);
float3 result = Shade(ray, hit);
Result[id.xy] = float4(result,1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment