
Having a devil of a time trying to get my privacy glass shader to ignore foreground objects (shader file provided)
Using Unity version 6000.0.72f1, URP package version 17
Link to the shader file: https://drive.google.com/file/d/1DbuKtRRFbwcuorUZYInWtSWPIlsI6M-p/view?usp=drive_link
Screenshot of the graph for anyone who wants to take a quick look without downloading the shader:
I've been having a blast trying to make this privacy window shader and I think it looks really cool in action, but I keep running into issues where foreground objects affect the shader's distortion and blur. Here's how it looks prior to adding any depth-testing.
I've tried maybe 4 or 5 different ways of fixing this that I can think of, primarily by testing the distorted screen UVs against the original UVs, and it helps a little bit, but there are thin pixel outlines no matter what I do. Here's the latest implementation that works almost perfectly:
Only glass distortion:
With blur and distortion applied:
As you can see it removes about 95% of the foreground object's influence, but those last pixels of colour really detract from the presentation and it's driving me nuts that I can't figure out what's causing it to happen. As far as I can tell I'm correctly applying the depth logic, so where are these pixels coming from?
The box blur function is an HLSL custom function that needs to be explicitly made depth-aware (and to my knowledge, should be), and the no-blur pathway just routes through a Scene Color node to bypass adding any kind of blur, putting out to the Emissive colour fragment shader the distorted UV and a final glass tint colour.
Here's the box blur code for anyone who wants to inspect that, too:
#ifndef SHADERGRAPH_PREVIEW
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareOpaqueTexture.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl"
float3 sum = float3(0.0, 0.0, 0.0);
float2 offsets[4] = {
float2(-1.0, -1.0),
float2(1.0, -1.0),
float2(-1.0, 1.0),
float2(1.0, 1.0)
};
[unroll]
for(int i = 0; i < 4; i++) {
float2 offsetUV = UV + (offsets[i] * BlurRadius);
float rawDepth = SAMPLE_TEXTURE2D_X_LOD(_CameraDepthTexture, sampler_CameraDepthTexture, offsetUV, 0).r;
float sampleDepth = LinearEyeDepth(rawDepth, _ZBufferParams);
if (sampleDepth < FragmentDepth) {
offsetUV = UV;
}
sum += SAMPLE_TEXTURE2D_X_LOD(_CameraOpaqueTexture, sampler_CameraOpaqueTexture, offsetUV, 0).rgb;
}
Out = sum * 0.25;
#else
Out = float3(0.0, 0.0, 0.0);
#endif
Any help or improvements would be greatly appreciated. Thanks!
Also let me know if any more context or disambiguation is needed.
Anyone who fixes the shader (and shares the fix here!) is 100% welcome to use it for themselves. I just want the darn thing working.
Also bonus points if anyone can also advise on rendering transparent materials through this shader too, currently it occludes any transparencies behind it.