Change fragment output color depending on pixel overlaps.

I’m trying to code a fragment shader that outputs color in the range of cold (dark blue) to hot (white, reds, yellows) depending on how many times the current fragment has been rendered to by the same mesh’s shader.

Basically, the more the model’s pixels, the warmer the color (in the overlapping pixels) should be.

Renderers have an optimization called depth culling. Essentially, for each pixel, it keeps track of the closest object from the camera that appears in that pixel. After depth culling, the color computations are done. By doing this, the renderer can avoid wasting time computing colors of things that are blocked by other things, especially in complex models with lots of overlaps.

Because of this process, it is difficult to obtain the amount of times each pixel is drawn to per frame, unless you can somehow hook into the depth culling process to count how much overlap is at each pixel (which may or may not be possible).

I can think of a hacky way around this, but it’s not very fast. The idea is to render each triangle of your model with a low alpha color onto an initially black texture. (If you enable transparency, depth culling should be disabled… though Unity might handle this automatically.) Since each triangle is transparent, areas with more overlaps will appear lighter in the texture, and areas with few overlaps will appear mostly dark. You can get a camera to render directly to a texture by setting its target texture.

You can then pass this texture to a shader which examines how light each pixel of the texture is, then maps that to some value in an array of colors (i.e. the colors for your heatmap).