18586
18586
https://ebookball.com/product/3-d-computer-graphics-mathematical-
introduction-with-opengl-1st-edition-by-medhat-rahim-19808/
https://ebookball.com/product/3d-computer-graphics-a-
mathematical-introduction-with-opengl-1st-edition-by-samuel-r-
buss-isbn-0521821037-9780521821032-14672/
https://ebookball.com/product/interactive-computer-graphics-a-
top-down-approach-with-shader-based-opengl-6th-edition-by-edward-
angel-dave-shreiner-isbn-0132545233-9780132545235-10844/
(Ebook PDF) Beginning Java Game Development & LibGDX 1st edition by
Lee Stemkoski 1484215001 9781484215005 full chapters
https://ebookball.com/product/ebook-pdf-beginning-java-game-
development-libgdx-1st-edition-by-lee-
stemkoski-1484215001-9781484215005-full-chapters-22644/
(Ebook PDF) Learn OpenGL ES For Mobile Game and Graphics Development
1st edition by Prateek Mehta 1430250542 9781430250548 full chapters
https://ebookball.com/product/ebook-pdf-learn-opengl-es-for-
mobile-game-and-graphics-development-1st-edition-by-prateek-
mehta-1430250542-9781430250548-full-chapters-22624/
https://ebookball.com/product/data-structures-and-algorithms-in-
python-1st-edition-by-michael-goodrich-roberto-tamassia-michael-
goldwasser-isbn-9781118476734-1118476735-15762/
https://ebookball.com/product/engineering-design-and-graphics-
with-solidworks-2016-1st-edition-by-james-bethune-
isbn-013450769x-9780134507699-18212/
Delphi Graphics and Game Programming Exposed with DirectX For versions
5 0 7 0 Table of Contents 1st Edition by Delphi Graphics
https://ebookball.com/product/delphi-graphics-and-game-
programming-exposed-with-directx-for-versions-5-0-7-0-table-of-
contents-1st-edition-by-delphi-graphics-11194/
Lee Stemkoski
Michael Pascale
First edition published 2022
by CRC Press
6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742
Reasonable efforts have been made to publish reliable data and information, but the author and
publisher cannot assume responsibility for the validity of all materials or the consequences of
their use. The authors and publishers have attempted to trace the copyright holders of all material
reproduced in this publication and apologize to copyright holders if permission to publish in this
form has not been obtained. If any copyright material has not been acknowledged please write
and let us know so we may rectify in any future reprint.
“The Open Access version of this book, available at www.taylorfrancis.com, has been made
available under a Creative Commons Attribution-Non Commercial-No Derivatives 4.0 license”
Trademark notice: Product or corporate names may be trademarks or registered trademarks and
are used only for identification and explanation without intent to infringe.
DOI: 10.1201/9781003181378
Authors, ix
v
vi ◾ Contents
INDEX, 331
Authors
ix
CHAPTER 1
Introduction to
Computer Graphics
DOI: 10.1201/9781003181378-1 1
2 ◾ Developing Graphics Frameworks with Python and OpenGL
at full (100%) intensity. Tese three colors are typically used since photore-
ceptors in the human eye take in those particular colors. Te triple (1, 0, 0)
represents red, (0, 1, 0) represents green, and (0, 0, 1) represents blue. Black
and white are represented by (0, 0, 0) and (1, 1, 1), respectively. Additional
colors and their corresponding triples of values specifying the amounts of
red, green, and blue (ofen called RGB values) are illustrated in Figure 1.4.
Te quality of an image depends in part on its resolution (the number of
pixels in the raster) and precision (the number of bits used for each pixel).
As each bit has two possible values (0 or 1), the number of colors that can
be expressed with N-bit precision is 2 N . For example, early video game
8
consoles with 8-bit graphics were able to display 2 = 256 diferent colors.
Monochrome displays could be said to have 1-bit graphics, while modern
displays ofen feature “high color” (16-bit, 65,536 color) or “true color”
(24-bit, more than 16 million colors) graphics. Figure 1.5 illustrates the
same image rendered with high precision but diferent resolutions, while
Figure 1.6 illustrates the same image rendered with high resolution but
diferent precision levels.
In computer science, a bufer (or data bufer, or bufer memory) is a part
of a computer's memory that serves as temporary storage for data while
it is being moved from one location to another. Pixel data is stored in a
region of memory called the framebufer. A framebufer may contain mul-
tiple bufers that store diferent types of data for each pixel. At a minimum,
the framebufer must contain a color bufer, which stores RGB values.
When rendering a 3D scene, the framebufer must also contain a depth
bufer, which stores distances from points on scene objects to the virtual
camera. Depth values are used to determine whether the various points
on each object are in front of or behind other objects (from the camera’s
perspective), and thus whether they will be visiblewhen the scene is ren-
dered. If one scene object obscures another and a transparency efect is
Introduction to Computer Graphics ◾ 5
in the Xbox video game console. In general, GPUs feature a highly parallel
structure that enables them to be more efcient than CPUs for rendering
computer graphics. As computer technology advances, so does the quality
of the graphics that can be rendered; modern systems are able to produce
real-time photorealistic graphics at high resolutions.
Programs that are run by GPUs are called shaders, initially so named
because they were used for shading efects, but now used to perform many
diferent computations required in the rendering process. Just as there are
many high-level programming languages (such as Java, JavaScript, and
Python) used to develop CPU-based applications, there are many shader
programming languages. Each shader language implements an application
programming interface (API), which defnes a set of commands, functions,
and protocols that can be used to interact with an external system—in this
case, the GPU. Some APIs and their corresponding shader languages include
Tis book will focus on OpenGL, as it is the most widely adopted graphics
API. As a cross-platform library, visual results will be consistent on any
supported operating system. Furthermore, OpenGL can be used in con-
cert with a variety of high-level languages using bindings: sofware librar-
ies that bridge two programming languages, enabling functions from one
language to be used in another. For example, some bindings to OpenGL
include
Each of these stages is described in more detail in the sections that follow;
the next chapter contains code that will begin to implement many of the
processes described here.
Figure 1.9 illustrates diferent renderings of a sphere that make use of these
attributes. Additional vertex attributes may be defned as needed.
During the geometry processing stage, the vertex shader is applied to
each of the vertices; each attribute variable in the shader receives data
from a bufer according to previously specifed associations. Te pri-
mary purpose of the vertex shader is to determine the fnal position of
Introduction to Computer Graphics ◾ 11
FIGURE 1.10 One scene rendered from multiple camera locations and angles.
FIGURE 1.11 A series of cubes rendered with orthogonal projection (a) and
perspective projection (b).
1.2.3 Rasterization
Once the fnal positions of each vertex have been specifed by the vertex
shader, the rasterization stage begins. Te points themselves must frst be
grouped into the desired type of geometric primitive: points, lines, or tri-
angles, which consist of sets of 1, 2, or 3 points. In the case of lines or
triangles, additional information must be specifed. For example, consider
an array of points [A, B, C, D, E, F] to be grouped into lines. Tey could
be grouped in disjoint pairs, as in (A, B), (C, D), (E, F), resulting in a set
of disconnected line segments. Alternatively, they could be grouped in
overlapping pairs, as in (A, B), (B, C), (C, D), (D, E), (E, F), resulting in a
set of connected line segments (called a line strip). Te type of geometric
Introduction to Computer Graphics ◾ 13
each interior point is interpolated from the values at the vertices: calculated
using a weighted average, depending on the distance from the interior
point to each vertex. Te closer an interior point is to a vertex, the greater
the weight of that vertex’s value when calculating the interpolated value.
For example, if the vertices of a triangle are assigned the colors red, green,
and blue, then each pixel corresponding to the interior of the triangle will
be assigned a combination of these colors, as illustrated in Figure 1.13.
FIGURE 1.14 An image fle (a) used as a texture for a 3D object (b).
print("Hello, world!")
print("Have a nice day!")
FIGURE 1.19 Results of running the Python program from Figure 1.18.
Figure 1.19 illustrates the results of running this code, which appear in a
shell window.
To verify that these packages have been installed correctly, open a new
IDLE shell window (restart IDLE if it was open before installation). To
check Pygame, enter the following code, and press the Enter key:
import pygame
You should see a message that contains the number of the Pygame
version that has been installed, such as "pygame 1.9.6", and a greet-
ing message such as "Hello from the pygame community". If
instead you see a message that contains the text No module named
'pygame', then Pygame has not been correctly installed. Furthermore,
it will be important to install a recent version of Pygame—at least a
development version of Pygame 2.0.0. If an earlier version has been
installed, return to the command prompt and in the install command
above, change pygame to pygame==2.0.0.dev10 to install a more
recent version.
Similarly, to check the Numpy installation, instead use the code:
import numpy
In this case, if you see no message at all (just another input prompt), then
the installation was successful. If you see a message that contains the text
No module named 'numpy', then Numpy has not been correctly
installed. Finally, to check PyOpenGL, instead use the code:
import OpenGL
As was the case with testing the Numpy package, if there is no message
displayed, then the installation was successful, but a message mentioning
that the module is not installed will require you to try re-installing the
package.
If you encounter difculties installing any of these packages, there is
additional help available online:
• Pygame: https://www.pygame.org/wiki/GettingStarted
• Numpy: https://numpy.org/install/
• PyOpenGL: at http://pyopengl.sourceforge.net/documentation/
installation.html
Introduction to Computer Graphics ◾ 21
be found via the download link previously mentioned. While a free trial
version is available, if you choose to use this sofware extensively, you are
encouraged to purchase a license.
Afer installation, start the Sublime Text sofware. A new editor window
will appear, containing an empty fle. As previously mentioned, Sublime
Text can be used to run Python scripts automatically, provided that Python
has been installed for all users of your computer and it is included on the
system path. To try out this feature, in the editor window, as shown in
Figure 1.21, enter the text:
print("Hello, world!")
Next, save your fle with the name test.py; the.py extension causes
Sublime Text to recognize it as a Python script fle, and syntax highlighting
will be applied. Finally, from the menu bar, select Tools > Build or press
the keyboard key combination Ctrl + B to build and run the application.
Te output will appear in the console area, as illustrated in Figure 1.22.
Introduction to Computer Graphics ◾ 23
Introduction to
Pygame and OpenGL
I n this chapter, you will learn how to create windows with Pygame
and how to draw graphics in these windows with OpenGL. You will
start by rendering a point, followed by lines and triangles with a single
color. Ten, you will draw multiple shapes with multiple colors, create a
series of animations involving movement and color transitions, and imple-
ment interactive applications with keyboard controlled movement.
DOI: 10.1201/9781003181378-2 25
26 ◾ Developing Graphics Frameworks with Python and OpenGL
First, you will create a class called Base that initializes Pygame and
displays a window. Anticipating that the applications created will eventu-
ally feature user interaction and animation, this class will be designed to
handle the standard phases or “life cycle” of such an application:
• Startup: During this stage, objects are created, values are initialized,
and any required external fles are loaded.
• Te Main Loop: Tis stage repeats continuously (typically 60 times
per second), while the application is running and consists of the
following three substages:
• Process Input: Check if the user has performed any action that
sends data to the computer, such as pressing keys on a keyboard
or clicking buttons on a mouse.
• Update: Changing values of variables and objects.
• Render: Create graphics that are displayed on the screen.
• Shutdown: Tis stage typically begins when the user performs an
action indicating that the program should stop running (for example,
by clicking a button to quit the application). Tis stage may involve
tasks such as signaling the application to stop checking for user input
and closing any windows that were created by the application.
to create a new fle named __init __.py (note the double underscore
characters that occur before and afer init). Any code in the __init __.
py fle will be run when modules from this package are imported into
another program; leave this as an empty fle. Next, also in the core folder,
create a new fle named base.py, and enter the following code (which con-
tains some basic comments that will be explained more fully afer):
import pygame
import sys
class Base(object):
def initialize(self):
pass
def run(self):
## startup ##
self.initialize()
## main loop ##
while self.running:
## process input ##
## update ##
self.update()
## render ##
# display image on screen
pygame.display.flip()
## shutdown ##
pygame.quit()
sys.exit()
import pygame
class Input(object):
def __init__(self):
Introduction to Pygame and OpenGL ◾ 31
def update(self):
# iterate over all user input events (such as
keyboard or
# mouse)that occurred since the last time
events were checked
# for event in pygame.event.get():
# quit event occurs by clicking button to
close window
if event.type == pygame.QUIT:
self.quit = True
At present, the Input class only monitors for quit-type events; in later
sections, keyboard functionality will be added as well. For now, return to
the Base class. Afer the import statements, add the code:
Tis will enable you to use the Input class from the input module
in the core package. It should be noted that the import statements
are written assuming that your application fles (which will extend the
Base class) will be stored in the main directory (which contains all the
packages).
Next, at the end of the init function, add the code:
Tis will create and store an instance of the Input class when the Base
class is created.
Finally, in the run function, afer the comment ## process input
##, add the code:
self.input.update()
if self.input.quit:
self.running = False
Tis will enable the user to stop the application, as described prior to the
code listing for the Input class.
32 ◾ Developing Graphics Frameworks with Python and OpenGL
You will next write an application that uses these classes to create a win-
dow. Te general approach in this and similar applications will to extend
the Base class, implement the initialize and update functions, and
then, create an instance of the new class and call the run function. To
proceed, in your main folder, create a new fle named test-2-1.py with
the code:
class Test(Base):
def initialize(self):
print("Initializing program...")
def update(self):
pass
void main()
{
// code statements here
}
will be supplied from the vertex shader (interpolated during the rasteriza-
tion stage), while out indicates values will be stored in one of the various
bufers (color, depth, or stencil).
Tere are two particular out variables that are required when writ-
ing shader code for a GPU program. First, recall that the ultimate goal
of the vertex shader is to calculate the position of a point. OpenGL uses
the built-in variable gl _ Position to store this value; a value must be
assigned to this variable by the vertex shader. Second, recall that the ulti-
mate goal of the fragment shader is to calculate the color of a pixel. Early
versions of OpenGL used a built-in variable called gl _ FragColor to
store this value, and each fragment shader was required to assign a value
to this variable. Later versions require fragment shader code to explic-
itly declare an out variable for this purpose. Finally, it should be men-
tioned that both of these variables are vec4 type variables. For storing
color data, this makes sense as red, green, blue, and alpha (transparency)
values are required. For storing position data, this is less intuitive, as a
position in three-dimensional space can be specifed using only x, y, and
z coordinates. By including a fourth coordinate (commonly called w and
set to the value 1), this makes it possible for geometric transformations
(such as translation, rotation, scaling, and projection) to be represented
by and calculated using a single matrix, which will be discussed in detail
in Chapter 3.
As indicated at the beginning of this section, the current goal is to write
a vertex shader and a fragment shader that will render a single point on
the screen. Te code presented will avoid the use of bufers and exclusively
use built-in variables. (You do not need to create any new fles or enter any
code at this time.) Te vertex shader will consist of the following code:
void main()
{
gl_Position = vec4(0.0, 0.0, 0.0, 1.0);
}
void main()
{
gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);
}
36 ◾ Developing Graphics Frameworks with Python and OpenGL
For more modern versions of OpenGL, where you need to declare a vari-
able for the output color, you can use the following code for the fragment
shader:
Taken together, the vertex shader and the fragment shader produce a
program that renders a point in the center of the screen, colored yellow. If
desired, these values can be altered within certain bounds. Te x, y, and z
components of the position vector may be changed to any value between
−1.0 and 1.0, and the point will remain visible; any values outside this range
place the point outside of the region rendered by OpenGL and will result
in an empty image being rendered. Changing the z coordinate (within this
range) will have no visible efect at this time, since no perspective trans-
formations are being applied. Similarly, the r, g, and b components of the
color vector may be changed as desired, although dark colors may be dif-
fcult to distinguish on the default black background color. It should also
be noted that the number types int and float are not interchangeable;
entering just 1 rather than 1.0 may cause shader compilation errors.
glCreateShader( shaderType )
Creates an empty shader object, which is used to store the source code of
a shader, and returns a value by which it can be referenced. Te type of
shader (such as a vertex shader or a fragment shader) is specifed with
the shaderType parameter, whose value will be an OpenGL constant
such as GL_VERTEX_SHADER or GL_FRAGMENT_SHADER.
glShaderSource( shaderRef, shaderCode )
Stores the source code in the string parameter shaderCode in the shader
object referenced by the parameter shaderRef.
glCompileShader( shaderRef )
Compiles the source code stored in the shader object referenced by the
parameter shaderRef.
Since mistakes may be made when writing shader code, compiling a shader
may or may not succeed. Unlike application compilation errors, which are
typically automatically displayed to the programmer, shader compila-
tion errors need to be checked for specifcally. Tis process is typically
handled in multiple steps: checking if compilation was successful, and if
not, retrieving the error message, and deleting the shader object to free up
memory. Tis is handled with the following functions:
glGetShaderInfoLog( shaderRef )
Returns information about the compilation process (such as errors and
warnings) from the shader referenced by the parameter shaderRef.
glDeleteShader( shaderRef )
Frees the memory used by the shader referenced by the parameter
shaderRef, and makes the reference available for future shaders that
are created.
@staticmethod
def initializeShader(shaderCode, shaderType):
if not compileSuccess:
# retrieve error message
errorMessage = glGetShaderInfoLog(shaderRef)
# free memory used to store shader program
glDeleteShader(shaderRef)
# convert byte string to character string
errorMessage = '\n' + errorMessage.
decode('utf-8')
# raise exception: halt program and print
error message
raise Exception( errorMessage )
glCreateProgram( )
Creates an empty program object, to which shader objects can be
attached, and returns a value by which it can be referenced.
glLinkProgram( programRef )
Links the vertex and fragment shaders previously attached to the pro-
gram object specifed by the parameter programRef. Among other
things, this process verifes that any variables used to send data from
the vertex shader to the fragment shader are declared in both shaders
consistently.
Other documents randomly have
different content
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
back
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookball.com