0% found this document useful (0 votes)
20 views104 pages

3 OpenGL

Uploaded by

bobbyjacky2
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)
20 views104 pages

3 OpenGL

Uploaded by

bobbyjacky2
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
You are on page 1/ 104

OpenGL

 A good resource for an introductory graphics course


OpenGL is the The Red Book)

 But you don’t have to buy it


because there’s an online version!

Current version is 9th edition


8th is available online

1
Writing OpenGL Applications: Tutorials

 http://www.opengl-tutorial.org
 http://alfonse.bitbucket.org/oldtut/
 http://www.opengl-tutorial.org/beginners-tutorials/tutorial-1-opening-a-window/
 https://en.wikibooks.org/wiki/OpenGL_Programming
 http://ogldev.atspace.co.uk/
 http://www.swiftless.com/
 http://antongerdelan.net/opengl/index.html
 http://www.songho.ca/opengl/index.html
 http://www.lighthouse3d.com/
 http://nehe.gamedev.net/
 http://www.g-truc.net/project-0026.html
 https://developer.nvidia.com/gameworks-vulkan-and-opengl-samples
The Programmer’s Interface

 A programmer sees the graphics system through a software


interface: the Application Programmer Interface (API)

 (OpenGL, Direct3D etc.)

3
OpenGL
What is OpenGL?

 OpenGL is a software API consisting of many functions that


allow you to talk to your graphics hardware. It is cross-
platform and is most commonly used in professional
graphics applications.

 Alternative API’s
 Direct3D:
◼ Proprietary, Microsoft-only software API for graphics
◼ Very well-supported by graphics card vendors
 Metal
◼ Graphics API developed by Apple
◼ https://en.wikipedia.org/wiki/Metal_(API)

5
OpenGL

⚫ www.opengl.org

⚫ Wikipedia OpenGL
– http://en.wikipedia.org/wiki/OpenGL

⚫ http://www.khronos.org/opengl
OpenGL Evolution

• OpenGL 4.6
OpenGL Evolution
OpenGL Evolution
OpenGL ES and WebGL

▪ OpenGL ES
▪ Designed for embedded and hand-held devices such as cell phones
▪ Based on OpenGL 3.1
▪ Shader based

▪ WebGL
▪ JavaScript implementation of OpenGL ES
▪ Runs on most recent browsers
▪ http://madebyevan.com/webgl-water/
WebGL

 JavaScript application programmer interface (API)


for 2D and 3D graphics!

 OpenGL ES 2.0 running in the browser,


implemented by all modern browsers!

 Overview, tutorials, documentation:!


 https://developer.mozilla.org/en-
US/docs/Web/API/WebGL_API!
Three.js!
 Cross-browser JavaScript library/API !

 Higher-level library that provides a lot of useful helper


functions, tools, and abstractions around WebGL – easy and
convenient to use!

 https://threejs.org/!

 Simple examples: https://threejs.org/examples/!

 Great introduction (in WebGL):!


 http://davidscottlyons.com/threejs/presentations/frontporch14/!
