0% found this document useful (0 votes)
13 views10 pages

OpenGL Basics: Resources & Sample Code

The document provides an introduction to OpenGL, detailing its resources, background, and components such as GL, GLU, and GLUT. It includes a simple OpenGL program example that demonstrates the creation of a wireframe house in 2D space, along with explanations of the code structure and graphics pipeline. Additionally, it discusses the initialization of a drawing window and the use of OpenGL libraries for rendering graphics.

Uploaded by

maayurishinde369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views10 pages

OpenGL Basics: Resources & Sample Code

The document provides an introduction to OpenGL, detailing its resources, background, and components such as GL, GLU, and GLUT. It includes a simple OpenGL program example that demonstrates the creation of a wireframe house in 2D space, along with explanations of the code structure and graphics pipeline. Additionally, it discusses the initialization of a drawing window and the use of OpenGL libraries for rendering graphics.

Uploaded by

maayurishinde369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

4. Introduction to OpenGL 4.

1 Resources
„ 4.1 Resources „ “OpenGL Programming Guide: The Official Guide to
„ 4.2 Background Learning OpenGL”, Woo, Neider, and Davis, Addison-
Wesley (aka “The Red Book”).
„ 4.3 GL/GLU/GLUT etc.
1st edition online: [Link]
„ 4.4 A Simple OpenGL Program
What the Program Does „ OpenGL/GLUT manuals
See COMP 372 Resources page
The Code
Aspects of the Code
„ 4.5 Geometric Primitives in OpenGL
© 2008 Burkhard Wuensche [Link] Slide 1 © 2008 Burkhard Wuensche [Link] Slide 2

Resources (cont’d) 4.2 Background


„ OpenGL homepage: [Link] „ SGI (Silicon Graphics Inc.) devised a proprietary
Examples, Discussion forums, etc. graphics language IrisGL
„ OpenGL Examples (see 372 Resources page)
„ IrisGL is a software interface to polygon-rendering
Consists of one solution (.sol)
with one project for each example
hardware and consists of a library of C functions to:
Contains all major examples from the OpenGL Programming define geometric objects in 2D and 3D.
Guide. Control how these objects are rendered in the frame
In order to run an example open the solution, choose an active buffer (set up view transformations, perspective
project, compile and execute it (try fog, teapots, material, transformations, illumination).
dof, aapoly).
„ The examples fogindex and aaindex require 256 colour mode. Output textured Gouraud-shaded polygons (with z-
Read comments at the beginning of each source files (you are buffering), plus lines and points.
not expected to understand them, yet).
© 2008 Burkhard Wuensche [Link] Slide 3 © 2008 Burkhard Wuensche [Link] Slide 4
Background (cont’d) OpenGL Applications
„ In 1992, SGI made the spec. publicly available, calling it OpenGL „ Professional 3D Graphics & Effects
Widely adopted by other graphics companies 3D graphics & special effects in the movie industry.
Specification maintained and expanded by the OpenGL Architectural Review CAD/CAM/CAE, entertainment, medical imaging and virtual reality.
Board (ARB)
Supported by most PC graphics card manufacturers All leading 3D modelling, rendering & animation, and visualization software
Standard for most Unix workstations, adopted by Apple for the Mac packages use OpenGL (3D StudioMax, Lightwave3D, AVS Express,
Incorporated into Windows 9X/NT/2000 Amira, …).
„ Competes with Direct-3D component of Direct-X „ Games
OpenGL allows hardware accelerated rendering,
„ In 2004, OpenGL 2.0 was released including a number of major texture-mapping and special effects.
additions to the standard. The most significant one is GLSL (the Many leading games support both OpenGL and
OpenGL Shading Language) which enables the programmer to DirectX (Halo 2, Half-Life 2, World of Warcraft etc.)
for hardware acceleration.
replace the OpenGL fixed-function vertex and fragment processing
„ Mobile applications
„ A public domain source-code implementation called Mesa is Nokia has licensed Hybrid Graphics’ OpenGL ES
available for a wide range of platforms [Link]
© 2008 Burkhard Wuensche [Link] Slide 5 © 2008 Burkhard Wuensche [Link] Slide 6

