Modifying G-Buffer in Unity 5

Low level access to the renderer G-Buffer offers us with the possibility to implement various effects. Although the Unity is high-level engine without access to the source code, we are still able to access and modify the low-level built-in shaders.

Currently, the G-Buffer of Unity 5 has following layout:

  • RT0: diffuse (RGB), occlussion / probably unused (A)
  • RT1: specular color (RGB), smoothness (A)
  • RT2: normal (RGB), unused (A, low precision)
  • RT3: emission (RGB), unused (A)

As we can see, there are 2 (+1) unused channels. These can be used to store some custom information, like character outline color (when doing outline post-effect), decal mask etc. This will be covered in the next article.

To be able to modify the shader, we must download Built-in shaders, which can be located at the following link. Extract these shaders into your Assets folder.

The built-in shader package contains many files, but we are interested only in some of them:

  • UnityStandardCore.cginc
  • UnityStandardInput.cginc
  • Standard.shader
  • StandardSpecular.shader
  • StandardShaderGUI.cs
UnityStandardCore.cginc

– deferred vertex & fragment shaders are located at the bottom of this file

UnityStandardInput.cginc

– contains definition of the input uniforms, structures and some functions related to these inputs

Standard.shader + STANDARDSPECULAR.SHADER

– contains actual Standard / Standard Specular shader. We are interested only in the Deferred pass.

StandardShaderGUI.cs

– contains definition of the editor GUI for these shaders. When we add our custom property, we want it to show in the Inspector. This file is the place where we link properties in shaders with editor GUI.

Modifying example

After looking at this files we are now able to modify them and add our custom properties.

For this example, let’s try to insert our own property called Desaturation. This property will be float in the [0;1] range, where 0 means original color and 1 means fully desaturated color.

We will start with modifying UnityStandardInput.cginc, where we will add:

Then, in the UnityStandardCore.cginc, we will modify the fragDeferred, where at the end of this function we will append (not tested):

At the Standard.shader and StandardSpecular.shader, we will add property:

Now, we can set the “_Desaturation”  property from the script by calling material.SetFloat(“_Desaturation”, value); – where value is the desaturation value.

We may also want to be able to modify this property from the Inspector window. To do this, we will modify the UnityStandardGUI.cs script with the following pseudocode:

Now, after we select some materials with Standard / Standard specular shaders, we will see the Desaturation slider at the bottom of the Inspector. This slider will be under our Custom properties label.