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

OpenGL: Understanding FOV and APIs

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

Topics covered

  • OpenGL examples,
  • OpenGL rendering techniques,
  • OpenGL community,
  • OpenGL development,
  • OpenGL applications,
  • OpenGL optimization,
  • graphics API,
  • WebGL,
  • polygon rendering,
  • OpenGL setup
0% found this document useful (0 votes)
42 views104 pages

OpenGL: Understanding FOV and APIs

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

Topics covered

  • OpenGL examples,
  • OpenGL rendering techniques,
  • OpenGL community,
  • OpenGL development,
  • OpenGL applications,
  • OpenGL optimization,
  • graphics API,
  • WebGL,
  • polygon rendering,
  • OpenGL setup

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

Common questions

Powered by AI

The OpenGL Utility Toolkit (GLUT) facilitates OpenGL application development by providing a simplified interface for managing windows, handling input devices, and performing basic event handling. GLUT is widely used for teaching and prototyping as it abstracts complex interactions, allowing developers to focus on graphics programming. However, GLUT lacks advanced features like multi-threading support, which are present in more modern windowing libraries such as GLFW. GLFW, besides supporting OpenGL, is also compatible with OpenGL ES and Vulkan, and offers greater flexibility and control over window creation, input handling, and advanced rendering context management. Therefore, while GLUT is suitable for quick development and learning, GLFW is preferred for more complex, full-featured applications .

The primary difference between OpenGL and Vulkan lies in their level of abstraction and control over the GPU. OpenGL is a high-level API which simplifies the graphics programming by hiding complex details from the programmer, making it easier to use but potentially less efficient. In contrast, Vulkan offers a lower-level API that provides more explicit control over GPU operations, which can lead to better performance but at the cost of increased complexity and a steeper learning curve. These differences affect their use cases in that OpenGL is more suitable for applications where ease of use and rapid development are prioritized, such as in educational environments or smaller projects. Vulkan, on the other hand, is better suited for applications that require maximum performance and fine-grained control, such as in game engines or high-performance computing .

The OpenGL Shading Language (GLSL) is crucial in rendering graphics as it allows developers to write programs that execute on the GPU to control the rendering pipeline stages. GLSL provides a high-level language for writing vertex, fragment, and geometry shaders, enabling developers to manipulate vertex data, perform complex lighting calculations, and apply textures directly on the GPU. This capability allows for more realistic rendering effects and better performance by offloading computations from the CPU to the GPU. GLSL's importance lies in its flexibility and power to create custom graphics effects, contributing to visually enriched applications .

OpenGL's non-object-oriented design impacts its functionality and flexibility by requiring programmers to manage state changes and rendering sequences independently of any object hierarchy. This design enables fine control over graphics operations and allows for procedural programming patterns, beneficial for applications where performance optimization and low-level graphics manipulation are needed. However, this can lead to code that is more difficult to manage, extend, or modify compared to object-oriented systems which group data and functionality into reusable classes. Programmers must explicitly handle graphical states and rendering steps, often resulting in complex and verbose codebases .

OpenGL's matrix modes, specifically the MODELVIEW and PROJECTION matrices, are significant for executing 3D transformations in graphics applications. The MODELVIEW matrix combines both modeling and viewing transformations, allowing developers to position and orient objects and the camera within a scene. The PROJECTION matrix, on the other hand, defines how objects are projected from 3D space onto a 2D screen through perspective or orthographic projections. These matrices enable the creation of photorealistic views by transforming object coordinates from model space to screen space in an efficient, structured manner. Proper manipulation of these matrix modes is crucial for achieving correct scene layouts and realistic perspectives, making them integral to 3D rendering .

Vertex attributes and transformation matrices in OpenGL contribute to efficient 3D rendering by efficiently encoding and manipulating vertex data and spatial transformations. Vertex attributes, such as positions, normals, colors, and texture coordinates, describe necessary input data for rendering, allowing the GPU to perform operations like lighting and texturing directly on a per-vertex basis. Transformation matrices apply necessary rotation, translation, and scaling operations to vertex data, facilitating the rendering pipeline stages from model space to world and screen space. Together, they enable highly optimized rendering processes that can handle complex scenes with minimal CPU overhead, leveraging the full power of the GPU for fast and realistic graphics .

The cross-platform nature of OpenGL is a major benefit compared to proprietary APIs like Direct3D, as it allows developers to write applications that run on various operating systems and devices without rewriting graphics code for each platform. This reduces development time and increases the reach of applications. However, the trade-off includes potential drawbacks such as performance overheads and less direct integration with certain platform-specific features that proprietary APIs might leverage (e.g., Direct3D's tight integration with Windows). While OpenGL is highly versatile, these drawbacks can affect applications that require maximum performance optimization on specific platforms .

OpenGL is a cross-platform software API that provides a set of functions to interact with graphics hardware directly. It allows developers to create both 2D and 3D graphics in a device-independent manner, making it particularly suitable for professional graphics applications. OpenGL achieves cross-platform compatibility by abstracting hardware-specific details through its API, making it versatile for various operating systems and devices. Its suitability for professional graphics applications comes from its widespread adoption and support from major graphics vendors, ensuring high performance and access to advanced graphical features .

The introduction of Vulkan as a successor to OpenGL marks a significant shift in graphics application development by providing a more direct, low-level interface to the GPU. This allows developers greater control over memory and compute resources, leading to more efficient and optimized applications. The impact of Vulkan's introduction includes the potential for higher performance across a wide range of devices, as well as enabling complex simulations and graphics effects through its fine-grained feature set. However, its complexity requires more sophisticated programming knowledge, potentially increasing development time and cost. Despite these challenges, Vulkan is expected to drive advancements in real-time graphics and computationally intensive tasks .

OpenGL's state machine architecture defines how graphics are rendered by maintaining a current state that affects rendering operations. This state consists of a collection of attributes and modes that remain in effect until explicitly altered by the programmer. As operations are processed, OpenGL applies the current state to determine how graphics are rendered. This architecture allows for complex, flexible rendering configurations through state changes without requiring significant modifications to existing code. The state machine design influences management by necessitating a careful organization of state changes, as improperly configured states can lead to unexpected rendering outputs .

You might also like