Open Graphics Library (OpenGL) is a cross-language cross-platform application programming interface (API) for rendering 2D computer graphics and 3D vector graphics.[1] In this tutorial we will be focusing on modern OpenGL from 3.3 and above, ignoring «immediate-mode», Displaylists and VBO’s without use of Shaders. I will be using C++ with SFML for window, image and context creation aswell as GLEW for modern OpenGL extensions, though there are many other librarys available.
1// Creating an SFML window and OpenGL basic setup.
2#include <GL/glew.h>
3#include <GL/gl.h>
4#include <SFML/Graphics.h>
5#include <iostream>
6
7int main() {
8 // First we tell SFML how to setup our OpenGL context.
9 sf::ContextSettings context{ 24, // depth buffer bits
10 8, // stencil buffer bits
11 4, // MSAA samples
12 3, // major opengl version
13 3 }; // minor opengl version
14 // Now we create the window, enable VSync
15 // and set the window active for OpenGL.
16 sf::Window window{ sf::VideoMode{ 1024, 768 },
17 "opengl window",
18 sf::Style::Default,
19 context };
20 window.setVerticalSyncEnabled(true);
21 window.setActive(true);
22 // After that we initialise GLEW and check if an error occurred.
23 GLenum error;
24 glewExperimental = GL_TRUE;
25 if ((err = glewInit()) != GLEW_OK)
26 std::cout << glewGetErrorString(err) << std::endl;
27 // Here we set the color glClear will clear the buffers with.
28 glClearColor(0.0f, // red
29 0.0f, // green
30 0.0f, // blue
31 1.0f); // alpha
32 // Now we can start the event loop, poll for events and draw objects.
33 sf::Event event{ };
34 while (window.isOpen()) {
35 while (window.pollEvent(event)) {
36 if (event.type == sf::Event::Closed)
37 window.close;
38 }
39 // Tell OpenGL to clear the color buffer
40 // and the depth buffer, this will clear our window.
41 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
42 // Flip front- and backbuffer.
43 window.display();
44 }
45 return 0;
46}
Loading Shaders ¶
After creating a window and our event loop we should create a function, that sets up our shader program.
1GLuint createShaderProgram(const std::string& vertexShaderPath,
2 const std::string& fragmentShaderPath) {
3 // Load the vertex shader source.
4 std::stringstream ss{ };
5 std::string vertexShaderSource{ };
6 std::string fragmentShaderSource{ };
7 std::ifstream file{ vertexShaderPath };
8 if (file.is_open()) {
9 ss << file.rdbuf();
10 vertexShaderSource = ss.str();
11 file.close();
12 }
13 // Clear the stringstream and load the fragment shader source.
14 ss.str(std::string{ });
15 file.open(fragmentShaderPath);
16 if (file.is_open()) {
17 ss << file.rdbuf();
18 fragmentShaderSource = ss.str();
19 file.close();
20 }
21 // Create the program.
22 GLuint program = glCreateProgram();
23 // Create the shaders.
24 GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
25 GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
26 // Now we can load the shader source into the shader objects and compile them.
27 // Because glShaderSource() wants a const char* const*,
28 // we must first create a const char* and then pass the reference.
29 const char* cVertexSource = vertexShaderSource.c_str();
30 glShaderSource(vertexShader, // shader
31 1, // number of strings
32 &cVertexSource, // strings
33 nullptr); // length of strings (nullptr for 1)
34 glCompileShader(vertexShader);
35 // Now we have to do the same for the fragment shader.
36 const char* cFragmentSource = fragmentShaderSource.c_str();
37 glShaderSource(fragmentShader, 1, &cFragmentSource, nullptr);
38 glCompileShader(fragmentShader);
39 // After attaching the source and compiling the shaders,
40 // we attach them to the program;
41 glAttachShader(program, vertexShader);
42 glAttachShader(program, fragmentShader);
43 glLinkProgram(program);
44 // After linking the shaders we should detach and delete
45 // them to prevent memory leak.
46 glDetachShader(program, vertexShader);
47 glDetachShader(program, fragmentShader);
48 glDeleteShader(vertexShader);
49 glDeleteShader(fragmentShader);
50 // With everything done we can return the completed program.
51 return program;
52}
If you want to check the compilation log you can add the following between glCompileShader()
and glAttachShader()
.
1GLint logSize = 0;
2std::vector<GLchar> logText{ };
3glGetShaderiv(vertexShader, // shader
4 GL_INFO_LOG_LENGTH, // requested parameter
5 &logSize); // return object
6if (logSize > 0) {
7 logText.resize(logSize);
8 glGetShaderInfoLog(vertexShader, // shader
9 logSize, // buffer length
10 &logSize, // returned length
11 logText.data()); // buffer
12 std::cout << logText.data() << std::endl;
13}
The same is possible after glLinkProgram()
, just replace glGetShaderiv()
with glGetProgramiv()
and glGetShaderInfoLog()
with glGetProgramInfoLog()
.
1// Now we can create a shader program with a vertex and a fragment shader.
2// ...
3glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
4
5GLuint program = createShaderProgram("vertex.glsl", "fragment.glsl");
6
7sf::Event event{ };
8// ...
9// We also have to delete the program at the end of the application.
10// ...
11 }
12 glDeleteProgram(program);
13 return 0;
14}
15// ...
Of course we have to create the vertex and fragment shader before we can load them, so lets create two basic shaders.
Vertex Shader
1// Declare which version of GLSL we use.
2// Here we declare, that we want to use the OpenGL 3.3 version of GLSL.
3#version 330 core
4// At attribute location 0 we want an input variable of type vec3,
5// that contains the position of the vertex.
6// Setting the location is optional, if you don't set it you can ask for the
7// location with glGetAttribLocation().
8layout(location = 0) in vec3 position;
9// Every shader starts in it's main function.
10void main() {
11 // gl_Position is a predefined variable that holds
12 // the final vertex position.
13 // It consists of a x, y, z and w coordinate.
14 gl_Position = vec4(position, 1.0);
15}
Fragment Shader
1#version 330 core
2// The fragment shader does not have a predefined variable for
3// the vertex color, so we have to define a output vec4,
4// that holds the final vertex color.
5out vec4 outColor;
6
7void main() {
8 // We simply set the output color to red.
9 // The parameters are red, green, blue and alpha.
10 outColor = vec4(1.0, 0.0, 0.0, 1.0);
11}
VAO and VBO ¶
Now we need to define some vertex position we can pass to our shaders. Lets define a simple 2D quad.
1// The vertex data is defined in a counter-clockwise way,
2// as this is the default front face.
3std::vector<float> vertexData {
4 -0.5f, 0.5f, 0.0f,
5 -0.5f, -0.5f, 0.0f,
6 0.5f, -0.5f, 0.0f,
7 0.5f, 0.5f, 0.0f
8};
9// If you want to use a clockwise definition, you can simply call
10glFrontFace(GL_CW);
11// Next we need to define a Vertex Array Object (VAO).
12// The VAO stores the current state while its active.
13GLuint vao = 0;
14glGenVertexArrays(1, &vao);
15glBindVertexArray(vao);
16// With the VAO active we can now create a Vertex Buffer Object (VBO).
17// The VBO stores our vertex data.
18GLuint vbo = 0;
19glGenBuffers(1, &vbo);
20glBindBuffer(GL_ARRAY_BUFFER, vbo);
21// For reading and copying there are also GL_*_READ and GL_*_COPY,
22// if your data changes more often use GL_DYNAMIC_* or GL_STREAM_*.
23glBufferData(GL_ARRAY_BUFFER, // target buffer
24 sizeof(vertexData[0]) * vertexData.size(), // size
25 vertexData.data(), // data
26 GL_STATIC_DRAW); // usage
27// After filling the VBO link it to the location 0 in our vertex shader,
28// which holds the vertex position.
29// ...
30// To ask for the attribute location, if you haven't set it:
31GLint posLocation = glGetAttribLocation(program, "position");
32// ..
33glEnableVertexAttribArray(0);
34glVertexAttribPointer(0, 3, // location and size
35 GL_FLOAT, // type of data
36 GL_FALSE, // normalized (always false for floats)
37 0, // stride (interleaved arrays)
38 nullptr); // offset (interleaved arrays)
39// Everything should now be saved in our VAO and we can unbind it and the VBO.
40glBindVertexArray(0);
41glBindBuffer(GL_ARRAY_BUFFER, 0);
42// Now we can draw the vertex data in our render loop.
43// ...
44glClear(GL_COLOR_BUFFER_BIT);
45// Tell OpenGL we want to use our shader program.
46glUseProgram(program);
47// Binding the VAO loads the data we need.
48glBindVertexArray(vao);
49// We want to draw a quad starting at index 0 of the VBO using 4 indices.
50glDrawArrays(GL_QUADS, 0, 4);
51glBindVertexArray(0);
52window.display();
53// ...
54// Ofcource we have to delete the allocated memory for the VAO and VBO at
55// the end of our application.
56// ...
57glDeleteBuffers(1, &vbo);
58glDeleteVertexArrays(1, &vao);
59glDeleteProgram(program);
60return 0;
61// ...
You can find the current code here: OpenGL - 1.
More VBO’s and Color ¶
Let’s create another VBO for some colors.
1std::vector<float> colorData {
2 1.0f, 0.0f, 0.0f,
3 0.0f, 1.0f, 0.0f,
4 0.0f, 0.0f, 1.0f,
5 1.0f, 1.0f, 0.0f
6};
Next we can simply change some previous parameters to create a second VBO for our colors.
1// ...
2GLuint vbo[2];
3glGenBuffers(2, vbo);
4glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
5// ...
6glDeleteBuffers(2, vbo);
7/ ...
8// With these changes made we now have to load our color data into the new VBO
9// ...
10glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
11
12glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
13glBufferData(GL_ARRAY_BUFFER, sizeof(colorData[0]) * colorData.size(),
14 colorData.data(), GL_STATIC_DRAW);
15glEnableVertexAttribArray(1);
16glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
17
18glBindVertexArray(0);
19// ...
Next we have to change our vertex shader to pass the color data to the fragment shader.
Vertex Shader
1#version 330 core
2
3layout(location = 0) in vec3 position;
4// The new location has to differ from any other input variable.
5// It is the same index we need to pass to
6// glEnableVertexAttribArray() and glVertexAttribPointer().
7layout(location = 1) in vec3 color;
8
9out vec3 fColor;
10
11void main() {
12 fColor = color;
13 gl_Position = vec4(position, 1.0);
14}
Fragment Shader
1#version 330 core
2
3in vec3 fColor;
4
5out vec4 outColor;
6
7void main() {
8 outColor = vec4(fColor, 1.0);
9}
We define a new input variable color
which represents our color data, this data
is passed on to fColor
, which is an output variable of our vertex shader and
becomes an input variable for our fragment shader.
It is important that variables passed between shaders have the exact same name
and type.
Handling VBO’s ¶
1// If you want to completely clear and refill a VBO use glBufferData(),
2// just like we did before.
3// ...
4// There are two mains ways to update a subset of a VBO's data.
5// To update a VBO with existing data
6std::vector<float> newSubData {
7 -0.25f, 0.5f, 0.0f
8};
9glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
10glBufferSubData(GL_ARRAY_BUFFER, // target buffer
11 0, // offset
12 sizeof(newSubData[0]) * newSubData.size(), // size
13 newSubData.data()); // data
14// This would update the first three values in our vbo[0] buffer.
15// If you want to update starting at a specific location just set the second
16// parameter to that value and multiply by the types size.
17// ...
18// If you are streaming data, for example from a file,
19// it is faster to directly pass the data to the buffer.
20// Other access values are GL_READ_ONLY and GL_READ_WRITE.
21glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
22// You can static_cast<float*>() the void* to be more safe.
23void* Ptr = glMapBuffer(GL_ARRAY_BUFFER, // buffer to map
24 GL_WRITE_ONLY); // access to buffer
25memcpy(Ptr, newSubData.data(), sizeof(newSubData[0]) * newSubData.size());
26// To copy to a specific location add a destination offset to memcpy().
27glUnmapBuffer(GL_ARRAY_BUFFER);
28// ...
29// There is also a way to copy data from one buffer to another,
30// If we have two VBO's vbo[0] and vbo[1], we can copy like so
31// You can also read from GL_ARRAY_BUFFER.
32glBindBuffer(GL_COPY_READ_BUFFER, vbo[0]);
33// GL_COPY_READ_BUFFER and GL_COPY_WRITE_BUFFER are specifically for
34// copying buffer data.
35glBindBuffer(GL_COPY_WRITE_BUFFER, vbo[1]);
36glCopyBufferSubData(GL_COPY_READ_BUFFER, // read buffer
37 GL_COPY_WRITE_BUFFER, // write buffer
38 0, 0, // read and write offset
39 sizeof(vbo[0]) * 3); // copy size
40// This will copy the first three elements from vbo[0] to vbo[1].
Uniforms ¶
Fragment Shader
1// Uniforms are variables like in and out, however,
2// we can change them easily by passing new values with glUniform().
3// Lets define a time variable in our fragment shader.
4#version 330 core
5// Unlike a in/out variable we can use a uniform in every shader,
6// without the need to pass it to the next one, they are global.
7// Don't use locations already used for attributes!
8// Uniform layout locations require OpenGL 4.3!
9layout(location = 10) uniform float time;
10
11in vec3 fColor;
12
13out vec4 outColor;
14
15void main() {
16 // Create a sine wave from 0 to 1 based on the time passed to the shader.
17 float factor = (sin(time * 2) + 1) / 2;
18 outColor = vec4(fColor.r * factor, fColor.g * factor, fColor.b * factor, 1.0);
19}
Back to our source code.
1// If we haven't set the layout location, we can ask for it.
2GLint timeLocation = glGetUniformLocation(program, "time");
3// ...
4// Also we should define a Timer counting the current time.
5sf::Clock clock{ };
6// In out render loop we can now update the uniform every frame.
7 // ...
8 window.display();
9 glUniform1f(10, // location
10 clock.getElapsedTime().asSeconds()); // data
11}
12// ...
With the time getting updated every frame the quad should now be changing from fully colored to pitch black. There are different types of glUniform() you can find simple documentation here: glUniform - OpenGL Refpage
Indexing and IBO’s ¶
Element Array Buffers or more commonly Index Buffer Objects (IBO) allow us to use the same vertex data again which makes drawing a lot easier and faster. here’s an example:
1// Lets create a quad from two rectangles.
2// We can simply use the old vertex data from before.
3// First, we have to create the IBO.
4// The index is referring to the first declaration in the VBO.
5std::vector<unsigned int> iboData {
6 0, 1, 2,
7 0, 2, 3
8};
9// That's it, as you can see we could reuse 0 - the top left
10// and 2 - the bottom right.
11// Now that we have our data, we have to fill it into a buffer.
12// Note that this has to happen between the two glBindVertexArray() calls,
13// so it gets saved into the VAO.
14GLuint ibo = 0;
15glGenBufferrs(1, &ibo);
16glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
17glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iboData[0]) * iboData.size(),
18 iboData.data(), GL_STATIC_DRAW);
19// Next in our render loop, we replace glDrawArrays() with:
20glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr);
21// Remember to delete the allocated memory for the IBO.
You can find the current code here: OpenGL - 2.
Textures ¶
To load out texture we first need a library that loads the data, for simplicity I will be using SFML, however there are a lot of librarys for loading image data.
1// Lets save we have a texture called "my_tex.tga", we can load it with:
2sf::Image image;
3image.loadFromFile("my_tex.tga");
4// We have to flip the texture around the y-Axis, because OpenGL's texture
5// origin is the bottom left corner, not the top left.
6image.flipVertically();
7// After loading it we have to create a OpenGL texture.
8GLuint texture = 0;
9glGenTextures(1, &texture);
10glBindTexture(GL_TEXTURE_2D, texture);
11// Specify what happens when the coordinates are out of range.
12glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
13glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
14// Specify the filtering if the object is very large.
15glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
16glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
17// Load the image data to the texture.
18glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y,
19 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr());
20// Unbind the texture to prevent modifications.
21glBindTexture(GL_TEXTURE_2D, 0);
22// Delete the texture at the end of the application.
23// ...
24glDeleteTextures(1, &texture);
Of course there are more texture formats than only 2D textures,
You can find further information on parameters here:
glBindTexture - OpenGL Refpage
glTexImage2D - OpenGL Refpage
glTexParameter - OpenGL Refpage
1// With the texture created, we now have to specify the UV,
2// or in OpenGL terms ST coordinates.
3std::vector<float> texCoords {
4 // The texture coordinates have to match the triangles/quad
5 // definition.
6 0.0f, 1.0f, // start at top-left
7 0.0f, 0.0f, // go round counter-clockwise
8 1.0f, 0.0f,
9 1.0f, 1.0f // end at top-right
10};
11// Now we increase the VBO's size again just like we did for the colors.
12// ...
13GLuint vbo[3];
14glGenBuffers(3, vbo);
15// ...
16glDeleteBuffers(3, vbo);
17// ...
18// Load the texture coordinates into the new buffer.
19glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
20glBufferData(GL_ARRAY_BUFFER, sizeof(texCoords[0]) * texCoords.size(),
21 texCoords.data(), GL_STATIC_DRAW);
22glEnableVertexAttribArray(2);
23glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
24// Because the VAO does not store the texture we have to bind it before drawing.
25// ...
26glBindVertexArray(vao);
27glBindTexture(GL_TEXTURE_2D, texture);
28glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr);
29// ...
Change the shaders to pass the data to the fragment shader.
Vertex Shader
1#version 330 core
2
3layout(location = 0) in vec3 position;
4layout(location = 1) in vec3 color;
5layout(location = 2) in vec2 texCoords;
6
7out vec3 fColor;
8out vec2 fTexCoords;
9
10void main() {
11 fColor = color;
12 fTexCoords = texCoords;
13 gl_Position = vec4(position, 1.0);
14}
Fragment Shader
1#version 330 core
2// sampler2D represents our 2D texture.
3uniform sampler2D tex;
4uniform float time;
5
6in vec3 fColor;
7in vec2 fTexCoords;
8
9out vec4 outColor;
10
11void main() {
12 // texture() loads the current texture data at the specified texture coords,
13 // then we can simply multiply them by our color.
14 outColor = texture(tex, fTexCoords) * vec4(fColor, 1.0);
15}
You can find the current code here: OpenGL - 3
Matrix Transformation ¶
Vertex Shader
1#version 330 core
2
3layout(location = 0) in vec3 position;
4layout(location = 1) in vec3 color;
5layout(location = 2) in vec2 texCoords;
6// Create 2 4x4 matricies, 1 for the projection matrix
7// and 1 for the model matrix.
8// Because we draw in a static scene, we don't need a view matrix.
9uniform mat4 projection;
10uniform mat4 model;
11
12out vec3 fColor;
13out vec2 fTexCoords;
14
15void main() {
16 fColor = color;
17 fTexCoords = texCoords;
18 // Multiplay the position by the model matrix and then by the
19 // projection matrix.
20 // Beware order of multiplication for matricies!
21 gl_Position = projection * model * vec4(position, 1.0);
22}
In our source we now need to change the vertex data, create a model- and a projection matrix.
1// The new vertex data, counter-clockwise declaration.
2std::vector<float> vertexData {
3 0.0f, 1.0f, 0.0f, // top left
4 0.0f, 0.0f, 0.0f, // bottom left
5 1.0f, 0.0f, 0.0f, // bottom right
6 1.0f, 1.0f, 0.0f // top right
7};
8// Request the location of our matricies.
9GLint projectionLocation = glGetUniformLocation(program, "projection");
10GLint modelLocation = glGetUniformLocation(program, "model");
11// Declaring the matricies.
12// Orthogonal matrix for a 1024x768 window.
13std::vector<float> projection {
14 0.001953f, 0.0f, 0.0f, 0.0f,
15 0.0f, -0.002604f, 0.0f, 0.0f,
16 0.0f, 0.0f, -1.0f, 0.0f,
17 -1.0f, 1.0f, 0.0f, 1.0f
18};
19// Model matrix translating to x 50, y 50
20// and scaling to x 200, y 200.
21std::vector<float> model {
22 200.0f, 0.0f, 0.0f, 0.0f,
23 0.0f, 200.0f, 0.0f, 0.0f,
24 0.0f, 0.0f, 1.0f, 0.0f,
25 50.0f, 50.0f, 0.0f, 1.0f
26};
27// Now we can send our calculated matricies to the program.
28glUseProgram(program);
29glUniformMatrix4fv(projectionLocation, // location
30 1, // count
31 GL_FALSE, // transpose the matrix
32 projection.data()); // data
33glUniformMatrix4fv(modelLocation, 1, GL_FALSE, model.data());
34glUseProgram(0);
35// The glUniform*() calls have to be done, while the program is bound.
The application should now display the texture at the defined position and size.
You can find the current code here: OpenGL - 4
1// There are many math librarys for OpenGL, which create
2// matricies and vectors, the most used in C++ is glm (OpenGL Mathematics).
3// Its a header only library.
4// The same code using glm would look like:
5glm::mat4 projection{ glm::ortho(0.0f, 1024.0f, 768.0f, 0.0f) };
6glUniformMatrix4fv(projectionLocation, 1, GL_FALSE,
7 glm::value_ptr(projection));
8// Initialise the model matrix to the identity matrix, otherwise every
9// multiplication would be 0.
10glm::mat4 model{ 1.0f };
11model = glm::translate(model, glm::vec3{ 50.0f, 50.0f, 0.0f });
12model = glm::scale(model, glm::vec3{ 200.0f, 200.0f, 0.0f });
13glUniformMatrix4fv(modelLocation, 1, GL_FALSE,
14 glm::value_ptr(model));
Geometry Shader ¶
Geometry shaders were introduced in OpenGL 3.2, they can produce vertices that are send to the rasterizer. They can also change the primitive type e.g. they can take a point as an input and output other primitives. Geometry shaders are inbetween the vertex and the fragment shader.
Vertex Shader
1#version 330 core
2
3layout(location = 0) in vec3 position;
4layout(location = 1) in vec3 color;
5// Create an output interface block passed to the next shader stage.
6// Interface blocks can be used to structure data passed between shaders.
7out VS_OUT {
8 vec3 color;
9} vs_out;
10
11void main() {
12 vs_out.color = color
13 gl_Position = vec4(position, 1.0);
14}
Geometry Shader
1#version 330 core
2// The geometry shader takes in points.
3layout(points) in;
4// It outputs a triangle every 3 vertices emitted.
5layout(triangle_strip, max_vertices = 3) out;
6// VS_OUT becomes an input variable in the geometry shader.
7// Every input to the geometry shader in treated as an array.
8in VS_OUT {
9 vec3 color;
10} gs_in[];
11// Output color for the fragment shader.
12// You can also simply define color as 'out vec3 color',
13// If you don't want to use interface blocks.
14out GS_OUT {
15 vec3 color;
16} gs_out;
17
18void main() {
19 // Each emit calls the fragment shader, so we set a color for each vertex.
20 gs_out.color = mix(gs_in[0].color, vec3(1.0, 0.0, 0.0), 0.5);
21 // Move 0.5 units to the left and emit the new vertex.
22 // gl_in[] is the current vertex from the vertex shader, here we only
23 // use 0, because we are receiving points.
24 gl_Position = gl_in[0].gl_Position + vec4(-0.5, 0.0, 0.0, 0.0);
25 EmitVertex();
26 gs_out.color = mix(gs_in[0].color, vec3(0.0, 1.0, 0.0), 0.5);
27 // Move 0.5 units to the right and emit the new vertex.
28 gl_Position = gl_in[0].gl_Position + vec4(0.5, 0.0, 0.0, 0.0);
29 EmitVertex();
30 gs_out.color = mix(gs_in[0].color, vec3(0.0, 0.0, 1.0), 0.5);
31 // Move 0.5 units up and emit the new vertex.
32 gl_Position = gl_in[0].gl_Position + vec4(0.0, 0.75, 0.0, 0.0);
33 EmitVertex();
34 EndPrimitive();
35}
Fragment Shader
1in GS_OUT {
2 vec3 color;
3} fs_in;
4
5out vec4 outColor;
6
7void main() {
8 outColor = vec4(fs_in.color, 1.0);
9}
If you now store a single point with a single color in a VBO and draw them, you should see a triangle, with your color mixed half way between red, green and blue on each vertex.
Quotes ¶
Books ¶
- OpenGL Superbible - Fifth Edition (covering OpenGL 3.3)
- OpenGL Programming Guide - Eighth Edition (covering OpenGL 4.3)