PyOpenGL Tutorial – Creating Graphics in Python

In this tutorial, we will be going through what is PyOpenGL? moving on we will be creating our first PyOpenGL program. Not only that you will also be guided to extend your skills using PyOpenGL for further use.

About PyOpenGL

The pyopengl library is an implementation of OpenGL for Python. It includes bindings to the GLUT library and is able to support multiple windowing systems, including X11, Windows, and Mac OS X.

Installation:

PyOpenGL is quite easy to install, Below are some of the methods that you can select according to your device’s Operating System.

Windows, Linux, and Mac:

Assuming that Python is already installed on your machine if it is not then you can walk through this Python installation guide. You can install PyOpenGL using Pip which is a Python package manager.

Open your Command Prompt and use the command

pip install PyOpenGL

Just to know We have another optimized version PyOpenGL library named “PyOpenGL-accelerate” which uses different Cython accelerator modules to speed up the process.

Use the following command to install “PyOpenGL-accelerate”.

pip install PyOpenGL-accelerate

To manually download PyOpenGL. Check out this site. Just make sure to download the bit version according to the Operating System.

To avoid any unnecessary errors we also need NumPy and PIL(Python Imaging Library) because PyOpenGL programs sometimes need to work with arrays and image data.

# for Numpy
Pip install numpy
# for PIL
Pip install PIL

Getting Started:

We are going to start with the basic concepts and then move on to the complex program, in
which we will animate a primitive shape.

PyOpenGL is a Python binding for OpenGL that is used to render 2D and 3D graphics. PyOpenGL is cross-platform which means it can be used on Popular OS like Windows, Mac
Linux, etc.

For this tutorial, we are going to use “glfw with PyOpenGL”. GLFW is a simple crossplatform
API for PyOpenGL which is going to help us in creating the main windows, in which the
graphics will be rendered

Note: use the command “pip install glfw” to install glfw on your machine.

Drawing a Triangle:

STEP 1:

import glfw
from OpenGL.GL import 
import numpy as np

First, we are going to make some imports that include glfw, NumPy, and OpenGL.GL. Here “
* ” means import everything. The reason why we need NumPy in PyOpenGL because it
cannot work with simple Python lists. So these lists need to be converted into NumPy arrays with a specific datatype.

Step 2:

glfw.init()
# creating a window with 800 width and 600 height
window = glfw.create_window(800,600,"PyOpenGL Triangle", None, None)
glfw.set_window_pos(window,400,200)
glfw.make_context_current(window)

Every Painter needs a canvas to draw his/her painting similarly we need to create a window
on which we are going to render 2D or 3D graphics.

● glfw.init() is used for initialization. Without initialization, we cannot access its functions.
● “glfw.create_window()” function is utilized in creating a window. This function takes in multiple arguments like “width, height, and Name of the window”.

All of the above are descriptive, no need for more explanation.

● “glfw.set_window_pos()” is used to set the position of a specific window of the device’s screen. This method requires three arguments “window name, x-axis, y-axis”.
● “glfw.make_context_current()” takes the window augment for current context.

Step3:

Here we created the vertices of our triangle in the form of a list and then convert it into a NumPy array.

vertices = [-0.5, -0.5, 0.0,
             0.5, -0.5,0.0,
             0.0, 0.5, 0.0]
v = np.array(vertices,dtype=np.float32)

Each of these three points in the list corresponds to the x,y,z location on a plane.

Left vertex = -0.5 , -0.5 ,0.0 (x,y,z)
Right vertex = 0.5 , -0.5, 0.0 (x,y,z)
Top vertex = 0.0, 0.5, 0.0 (x,y,z)

As our triangle is 2d, so the z-axis is 0.

Have a look at this pictorial representation of a triangle on the canvas. The center point of
the triangle is (0,0).

triangle

Next, we converted this list into a NumPy array using the numpy.array() function.

Step 4 :

