I'm using HDRP and I would like to extend it without actually modifying HDRP code or writting my own SRP.
I'd like to:
- Render some objects with a custom shader
- Have those objects increase a stencil value
- Setup the stencil state for the next camera in the list so that the main scene only renders again when the stencil matches that value
Here's my pseudo-code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using RenderPipeline = UnityEngine.Rendering.RenderPipelineManager;
public class MyRenderTest : MonoBehaviour
{
private ushort m_StencilValue = 0; // The scene is only rendered if the stencil equals to this value
void OnEnable()
{
RenderPipeline.beginContextRendering += OnBeginContextRendering;
RenderPipeline.beginCameraRendering += OnBeginCameraRendering;
RenderPipeline.endCameraRendering += OnEndCameraRendering;
}
void OnDisable()
{
RenderPipeline.endCameraRendering -= OnEndCameraRendering;
RenderPipeline.beginCameraRendering -= OnBeginCameraRendering;
RenderPipeline.beginContextRendering -= OnBeginContextRendering;
}
void OnBeginContextRendering(ScriptableRenderContext context, List<Camera> cameras)
{
m_StencilValue = 0;
// Unity clears the main stencil buffer before this call, so no need to do it ourselves
}
void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
{
SetStencilFunction(EQUAL, m_StencilValue); // Only render when the stencil equals m_StencilValue
SetStencilOperation(KEEP); // Keep the value for the HDRP camera render
// After this, HDRP would render the camera only where the stencil operation is verified
}
void OnEndCameraRendering(ScriptableRenderContext context, Camera camera)
{
SetStencilOperation(INCREMENT);
DrawCustomObjects(); // Drawing the custom objects should increment the stencil value
m_StencilValue++;
}
}
I also thought of hooking up Custom Passes but the problem is the same, I can't find a way to actually set the Stencil Test Function and Stencil Operation.
Is this possible?