Book Image

GLSL Essentials

By : Jacobo Rodriguez
Book Image

GLSL Essentials

By: Jacobo Rodriguez

Overview of this book

Shader programming has been the largest revolution in graphics programming. OpenGL Shading Language (abbreviated: GLSL or GLslang), is a high-level shading language based on the syntax of the C programming language.With GLSL you can execute code on your GPU (aka graphics card). More sophisticated effects can be achieved with this technique.Therefore, knowing how OpenGL works and how each shader type interacts with each other, as well as how they are integrated into the system, is imperative for graphic programmers. This knowledge is crucial in order to be familiar with the mechanisms for rendering 3D objects. GLSL Essentials is the only book on the market that teaches you about shaders from the very beginning. It shows you how graphics programming has evolved, in order to understand why you need each stage in the Graphics Rendering Pipeline, and how to manage it in a simple but concise way. This book explains how shaders work in a step-by-step manner, with an explanation of how they interact with the application assets at each stage. This book will take you through the graphics pipeline and will describe each section in an interactive and clear way. You will learn how the OpenGL state machine works and all its relevant stages. Vertex shaders, fragment shaders, and geometry shaders will be covered, as well some use cases and an introduction to the math needed for lighting algorithms or transforms. Generic GPU programming (GPGPU) will also be covered. After reading GLSL Essentials you will be ready to generate any rendering effect you need.
Table of Contents (13 chapters)

Raw data computations


The following sample code is another very simple compute shader example, but it completes the basic sets of operations. First, we handled image data, now, we will handle raw data. In this example, the shader will receive two arrays of the same size, and we will use the shader to sum them together into a third array.

As always, let's go first with the shader's code:

#version 430
layout (local_size_x = 16, local_size_y = 1, local_size_z = 1) in;
uniform int BufferSize;
layout(std430, binding = 0) buffer InputBufferA{float inA[];};
layout(std430, binding = 1) buffer InputBufferB{float inB[];};
layout(std430, binding=2) buffer OutputBuffer{float outBuffer[];};
void main()
{
  uint index = gl_GlobalInvocationID.x;
  if(index >= BufferSize)
  {
    return;
  }
  outBuffer[index] = inA[index] + inB[index];
}

As you can see, we are using each work item to process only one array's element. The two important things here are the declaration of the buffers and the return that controls...