4.3 GL/GLU/GLUT etc GL/GLU/GLUT etc (cont’d)


„ GL is the main function library for polygon rendering
„ In usual C implementations, OpenGL has three All function names begin with "gl”
components Increasingly, the GL functions are done in hardware on the graphics card.
GL, GLU and GLUT „ GLU is the OpenGL Utility library
There may also be a package for directly interfacing to a Extra functions, such as tesselations of spheres, cones, curved surfaces …
particular windowing system e.g. GLX for OpenGL on X- All function names begin with "glu”
window systems, but we’ll ignore. Functionality provided through calls to GL functions
Application Program „ GLUT, the OpenGL Utility Toolkit
Graphical User Interfaces (GUIs)
are often developed using a Not officially specified/supported by ARB
GLUT
platform independent scripting Provides support for a windowing environment in a window-system
GLU independent manner
language (Python, Tcl/Tk)
„ Window creation/destruction, Pop-up menus, Mouse and keypress
GL
interactions
Hardware-specific drivers But rather limited (e.g. no pull down menus, toolbars, panes, splits, scrolling,
…)
© 2008 Burkhard Wuensche [Link] Slide 7 © 2008 Burkhard Wuensche [Link] Slide 8
GL/GLU/GLUT etc (cont’d) How to use OpenGL?
„ A typical OpenGL program looks like this:
„ OpenGL, GLU and GLUT come as include libraries (.lib) and
as dynamic link libraries (.dll) Create_a_Window // open a window into the frame buffer into which the
„ Two versions: Microsoft ([Link], [Link], [Link]) // program will draw.
// A GL context is associated with the window and all
and Silicon Graphics ([Link], [Link], [Link]). // subsequent OpenGL commands are with respect to the
We are using the Microsoft version. // current context:
Microsoft libraries very old, but you get access to the latest OpenGL Define_view // Specify how scene (2D or 3D) is mapped onto a window
functionality by using OpenGL extensions // on the screen
([Link] Define_rendering_parameters // For example, lighting
and by downloading a suitable driver for your graphics card Draw_the_scene // Set colour or material properties of objects.
„ Both versions use the same header files (gl.h, glu.h, glut.h) // Draw object
// Note: A scene (a collection of geometric objects) must be
„ Downloads, manuals and examples are available on the // converted into primitives (polygons) before calling the
COMP 372 Resources page. // OpenGL drawing routines. GLUT defines a number of
// geometric objects (sphere, torus, …) using polygons.
© 2008 Burkhard Wuensche [Link] Slide 9 © 2008 Burkhard Wuensche [Link] Slide 10

4.4 A Simple OpenGL Program What the program does


„ What the program does
„ Defines a simple house shape in wireframe form
„ The code
(i.e. made up of straight lines representing the
edges) in 2D-space.
„ Aspects of the code y

Include the graphic libraries


‹ Displays a picture
Represent the Wireframe House
of the house using
Create a Drawing window
a 2D orthographic
Initialise window & view projection x

Draw the Picture – Maps a section of


„ Summary the 2D coordinate
„ Remarks system onto the
„ Exercises output window. The Situation The Program Output
© 2008 Burkhard Wuensche [Link] Slide 11 © 2008 Burkhard Wuensche [Link] Slide 12
#include <windows.h>
The code void init(void) {
The code (cont’d)
#include <gl/gl.h> // select clearing color (for glClear)
#include <gl/glu.h> glClearColor (1.0, 1.0, 1.0, 0.0); // RGB-value for white
#include <gl/glut.h> // initialize view (simple orthographic projection)
GLdouble halfWidth=(GLdouble) windowWidth/2.0;
const int windowWidth=300; const int windowHeight=400; GLdouble halfHeight=(GLdouble) windowHeight/2.0;
// define vertices and edges of the house glMatrixMode(GL_PROJECTION);
const int numVertices=5; const int numEdges=6; glLoadIdentity();
const float vertices[numVertices][2] = {{0.0, 0.0},{100.0, 0.0},{0.0, 100.0},{100.0, 100.0},{50.0, gluOrtho2D(-halfWidth, halfWidth, -halfHeight, halfHeight);
150.0}}; }
const int edges[numEdges][2] = {{0, 1},{1, 3},{3, 2},{2, 0},{2, 4},{3, 4}};
// create a single buffered colour window
void display(void){ int main(int argc, char** argv){
glClear(GL_COLOR_BUFFER_BIT); // clear all pixels in frame buffer glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glColor3f (1.0, 0.0, 0.0); // draw edges in red [given as RGB (red,green,blue) value] glutInitWindowSize(windowWidth, windowHeight);
glBegin(GL_LINES); glutInitWindowPosition(100, 100);
for(int i=0;i<numEdges;i++){ glutCreateWindow("My first OpenGL program");
glVertex2fv(vertices[edges[i][0]]); init (); // initialise view
glVertex2fv(vertices[edges[i][1]]); } glutDisplayFunc(display); // draw scene
glEnd(); glutMainLoop();
glFlush (); // start processing buffered OpenGL routines return 0;
} }
© 2008 Burkhard Wuensche [Link] Slide 13 © 2008 Burkhard Wuensche [Link] Slide 14

OpenGL code Ù Graphics Pipeline Aspects of the Code


y No model transformations in example!
Define vertices
(glVertex2fv)
x MODELVIEW
Transformation
„ Include the graphic libraries
„ Define the scene
PROJECTION
Clipping Transformation
Illumination
„ Create a drawing window
No clipping! No illumination
Project vertices onto OpenGL
window (gluOrtho2D) – uses
in example! „ Initialise window & view
info from GLUT initialisation
„ Draw the scene
Viewport
Rasterization Display
Transformation

No viewport Vertices get assembled to


transformation! lines [glBegin(GL_LINES)]
and drawn on the screen
© 2008 Burkhard Wuensche [Link] Slide 15 © 2008 Burkhard Wuensche [Link] Slide 16
Including the graphic libraries Defining the Scene
„ Have a vertex table and an edge table
„ #include <windows.h> const int numVertices=5;
includes constants and function prototypes of the Graphic Device Interface const int numEdges=6;
(GDI), which is at the core of all Windows graphics. const float vertices[numVertices][2] = {{0.0, 0.0},
„ #include <gl/gl.h> {100.0, 0.0},{0.0, 100.0},{100.0, 100.0},{50.0, 150.0}};
const int edges[numEdges][2] = {{0, 1},{1, 3},{3, 2},
#include <gl/glu.h>
{2, 0},{2, 4},{3, 4}};
#include <gl/glut.h>
„ Each vertex table array entry is an array of 2 floats, y
include constants and function prototypes of the OpenGL, GLU, representing a point in R2 [2D-space]
and GLUT libraries, respectively. „ Edge table values are indices into vertex table 4
Header files are stored in a subdirectory ‘gl’ of the Visual C++ e.g. edge {1,3} is the edge from
100

‘include’ directory. V1=(100.0, 0.0) to V3 =(100.0, 100.0). 2 3


Ordering of both vertex table and edge table is arbitrary
glut.h includes all other header files, but it is good style to Ordering of vertices in an edge is also arbitrary,
include them explicitly as done above 0 1
e.g. {1,3} is identical to {3,1} 0
0 100
x
© 2008 Burkhard Wuensche [Link] Slide 17 © 2008 Burkhard Wuensche [Link] Slide 18

Creating a Drawing Window Creating a Drawing Window (cont’d)


„ glutInit(int *argcp,char** argv); „ glutInitWindowPosition(int x, int y);
Initiates Window session with the underlying operating x and y coordinate of the screen location of the to be
system (OS) created window.
Uses command line arguments from main() [OS-specific]. „ glutCreateWindow(char* s);
„ glutInitDisplayMode(unsigned int mode); Create window with the title s.
Specifies display mode for the to be created window . Size, location, and mode of the window are specified by
Select single buffered (GLUT_SINGLE) colour (GLUT_RGB) the current state of the OpenGL program (set by the
window (i.e. the window is associated with one frame buffer previous three commands).
of RGB values). Returns a unique window identifier. Important when using
„ glutInitWindowSize(int width, int height); multiple windows.
Width and height (in pixels) of the to be created window.

© 2008 Burkhard Wuensche [Link] Slide 19 © 2008 Burkhard Wuensche [Link] Slide 20
Initialisation window & view Initialisation window & view (cont’d)
‹ gluOrtho2D(Gldouble left, Gldouble right, Gldouble
bottom, Gldouble top);
‹ glClearColor(Glclampf red, Glclampf green, Glclampf blue, – Defines a 2D orthographic projection matrix.
Glclampf alpha);
– Maps a section of the 2D world coordinates (the coordinates in which the scene
– Set colour used for clearing (glClear()) the drawing window. is defined) onto the drawing window.
– Colour is an RGBA tuple (red, green, blue, alpha) where alpha is transparency. – Ratio (right-left):(top-bottom) should be the same as width:height of the window
– Arguments are floats (values are clamped to the range [0,1]) →otherwise scene is distorted
y
‹ glMatrixMode(Glenum mode); 200

– Applies subsequent matrix operations to the matrix stack specified by mode.


– GL_PROJECTION selects the projection matrix stack. y
200
– The projection matrix specifies how the scene (2D or 3D) is projected onto the x
-150 150
2D drawing window.

‹ glLoadIdentity(); 150
x
-150

– Initialise the matrix stack with an identity matrix.


-200 -50

(a) Using ‘gluOrtho2D(-150, 150, -200, 200)’ (b) Using ‘gluOrtho2D(-150, 150, -50, 200)’

© 2008 Burkhard Wuensche [Link] Slide 21 © 2008 Burkhard Wuensche [Link] Slide 22

gluOrtho2D gluOrtho2D (cont’d)


‹ How does gluOrtho2D do the mapping?
‹ gluOrtho2D implements a (world-)window-to-viewport mapping.

‹ The world-window is the section of the world coordinates we want to display ⎛ x⎞


Denote the world coordinates by x = ⎜ ⎟
(specified by the coordinates w.l, w.r, w.b, w.t). ⎝ y⎠
‹ The viewport is the drawing window on the screen.
⎛u⎞
‹ The viewport is described with respect to the screen coordinates (eg. top-left pixel and the screen coordinates by u = ⎜ ⎟
of the screen is (0,0) and the bottom-right pixel of screen (1023,767)). ⎝v⎠
‹ The viewport is then specified by the coordinates v.l, v.r, v.t and v.t with respect then the world-to-viewport mapping is described by the equation
to those screen coordinates. u

y v
w.t
⎛ u ⎞ ⎛ A 0 ⎞ ⎛ x ⎞ ⎛ C ⎞ ⎛ Ax + C ⎞
200
v.t
⎜ ⎟=⎜ ⎟⎜ ⎟ + ⎜ ⎟ = ⎜ ⎟
⎝ v ⎠ ⎝ 0 B ⎠ ⎝ y ⎠ ⎝ D ⎠ ⎝ By + D ⎠
150
x
-150

v.b This equation can be described by a single matrix multiplication


w.b -200
(see chapter 54). The matrix is pushed onto the projection matrix stack!
w.l w.r
v.l v.r
© 2008 Burkhard Wuensche [Link] Slide 23 © 2008 Burkhard Wuensche [Link] Slide 24
gluOrtho2D (cont’d) Drawing the Scene
x u
w.l w.r v.l v.r ‹ glClear(GLbitfield mask );
– Clears all pixels in the buffer specified by mask.
The ratio of the distances of x to the left and right window boundary must be equal
– In order to clear colour buffer use GL_COLOR_BUFFER_BIT as mask.
to the ratio of u to the left and right viewport boundaries (proportionality of x) → Sets all pixels of the drawing window to the previously defined ‘clear-colour’.
u − v.l x − w.l v.r − v.l ⎛ v.r − v.l ⎞
= or u = x + ⎜ v.l − w.l ⎟ ‹ glColor3f(GLfloat red, GLfloat green, GLfloat blue );
v.r − v.l w.r-w.l w.r − w.l ⎝ w.r − w.l ⎠
– Sets colour for subsequent drawing commands.
Comparing coefficents with the linear equation from the previous slide gives
– Colour is an RGB tuple (red, green, blue).
v.r − v.l
A= and C = v.l − A * w.l – Many different versions of this command are available:
w.r − w.l – void glColor3b( GLbyte red, GLbyte green, GLbyte blue )
– void glColor3d( GLdouble red, GLdouble green, GLdouble blue)
– void glColor4f( GLfloat red, GLfloat green, GLfloat blue,
Similarly proportionality for y gives GLfloat alpha )
v.t − v.b see manual for a complete listing
B= D = v.b − B * w.b

and
w.t − w.b
© 2008 Burkhard Wuensche [Link] Slide 25 © 2008 Burkhard Wuensche [Link] Slide 26

Drawing the Scene (cont’d) Summary „ An OpenGL program has 3 important parts:
‹ glBegin(Glenum mode); Like all C programs it has a main function,
… which is used to initialise the drawing window
void display(void){
and set up the scene and event handling.
glEnd(); // draw scene objects
} Before drawing a scene the scene and the
– glBegin and glEnd delimit the vertices that define a primitive or a group of like virtual camera (view of the scene) must be
primitives. defined
– The type of primitive is specified by the argument mode. void init(void) { „ Can be done inside the display function

– GL_LINES treats each pair of vertices as an independent line segment. Vertices 2n-1 // set up background colour, window etc. but more efficient to define a separate
// set up view projection (e.g. glOrtho2D) method init.
and 2n define line n. N/2 lines are drawn. // set up scene Only called once, except if the view is
„
} changed (e.g. zoom in).
‹ glVertex2fv(const GLfloat *v ) Scene is draw by the display function.
– v specifies a pointer to an array of two float numbers representing a vertex. „ Window must be redrawn if it is created,
int main(int argc, char** argv){
– the glVertex command is used within glBegin/glEnd pairs to specify point, line, moved or uncovered.
// create a single buffered colour window
and polygon vertices. The current color, normal, and texture coordinates are associated // initialise view and scene „ Performed automatically by GLUT by
with the vertex when glVertex is called. // set up event handling calling glutDisplayFunc(display).
glutDisplayFunc(display); // draw scene „ Two parts missing in our example:
‹ glFlush() glutMainLoop(); could define reshape function in case the
return 0; drawing window is resized.
– empties all buffers, causing all issued commands to be executed as quickly as they are } event handling (mouse and keyboard input).
accepted by the actual rendering engine.
© 2008 Burkhard Wuensche [Link] Slide 27 © 2008 Burkhard Wuensche [Link] Slide 28
Remarks Remarks (cont’d)
„ Note that many methods (e.g. glColor2f, glVertex2fv) are of the form:
glXXX<n><t>[v], where „ The GL data types (Glfloat, Gldouble, …) are not C types.
For example, GLint is not necessarily equivalent with the C type int.
n is dimension of quantity being defined (3 ⇒ 3-space)
t is type of parameter (f = float) The reason for this is that OpenGL needs for each data type a certain
minimum number of bits in order to get the necessary precision for graphics
optional v denotes “vector” parameter, e.g. glVertex3fv takes a 3-element
operation.
array of floats as a parameter, whereas glVertex3f takes three separate
The corresponding C data types are specified in the file gl.h, e.g.
floats, (x,y,z)
typedef float GLfloat;
„ OpenGL often defines several different forms of each call, e.g.
glVertex{234}{sifd}[v] typedef float GLclampf;
24 forms in total! typedef double GLdouble;
In 372 we are using the f form (float) everywhere …
„ Simplest to stick with a single type when learning Hence if you use float instead of Glfloat you won’t get a warning
„ Although double is often a little more convenient, it costs too much in message. However, it’s a good style to use the GL data types in case you
memory and performance. port you program to another machine.
© 2008 Burkhard Wuensche [Link] Slide 29 © 2008 Burkhard Wuensche [Link] Slide 30

Exercises [Try doing all these] 4.5 Geometric Primitives in OpenGL


„ As mentioned before the command sequence
glBegin(Glenum mode);
„ Change the program to draw the picture in white on a black background

„ Change the program to use glVertex2f everywhere instead of glVertex2fv. glEnd();
„ Modify the program such that the left-bottom corner of the house is at the left- defines a primitive or a group of like primitives from the N vertices defined in
bottom corner of the window between.
Do this by modifying the vertex table only
Do this by modifying the arguments of gluOrtho2D only The argument mode specifies how the vertices are interpreted and can be any
„ Add a variable f to the program and modify the program such that it increases of the following:
GL_POINTS GL_LINES
the size of the picture in the output window by a factor f.
„ Draw only the vertices of the house (use GL_POINTS) GL_LINE_STRIP GL_LINE_LOOP
In order to better see the points call glPointSize(3.0)before GL_TRIANGLES GL_TRIANGLE_STRIP
glBegin.
GL_TRIANGLE_FAN GL_QUADS
GL_QUAD_STRIP GL_POLYGON

© 2008 Burkhard Wuensche [Link] Slide 31 © 2008 Burkhard Wuensche [Link] Slide 32
Geometric Primitives (cont’d) Geometric Primitives (cont’d)
„ GL_POINTS „ GL_LINE_STRIP
treats each vertex as a single point. draws a connected group of line segments from the first vertex to the
vertex n defines point n (n=0,...,N-1). last.
vertices n and n+1 define line n (n=0,...,N-2).
„ GL_LINES „ GL_LINE_LOOP
treats each pair of vertices as an independent line segment. as above, but additionally a line segment is drawn from the last vertex to
Vertices 2n and 2n+1 defines line n (n=0,...,N/2-1). the first.

© 2008 Burkhard Wuensche [Link] Slide 33 © 2008 Burkhard Wuensche [Link] Slide 34

Geometric Primitives (cont’d) Geometric Primitives (cont’d)


„ GL_TRIANGLES „ GL_TRIANGLE_FAN
treats each triplet of vertices as one independent triangle. draws a connected group of triangles. Each pair of vertices after the first
vertices 3n, 3n+1 and 3n+2 define triangle n (n=0,…,N/3-1). vertex defines one triangle with the first vertex.
„ GL_TRIANGLE_STRIP vertices 0, n+1 and n+2 defines triangle n (n=0,…,N-3).
„ GL_POLYGON
draws a connected group of triangles with the first three vertices defining
a triangle and each subsequent vertex forming a triangle with the last two draws a single convex polygon defined by the vertices 0 to N-1.
vertices of the previous triangle.
for even n vertices n, n+1 and n+2 define triangle n, for odd n vertices
n+1, n and n+2 define triangle n (n=0,…,N-3).

© 2008 Burkhard Wuensche [Link] Slide 35 © 2008 Burkhard Wuensche [Link] Slide 36
Geometric Primitives (cont’d) Remarks
„ GL_QUADS
„ Geometric primitives are defined identical in 2D and 3D with the dimension of
treats each group of four vertices as an independent quadrilateral.
the vertices being the only difference.
vertices 4n , 4n+1 , 4n+2 and 4n+3 define quadrilateral n (n=0,…,N/4-1).
„ The vertices of a triangle strip or quad strip should be all either in clockwise or
„ GL_QUAD_STRIP
in anticlockwise order (necessary for a consistent surface orientation in 3D).
draws a connected group of quadrilaterals with the first four vertices
defining one quadrilateral and each subsequent pair of vertices defining a „ Point size is modified with glPointSize(Glfloat size).
quadrilateral with the last two vertices of the previous one. „ Line width is modified with glLineWidth(Glfloat width).
vertices 2n , 2n+1 , 2n+3 and 2n+2 define quadrilateral n (n=0,…,N/2-2). „ Can apply a colour either to all vertices or to each vertex individually. In the
latter case the vertex colours are interpolated.

© 2008 Burkhard Wuensche [Link] Slide 37 © 2008 Burkhard Wuensche [Link] Slide 38

You might also like