I started developing games at the young age of sixteen,. It’s been ten years now, and the landscape of indie and hobbyist game development has changed since then. Back then, Unity was still young, and not popular as it is today. Do you know how popular Unity is today? The magnitude of Unity’s popularity can be seen by Global Game Jam 2019’s technology stats which I will plot here:

 

Global Game Jam 2019 Technology Stats. A whopping 74% used Unity!

What can be concluded from this chart, but the fact that Unity is rather popular? And its popularity is well-deserving. What astounds me is that 28 teams have used Processing. If you don’t know what Processing is, it’s a Java library/stand-alone package which is mainly used for Creative Programming, something cooked up by people who had too much time on their hands. But funnily enough, there’s one feature in Processing which I admire, and that’s filtering the image based on a given fragment shader. But it is, in no way, suitable for making games! For God’s Sake, if you want something simple, Why Don’t You Ask Evans?

 

I know I am burying the lede here, and people have told me not to before, but I want to enjoy writing these blog posts, and nothing’s more enjoyable more than talking about an author you admire. Why Didn’t They Ask Evans is a work of detective fiction by Dame Agatha Christie. I won’t spoil the book for you, but it’s about Bobby Jokes and his girl toy Frankie. Bobby, whilst golfing, stumbles upon a near-dead man on the rocks. The man mumbles “Why didn’t they ask Evans?” This book is about Occam’s Razor: Usually, the simplest answer to something is the best answer. So if you want to make a game, and don’t want to use Unity, what is the simplest answer? Grist to Our Mill, Godot Engine (pronounced Gow-Dow)!

 Only a couple of people had used this engine in this years Game Jam, and it was a point of pride for them. They called themselves “hipsters of the game developing world”. But let’s not fret, Godot is becoming more and more popular, and by this time next year, a lot more people will be using it. I wish to do my part in introducing this wonderful engine to the game making public. It’s not great for 3D games, but it’s awesome for 2D games.

Godot is only 18 megabytes, and can be downloaded from here. Along with the engine, download the Export Templates, and also, if you’re a Blender man, Better Collida Exporter which improves the exporting of .dae files in Blender. You know what’s the best thing about Godot is? It’s free, or as Richard Stallman puts it, free as in freedom. There are many free engines around but certainly, Godot is heads ans shoulders above the rest.

 Extract Godot somewhere where you keep your game development files. Start a new project, or download a template. Here, I have downloaded a template called “Platformer 2D”.

 

On the top-left you see the FileSystem file browser. I don’t use this function, I drag and drop my files onto the…

On bottom-left you see your project files. Icon.png is what Godot displays in the project manager. It’s the identity of your project! So use a good picture.

The bar on the top navigates between your 2D, 3D, and code. Also, AssetLib wihch is Godot’s version of Asset Store.

Below that is your level editor.

On the top-right you’ll see the Scene nodes. Godot’s node system is very intuitive, and we’ll introdue some of the nodes later on. Tabbed next to the Node system is the Import settings.

On the bottom-right you’ll see the Inspector. Here, you, per example, add a sprite to a texture, set a music to loop, or create a particle system. Everything done here can also be done in the code section. Tabbed next to the Inspector is the Node settings, which comprises of Alarms, and Groups.

Okay, now let’s see what goes into the making of Godot Engine. Hit Help->About and look at the third party licenses. Here we see that Godot uses zlip, curl, TinyEXR, NanoSVG, GLAD, and most importantly, SDL, amongst so many other things. Truly, a pinnacle of FOSS development. Just 10 years ago, this would have been an impossible feat to achieve. But thanks to many OSS projects, and Github, today, we have Godot. Thanks, RMS! You are truly the man who eats foot cheese, but your efforts has also given us so many wonderful things.

Godot uses OpenGL through SDL. And GLAD as OpenGL Function loader (I know it’s not important, but for me, these things are exciting). Currently, it doesn’t have an Official .gitignore but there’s an unofficial one. If you wish to create a repository for your game, make sure there’s a .t prefix before your scene and file names, otherwise, they will be binary, and completely unsuitable for a version control system like Github.

