Before all
OpenGL drawing process
- Read obj file from vertices vector
- Vertex Buffer Object (VBO)
- Generate vertex buffer object
- Copy the vertices vector to the VBO (reside in GPU memory)
- First need to bind the buffer using
glBindBuffer
- Then copy the data using
glBufferData
to load the vertices data to the buffer object - After finishing the buffer loading, unbind using
glBindBuffer
with 0 as the object id.
- First need to bind the buffer using
- Vertex attribute specification
- Tell the OpenGL how to interpret the buffer data, which can be used in shader language
glVertexAttribPointer
: specifies the start and stride of an attributeglEnableVertexAttribArray(NUM)
: enable theNUMth
attribute- In GLSL, use
layout(location = 0)
to load the attribute 0
- Vertex Array Object (VAO)
- Store vertex specs and which VBO to use
- Use
glGenVertexArrays
to generate id glBindVertexArray
to bind and unbind- The VBO will bind to the VAO when specifying the buffer type to be
GL_ARRAY_BUFFER
, need to bind VBO after binding VAO
- Vertex shader
- write to
gl_Position
variable for the position of each vertex - Get input from the VAO
- Can also have output
#version 330 core layout (location = 0) in vec3 aPos; // the first attribute layout (location = 1) in vec3 aColor; // the second attribute out vec3 ourColor; // pass the color data to the fragment shader void main() { gl_Position = vec4(aPos, 1.0); // output ourColor = aColor; };
- write to
- Fragment shader
- Compute the color of the pixels in RGBA
- Also lighting and texture
version 330 core out vec4 FragColor; // output color in vec3 ourColor; // vertex color, passed by the vertex shader void main() { FragColor = vec4(ourColor, 1.0f); }
- Shader Compiling and Linking
- Compile shader source code at run time
glCreateShader
glShaderSource
glCompileShader
- Link shaders outputs and inputs
glCreateProgram
glAttachShader
: attach shader to the programglLinkProgram
glDeleteShader
: once linked, no longer needed
glUseProgram
: use the linked shader program
- Compile shader source code at run time
- Drawing!
glDrawArrays(type, first, count)
: draw the surfaces using arrays of vertices, normals, and colors starting from first and end after drawingcount
vertices, along with type specifiedglDrawElements
: draw VAO using the element buffer object (EBO), which specifies the indices of the vertices to form surfaces and draw.
OpenGL Shader
glGetUniformLocation
: get the location of the uniform variableglUniformMatrix4fv
: send the uniform value to the shader