I'm a gameplay programmer
focused on developing
engaging and unique experiences!

My Resume Learn more

Abstracting Shaders with Materials

Shaders are an incredibly powerful tool for programmers and artists to dictate how meshes are rendered on screen. However, because they are primarily code, abstracting away the need to edit them in a text editor can greatly increase iteration time. This is where the concept of materials come in. Materials mainly act as a wrapper around shaders while exposing constant data parameters that can affect how the shader behaves. A very simple example of one can be seen below:

    path_effect = "Effects/standard.effect",
    color = { 1.0, 1.0, 1.0, 1.0 },

This material has a path to an effect, which is another wrapper around a vertex and a fragment shader. The main thing to note is the color property, which is the material's constant data that can affect how the specified effect behaves. Something to note about this data is that it's optional, as not every material will require a color to be set by a user.

Using Materials

With a material implemented, we could output the example scene below with a single effect!

This scene has 12 sphere meshes and 1 plane mesh all rendered using the same effect! We achieve the different colors by specifying different colors in different materials. Another benefit of materials is that we can quickly change the desired color by simply editing the color in the material file. No shader editing necessary!

Sorting Render Commands by Material

Something we must also keep in mind is the order of our draw calls. Now that we've abstracted away effects behind materials, we should see meshes being drawn in groups based on their materials. Below is an animation demonstrating meshes being drawn by material and distance from the camera.

Reducing Shader Bindings

Lastly, by implementing materials we also want to ensure we don't rebind effects if we're still using the same shader! Something to also note is that even if we use different materials, if they have the same effect we don't have to rebind them! In that case, we would only need to update the per material constant data.

The image below shows two draw calls in green before we set a new shader in yellow. Something else to also note is the updating of material data in red that happens when we are using the same effect, but using different constant data.

No Comments Yet.

Leave a comment