glEnableClientState(GL_VERTEX_ARRAY)
glVertexPointer(3, GL_FLOAT,0,v)
# setting color for background
glClearColor(0,0,0,0

glEnableClientState() is used to enable client-side capabilities.

We have set the background color using glClearColor(0,0,0,0). Which takes in R,G,B,A as an argument.

Step 5:

while not glfw.window_should_close(window):

   glfw.poll_events()
   glClear(GL_COLOR_BUFFER_BIT)

   glDrawArrays(GL_TRIANGLES,0,3)
   glfw.swap_buffers(window)

glfw.terminate()

Next, we have created a loop that will execute until the window we created is not closed.

● glfw.poll_events() is used to check for events applied to windows.
● glClear() is going to clean the screen every time the loop runs, to ensure that there is
nothing on the screen before we render graphics.
● And finally, the glDrawArrays() that is going to draw triangles.

Syntax:

glDrawArray(Mode, first, count)
Here count is the number of indices to be rendered. In our case, it is 3.

Full Code:

import glfw
from OpenGL.GL import *
import numpy as np

# initializing glfw
glfw.init()

# creating a window with 800 width and 600 height
window = glfw.create_window(800,600,"PyOpenGL Triangle", None, None)
glfw.set_window_pos(window,400,200)
glfw.make_context_current(window)

vertices = [-0.5, -0.5, 0.0,
             0.5, -0.5,0.0,
             0.0, 0.5, 0.0]

v = np.array(vertices,dtype=np.float32)

# for drawing a colorless triangle
glEnableClientState(GL_VERTEX_ARRAY)
glVertexPointer(3, GL_FLOAT,0,v)

# setting color for background
glClearColor(0,0,0,0)

while not glfw.window_should_close(window):

glfw.poll_events()
glClear(GL_COLOR_BUFFER_BIT)

glDrawArrays(GL_TRIANGLES,0,3)
glfw.swap_buffers(window)

glfw.terminate()

Triangle using PyOpenGL

Adding Colors and Animation:

WE have simply added a list of Colors, converted it into a NumPy array. And then we enable
the client-side using the glEnableClientState().

Next, we added an extra function glrotatef() inside the while loop for animation.

Syntax:

glrotatef(angle,x ,y ,z)

import glfw
from OpenGL.GL import *
import numpy as np

glfw.init()

window = glfw.create_window(800,600,"PyOpenGL Triangle", None, None)
glfw.set_window_pos(window,400,200)
glfw.make_context_current(window)

vertices = [-0.5, -0.5, 0.0,
             0.5, -0.5,0.0,
             0.0, 0.5, 0.0]

#list of colors
colors = [1.0, 0, 0,
          0, 1.0, 0,
          0, 0, 1.0 ]

v = np.array(vertices,dtype=np.float32)
c = np.array(colors, dtype=np.float32)

# for drawing a colorless triangle
glEnableClientState(GL_VERTEX_ARRAY)
glVertexPointer(3, GL_FLOAT,0,v)

glEnableClientState(GL_COLOR_ARRAY)
glColorPointer(3, GL_FLOAT,0,c)

# setting color for the background

glClearColor(1,1,1,0)

while not glfw.window_should_close(window):

# the function below will keep calling until the window is not
closed

glfw.poll_events()
glClear(GL_COLOR_BUFFER_BIT)

# adding animation
glRotatef(0.1,0,1,0)
glDrawArrays(GL_TRIANGLES,0,3)
glfw.swap_buffers(window)

glfw.terminate()

Conclusion:

Till now we have covered creating a simple triangle using PyOpenGL. Next, we added
another feature to the program which is going to add color and animate the triangle to rotate on the y-axis.

This tutorial is going to end here but not Your journey with PyOpenGL, I have found some
amazing resources where you can expand your knowledge and explore PyOpenGL
in-depth. Check these links below 👇.

Create an animated 3D cube in PyOpenGL.
Official Documentation

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Subscribe to get IQ's , Tutorials & Courses