Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Rendering;
- [DefaultExecutionOrder(-500)]
- public class ShadowVolumeManager : MonoBehaviour
- {
- public Material stencilMat; // assign Hidden/StencilShadowVolume here
- Camera mainCam;
- CommandBuffer cb;
- List<StencilShadowCaster> casters = new List<StencilShadowCaster>();
- public static ShadowVolumeManager Instance { get; private set; }
- void Awake()
- {
- if(Instance != null && Instance != this)
- Destroy(gameObject);
- else
- Instance = this;
- mainCam = Camera.main;
- cb = new CommandBuffer { name = "Shadow Volume Stencil Pass" };
- // attach before Unity does its lighting
- mainCam.AddCommandBuffer(CameraEvent.BeforeLighting, cb);
- }
- public void Register(StencilShadowCaster c)
- {
- if(!casters.Contains(c))
- casters.Add(c);
- }
- void LateUpdate()
- {
- // rebuild CommandBuffer each frame
- cb.Clear();
- // 1) Ensure stencil is zeroed where there is no shadow
- cb.ClearRenderTarget(
- false, // don't touch color
- false, // don't touch depth
- Color.clear, // N/A
- 0 // reset stencil to 0
- );
- // 2) Draw *all* shadow‐volumes into stencil
- foreach(var caster in casters)
- {
- var vol = caster.BuildVolumeMesh();
- cb.DrawMesh(vol, Matrix4x4.identity, stencilMat, 0, 0);
- }
- // ** Unity now proceeds with its usual Forward lighting. **
- // All of your existing shaders & lights work exactly the same—but
- // GPU will skip fragments where stencil!=0 (in shadow).
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement