Advertisement
noradninja

ShadowVolumeManager

May 11th, 2025
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.78 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using UnityEngine.Rendering;
  4.  
  5. [DefaultExecutionOrder(-500)]
  6. public class ShadowVolumeManager : MonoBehaviour
  7. {
  8.     public Material stencilMat; // assign Hidden/StencilShadowVolume here
  9.     Camera mainCam;
  10.     CommandBuffer cb;
  11.     List<StencilShadowCaster> casters = new List<StencilShadowCaster>();
  12.  
  13.     public static ShadowVolumeManager Instance { get; private set; }
  14.  
  15.     void Awake()
  16.     {
  17.         if(Instance != null && Instance != this)
  18.             Destroy(gameObject);
  19.         else
  20.             Instance = this;
  21.  
  22.         mainCam = Camera.main;
  23.         cb = new CommandBuffer { name = "Shadow Volume Stencil Pass" };
  24.  
  25.         // attach before Unity does its lighting
  26.         mainCam.AddCommandBuffer(CameraEvent.BeforeLighting, cb);
  27.     }
  28.  
  29.     public void Register(StencilShadowCaster c)
  30.     {
  31.         if(!casters.Contains(c))
  32.             casters.Add(c);
  33.     }
  34.  
  35.     void LateUpdate()
  36.     {
  37.         // rebuild CommandBuffer each frame
  38.         cb.Clear();
  39.  
  40.         // 1) Ensure stencil is zeroed where there is no shadow
  41.         cb.ClearRenderTarget(
  42.             false,              // don't touch color
  43.             false,              // don't touch depth
  44.             Color.clear,        // N/A
  45.             0                   // reset stencil to 0
  46.         );
  47.  
  48.         // 2) Draw *all* shadow‐volumes into stencil
  49.         foreach(var caster in casters)
  50.         {
  51.             var vol = caster.BuildVolumeMesh();
  52.             cb.DrawMesh(vol, Matrix4x4.identity, stencilMat, 0, 0);
  53.         }
  54.  
  55.         // ** Unity now proceeds with its usual Forward lighting. **
  56.         // All of your existing shaders & lights work exactly the same—but
  57.         // GPU will skip fragments where stencil!=0 (in shadow).
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement