Access depth buffer in canvas_item shader

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By hexaquo

I’m working on a raymarching shader, which is a canvas_item shader on a full-screen ColorRect - it reads from the SCREEN_TEXTURE and adds the raymarched objects to that color.

Currently, raymarched objects are always on top of other objects drawn by the engine. I’d like to access the depth buffer in my shader so that I can stop the march when I’m exceeding the depth at that pixel. However, I can’t find a way to access the depth buffer in a canvas_item shader in the documentation - there’s only SCREEN_TEXTURE with no depth component.

I’ve also tried turning it into a spatial shader, but it seems like 2D objects like ColorRects don’t do anything with those.

Is there a way to do this?

:bust_in_silhouette: Reply From: hexaquo

I figured out an alternative: Instead of a canvas_item shader, I use a spatial shader on a quad which is always positioned exactly in the viewport. When setup correctly, this looks and works exactly the same as a canvas_item shader on a full-screen texture, but it gives access to all the nice spatial built-ins! It even works in the editor since you can directly access the CAMERA_MATRIX etc. instead of having to pass them as uniform variables.

This tutorial has been very helpful: https://docs.godotengine.org/fi/latest/tutorials/shading/advanced_postprocessing.html