Shading Language

Introduction

cerlib uses its own platform-agnostic shading language.

It includes a hand-written, small and efficient compiler that translates its shaders to native shading languages such as GLSL, HLSL and MSL.

The language is designed as a C-like language with simple constructs. Its goal is to provide an easy to understand shading language tailored to cerlib’s domain, namely sprite shading.

The advantage of having a custom shading language is the ability to closely match it to what the library is capable of. Conversely, the library can optimize how shader data is stored and sent to the GPU, because it understands the language’s behavior and restrictions.

Users of GLSL, HLSL or MSL should feel familiar with the language.

Basic Syntax

Functions

Similar to C++, a function is defined in the form of:

Vector3 multiply_add(Vector3 first, Vector3 second, Vector3 third)
{
  return first * second + third;
}

With the difference being that a function starts with the fn keyword and specifies its return type after an -> arrow.

Some rules for functions:

  • Every function must return a value; there is no void type
    • A function is allowed at most one return statement, which must be the last statement in its body
  • Function parameters are immutable
  • Function overloading is not allowed
  • Every code block must be surrounded by { and }, even if it contains a single statement

Comments

Comments start with //. Multiline comments in the form of /* ... */ are not supported.

Variables

There are two ways to define a variable: mutable and immutable. Mutable variables are defined using the var keyword, while immutable variables are defined using the const keyword:

var a = 1;
a = a * 2; // ok: value of a can be changed
a += 2;
 
const b = 2;
b = b * 2; // error: value of b can't be changed
b += 3;

In either case, every variable statement has to be initialized with an expression, from which its type is deduced. There is no explicit type declaration for variables.

The prefix cer_ is a reserved prefix for built-in variables and may not be used as a prefix for identifiers.

Data Structures

A data structure is defined using the struct keyword:

// Definition:
struct LightingResult
{
  Vector3 diffuse;
  Vector3 specular;
  float intensity;
}
 
// Usage:
const result = LightingResult
{
  diffuse   = Vector3(1, 2, 3),  // initialize field 'diffuse'
  specular  = Vector3(4, 5, 6),  // initialize field 'specular'
  intensity = 7.0                // initialize field 'intensity'
};

When initializing a struct, all or none of its fields must be initialized. The following would therefore be not allowed:

const result = LightingResult
{
  diffuse = Vector3(1, 2, 3)
}; // error: missing initializers for fields 'specular' and 'intensity'

Whereas this would be allowed:

const result1 = LightingResult{};
result1.diffuse = Vector3(1, 2, 3); // error: 'result1' is immutable
 
var result2 = LightingResult{};
result2.diffuse = Vector3(1, 2, 3); // ok: result2 is mutable

If Statements

Use if statements to conditionally execute a portion of code at runtime:

Vector3 some_conditions(Vector3 v)
{
  var result = v;
  const len = length(v);
 
  if (len > 4.0)
  {
    result *= 10.0;
  }
  else if (len > 2.0)
  {
    result *= 5.0;
  }
  else
  {
    result = Vector3(0);
  }
 
  return result;
}

Ternary conditional operators are also supported:

float max(float a, float b)
{
  return a > b ? a : b;
}

Loops

Loops can be realized using a for statement. A for loop requires a name for the iterator variable and a range in the form of <start> .. <end_exclusive>:

var sum = 0;
for i in 1 .. 4 // i will be 1, 2, 3
{
  sum += i;
}
// sum: 1+2+3 = 6

The iterator variable (in this case i) is immutable.

Shader Functions

Shader functions are the main entry points in a shader and are always called main:

Vector4 main()
{
  return Vector4(0);
}

There are special restrictions for shader functions. For example, a shader function must always return a value of type Vector4, which is the output pixel color.

Using Shaders

The default way to use shaders is to load them using the cer::load_shader function, which loads a shader stored on disk. In this chapter however we’ll look at how a shader can be constructed directly from a C++ string. It’s as simple as:

cer::Shader shader{"My Shader", my_shader_code};

Where my_shader_code is a string object. The first parameter is the shader’s name and is used to report it in compilation error messages. If the constructor didn’t throw an exception, the shader was compiled successfully and is ready for use.

Parameters

A shader can declare parameters that are accessible to all functions within it, for example:

Vector3 some_color;
float intensity = 1.0; // Assigning a default value
 
Vector3 some_function(Vector3 value)
{
  return value + some_color;
}

Parameter declarations may optionally assign a default value. If no default value is specified for a parameter, it receives a zero-value. Meaning that a float will be 0.0, a Vector2 will be Vector2(0, 0), a Matrix will be all zeroes, etc.

Supported parameter types are:

  • bool
  • intuintfloat
  • Vector2Vector3Vector4
  • Matrix
  • Image

The compiler will optimize any unused parameters away.

Setting parameter values

To set parameters on shader objects, call the cer::Shader::SetValue method:

myShader.set_value("base_color", cer::Vector3{1, 0, 0});
myShader.set_value("intensity", 2.0f);

The method has overloads for each parameter type. When attempting to set a value that is incompatible with the parameter type, an exception is thrown.

Conversely, shader parameter values can be obtained using the cer::Shader::GetValue method:

std::optional<cer::Vector3> base_color = my_shader.vector3_value("base_color");
std::optional<float>        intensity  = my_shader.float_value("intensity");

The value of a parameter is always part of a shader object’s state. This means that shader parameters can be updated even when a shader is not actively used.

Array parameters

It’s possible to declare array parameters for scalar types using an array specifier:

// Arrays must always have a known size at compile time.
Vector3[12] some_array_of_3d_vectors;
 
// Expressions may be used as an array size, but are required to be known at compile time.
const some_value = 4;
const some_constant = 12 * some_value;
 
float[some_constant + 2] some_array_of_floats;

Setting array parameter values are also modified using the set() method. Arrays are specified as std::span values:

my_shader.set_value("some_floats", {{ 0.5f, 1.0f, 1.25f, 5.0f }});

Next: Custom Shaders