How to use OpenGL in C++?
When we hear the term OpenGL, what do we understand by this term, well this term simply means Open Graphic Library which tends to be a very powerful and engaging tool for 2D and 3D graphics. It opens a lot of doors and huge possibilities for a lot of people who want to make it big in the creative field.
When we work with OpenGL and combine it with C++, it becomes a very powerful tool for several functions. This basically lends a powerful hand to developers to make such interesting and vivid games that keep you on the hook from the beginning, and their UI is what pulls the gamers or the users at the very initial stage. It helps developers to create very powerful apps and games. In this tutorial, we will try to figure out and understand how we can use the graphics library to yield powerful results and understand them in little depth as well. The main agenda of OpenGL is to help the new developers understand its concept and bring their ideas to life.
![How to use OpenGL in C++?](https://static.tutorialandexample.com/cpp/how-to-use-open-gl-in-cpp1.png)
Understanding the Basics
Before we move any further and start coding, we need to understand the core elements and the basics of OpenGL. When we talk about OpenGL, it simply means that we have a certain rule book according to which we can create certain 2D or 3D pictures and images. It basically gives developers an edge in how to make things better, how to work with the graphic card available on computers, and how to make that work and cool graphics and pictures appear on the screen. In this tutorial, we will see implementation as well as how to use it in C++.
Setting Up the Environment
In order to start using OpenGL in C++, we need to first make sure that our computer is ready to work with OpenGL. First, we need to download a special library called the GLUT or the GLFW. This kind of library makes it very easy for Windows to handle large amounts of inputs and also helps in working with different kinds of computers. After we have installed the library, we have to make sure that we have a special entity installed on the computer, which is the C++ compiler; there are several different compilers present on the internet, so we can easily choose the one depending on the requirements of our system. Once we have installed the compiler, we can move ahead and start writing our code with OpenGL.
Creating a Window
The very first thing that we do when we start writing our code with OpenGL is to make sure that we are creating a window to make sure that we have something to display our pictures on. With the help of the libraries mentioned above in the tutorial, we can easily create our window with only a few lines of code. After this, we can easily explore and draw different kinds of graphics on our screen.
Features
In this section of the tutorial, we are going to see some features or characteristics of OpenGL. Let's look at them one by one: -
Cross Platform Compatibility
OpenGL works on different systems, such as Windows, MacOS, and Linux, so developers can easily make graphics on any device or system. We don't have to depend on any one platform. We can easily make them even on mobile devices.
Hardware
OpenGL uses the system's existing power to make graphics, such as using the graphics card in the system to make graphics run faster and even better on the computer. This, in fact, helps programs that might contain graphics and other things look even better and also helps them run smoothly.
Flexible Rendering Pipeline
It also helps developers feel powerful as it leverages their power to dominate how they want to design the graphics at different stages of development. It helps in adding colours to the features of graphics, it helps us in designing, and it also makes sure that we can decide every little detail of the graphics.
Support 2D and 3D Graphics
OpenGL helps us create simple and complex objects or graphics in both 2D and 3D on the window screen. Using this, we can create basic graphics such as points, lines or circles as well as more complex ones such as 3D graphics. This becomes very useful when we have to make scientific visuals, games or other more important stuff.
Language Support
OpenGL contains a special language known as the GLSL, which stands for shading language. It helps developers in creating good stuff when we are trying to create graphics on the screen. With the help of this technology, we can easily manipulate and control the degrees of the shadows that we fix in our graphics or visuals.
Example
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
// Vertex shader source code
const char* vertexShaderSource = R"(
#version 330 core
layout (location = 0) in vec3 aPos;
void main() {
gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
}
)";
// Fragment shader source code
const char* fragmentShaderSource = R"(
#version 330 core
out vec4 FragColor;
void main() {
FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);
}
)";
int main() {
// Initialize GLFW
if (!glfwInit()) {
std::cerr << "Failed to initialize GLFW" << std::endl;
return -1;
}
// Create a windowed mode window and its OpenGL context
GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGL Window", NULL, NULL);
if (!window) {
std::cerr << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
// Make the window's context current
glfwMakeContextCurrent(window);
// Initialize GLEW to enable OpenGL functionality
if (glewInit() != GLEW_OK) {
std::cerr << "Failed to initialize GLEW" << std::endl;
return -1;
}
// Define the vertices of the triangle
float vertices[] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
// Create a Vertex Buffer Object (VBO) to store the vertex data
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Create a Vertex Array Object (VAO) to store the vertex attribute configuration
GLuint VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// Compile and link the vertex shader
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
// Check for vertex shader compilation errors
GLint success;
GLchar infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cerr << "Vertex shader compilation failed: " << infoLog << std::endl;
return -1;
}
// Compile and link the fragment shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// Check for fragment shader compilation errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cerr << "Fragment shader compilation failed: " << infoLog << std::endl;
return -1;
}
// Create and link the shader program
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// Check for shader program linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cerr << "Shader program linking failed: " << infoLog << std::endl;
return -1;
}
// Use the shader program
glUseProgram(shaderProgram);
// Render loop
while (!glfwWindowShouldClose(window)) {
// Clear the color buffer
glClear(GL_COLOR_BUFFER_BIT);
// Draw the triangle
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
// Swap front and back buffers
glfwSwapBuffers(window);
// Poll for and process events
glfwPollEvents();
}
// Clean up resources
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteProgram(shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// Terminate GLFW
glfwTerminate();
return 0;
}
Output:
![How to use OpenGL in C++?](https://static.tutorialandexample.com/cpp/how-to-use-open-gl-in-cpp2.png)
Example 2:
#include <iostream>
#include <cmath>
#include <GL/glut.h> // Assuming OpenGL and GLUT are properly installed and configured
#define pi 3.142857
void myInit() {
glClearColor(0.0, 0.0, 0.0, 1.0);
glColor3f(0.0, 1.0, 0.0);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-780, 780, -420, 420);
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
float x, y, i;
for (i = 0; i < (2 * pi); i += 0.001) {
x = 200 * cos(i);
y = 200 * sin(i);
glVertex2f(x, y);
}
glEnd();
glFlush();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(1366, 768);
glutInitWindowPosition(0, 0);
glutCreateWindow("Circle Drawing");
myInit();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
Output:
![How to use OpenGL in C++?](https://static.tutorialandexample.com/cpp/how-to-use-open-gl-in-cpp3.png)
Conclusion
As we draw curtains on our exploration of OpenGL, we just want to say that if we use OpenGL and that too with the combination of C++, then we can make really cool graphics and stuff, and this can make a very good impact while creating games and visuals. To start your graphical journey, I recommend learning the basics from this tutorial and starting to make visually appealing graphics. So, jump in and let your inner creativity shine and make cool graphics.ce more for cache memory loading following bucket sorting.language..