Let’s take a look at some of Godot’s nodes:

 

  • Every node has a parent. In a 2D game, most of the nodes you use inherit from Node2D.
  • Every node can have as many children as it wants. Usually, an Area 2D node has a Sprite 2D node, and a script attached to it.
  • Particles 2D generates a 2D particle system, probably using textured OpenGL points. I must do a tutorial on them one day.
  • Path 2D, gives a path to the parent node it’s attached to.
  • RayCast 2D, it casts a ray in the 2D space and if it hits somewhere, it alerts the parent node.
  • Polygon 2D, a 2D polygon.
  • Sprite, one of the most-used of the Node2D nodes. It’s usually attached to a Kinematic, Static, or an Area 2D object.
  • TileMap, a set of tiles.

As I said, nodes are very intuitive.

Now, let’s take a look at Godot’s scripting language, called GD Script, which is very similar to Python. You can also use C# if you have downloaded the Mono version:

extends Node

var lives = 4
var coins = 0
var punto

func _ready():
	self.pause_mode = PAUSE_MODE_PROCESS

func _process(delta):
	if Input.is_action_just_pressed("ui_cancel"):
		if get_tree().paused == false:
			get_tree().paused = true
		else:
			get_tree().paused = false
	
	if lives == 0 and punto == null:
		print("Perdiste")
		get_tree().quit()

_ready() function is kin to Unity’s start(), and Godot has two functions which can be equated to Unity’s update(). The first one is _process() which is the normal update, the next one is _physics_process() which is used for synchronization with the physics engine. Also, as you can see, delta time is passed to the function as a parameter, something which all engines must do! 

So why do I say Godot is Grist to Our Mill? Because for far too long, before or after Unity became popular, we relied on tools that simply weren’t up to it. Tools that were buggy, run-down, or simply wrong (looking at you, Processing!). Godot is free, Godot is ever-changing and Godot is ever-wonderful. It’s still in development, but you can always rely on it to make you a good game, free of charge, with all the features intact.

Back in 2016, when I first started out with Godot, there were not that many tutorials around. But these days it’s just a matter of Google search to access the best of Godot tutorials. And if you like books, you can always buy Godot Engine Game Development in 24 Hours which is how I learned Godot. And you can always ask /r/Godot. Q&A is also always around to answer your questions.

 

 

Well, that is it for today’s post! You see, I, too, can post about game engines, and my posts are not always either about weird Python scripts that I’ve written, or OpenGL. Thanks, and have a nice day!

As the inquisitive reader may have guessed, or simply, googled my name, I hail from Persia, where Prince of Persia (as most people here put it, pe-rance of per-sh-ee-a)  games and the movie are set. Some people complained that Persians are brown, and the fact that in the movie had hasted a Nordic actor to play the role of the Prince was rather insulting and racist, however, what these warriors choose to ignore is that Persians, and most other Iranic tribes at the time, such as Parthians (Parthia, where I live) and Medians were, in fact white. Let’s not beat around the bush here. For nationalistic reasons, I never played the reboot, or the trilogy, I just played the 2D platformer on a Sega Genesis emulator. Anyways, I thought the reboot was the first instance of cel shading in computer games, however, I was wrong. Ten years before, a Dreamcast game by the name of Jetset Radio (pictured above) had set the trend. I’m too young for Dreamcast and I’ve never seen one even. But it must have been helluva game judging by the videos I’ve seen of it.

 

Legend of Zelda: Skyward Sword, one of the better games using cel shading

But what is cel shading or as Graham Sellers puts it, cell shading [sic]? It’s basically the process of using tricks in the render pipelien to make everything appear as if they were drawn by hand. The alternative approach for naming this technique is toon shading.

 

Cinema 4D’s “Toon” Effect

To find out which games use this effect, I headed to my trusty hangout, TVTropes.org, a wiki created using PMWiki and serving astray, bored media lovers for years… and in its cel shading page, it said:

Cel Shading applies first and foremost to the way the lighting is rendered.

This layman explanation is exactly, how I would describe it. Indeed, cel shading is rendering of the diffuse light channel. Texturing, and rendering. I know that light is a component of the material, and not something to be rendered, but using LUTs, we can achieve exactly this.

Anyways, what is  LUT?

 

 

A shot from Tintin’s Assets… I really don’t know what a plastic shader is. You could fill a data center with the things I don’t know!

Color LUT

If you have played around in Da Vinci Resolve, you’ll know what LUT is. It’s short for Look Up Table. Imagine you wish to change a series of colors to another series of colors. Each color must correspond to another. This is where Color LUT comes into play.

 

A LUT

In OpenGL, each LUT is a 1D array that corresponds to a number between 0.0f and 1.0f. This number is the intensity of the diffuse component of the Phong lighting system (remember the last post? Phong lighting is different from Phong material). Imagine this, if you will.

 

\vec{N} is normal vector, \vec{L} is the light vector. the LUT maps each color to each intensity using the formula. \alpha is dependent on your code.

 Let’s put it all together and see what happens.

Note: These are taken from OpenGL Superbible 7ed, by Graham Sellers.

 

Cel Shading in OpenGL

First, our front-end, at least, a part of it:

Listing 1: OpenGL Cel Shading Front End

 

//declare our LUT
static const GLubyte toon_tex_data[] =
{
    0x44, 0x00, 0x00, 0x00,
    0x88, 0x00, 0x00, 0x00,
    0xCC, 0x00, 0x00, 0x00,
    0xFF, 0x00, 0x00, 0x00
};

glGenTextures(1, &tex_toon); //Generate texture
glBindTexture(GL_TEXTURE_1D, tex_toon); //Bind texture, a 1D texture
glTexStorage1D(GL_TEXTURE_1D, 1, GL_RGB8, sizeof(toon_tex_data) / 4);
glTexSubImage1D(GL_TEXTURE_1D, 0,
                0, sizeof(toon_tex_data) / 4,
                GL_RGBA, GL_UNSIGNED_BYTE,
                toon_tex_data); //Pass the data
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); //Conditions

Note that all the codes are explained in comments, and this is an introductory article, and not a tutorial, so I don’t see fit to explain the code in detail. You can buy OpenGL Superbible and see for yourself.

Listing 2: Partial of Cel Shading Vertex Shader

 

#version 420 core

uniform mat4 mv_matrix;
uniform mat4 proj_matrix;

layout (location = 0) in vec4 position;
layout (location = 1) in vec3 normal;

out VS_OUT
{
    vec3 normal;
    vec3 view;
} vs_out;

void main(void)
{
    vec4 pos_vs = mv_matrix * position;

    // Calculate eye-space normal and position
    vs_out.normal = mat3(mv_matrix) * normal;
    vs_out.view = pos_vs.xyz;
// Send clip-space position to primitive assembly
    gl_Position = proj_matrix * pos_vs;
}

And finally, our fragment shader.

Listing 3: Cel shading fragment shader.

 

#version 420 core

layout (binding = 0) uniform sampler1D tex_toon;

uniform vec3 light_pos = vec3(30.0, 30.0, 100.0);

in VS_OUT
{
    vec3 normal;
    vec3 view;
} fs_in;

out vec4 color;

void main(void)
{
    // Calculate per-pixel normal and light vector
    vec3 N = normalize(fs_in.normal);
    vec3 L = normalize(light_pos - fs_in.view);
// Simple N dot L diffuse lighting
    float tc = pow(max(0.0, dot(N, L)), 5.0);

    // Sample from cell shading texture
    color = texture(tex_toon, tc) * (tc * 0.8 + 0.2);
}

If we load a donut model into the program, this is what we’ll get:

 

Well, hope you enjoyed it! I’m currently learning After Effects. And I may write a book about it. What do you think?



We do not expect to be able to display the object exactly as it would appear in reality, with texture, overcast shadows, etc. We hope only to display an image that approximates the real object closely enough to provide a certain degree of realism.


Bui Tuong Phong

 Bui Tuong was born in 1941, and became a computer scientist during the hobnobbing affair of the Vietnam War. It must have been pretty difficult for him to complete his education is the toxic environment of the 60s, let alone, be drafted to fight in the country of his fore bearers! But he managed to stay alive, until 1975, before leukemia took his life, just 2 short years before he gave us the basis of light and shading today: the Phong shader. Vietnamese names are comprised of three parts: the paternam name, the middle name, and the given name. All along, when people say “Phong shader”, they are referring to Bui Tuong’s given name. Read more about given names on Wikipedia.

Not sure if it’s Phong, but if Google is to be believed, it’s him.


“Softly let the balmy sunshine
Play around my dying bed,
E’er the dimly lighted valley
I with lonely feet must tread. “


Let The Light Enter – Poem by Frances Ellen Watkins Harper

There’s some extremely concise math behind Phong Shader. Which you need not know, really, unless you aspire to be a graphics programmer like yours truly. However, knowing them, even glancing at them will be beneficial in the long run. The following is extracted from OpenGL Superbible, 7th Edition by Graham Sellers and the Kronos Group ARB Foundation.

 

A) Some Concepts

First, let me get some concepts out of the way. If you have been 3D modelling or game developing for more than a minute, you will certainly be positioned in their line of fire, but a reminder won’t hurt.

 

A-1) Ambient Light

Most books, especially rather shoddy ones, compare this sort of light with sunlight, however, this is simply wrong. Ambient light is not sunlight. It comes from every direction, meaning, it’s omnipresent, but in calculations, it’s just a vector with 3 members. In Phong shading, it gets added at the end, but is not modified.


A-2) Diffuse Light

Diffuse light has a direction. In fact, it’s the directional component of a light source [sic]. In cinema, light is diffused with a softbox, and in computer graphics, light is diffused with the formula which we’ll put forward later. The magnitude, that is, the size of the diffuse light depends on the surface. For example, if our surface is a matte surface that absorbs more light than reflecting, the magnitude must be higher than when our surface is glossier.

Reflection/Absorption of Diffuse Light from a Matte Display
A-3) Specular Highlight

Like diffuse light, specular light is directional, but based on the glossiness of the surface, it leaves a highlight which is called shininess. In real life, shininess is not an inherent part of the material. In fact, a coat of film, or a speck of wax, will add more to its shininess than anything else ever could. Specular shininess is a factor which is set between 0 and 128, because beyond 128, it won’t affect the shader much.

“Coated Paper”, construction paper with a film of gloss over them. Childhood Paradise.
A- 4) Albedo

It’s the proportion of the incident light which is reflected away by the surface.

A-5) Phong Formula

The formula for calculating a Phong material is as follows:

I_p = k_ai_a + k_d\left(\vec{L}.\vec{N}\right)i_d + k_s\left(\vec{R}.\vec{V}\right)^\alpha i_s

Where:

k_a: Ambient material

k_d: Diffuse material

k_s: Specular material and \alpha: shininess factor

i_a: Ambient light

i_d: Diffuse light

i_s: Specular light

You may ask, what about the vectors? Well, no worries, we’ll cover them now:

\vec{N}: Surface normal

\vec{L}: Unit vector from the point being shaded into the light (in other words, the light vector)

\vec{R}: The reflection of the negative of the light vector

\vec{N}: Vector to the viewer

 

 

B) Gouraud Shading

Before stampeding towards Phong shader, let’s show how you can achieve Gouraud shading in GLSL. Note that I’m using version 4.1 of GLSL, as per Superbible’s instructions, however, you may be a fan of www.learnopengl.com and use 3.3. Doesn’t matter, same thing. So let’s see what a gouraud shading is. Is it edible, is it a suppository, or is it some sort of a sex toy. 

This method of shading was invented by Henri Gouraud in 1971. It’s not superior to Phong shading by any means, and these days, it’s mostly used as a less GPU-intensive preview method in software such as Cinema 4D. The problem is, that the glint it generates looks like a spark, as shown in the picture below:

 

This is caused by interpolating color between the vertices, and discontinuity between triangles because the colors are being interpolated linearly, and is only solved by Phong shader. Let’s see how we can do Gouraud shading in GLSL 4.1.

Listing 1: Per-vertex Gouraud Shading in GLSL 4.1

#version 410 core

// Per-vertex inputs
layout (location = 0) in vec4 position;
layout (location = 1) in vec3 normal;

// Matrices we'll need
layout (std140) uniform constants
{
    mat4 mv_matrix;
    mat4 view_matrix;
    mat4 proj_matrix;
};

// Light and material properties
uniform vec3 light_pos = vec3(100.0, 100.0, 100.0);
uniform vec3 diffuse_albedo = vec3(0.5, 0.2, 0.7);
uniform vec3 specular_albedo = vec3(0.7);
uniform float specular_power = 128.0;
uniform vec3 ambient = vec3(0.1, 0.1, 0.1);

// Outputs to the fragment shader
out VS_OUT
{
    vec3 color;
} vs_out;

void main(void)
{
    // Calculate view-space coordinate
    vec4 P = mv_matrix * position;

    // Calculate normal in view space
    vec3 N = mat3(mv_matrix) * normal;
    // Calculate view-space light vector
    vec3 L = light_pos - P.xyz;
    // Calculate view vector (simply the negative of the view-space position)
    vec3 V = -P.xyz;

    // Normalize all three vectors
    N = normalize(N);
    L = normalize(L);
    V = normalize(V);
    // Calculate R by reflecting -L around the plane defined by N
    vec3 R = reflect(-L, N);

    // Calculate the diffuse and specular contributions
    vec3 diffuse = max(dot(N, L), 0.0) * diffuse_albedo;
    vec3 specular = pow(max(dot(R, V), 0.0), specular_power) * specular_albedo;

    // Send the color output to the fragment shader
    vs_out.color = ambient + diffuse + specular;

    // Calculate the clip-space position of each vertex
    gl_Position = proj_matrix * P;
}

And now, the fragment shader.

Listing 2: Fragment shader of the same concept.

 

#version 410 core

// Output
layout (location = 0) out vec4 color;

// Input from vertex shader
in VS_OUT
{
    vec3 color;
} fs_in;

void main(void)
{
    // Write incoming color to the framebuffer
    color = vec4(fs_in.color, 1.0);
}

C) Phong Shading

Before going forward, keep in mind that Phong shading and Phong lighting are two different concepts. You can get rid of Gouraud’s “starburst” by using more vertices, but why do that when Phong shading is around? In Phong shaing, instead of interpolating the color between vertices (as seen in Listings 1 and 2), we interpolate the surface normals between the vertices, and the use the generated normal to perform the entire lighting calculation for each pixel, not each vertex. However, this means more work to be done in the fragment shader, as we’ll see in Listing 4. But first, let’s see the vertex shader.

Listing 3: Phong shader’s vertex shader in GLSL 4.1.

#version 410 core

// Per-vertex inputs
layout (location = 0) in vec4 position;
layout (location = 1) in vec3 normal;

// Matrices we'll need
layout (std140) uniform constants
{
    mat4 mv_matrix;
    mat4 view_matrix;
    mat4 proj_matrix;
};

// Inputs from vertex shader
out VS_OUT
{
    vec3 N;
    vec3 L;
    vec3 V;
} vs_out;

// Position of light
uniform vec3 light_pos = vec3(100.0, 100.0, 100.0);

void main(void)
{
    // Calculate view-space coordinate
    vec4 P = mv_matrix * position;

    // Calculate normal in view-space
    vs_out.N = mat3(mv_matrix) * normal;

    // Calculate light vector
    vs_out.L = light_pos - P.xyz;

    // Calculate view vector
    vs_out.V = -P.xyz;

    // Calculate the clip-space position of each vertex
    gl_Position = proj_matrix * P;
}

Nothing much has changed. But the same isn’t true for the fragment shader.

Listing 4: Phong shading’s fragment shader.

 

#version 410 core

// Output
layout (location = 0) out vec4 color;

// Input from vertex shader
in VS_OUT
{
    vec3 N;
    vec3 L;
    vec3 V;
} fs_in;

// Material properties
uniform vec3 diffuse_albedo = vec3(0.5, 0.2, 0.7);
uniform vec3 specular_albedo = vec3(0.7);
uniform float specular_power = 128.0;
uniform vec3 ambient = vec3(0.1, 0.1, 0.1);

void main(void)
{
    // Normalize the incoming N, L and V vectors
    vec3 N = normalize(fs_in.N);
    vec3 L = normalize(fs_in.L);
    vec3 V = normalize(fs_in.V);

    // Calculate R locally
    vec3 R = reflect(-L, N);

    // Compute the diffuse and specular components for each fragment
    vec3 diffuse = max(dot(N, L), 0.0) * diffuse_albedo;
    vec3 specular = pow(max(dot(R, V), 0.0), specular_power) * specular_albedo;

    // Write final color to the framebuffer
    color = vec4(ambient + diffuse + specular, 1.0);
}

Well, that is it for this lesson. I hope you enjoyed it. If this has sparked your interest in OpenGL, you buy OpenGL Superbible from Amazon, or head to learnopengl.com. If you can’t make heads or tails of the shaders, I recommend Book of Shaders. Please leave a comment. Thank you.