Monday, January 14, 2019

Best way to create a Chromadepth shader for unity?


I'm trying to create a chromadepth environment in unity3D. So the camera sees close objects colored as red, and then farthest objects as blue. And everything in between falls down the color spectrum (Red orange yellow green blue)



I've looked into a few things such as z depth or even using fog for this kind of thing. But I'm not sure what the best way to approach this is; or maybe it's already been done before but I couldn't find it in the asset store. I Thanks in advance for your thoughts and time, it is much appreciated.



Answer



Here's a simple version which should work both as a fullscreen post effect or as an object in the world, like a magic lens you can look through.


Animation showing a camera panning in & out of a scene with a sliding window rendering the scene's depth in a white-yellow-red-purple spectrum


Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 3.0

#include "UnityCG.cginc"

struct appdata
{
float4 vertex : POSITION;
};

sampler2D _MainTex;
// Request camera depth buffer as a texture.
// Incurs extra cost in forward rendering, "just there" in deferred.

sampler2D _CameraDepthTexture;

void vert (
float4 vertex : POSITION,
out float4 outpos : SV_POSITION)
{
outpos = UnityObjectToClipPos(vertex);
}

fixed4 frag (UNITY_VPOS_TYPE screenPos : VPOS) : SV_Target

{
// Convert pixel coordinates into screen UVs.
float2 uv = screenPos.xy * (_ScreenParams.zw - 1.0f);
// Depending on setup/platform, you may need to invert uv.y

// Sample depth buffer, linearized into the 0...1 range.
float depth = Linear01Depth(
UNITY_SAMPLE_DEPTH(tex2D(_CameraDepthTexture, uv)));

// Compressing the range, so we get more colour

// variation close to the camera.
depth = saturate(2.0f * depth);
depth = 1.0f - depth;
depth *= depth;
depth = 1.0f - depth;

// Use depth value as a lookup into a colour
// ramp texture of your choosing.
fixed4 colour = tex2D(_MainTex, depth);


return colour;
}
ENDCG
}

Here I'm using the VPOS semantic to simplify calculating the position of the fragment on the screen. If you need to support shader models below 3 there are other ways to do this, they're just a little messier. ;)


Here's me playing around with this a bit more... Animation of a green sonar wave passing over a dark scene and illuminating it


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...