Skip to content

Instantly share code, notes, and snippets.

@hvent90
Created January 21, 2019 21:40
Show Gist options
  • Save hvent90/238fb093ad9031a673c2a056a91b19bc to your computer and use it in GitHub Desktop.
Save hvent90/238fb093ad9031a673c2a056a91b19bc to your computer and use it in GitHub Desktop.
Shader "Raymarch/RaymarchHDRP"
{
SubShader
{
Cull Off ZWrite Off ZTest Always
Pass
{
HLSLPROGRAM
#pragma target 3.5
#pragma vertex vert
#pragma fragment frag
#include "Packages/com.unity.postprocessing/PostProcessing/Shaders/StdLib.hlsl"
#include "HLSLSupport.cginc"
TEXTURE2D_SAMPLER2D(_MainTex, sampler_MainTex);
half4 _MainTex_ST;
uniform float4 _CamWorldSpace;
uniform float4x4 _CamFrustum, _CamToWorld;
uniform int _MaxIterations;
uniform float _MaxDistance;
uniform float _MinDistance;
float4 _Tint;
#define UNITY_MATRIX_MVP mul(unity_MatrixVP, unity_ObjectToWorld)
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 texcoord : TEXCOORD0;
float2 texcoordStereo : TEXCOORD1;
float3 ray : TEXCOORD2;
};
v2f vert(AttributesDefault v)
{
v2f o;
half index = v.vertex.z;
o.vertex = float4(v.vertex.xy, 0.0, 1.0);
o.texcoord = TransformTriangleVertexToUV(v.vertex.xy);
#if UNITY_UV_STARTS_AT_TOP
o.texcoord = o.texcoord * float2(1.0, -1.0) + float2(0.0, 1.0);
#endif
o.texcoordStereo = TransformStereoScreenSpaceTex(o.texcoord, 1.0);
o.ray = _CamFrustum[(int)index].xyz;
o.ray /= abs(o.ray.z);
o.ray = mul(_CamToWorld, o.ray);
return o;
}
float sdSphere(float3 position, float3 origin, float radius)
{
return distance(position, origin) - radius;
}
fixed4 raymarching(float3 ro, float3 rd) {
fixed4 result = float4(1, 1, 1, 1);
float t = 0; // Distance Traveled from ray origin (ro) along the ray direction (rd)
for (int i = 0; i < _MaxIterations; i++)
{
if (t > _MaxDistance)
{
// todo: draw environment
result = float4(rd, 1);
break;
}
float3 p = ro + rd * t; // This is our current position
float d = sdSphere(p, float3(0, 0, 0), 1.0);
if (d <= _MinDistance) // We have hit something
{
// shading
result = float4(0.2, 0.2, 0.2, 1);
break;
}
t += d;
}
return result;
}
float4 frag(v2f i) : SV_Target
{
float3 rayDirection = normalize(i.ray.xyz);
float3 rayOrigin = _WorldSpaceCameraPos;
fixed4 result = raymarching(rayOrigin, rayDirection);
return result;
}
ENDHLSL
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment