How to Shaders

Last updated 6 months ago

Intro to the engine's shading API - GLSLProgram

Manage shaders via the GLSLProgram

GLSLProgram.hpp - class declarations
GLSLProgram.cpp - class implementation

Example shader implementations

Basic pixel position & color manipulation.

Vertex
Fragment
Geometry
Tesselation
Tesselation control
shader.vert
#version 450 core
uniform mat4 model_view;
uniform mat4 projection;
layout(location = 0) in vec4 position;
layout(location = 0) out vec4 vertex_pos;
void main(void)
{
gl_Position = projection * model_view * position;
vertex_pos = position;
}
shader.frag
#version 450 core
struct material
{
vec4 emissive;
};
// Incoming vertex position
layout(location = 0) in vec4 vertex_pos;
uniform material mat;
out vec4 outputF;
void main(void)
{
outputF = mat.emissive;
}
shader.geom
#version 450 core
layout (triangles) in;
layout (points, max_vertices = 3) out;
void main(void)
{
int i = 0;
do
{
gl_Position = gl_in[i].gl_Position;
EmitVertex();
} while (i++ < gl_in.length());
EndPrimitive();
}
shader.tes
#version 450 core
layout (triangles, equal_spacing, cw) in;
void main(void)
{
gl_Position = (gl_TessCoord.x * gl_in[0].gl_Position +
gl_TessCoord.y * gl_in[1].gl_Position +
gl_TessCoord.z * gl_in[2].gl_Position);
}
shader.tcs
#version 450 core
layout (vertices = 3) out;
void main(void)
{
// Only if I am invocation 0...
if(gl_InvocationID == 0)
{
gl_TessLevelInner[0] = 5.0;
gl_TessLevelOuter[0] = 5.0;
gl_TessLevelOuter[1] = 5.0;
gl_TessLevelOuter[2] = 5.0;
}
// Everybody copies their input to their output
gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
}

Require the shader class in your application

#include "graphics/shaders/GLSLProgram.hpp"

Instantiate a shader program object

// using default ctor
GLSLProgram shader;

Compile & Build the shader program from your sources

Vertex & Fragment shaders are both enough and mandatory to start with.

std::string and char* sources are accepted can be file path or a shader code as a string

Example

Compile shader from file

// load and compile shaders
shader.CompileShaderFile("res/shaders/example.vert", GLSLShader::GLSLShaderType::VERTEX);
shader.CompileShaderFile("res/shaders/example.frag", GLSLShader::GLSLShaderType::FRAGMENT);

Build the comiled shader

// link the shades into the program
shader.Build();

Use the shader or change the shader that is currently in use

Bind current shader

shader.Enable();

Unbind current shader

shader.Disable();