Following are the step needed to render any Mesh on to the screen:
- Set vertex and fragment shader program(instruction) on to the render pipeline.
- Load mesh data onto the RAM.
- Pass Mesh data from CPU to GPU/Render pipeline for rendering.
- Now all the mesh will be rendered by the same shader program passed on step 1, until we set a new shader program.
Working of shader:
Even though we are running this code for the web the same code will also run for other platforms that use OpenGL.
Vertex Shader:
Its main function is to convert the vertices’ 3D coordinates from the local space of the model to the 2D screen space where they will be shown.
The vertex shader’s primary function is to transform vertex locations. This entails using transformations such as translation, rotation, and scaling to position the 3D object within the 3D scene.
- As in c/c++ we have a starting point main() function, same as in the shader we have a starting point main() function for vertex shader.
void main() {
} - position : This is the mesh vertex xyz coordinate position in object space.
- modelViewMatrix: Move 3D position from model(object) space to world(scene) space.
- projectionMatrix: Convert 3D coordinates to 2D screen coordinates (screen space). This transformation takes into consideration perspective, making items farther away from the camera appear smaller.
- gl_Position: is a predefined vec4 variable defined by OpenGL which is available only in the vertex shader. and used to hold processed vertex position.
Fragment Shader:
Following program will render each pixel of the object to red.
gl_FragColor: It’s a built-in global variable in glsl that will be used to determine the colour of each pixel.
Try changing colour to green or blue.
gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0); // rgba