Determine correct cascade inside a fragment shader

I’m working on a custom shadow receiving shader to provide greater control over the appearance of the built in shadows, and I’ve hit a bit of a snag determining what shadow cascade to use for any given fragment.

I know that the unity_World2Shadow array elements correspond to each cascade, and it would usually be a simple matter of checking distance from camera and dividing by cascade size, but since glsl only allows array access with compile time constants, I’m hoping that theres a macro or variable in the shader include files I’m missing to handle this task.

My fragment program is below, you can see that I’m determining which cascade I should use (the index variable), but I’m not really sure how to go from that to actually getting the correct _World2Shadow matrix without a lot of (hopefully) unnecessary operations. Thanks in advance for any help/tips/advice you can provide :smile:.

float4 frag(vOUT i) : COLOR
{
    int index = int( distance(_WorldSpaceCameraPos,i.lightPos) / _CASCADE_SIZE);
				
    float4x4 shadowMatrix = unity_World2Shadow[3]; //this 3 should be index.
											
    float4 l = mul(shadowMatrix, i.lightPos); 

    float dist =  UNITY_SAMPLE_SHADOW_PROJ(_ShadowMapTexture, l);
    dist = _LightShadowData.r + dist * (1-_LightShadowData.r);							
}

In AutoLight.cginc I can only see two instances of unity_World2Shadow and they both use [0].

They’re used in TRANSFER_SHADOW_COLLECTOR from UnityCG.cginc, and in unitySampleShadow() in Internal-PrePassCollectShadows.shader, but I don’t have the knowledge or patience to figure out exactly what they’re for.