Three.js: Scene Graph Based
Vulkan!

 “Successor” to OpenGL (https://en.wikipedia.org/wiki/Vulkan_(API))

 Vulkan supports hardware with a wide range of hardware capabilities


 Mobile OpenGL ES 3.1 up to desktop OpenGL 4.5 and beyond

 One unified API framework for desktop, mobile, console, and embedded
 No “Vulkan ES” or “Vulkan Desktop”

 Vulkan precisely defines a set of “fine-grained features”


 Features are specifically enabled at device creation time (similar to extensions)
 Consistently available on that platform
 https://web.archive.org/web/20200613174246/http://ogldev.atspa
ce.co.uk/www/tutorial50/tutorial50.html
OpenGL
Introducing OpenGL

 Mid-level, device-independent, portable graphics


subroutine package

 Developed primarily by SGI (from GL, 1982)

 2D/3D graphics, lower-level primitives (polygons)

 Does not include low-level I/O management

 Basis for higher-level libraries/toolkits


What Constitutes OpenGL?
 Consists of a set of functions (about 670) stored in the main
library GL

 Early versions operate as a state machine that controls a well-


defined set of drawing operations

 It is not object-oriented. It is now bundled with Windows


(except GLUT/freeGLUT library).

 ** as of OpenGL 3.0, move away from state oriented API


 Can still use state machine code
Related API’s
 GLUT (OpenGL Utility Toolkit) (see freeGlut)
 Library used to create screen windows, manage mouse/key events etc.
windowing API
 Not officially part of OpenGL – typically needs to be downloaded and
installed by programmer

 GLFW (http://www.glfw.org/)
 free, Open Source, multi-platform library for OpenGL, OpenGL ES and
Vulkan development on the desktop
 provides a simple API for creating windows, contexts and surfaces,
receiving input and events.
 written in C, native support for Windows, OS X and many Unix-like systems
such as Linux and FreeBSD
Related API’s
 GLU (OpenGL Utility Library)
 Part of OpenGL

 NURBS, tessellators, quadric shapes, etc

 GLX, WGL, CGL


 Glue between OpenGL and windowing systems

 GLX (Linux), WGL (Windows), CGL (OS X)

 GLSL (OpenGL Shading Language)


 Language to program vertex and fragment shaders
GLUT - GL Utility Toolkit

 OpenGL Utility Toolkit (GLUT)


 Provides functionality common to all window systems
◼ Open a window
◼ Get input from mouse and keyboard
◼ Menus
◼ Event-driven

 Code is OS independent but GLUT lacks the functionality


of a good toolkit for a specific platform
◼ No slide bars

20
Example GLUT Window
Better GLUT Alternatives: freeGlut
 freeGlut (freeglut.sourceforge.net) ***
 http://seevisionc.blogspot.ca/2013/08/setting-up-freeglut-and-
gltools-with.html
 GLFW (http://www.glfw.org/)

 SDL (Simple Direct Media Layer)


 cross platform multimedia library

 WGL
 set of windows API’s used to set up OpenGL

 www.opengl.org/resources/libraries/windowtoolkits/
GLU – GL Utility Library

 Higher-level library: wraps some of OpenGL’s functions

 GLU provides functions for:


 setting up viewing and projection
 describing complex objects with line and polygon approximations
 displaying quadrics and B-splines
 processing surface rendering operations

 GLU functions start with prefix glu

23
OpenGL Extension Wrangler Library (GLEW)

 OpenGL extensions:
 Card manufacturers may implement new proprietary features after
latest OpenGL version released
 These features are published, made available as extensions to latest
OpenGL
 GLEW: library to access OpenGL extensions on a
graphics card
What’s in OpenGL?

 Functions that specify what we need to form an


image
 Objects
 Viewer

 Light Source(s)

 Materials

 Other information
 Input from devices such as mouse and keyboard
 Capabilities of system
25
Aside: Scene Description

(Massive) pile of data that describes a scene


– Fed into a rendering “pipeline” to create the final image

1. Geometry: describes 3D objects, usually vertices and triangles


2. Textures: describe surface details, raster images
3. Lights: mathematical description of light sources (position etc.)
4. Camera: position, orientation, field of view (zoom etc.)

26
Object (Model) Specification

 Most APIs support a limited set of primitives including:

 Points (0D object)


 Line segments (1D objects)
 Polygons (2D objects)
 Some curves and surfaces
◼ Quadrics
◼ Parametric polynomials

 All are defined through locations in space or vertices

27
Camera Specification

 Six degrees of freedom


 Position of center of lens (x,y,z)
 Orientation (roll, pitch, yaw)
 Lens
 Film size
 Orientation of film plane

28
Lights and Materials Specification

 Types of lights
 Point light sources vs distributed light sources
 Spot lights
 Near and far light sources (e.g. sun)
 Color of light

 Material properties of models (i.e. how light is


reflected)
 Absorption: color properties
 Scattering
◼ Diffuse
29
◼ Specular
OpenGL State Machine

 OpenGL was initially designed as a state machine. A


collection of attributes (or modes) define the state of the
machine. Once defined attributes remained in effect until you
changed them.

 You define an object with geometric primitives

 An attribute is any property that determines how a primitive


is to be rendered (e.g. color).

30
OpenGL State

 OpenGL functions are of two types

 Primitive generating (i.e. triangle, line segment etc)


◼ Can cause output if primitive is visible
◼ How vertices are processed (e.g. translated) and
appearance of primitive (e.g. color) are controlled by the
state

 State changing
◼ Transformation functions (modeling, viewing)
◼ Attribute functions (set color etc.)
31
OpenGL: Conventions
 Functions in OpenGL start with gl
 Most functions just gl (e.g., glColor())

 Functions
starting with glu are utility functions (e.g.,
gluLookAt())

 Function starting with glut ...

 Functions
starting with glx are for interfacing with
the X Windows system
32
OpenGL: Conventions

 Function names indicate argument type and number


 Functions ending with f take floats
 Functions ending with i take ints
 Functions ending with b take bytes
 Functions ending with ub take unsigned bytes
 Functions that end with v take an array.

 Examples
– glColor3f() takes 3 floats
– glColor4fv() takes an array of 4 floats

33
OpenGL: Conventions

 Constants written in CAPITAL letters

 Example: GLUT_SINGLE, GLUT_RGB

 Use the bitwise or command (x | y) to combine


constants

34
Lack of Object Orientation

 OpenGL is not object oriented so that there are


multiple functions for a given logical operation
 glVertex3f
– glVertex2i
– glVertex3dv

 Underlying storage mode is the same

35
OpenGL function format
function name
dimensions

glVertex3f(x,y,z)

x,y,z are floats


belongs to GL library

glVertex3fv(p)

p is a pointer to an array

36
OpenGL Geometric Primitives

 OpenGL uses only a very small number of primitives

 Points

 Linesegments
 Polygons

 Bitmaps/Images

37
Primitive Types

 GL_POINTS
 GL_LINE
 {S | _STRIP | _LOOP}
 GL_TRIANGLE
 {S | _STRIP | _FAN}
 GL_QUAD
 {S | _STRIP}
 GL_POLYGON

38
Polygon types
Polygon types
GL_POLYGON

 List of vertices defines polygon edges


 Polygon must be convex

41
Polygon Issues

 OpenGL will only display polygons correctly that are


 Simple: edges cannot cross
 Convex: All points on line segment between two points in a polygon
are also in the polygon
 Flat: all vertices are in the same plane

 User program can check if above true


 OpenGL will produce output if these conditions are violated but it
may not be what is desired

 Triangles satisfy all conditions


42
Polygon Issues

non-simple polygon non-convex polygon

43
Vertex Attributes

 Each vertex must be specified by at least a (x, y, z)


position ( e.g. use glVertex(x,y,z) ).

 OpenGL has other built in attributes:


 Normals (i.e. normal vectors)
 Color

 Texture coordinates

44
Other Attributes

 Attributes are part of the OpenGL state and


determine the appearance of objects
 Color (points, lines, polygons)
 Size and width (points, lines)

 Stipple pattern (lines, polygons)

 Polygon mode
◼ Display as filled: solid color or stipple pattern
◼ Display edges
◼ Display vertices

45
Attributes for (a) lines and (b) polygons
Filled objects
Methods of displaying a polygon
PreBuilt OpenGL 3D Shape Primitives

 Parametric:
 Cylinder

 Sphere

 Cone

 Disk

 Torus

 Special functions via


 GLU and GLUT library
GLUT Shape Primitives

 glutWireCube(size);
 glutSolidCube(size);
 glutWireSphere (r, nLongitudes, nLatitudes);
 glutSolidSphere (r, nLongitudes, nLatitudes);
 glutWireCone(rBase, height, nLong, nLat);
 glutSolidCone(rBase, height, nLong, nLat);
 glutWireTorus(rCrossSection, rAxial, nConcentric, nRadial);
 glutWireTorus(rCrossSection, rAxial, nConcentric, nRadial);
 glutWireTeapot(size);
 glutSolidTeapot(size);
Stroke text (Post-Script font)
Raster text
Stroke-text Attributes
Color
RGB color

 Each color component is stored separately in the


frame buffer

 Usually 8 bits per component in buffer

 Note in glColor3f the color values range from


0.0 (none) to 1.0 (all), whereas in glColor3ub
the values range from 0 to 255

55
Smooth Color

 Default is smooth shading


 OpenGL interpolates vertex colors across visible polygons

 Alternative is flat shading


 Color of first vertex

determines fill color


 glShadeModel
(GL_SMOOTH)
or GL_FLAT

56
Drawing in OpenGL
1 - Immediate Mode Rendering (Old Style)

The simplest way to draw mesh of triangles is to use the old


OpenGL begin and end functions.
1. Declare our primitive (e.g. triangle):
 glBegin( … )
2. Specify our vertices (x, y, z) and attributes
 glVertex*( … )
 glNormal*( … )
3. Declare that we are finished:
 glEnd()
4. Force execution of previous commands (i.e. start rendering)
 glFlush() or glSwapBuffers()
58
1 - Immediate Mode Rendering (Old Style)

type of object
location of vertex

glBegin(GL_POLYGON)
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glVertex3f(0.0, 0.0, 1.0);
glEnd( );

end of object definition

59
2 - Drawing Mesh using Vertex Arrays**

 The downside of using glBegin, glEnd with glVertex is that for


anything but simple models, we must make an enormous
number of function calls (i.e. “draw calls”)

 Consider a cube. Each vertex needs to be declared three


times, once for each cube face it is a part of, resulting in 24
glVertex() function calls.

**NOT Vertex Array Objects


(VAOs)
2 - Drawing Mesh using Vertex Arrays

 OpenGL provides vertex array routines that allow you to


specify vertex data using arrays and fewer function calls.
 You must enable your array:
 glEnableClientState( … )
◼ Specify the type of array (GL_VERTEX_ARRAY)

 You must specify data for your array


 glVertexPointer( … )
◼ Specify the number of coordinates per vertex, type, byte offset between vertices, and a
pointer to the first vertex in input array

 All other attributes (e.g. normals) have their own arrays.


 More on this in upcoming lecture
2 - Drawing Mesh using Vertex Arrays

 There are three ways to access elements of the vertex array:


 glArrayElement( …)
◼ Draws a single vertex

 glDrawArrays( … )
◼ Draws a sequence of vertices

 glDrawElements( … )
◼ Draws a sequence of vertices based on an indexed array.
◼ Generally you want to use this one.
2 - Drawing Mesh using Vertex Arrays and Index Buffer

 Index buffer contains Vertex Buffer Index Buffer


offsets into vertex buffer
0: (x, y, z) 0, 1, 2
1: (x, y, z) 1, 3, 2
 Used to share vertices 2: (x, y, z) 2
between triangles
3: (x, y, z)

3
 Also specifies rendering
order
0
1
2 - Drawing using Vertex Arrays: Example

// Sample code using vertex arrays


void init_array()
{
float vertices[] = { 1.0, 0.0, 0.0,
0.0, 1.0, 0.0
0.0, 0.0, 1.0 };
glEnableClientState( GL_VERTEX_ARRAY );
glVertexPointer( 3, GL_FLOAT, 0, vertices );
}

void display_square()
{
unsigned int indices[] = { 0, 1, 2 };
glDrawElements( GL_TRIANGLES, 3, GL_UNSIGNED_INT, indices );
}
3 - Drawing Mesh using VBOs (GPU based)

 VBO: Vertex Buffer Object


 1 - Put geometric data (e.g. vertex positions) into an array

vec3 points[3];
points[0] = vec3(0.0, 0.0, 0.0);
points[1] = vec3(0.0, 1.0, 0.0);
points[2] = vec3(0.0, 0.0, 1.0);

 2 - Send array to GPU

 3 - Tell GPU to render array as triangles


3 - Drawing Mesh using VBOs (GPU based)

 VBO : “Handle” to GPU memory for vertices


 Leaving geometry info on the GPU avoids wasting the
bandwidth that re-uploading to GPU across bus for every
frame
 Contents of VBO may be modified after creation
◼ But often don’t need to be update all of it – just parts

 Can store any attributes, more than just vertex


position:
 Color
 Normal

 Texture coordinates

More on VBO in upcoming lecture


4 – Drawing Mesh using VAOs

 Vertex Array Objects


 “Container” for VBOs
 See OpenGL Mesh Rendering Lecture Notes
Nice Guide to OpenGL Rendering
 https://github.com/cs123tas/docs/blob/master/O
penGL-Guide.md
Interpolation
Interpolation of Vertex Colors

// Example equilateral triangle


glBegin(GL_LINE_LOOP);
glColor3f(1, 0, 0);
glVertex3f(-.5, -.5, 0);
glColor3f(0, 1, 0);
glVertex3f(.5, -.5, 0);
glColor3f(0, 0, 1);
glVertex3f(0, 0.366, 0);
glEnd();

Interpolation automatically done during rasterization


Interpolation of vertex colors

// Example equilateral triangle


glBegin(GL_TRIANGLES);
glColor3f(1, 0, 0);
glVertex3f(-.5, -.5, 0);
glColor3f(0, 1, 0);
glVertex3f(.5, -.5, 0);
glColor3f(0, 0, 1);
glVertex3f(0, 0.366, 0);
glEnd();

Interpolation automatically done during rasterization


Interpolation

 Many attributes, including user-defined, are


interpolated during rasterization

 e.g. colors, depth, normal vectors, texture


coordinates, …
 More on this in later lectures
OpenGL Main Loop
OpenGL Main Loop

 As we have seen, modeling, rendering, displaying, are


implemented within a so-called graphics/rendering pipeline

Model World Eye


Coordinates Coordinates Coordinates
Modeling Viewing
Vertex Transformation Transformation

Screen (Window) Normalized Device Clip


Coordinates Coordinates Coords.
Viewport Perspective Projection
Transformation Division Transformation

74
Reminder: The Camera Analogy (3D)

1. Compose and arrange the scene (Modeling Transformations)


2. Set up the tripod and point the camera at the scene (Viewing
transformation)
3. Choose a camera lens or adjust the zoom (Projection
transformation)
4. Determine how large you want the final “photograph” to be
(e.g. wallet size, portrait size) (Viewport transformation: i.e.
screen window)

75
Modelling Transformation

 How do we put objects (models) into the scene (i.e. the


world)?

 A:
◼ Hard code the coordinates of each vertex (i.e. set their x,y,z coordinates
to where you want them)
 B:
◼ Construct a model in its own local (“Model-based”) coordinate system,
◼ make a copy of it (an instance),
◼ then translate/scale/rotate into scene (using glTranslate(),glScale(),
glRotate() etc.) into the world coordinate system
76
Modelling Complex Multi-part Objects
⚫ We can also compose a more complex object (e.g. a nail) by
putting its parts together with transformations.

Translate , T1

Scale & translate , T2S


modeling
coordinates

World coord

Primitives
Rotate& translate , T3R

Composition
77
OpenGL Matrix Modes
T2Sp
 Suppose we want to model some
objects (e.g. red triangles)
Sp T1Sp

p
 We start with simple primitive (blue triangle), defined in its own local (i.e.
model) coordinate system, then copy it, scale it and move it to desired location
in the scene (i.e. world coordinate system) (modelling transformation)
 An image of these objects is created by rendering process. Part of this process
is the viewing and projection operations.
 In OpenGL, modeling + viewing + projection transformations are each
implemented with a transformation matrix (Next week’s lecture).
78
Transformation via a Matrix
 glTranslate(), glRotate(), glScale() and other geometric
transformations are implemented using matrices
OpenGL Matrix Modes
 A sequence of transformations (modeling+viewing+projection) can be
multiplied together (concatenated) to form a single matrix.
 This matrix (the current transformation matrix – CTM) forms a part of the
state of OpenGL
 There are two matrix modes in OpenGL which are used to setup two
matrices:
 MODELVIEW matrix – Modeling Matrix * Viewing Matrix
 PROJECTION matrix
 glMatrixMode() is used to set the mode:
 glMatrixMode(GL_PROJECTION)
 glMatrixMode(GL_MODELVIEW)
 Default setting is MODELVIEW matrix
80
Modelling Transformation Example

// Sample code showing matrix transformations


// assume glMatrixMode( GL_MODELVIEW ); has been called
// previously in the openGL initialization code

void display_object()
{

// Some transformations
glTranslatef( 0.0, 0.0, -2.0 );
glRotatef( 45.0, 0.0, 0.0, 1.0 );
glScalef( 2.0, 2.0, 2.0 );
draw_object();
}
Code for draw object() function would use immediate mode or VAO or VBO to draw object
OpenGL Camera: Viewing Transformation

 By default, OpenGL places a camera at the origin in world


coordinates pointed in the negative z direction

 In 3D applications, use gluLookAt() to set the desired view


of the world (i.e. Set up the camera)

 Viewing transformation transforms object vertices from


world coordinates to view (i.e. camera or eye) coordinates.

82
3D viewing: use gluLookAt(...) to position the camera

yw

xw

zw
Projection Transformation
 Projection matrix defines the type of projection (orthographic or
perspective) and the view volume . Think of it as setting the type of
lens on the camera (i.e. whether you want to zoom in or out)

 The default is orthographic and the viewing volume is a box


centered at the origin with a side of length 2

 glOrtho(left, right, bottom, top, near, far)


 the near and far distances are measured from the camera position.
 gluPerspective( fov, aspectRatio, near, far )
 fov: field of view (degrees)
84
Orthographic Projection
Perspective Projection
Orthographic View Volume

Projection Plane
Perspective View Volume
Projection Plane
2D Viewing/Projection Transformation
 If the application is 2D, we can use the function gluOrtho2D(left, right, bottom, top)
(NOTE: not glOrtho() but gluOrtho2D())

 gluOrtho2D() calls gluLookAt() and sets the camera on the z axis looking toward the
origin

 gluOrtho2D() also calls glOrtho() and creates a very thin orthographic view volume so
all 2D objects essentially have their vertex z values = 0

 You can use 2D vertex commands place all vertices in the plane z=0 (e.g.
glVertex2f(x,y) )

 The view volume (also called the clipping volume) essentially becomes a clipping
rectangle (also called a clip window or view window)
89
• “2D” orthographic view: gluOrtho2D() calls gluLookAt() and
glOrtho()
Basic OpenGL Program
Basic OpenGL Program Sequence
1. Use glutCreateWindow() to create window on screen
2. You decide on your world coordinate ranges (store in global variables)
 (xmin, xmax, ymin, ymax, zmin, zmax)
 you never actually specify to openGL what your world range is!!!
3. Use gluLookAt() to position the camera in the world and where it is aimed
4. Use gluOrtho()/gluPerspective() to define what part of this world to look at
 i.e. zoom in or out
5. Use glViewport() to define part of screen window you will use
6. Create your objects (models) and move them (translate, rotate, scale) into
the world
7. Draw the scene (i.e. call glFlush() or glutSwapBuffers())
 glutswapBuffers() for moving objects – uses double buffering
Viewports (Screen Mapping)

 There is a difference between the viewport and the screen window


 Do not have use the entire window for the viewport: glViewport(x, y, w, h)
 Values in pixels (screen coordinates)

93
Basic OpenGL Program Structure

 Most OpenGL programs have a similar structure that


consists of the following functions
– main():
◼ defines the callback functions
◼ opens one or more windows with the required properties
◼ enters event loop (last executable statement)
– initGL(): sets the openGL state variables
◼ Viewing
◼ Attributes
 callback functions
◼ Display (draw) function
◼ Input (mouse, keyboard) and window functions

94
main.c

#include <GL/glut.h> Includes gl.h


int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,250);
glutInitWindowPosition(0,0); define window properties
glutCreateWindow("Simple");
glutDisplayFunc(display);
display callback
initGL();
set OpenGL state (user defined function)
glutMainLoop();
}
enter event loop (never returns)
95
GLUT functions
 glutInit allows application to get command line arguments and
initializes system
 gluInitDisplayMode requests properties for the window (the rendering
context)
 RGB color
 Single buffering
 Properties logically ORed together
 glutWindowSize in pixels
 glutWindowPosition from top-left corner of display
 glutCreateWindow create window with title “Simple”
 glutDisplayFunc display callback
 glutMainLoop enter infinite event loop

96
GLUT Windows
 Create a top-level window with:
 int id = glutCreateWindow(char *name);

 Create sub-windows with:


 glutCreateSubWindow(int id, x, y, w, h);

 id: ID of the parent window

 x, y: Position relative to the parent window

 w, h: Width and height in pixels

 Set the current window:


 glutSetWindow( int id );

 Get the id of the current window:


 int id = glutGetWindow(void);
Event Loop

 Note that OpenGL programs define a display


callback function, typically named display
 Every glut program must have a display callback

 The display callback is executed whenever OpenGL


decides the display must be refreshed, for example
when the window is opened

 The main function ends with the program entering an


event loop
98
Initialize OpenGL Matrices
• Typically these functions are called once but you can call them as many times as
you like in the display callback function (e.g. you want to move the camera)
• Here is where you could initialize your own global variables and data structures

void initGL(unsigned int w, unsigned int h)


{
glViewport(0, 0, 500, 250);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0,(double)w/(double)h,0.1,20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
} 99
initGL(): Setup Viewport, Default Viewing and Projection

 glViewport(0, 0, width, height);


 Define the portion of the window you created with glutCreateWindow that you
wish to draw your scene (typically whole window)
 glMatrixMode(GL_PROJECTION);
 The matrix we’re going to set is the PROJECTION matrix
 glLoadIdentity();
 Make PROJECTION matrix the identity matrix initially
 gluPerspective (fov, aspect, near, far);
 Create a perspective projection matrix that defines a view volume of your
world. Default camera is at (0,0,0) with y up and looking down –z axis.
 glMatrixMode (GL_MODELVIEW);
 Future transformations (gluLookAt, glRotate, glScale etc) called in display()
function will affect MODELVIEW matrix
100
Display (i.e. draw) Callback Function
void display()
{
glClear(GL_COLOR_BUFFER_BIT);

// do viewing or modeling transformations here


// e.g.: gluLookAt() if you want to change the camera
// or glTranslate(), glScale(),glRotate() to move objects

// Draw the scene. In this simple example – one polygon


glBegin(GL_POLYGON);
glVertex3f(-25.0, -25.0, 0.0);
glVertex3f( 25.0, -25.0, 0.0);
glVertex3f( 25.0, 25.0, 0.0);
glVertex3f(-25.0, 25.0, 0.0);
glEnd();

glFlush();
} 101
Compiling OpenGL Programs
Compilation on Windows

 Visual Studio
 Get glut.h, glut32.lib and glut32.dll from web
◼ Use freeglut!!
 Create a win32 console application
 Click next then check Empty Project
 Add opengl32.lib, glu32.lib, glut32.lib to project settings (under link
tab – see posted instructions on D2L

 Cygwin (linux under Windows)


 Can use gcc and similar makefile to linux
 Use –lopengl32 –lglu32 –lglut32 flags
103
OpenGL #defines

 Most constants are defined in the include files gl.h, glu.h


and glut.h
 Note #include <GL/glut.h> should automatically include the others
 Examples
– glBegin(GL_POLYGON)
– glClear(GL_COLOR_BUFFER_BIT)

 include files also define OpenGL data types: GLfloat,


GLdouble,….

104

You might also like