0% found this document useful (0 votes)
24 views15 pages

Introduction To OPen GL

The document provides an introduction to OpenGL and discusses its core concepts including the rendering pipeline, API functions, primitive geometry, color models, transformations, and state management. Key topics covered include initializing OpenGL, registering callback functions, and the basic structure of OpenGL programs.

Uploaded by

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

Introduction To OPen GL

The document provides an introduction to OpenGL and discusses its core concepts including the rendering pipeline, API functions, primitive geometry, color models, transformations, and state management. Key topics covered include initializing OpenGL, registering callback functions, and the basic structure of OpenGL programs.

Uploaded by

Marvin Marquez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

Graphics Programming

Introduction to OpenGL
Outline
• What is OpenGL
• OpenGL Rendering Pipeline
• OpenGL Utility Toolkits
• OpenGL Coding Framework
• OpenGL API
Graphics System
I I
Function
I I
I I
I I
I I
I
I I
I I
A DT
What is OpenGL
OpenGL
• A software interface to graphics hardware
• A 3D graphics rendering API (>120 functions)
• Hardware independent
• Very fast (a standard to be accelerated)
A History of OpenGL
• Was SGI's Iris GL - “OperT’GL
• “Open” standard allowing for wide range hardware platforms
• OpenGL v1.0 (1992)
• OpenGL v1.1 (1995)
• OpenGL v1.4 (latest)
• Governed by OpenGL Architecture Review Rnorrl fARPU
Graphics Process
Geometric Primitives
Rendering
Frame
Buffer
Image Primitives
OpenGL Architecture
Unpack
Displiy Lnts
/
* Imagt Ravttdutloci
Pixd OptrafWH |
»
i
i
i _____________ C
M.....I ! lament
0|wal|m • ►
i
i
i
i
i z—^-u- > Tixturc
i
----------------\\
TO FRAME HUFFFH >j
OpenGL is Not a Language
It is a Graphics Rendering API
Whenever we say that a program is OpenGL-based or OpenGL applications, we mean that
it is written in some nrnaramminn lanniiAnp f^imh C./C-i-i-^
Window Management
• OpenGL is window and operating system independent
• OpenGL does not include any functions for window management, user
interaction, and file I/O
Ila ■ a ■ ■ I I r
Window Management API
We need additional libraries to handle window management
• GLX/AGL/WGL
- glue between OpenGL and windowing systems
• GLUT
— V\/inrln\A/ lntarfanp/1 Itilitv tnnlkit
OpenGL API Hierarchy
OpenGL Division of Labor
• GL
- “core” library of OpenGL that is platform independent
• GLU
- an auxiliary library that handles a variety of sraohics accessory functions
Libraries and Headers
Library Name Library File Header File Note
OpenGL opengl32.1ib (PC) -lgl (UNIX) gl.h “core” library
Auxiliary library glu32.1ib (PC) -lglu glu.h handles a variety of accessory
functions
Utility toolkits glut32.1ib (PC) glut.h window
Learning OpenGL with GLUT
• GLUT is a Window Manager (handles window creation, user interaction,
callbacks, etc)
• Platform Independent
• Makes it easy to learn and write OpenGL programs without being distracted by
your environment
Environment Setup
• All of our discussions will be presented in C/0++ language
• Use GLUT library for window managements
• Files needed
gl.h, glu.h, glut.h
opengl32.lib, glu32.lib, glut32.lib
Usage
Include the necessary header files in your code
#include <GL/gl.h> #include <GL/glu.h>
#include <GL/glut.h>
// “core”, the only thing is required
// handles accessory functions
// handles window managements
void main( int argc, char **argv ) {
Usage
Link the necessary Libraries to your code
• Link GL library
- Link opengl32.1ib (PC), or -lgl (UNIX)
• Link GLU library
- Link glu32.1ib (PC), or -lglu (UNIX)
_ T • 1_ T Trpi 1’1_
OpenGL Data Types
To make it easier to convert OpenGL code from one platform to another, OpenGL
defines its own data types that map to normal C data types
OpenGL Data Types
OpenGL Data Type Representation As C Type
GLbyte 8-bit integer signed char
GLshort 16-bit integer short
GLint, GLsizei 32-bit integer long
GLfloat 32-bit float float
GLdouble 64-bit float double
OpenGL Function Naming
OpenGL functions all follow a naming conventioi that tells you which library the
function is from, and how many and what type of arguments that the function takes
OpenGL Function Naming
gl library Root command, # of arguments, type of arguments
f: the argument is float type
Basic OpenGL Coding Framework
1. Configure GL (and GLUT)
- Open window, Display mode,...
2. Initialize OpenGL state
- background color, light, View positions,.
3. Register callback functions
A Sample Program
void main (int argc, char **argv)
{
A glut I nit (&argc, argv);
glutlnitDisplayMode (GLUTJSINGLE I GLUT_RGB);
glutlnitWindowSize (500, 500);
glutCreateWindow (“My First Program"); j
myinit (); }
— iTA!--1__17__/ JI--1__
1: Initializing & Creating Window
Set up window/display you’re going to use
void main (int argc, char **argv)
{
glutlnit (&argc, argv); // GLUT initialization
glutlnitDisplayMode (GLUT_SINGLE I GLUT_RGB); // display mode glutlnitWindowSize
(500, 500); // window size
GLUT Initializing Functions
• Standard GLUT initialization
glutlnit (int argc, char ** argv)
• Display model
glutlnitDisplayMode (unsigned int mode)
• Window size and position
glutlnitWindowSize (int width, int height)
2: Initializing OpenGL State
Set up whatever state you’re going to use
void myinit(void)
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
// background color
// line color
// followings set up viewing
Callback Functions
• Callback Function
Routine to call when something happens
- window resize, redraw, user input, etc
GLUT uses a callback mechanism to

GLUT Callback Functions


Contents of window need to be refreshed glutDisplayFunc()
Window is resized or moved
glutReshapeFunc()
Key action
glutKeyboardFunc()
Mouse button action
glutMouseFunc()
Mouse moves while a button is pressed
3: Register Callback Functions
Set up any callback function you're going to use
void main (int argc, char **argv)
glutDisplayFunc ( display); glutReshapeFunc ( resize ); oliif KpvhnardFnnr i kpv V
// display callback
// window resize callback
// kpvhnjird callback
Rendering Callback
It’s here that does all of your OpenGL rendering
void di splay ( void )
{
typedef GLfloat point2[2];
point! vertices[3]={{0.0, 0.0}, {250.0,500.0}, {500.0, 0.0}}; inti, j, k; int
rand();
pICIpaHGE COLOR RITFFFR RITk
Window Resize Callback
It’s called when the window is resized or moved
void resize(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadldentityO;
Keyboard Input Callback
It’s called when a key is struck on the keyboard
void key( char mkey, int x, int y ) {
switch( mkey)
{
case ‘q’:
Event Process Loop
This is where your application receives events, and schedules when callback
functions are called
void main (int argc, char **argv) {
Let’s go Inside
• OpenGL API
-Geometric Primitives
- Color Mode
- Managing OpenGL’s State
-Transformations
OpenGL API Functions
• Primitives
- A point, line, polygon, bitmap, or image
• Transformation
- Rotation, size, perspective in 3D coordinate space
• Color mode
- RGB, RGBA, Color index
• Materials lighting and shading
Apcnmfplv rnmnnfp fhp rnlnr nf finv nninf oivpn fhp miifprijil nrnnprfi
Geometric Primitives
Geometry Commands
• glBegin(GLenum type)
marks the beginning of a vertex-data list that describes a geometric primitives
• glEnd (void)
mark« flip pnd nfa vprtP.Y-data list
Specifying Geometric Primitives
glBegin( );
glVertex*(...);
glVertex*(...); glEnd();
Example
void drawSquare (GLfloat *color) {
glColor3fv (color); glBegin(GL_POLYGON);
glVertex2f ( 0.0,0.0 );
glVertex2f (1.0,0.0);
Primitives and Attributes
Draw what...
- Geometric primitives
• points, lines and polygons
How to draw...
Attributes
• An attribute is any property that determines how a geometric primitives is to
be rendered
• Each time, OpenGL processes a vertex, it uses data stored in its internal
attribute table
Example
glPointSize(3.0);
glShadeModel(GL_SMOOTH); glBegin(GL_LINE);
glColor4f( 1.0, 1.0, 1.0, 1.0);
glVertex2f(5.0, 5.0);
OpenGL Color
• There are two color models in OpenGL
- RGB Color (True Color)
- Indexed Color (Color map)
• The type of window color model is requested from the windowing system. O non
AI has no command to control
Color Cube
RGB Color
• R, G, B components are stored for each pixel
• With RGB mode, each pixel’s color is independent of each other
RGB Color
Red
isaaiiMiii
Green
How Many Colors?
„ . , ncolor depth
Color number = 2 -
For example:
4-bit color
24 = 16 colors
8-bit color
How Much Memory?
Buffer size = width * height *color depth
For example:
If width = 640, height = 480, color depth = 24 bits Buffer size = 640 * 480 * 24 =
921,600 bytes
_ A/IM _ 4QA

Alpha Component
Alpha value
A value indicating the pixels opacity
Zero usually represents totally transparent and the maximum value represents
completely opaque
Alpha buffer
RGB Color Commands
• glColor*(...)
specifies vertex colors
• glClearColor(r, g, b, a)
sets current color for cleaning color buffer
Example
glutlnitDisplayMode (GLUT_RGBA); glClear Color (1.0,1.0,1.0,1.0);
void drawLine (GLfloat *color) {
glColor3fv (color); glBegin(GL_LINE);
Indexed Color
• Historically, color-index mode was important because it required less memory
• Use Color-map (lookup table)
• With color-index mode, each pixel with
Color Lookup Table
Index
0
1
Red Green Blue
0 0 0
120 123 187

• • • • • • • • •
253
RGBA vs. Color Index Mode
Color index model
Index R G B
0 0 0 0
— I 120 123 187
2
• • • • • • • • • • • •
254
Color Index Commands
• gllndex*(...)
specifies vertex colors
• glClearIndex(Glfloat index)
sets current color for cleaning color buffer.
Shading Model
Red
Shading Model
Blue
Green
✓ r. /
\ ✓
V ✓
/ / f MM MB ■ - T \ I \ I I \ I ' ■■_rL h
1
i i i
i
i i
i
• / V
Red
Shading Model Commands
• glShadeModel(mode)
set the shading mode. The mode parameter can be GL_SMOOTH (the default) or GL_FLAT.
Flat shading: the color of one particular vertex of an independent primitive is
duplicated across all the nri mi five’s vertices to render that nrimitive.
OpenGL’s State Machine
In OpenGL, all rendering attributes are encapsulated in the OpenGL State
- rendering styles
-color
-shading
OpenGL’s State Management
Setting Vertex Attributes
- glPointSize(...)
- glLineWidth(...)
- glColor*(...)
- glNormal*(...)
- glTexCoord*(...)
-- point size -- line width
— color
— normal
-- texturing
> Attribute
Controlling State Functions
• OpenGL has many states and state variables can be changed to control rendering
Ex.
- GL_LIGHTING
- GL_DEPTH_TEST
- GL_SHADE_MODEL
Controlling State Functions
• By default, most of the states are initially inactive. These states can be turn
on/off by using:
• glEnable (Glenum state)
turn on a state
Example
gl Enable (GL_LIGHTING);
gl ShadeModel (GL_SMOOTH); glBegin(GL_LINE);
glColor3f(1.0, 1.0, 1.0);
glVertex2f(5.0, 5.0);
glColor3f(0.0, 1.0, 0.0);
OpenGL Transformations
Graphics Pipeline
Object
Object Coordinates
Transformation
Object -> World
World
World Coordinates
Transformation
World -> Viewport
Viewport
Clipping
Camera Analogy
The graphics transformation process is analogous to taking a photograph with <
camera
- Position camera
- Place objects
Transformations and Camera Analogy
• Viewing transformation
- Positioning and aiming camera in the world.
• Modeling transformation
- Positioning and moving the model.
• Projection transformation
— AdiiiQtincy fhp lpnc nf fhp enmpra
OpenGL Transformation Pipeline
eve

normalized device
window
Projection
Matrix
Projection
h
Perspective
Division
Viewport
Transform
Transformations in OpenGL
• Transformations are specified by matrix operations. Desired transformation
can be obtained by a sequence of simple transformations that can be concatenated
together.
• Transformation matrix is usually represented
Programming Transformations
• In OpenGL, the transformation matrices are part of the state, they must be
defined prior to any vertices to which they are to apply.
• In modeling, we often have objects specified in their own coordinate systems
and must use transformations to bring the objects into the scene.
Steps in Programming
• Define matrices:
- Viewing/modeling, projection, viewport...
• Manage the matrices
- Including matrix stack
• Composite transformations
Transformation Matrix Operation
• Current Transformation Matrix (CTM)
- The matrix that is applied to any vertex that is defined subsequent to its
setting.
• If change the CTM, we change the state of the system.
Current Transformation Matrix
The CTM can be set/reset/modify (by postmultiplication) by a matrix
Ex:
C <= M
C <= CT
// set to matrix M
// post-multiply by T
Current Transformation Matrix
• Each transformation actually creates a new matrix that multiplies the CTM;
the result, which becomes the new CTM.
• CTM contains the cumulative product of multiplying transformation matrices.
Viewing-Modeling Transformatioi
• If given an object, and I want to render it from a viewpoint, what information do
I have to have?
-Viewing position
- Which way I am looking at
- Which way is “up”
Viewing Position
Where I am and Looking at
______________.y
View-up vector (up,, up>, upz)
Define Coordinate System
In the default position, the camera is at the origin, looking down the
+Y
If we use OpenGL
• Look-At Function
gluLookAt (eye*, eyey, eye?, atr, aty, at?, up*, up.v, up?)
Define a viewing matrix and multiplies it to the right of the current matrix.
Ways to Specify Transformations
• In OpenGL, we usually have two styles of specifying transformations:
- Specify matrices ( glLoadMatrix, glMultMatrix )
- Specify operations ( glRotate, glTranslate )
Specifying Matrix
• Specify current matrix mode
• Modify current matrix
• Load current matrix
• Multiple current matrix
Specifying Matrix (1)
• Specify current matrix mode
glMatrixMode (mode)
Specified what transformation matrix is modified.
mode\
Specifying Matrix (2)
• Modify current matrix
glLoadMatrix{fd} ( Type )
Set the 16 values of current matrix to those specified by m.
Specifying Matrix (3)
• Modify current matrix
glLoadldentity (void)
Set the currently modifiable matrix to the 4x4 identity matrix.
Specifying Matrix (4)
• Modify current matrix
glMultMatrix{fd} ( Type )
Multiple the matrix specified by the 16 values pointed by m by the current matrix,
and stores the rnciilt o c> /'lirriitTf wi o tvi v
Specifying Operations
• Three OpenGL operation routines for modeling transformations:
-Translation
- Scale
- Rotation
Recall
• Three elementary 3D transformations
1 0 0 dx
Translation:
0 dy
1 dz
0 0 0 1
To n n n"l
Recall
1 0 0 0
Rotation Rx(0)
cos0 -sin# 0
sin# cos# 0
0 0 0 1
Rotation Ry(6)
cos# 0 sin# 0
0 10 0
-sin# 0 cos# 0
0 0 0 1
Specifying Operations (1)
• Translation
glTranslate {fd} (TYPE x, TYPE j, TYPE z)
Multiplies the current matrix by a matrix that translates an object by the given x,
y, z.
Specifying Operations (2)
• Scale
glScale {fd} (TYPE*, TYPE j, TYPE z) Multiplies the current matrix by a matrix that
scales an object by the given x, y, z.
Specifying Operations (3)
• Rotate
glRotate {fd} (TPE angle, TYPE*, TYPEy, TYPE z) Multiplies the current matrix by a
matrix that rotates an object in a counterclockwise direction about the nr from
orisin through the noint bv the siven x. v. z. The
Example
Let’s examine an example:
- Rotation about an arbitrary point
Question:
Rotate a object for a 45.0-degree about the line through the origin and the point
(1.0, 2.0, 3.0) with
Rotation About an Arbitrary Point
1. Translate object through vector-V.
T(-4.0, -5.0, -6.0)
2. Rotate about the origin through angle 0.
R(45.0)
3. Translate back through vector V
OpenGL Implementation
gIMatrixMode (GL_MODEVIEW); glLoadldentity ();
glTranslatef (4.0, 5.0, 6.0);
glRotatef (45.0, 1.0, 2.0, 3.0);
rrlTranc 1 (_/1A A A CA*
Order of Transformations
• The transformation matrices appear in reverse order to that in which the
transformations are applied.
• In OpenGL, the transformation specified most recently is the one applied
first.
Order of Transformations
• In each step:
c<=i
C <= CT(4.0, 5.0, 6.0)
C <= CR(45, 1.0, 2.0, 3.0)
C < = CT(-4.0, -5.0, -6.0)
• Finally
Matrix Multiplication is Not Commutative
First rotate, then translate =>
Matrix Stacks
• OpenGL uses matrix stacks mechanism to manage transformation hierarchy.
• OpenGL provides matrix stacks for each type of supported matrix to store
matrices.
- Model-view matrix stack
Matrix Stacks
Current matrix is always the topmost matrix of the stack
We manipulate the current matrix is that we actually manipulate the topmost matrix.
Push
Manipulating Matrix Stacks (1)
Remember where you are
glPushMatrix (void)
Pushes all matrices in the current stack down one level. The topmost matrix is
copied, so its contents

th
Manipulating Matrix Stacks (2)
Go back to where you were
glPopMatrix (void)
Pops the top matrix off the stack, destroying the contents of the popped matrix.
What was the fnrx mnfriv za <? flnzi t/\r\
Manipulating Matrix Stacks (3)
The depth of matrix stacks are implementation-dependent.
The Modelview matrix stack is guaranteed to be at least 32 matrices deep.
The Projection matrix stack is guaranteed to be at least 2 matrices deep.
glGetlntegerv ( Glenum pname, Glint *parms )
Projection Transformation
• Projection & Viewing Volume
• Projection Transformation
• Viewpoint Transformation
OpenGL and Windows Screen

Windows Screen Mapping


OpenGL Screen Mapping
Y Positive
(0,0)1
Positive -------X

Orthographic Projection
• Vertexes of an object are projected towards infinity
• Points projected outside view volume are clipped out
_ -X______J__________X
Orthographic Viewing Volume
Orthographic Projection Commands
• glOrtho( left, right, bottom, top, zNear, zFar )
Creates a matrix for an orthographic viewing volume and multiplies the current
matrix by it
gluOrtho2D( left, right, bottom, top )
Orthographic Projection (Example)
Define a 500x500 viewing rectangle with the lower-left corner of the rectangle at
the origin of the 2D system
glMatrixMode(GL_PROJECTION)
glLoadldentityO;
Perspective Projection Volume
Perspective Projection Commands
glFrustum( left, right, bottom, top, zNear, zFar )
Creates a matrix for a perspective viewing frustum and multiplies the current
matrix by it.
Perspective Projection Commands
gluPerspective( fovy, aspect, zNear, zFar )
Creates a matrix for an perspective viewing frustum and multiplies the current
matrix by it.
✓ f
X
Hidden-Surface Removal
z-buffer algorithm
- Image-space check
- The worst-case complexity is proportional to the number of polygons
_ PAniiirAC o rlAnth
Remember to Initialize
glutInitDisplayMode(GLUT_DOUBLEIGLUT_RBGIGLUT_DEPTH);
You can also clear the depth buffer (as we did for color buffer)
glCIear(GL_DEPTH_BUFFER_BIT)
Viewing a 3D world
View up
. _ . View Right
Aspect Ratio =-------—
ViewUp

View right
Viewpoint
• Viewpoint
-The region within the window that will be used for drawing the clipping area
- By default, it is set to the entire rectangle of the window that is opened
- Measured in the window coordinates,
Viewpoint Transformation
Aspect Ratio
• The Aspect Ratio of a rectangle is the ratio of the rectangle’s width to its
height:
e.g. Aspect Ratio = width/height
Viewport aspect ratio should be same as
Viewpoint Commands
• glViewport( x, y, width, height)
Defines a pixel rectangle in the window into which the final image is mapped
(x, y) specifies the lower-left corner of the viewport
Lighting
• Point light source - approximates the light source as a 3D point in space.
Light rays emanate in all directions.
• Distributed light source - approximates the lighl source as a 3D object.
Light rays usually emanate in specific directions.
• Spotlights - characterized by a narrow range of angles through which light is
emitted.
_ nrm/i/do iinifrvrm ilh iminotinn
Light Model
• Ambient
The combination of light reflections from various surfaces to produce a uniform
illumination. Background light.
• Diffuse
Uniform light scattering of light rays on a surface. Proportional to the “amount of
light” that hits the surface. Depends on the surface normal and liaht vector.
Light Model
Light at a pixel from a light = Ambient +
Diffuse +
Specular
Ilight ^ambient + ^diffuse + * specular
liehts-\
Shading
Flat Shading
- Calculate one lighting calculation (pick a vertex) per triangle
- Color the entire triangle the same color
Gouraud Shading
- Calculate three lighting calculations (the vertices) per triangle
- Linearly interpolate the colors as you scan convert
Lighting in OpenGL
• OpenGL supports the four types of light sources.
• OpenGL allows at least eight light sources set in a program.
• We must specify and enable individually
Steps of Specifying Lighting
• Define normal vectors for each vertex of every object.
• Create, position, and enable one or more light sources.
• Select a lighting model.
• Dpfinp matprial nrnnprtip.Q for thp nhiprts; ir
Creating Light Sources
• Define light properties
- color, position, and direction
glLight*(Glenum light, Glenum pname, TYPE param
Create the light specified by light, which can be
Creating Light Sources
Color
GLfloat light_ambient[{ = {0.0, 0.0, 1.0, 1.0);
GLfloat lght_diffuse[] = {1.0, 1.0, 1.0, 1.0);
glLightfv (GL_LIGHT0, GL_AMBIENT, lgiht.ambient); elLightfv (GL_LIGHT1, GL_DIFFUSE,
lgiht.diffuse);
Creating Light Sources
Position
GLfloat light_position| ] = {1.0, 1.0, 1.0, 0.0); glLightfv (GL_LIGHT0,
GL_POSITION, lgiht.position);
GLfloat spot_dir[] = {-1.0, -1.0, 0.0); glLightfv (GLJLIGHT1, GL_SPOT_DIRECTION,
spot_dir);
Creating Light Sources
Controlling a Light’s Position and Direction
OpenGL treats the position and direction of a light source just as it treats the
position of a geometric primitives. In other word, a light source is subject to the
same matrix transformations as a primitives.
Selecting Lighting Model
• OpenGL notion of a lighting model has three components:
- The global ambient light intensity.
- Whether the viewpoint position is local to the scene or whether it should be
considered to be infinite distance away.
- Whether lighting calculations should be performed differently for both the
front and back faces of objects.
glLightModel*(Glenum pnatne, TYPE param)
Selecting Lighting Model
• Global ambient light
GLfloat lmodel_ambient[] = (0.2, 0.3, 1.0, 1.0); glLightModelfv
(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
• Local or Infinite Viewpoint
glLightModelfi (GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
• Two-sided Lighting
Defining Material Properties
• OpenGL supports the setting of material properties of objects in the scene
- Ambient
- Diffuse
- Specular
- Shininess
glMaterial*(Glenum face, Glenum pname, TYPE param)
OpenGL Image Path
Texture Mapping in OpenGL
Steps in Texture Mapping
- Create a texture object and specify a texture for that object.
- Indicate how the texture is to be applied to each pixel.
- Enable texture mapping.
- Draw the scene, supplying both texture and geometric coordinates.
Specifying the Texture
GLubyte image[rows][cols]
void gITexImage2D (GLenum target, GLint level, GLint interna I Format, GLsizei
width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid
'^pixels')
T Z^X 4" Z~X •
Z~X 4“ I'X X J « X 4- 1 Z“X X-'X z 1 /x
v 'i
4“ l^x r'x w y z-x
Texture Object
• Texture objects are an important new feature since OpenGL 1.1. A texture
object stores data and makes it readily available.
• To use texture objects for your texture data, take these steps:
- Generate texture names.
Naming a Texture Object
• Any nonzero unsigned integer may be used as a texture name. To avoid accidentally
resulting names, consistently use glGenTexture() to provide unused texture names.
Creating and Using Texture Objecl
• The same routine, glBindTexture(), both creates and uses texture objects.
void glBindTexture (GLenum target, GLuint textureName)
When using it first time, a new texture object is created. When binding to
previously created texture
./"X K « Z-~V 4- 4~ "L-% 4- 4-

Cleaning Up Texture Objects


void gIDeleteTexture (GLsizei n, const GLuint textureNames)
Delete n texture object, named by elements in the array textureNames. The freed
texture names may now be reused.
Set Texture Parameters
void glTexParameter* (GLenum target, GLenum pname, TYPE param)
Set various parameters that control how a texture is treated as it’s applied or
stored in a texture object.
How to control texture mapping and rendering?
Texture Mapping Process
Object -> Texture
Transformation
Screen -> Object
Transformation

Rendering the Texture


• Rendering texture is similar to shading: It proceeds across the surface pixel-by
pixel. For each pixel, it must determine the corresponding texture coordinates (s,
t), access the texture, and set the pixel to the proper texture color.
Combining Lighting and Texturing
• There is no lighting involved with texture mapping
• They are independent operations, which may be combined
• It all depends on how to “apply” the
Set Texturing Function
void glTexEnv (GLenum target, GLenum pname, TYPE param)
Set the current texturing function.
We can use directly the texture colors to paint the object, or use the texture
values to modulate or blend the color in the texture map with the original color of
Assigning Texture Coordinates
void glTexCoord* (TYPE coords)
Sets the current texture coordinates. Subsequent calls to glVertex*() result in
those vertices being assigning the current texture coordinates.
gl Begi n( GL_QUAN) {
alTexCoord2f (0, 0): alVertex2f (0, 0, 5):
Remember to Enable Texture
glEnable (GL_TEXTURE_2D) glDisable (GL_TEXTURE_2D)
Enable/disable texture mapping
Automatic Texture-Coordinate Generatioi
• OpenGL can automatically generate texture coordinate for you.
void glTexGen* (GLenum coord, GLenum pname, TYPE param
Specifies the function for automatically generating texture coordinates.
Recall Aliasing
• Aliasing manifests itself as “jaggies” in graphics. Thus we don’t have enough
pixels to accurately represent the underlying function.
• Three reasons
- Pixel numbers are fixed in the frame buffer
- Pixel locations are fixed on a uniform
- Pixel size/shape are fixed
Increase Rendering Resolution
Render the image at a higher resolution and downsample (like you are letting your
eye do some filtering).
Mip Mapping
• MIP - multium in parvo - many in a small place.
• Build a pyramid of images, each smaller and filtered from the original.
Mipmapping
• Thus as we render, we choose the texture that best “fits” what you are
drawing.
• OpenGL supports mipmapping
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, width, height, GL_RGBA, GL_UNSIGNED_BYTE,
image);
Bump Mapping
• We can also use textures for so much more than just images!
• We can use the textures as a “road map” on how to perturb normals across a
surface.
• As we shade each pixel, perturb the
Environmental Mapping
• Highly reflective surface are characterized by specular reflections that
mirror the environment.
• We can extend our mapping techniques to obtain an image that approximates the
desired reflection by extending texture maps to environmental (reflection) maps.
Environmental Mapping
Two-pass texture mapping
(1) Map the texture to a 3D intermediate surface.
(2) Map the intermediate surface to the surface being rendered.
Object in environment
Environmental Mapping
Then, we need to map the texture values on the intermediate surface to the desired
surface.
n
Now It’s Your Turn
• Find a good reference/book
• Play with an example
• Make your own code
Computer graphics is best learned

You might also like