Stencil - supyrb/ConfigurableShaders GitHub Wiki

Shaders can not only write in the color buffer (what the player sees) and the depth buffer (how far an object is away from the camera), they can also write in the stencil buffer. The stencil buffer is a separate buffer which won't be rendered in any way, but can be used to read and write values to change the rendering of other materials. Think of the stencil buffer as a greyscale image with 256 values. Normally every pixel has a value of 0 (black). Every material can read from that buffer and then decide what to do (including changing the stencil value). More on stencil operations in the Manual.

Stencil shader inspector with dropdown enums
Shader File

Usage

Shader "ConfigurableShaders/Rendering"
{
	Properties
	{
		...

		[Header(Stencil)]
		_Stencil ("Stencil ID [0;255]", Float) = 0
		_ReadMask ("ReadMask [0;255]", Int) = 255
		_WriteMask ("WriteMask [0;255]", Int) = 255
		[Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp ("Stencil Comparison", Int) = 3
		[Enum(UnityEngine.Rendering.StencilOp)] _StencilOp ("Stencil Operation", Int) = 0
		[Enum(UnityEngine.Rendering.StencilOp)] _StencilFail ("Stencil Fail", Int) = 0
		[Enum(UnityEngine.Rendering.StencilOp)] _StencilZFail ("Stencil ZFail", Int) = 0
	}

	SubShader
	{
		Stencil
		{
			Ref [_Stencil]
			ReadMask [_ReadMask]
			WriteMask [_WriteMask]
			Comp [_StencilComp]
			Pass [_StencilOp]
			Fail [_StencilFail]
			ZFail [_StencilZFail]
		}

		Pass
		{
			Tags { "RenderType"="Opaque" "Queue" = "Geometry" }

			...
		}
	}
}

References

Stencil Operation

Manual
Enum

public enum StencilOp
{
	Keep = 0,
	Zero = 1,
	Replace = 2,
	IncrementSaturate = 3,
	DecrementSaturate = 4,
	Invert = 5,
	IncrementWrap = 6,
	DecrementWrap = 7
}

Compare Function

Manual
Enum

// Comarison between the reference value (r) and the value in the buffer (b). e.g. CompareValue Less -> r < b
public enum CompareFunction
{
	Disabled = 0,
	Never = 1,
	Less = 2,
	Equal = 3,
	LessEqual = 4,
	Greater = 5,
	NotEqual = 6,
	GreaterEqual = 7,
	Always = 8
}