Skip to content

Instantly share code, notes, and snippets.

@quizcanners
Last active March 19, 2021 12:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quizcanners/df710cd3d88037e4ece87e45b3313a73 to your computer and use it in GitHub Desktop.
Save quizcanners/df710cd3d88037e4ece87e45b3313a73 to your computer and use it in GitHub Desktop.
// https://gist.github.com/hecomi/9580605
//Dirctionary:
View Matrix : camera.worldToCameraMatrix
// How to project a texture:
//cs:
projectionMatrix = camera.projectionMatrix * camera.worldToCameraMatrix
//vert:
o.coords = mul(projectionMatrix, o.worldPos);
//frag:
o.coords.xy /= o.coords.w;
o.coords.xy = (o.coords.xy+1) * 0.5;
float4 col = tex2D(_MainTex, o.shadowCoords);
// Sampling custom shadow
//cs:
private readonly ShaderProperty.MatrixValue _spMatrix = new ShaderProperty.MatrixValue("pp_ProjectorMatrix");
private readonly ShaderProperty.TextureValue _spDepth = new ShaderProperty.TextureValue("pp_DepthProjection");
private readonly ShaderProperty.VectorValue _spPos = new ShaderProperty.VectorValue("pp_ProjectorPosition");
private readonly ShaderProperty.VectorValue _spZBuffer = new ShaderProperty.VectorValue("pp_ProjectorClipPrecompute");
private readonly ShaderProperty.VectorValue _camParams = new ShaderProperty.VectorValue("pp_ProjectorConfiguration");
private void OnPostRender() {
if (!_depthCamera) return;
_spMatrix.GlobalValue = _depthCamera.projectionMatrix * _depthCamera.worldToCameraMatrix;
_spDepth.GlobalValue = _depthTarget;
_spPos.GlobalValue = transform.position.ToVector4(0);
var far = _depthCamera.farClipPlane;
var near = _depthCamera.nearClipPlane;
_camParams.GlobalValue = new Vector4(
_depthCamera.aspect,
Mathf.Tan(_depthCamera.fieldOfView * Mathf.Deg2Rad * 0.5f),
near,
1f/far);
var zBuff = new Vector4(1f - far / near, far / near, 0, 0);
zBuff.z = zBuff.x / far;
zBuff.w = zBuff.y / far;
_spZBuffer.GlobalValue = zBuff;
}
// Struct:
float4 worldPos : TEXCOORD0; // Make sure it is float4
float4 shadowCoords : TEXCOORD6;
// In Vert:
o.worldPos = mul(unity_ObjectToWorld, float4(v.vertex.xyz,1.0f));
o.shadowCoords = mul(pp_ProjectorMatrix, o.worldPos);
// In Frag:
float camAspectRatio = pp_ProjectorConfiguration.x;
float camFOVDegrees = pp_ProjectorConfiguration.y;
float deFar = pp_ProjectorConfiguration.w;
o.shadowCoords.xy /= o.shadowCoords.w;
float alpha = max(0, 1 - dot(o.shadowCoords.xy, o.shadowCoords.xy));
float viewPos = length(float3(o.shadowCoords.xy * camFOVDegrees,1))*camAspectRatio;
float depth = tex2D(pp_DepthProjection, (o.shadowCoords.xy + 1) * 0.5);
float dist = viewPos / (pp_ProjectorClipPrecompute.x * (1 - depth) + pp_ProjectorClipPrecompute.y);
float True01Range = length(o.worldPos - pp_ProjectorPosition.xyz) * deFar;
return max(0, alpha - abs(True01Range - dist) * 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment