Texture Mapping

1 / 75

# Texture Mapping - PowerPoint PPT Presentation

Texture Mapping. LIN Tao. Lecture Objectives. Apply a texture by assigning texture coordinates to a polygon explicitly Modify texture parameters Identify the advantages and disadvantages of the different filters available for textures Create textures with multiple levels of detail (mipmaps)

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about 'Texture Mapping' - emmanuel-dalton

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

### Texture Mapping

LIN Tao

Lecture Objectives

Apply a texture by assigning texture coordinates to a polygon explicitly

Modify texture parameters

Identify the advantages and disadvantages of the different filters available for textures

Create textures with multiple levels of detail (mipmaps)

Use texture objects to improve performance

Modify the texture environment

Use OpenGL and GLU to generate texture coordinates automatically

The Limits of Geometric Modeling

Although graphics cards can render over 10 million polygons per second, that number is insufficient for many phenomena

Clouds

Grass

Terrain

Skin

Modeling an Orange（1）

Consider the problem of modeling an orange (the fruit)

Too simple

Replace sphere with a more complex shape

Does not capture surface characteristics (small dimples)

Takes too many polygons to model all the dimples

Modeling an Orange (2)

Take a picture of a real orange, scan it, and “paste” onto simple geometric model

This process is known as texture mapping

Still might not be sufficient because resulting surface will be smooth

Need to change local shape

Bump mapping

Three Types of Mapping

Texture Mapping

Uses images to fill inside of polygons

Environment (reflection mapping)

Uses a picture of the environment for texture maps

Allows simulation of highly specular surfaces

Bump mapping

Emulates altering normal vectors during the rendering process

Texture Mapping

geometric model

texture mapped

OpenGL as Pipeline Architecture

Per Vertex

Operations &

Primitive

Assembly

Polynomial

Evaluator

DisplayList

Per Fragment

Operations

Frame

Buffer

CPU

Rasterization

Texture

Memory

Pixel

Operations

Where does mapping take place?

Mapping techniques are implemented at the end of the rendering pipeline

Very efficient because few polygons make it past the clipper

Is it simple?

Although the idea is simple---map an image to a surface---there are 3 or 4 coordinate systems involved

2D image

3D surface

Coordinate Systems

Parametric coordinates

May be used to model curves and surfaces

Texture coordinates

Used to identify points in the image to be mapped

Object or World Coordinates

Conceptually, where the mapping takes place

Window Coordinates

Where the final image is really produced

What is a Texture?
• A texture image is a rectangular array of pixel data
• Usually a 2D array, but can be 1D or 3D
• A "texture pixel" is called a "texel”
• Can contain color, luminance and/or alpha information
What Information Does a Texture Contain?

struct texel{

unsigned char lumin;

};

A one component texture contains Luminance, Intensity, or Alpha data.

Examples: Wood, grass, sand

struct texel{

unsighed char lumin;

unsigned char alpha;

};

A two component texture contains Luminance and Alpha (transparency) data.

Examples: Trees, clouds

struct texel{

unsighed char b;//blue

unsigned char g;//green

unsigned char r;//red

};

A three component texture contains Red, Green, and Blue values.

Examples: Fabrics, bricks

struct texel{

unsigned char a;//alpha

unsigned char b;//blue

unsigned char g;//green

unsigned char r;//red

};

A four component texture contains Red, Green, Blue, and Alpha values.

Examples: Objects

What is Texture Mapping?

//left top

glTexcoord2f(..)

glVertex3f(...);

//left bottom

glTexcoord2f(..)

glVertex3f(...);

//right top

glTexcoord2f(..)

glVertex3f(...);

//right bottom

glTexcoord2f(..)

glVertex3f(...);

Applying textures (images) to polygons.

Based on parametric texture coordinates

glTexCoord*() specified at each vertex

Mapping a Texture

Texture Space

Object Space

t

1, 1

(s, t) = (0.2, 0.8)

0, 1

A

a

c

(0.4, 0.2)

b

B

C

(0.8, 0.4)

s

0, 0

1, 0

The basic texture mapping steps are:

• Specify the texture.
• glTexImage ；gluScaleImage
• Indicate how the texture is to be applied to each pixel.
• glTexEnv ；glTexParameter
• Enable texture mapping.
• glEnable
• Draw the scene, providing geometric and texture coordinates.
• glTexCoord
Define Image as a Texture

glTexImage2D( target, level, components, w, h, border, format, type, texels );

target: type of texture, e.g. GL_TEXTURE_2D

level: used for mipmapping (discussed later)

components: elements per texel

w, h: width and height of texels in pixels

border: used for smoothing (discussed later)

format and type: describe texels

texels: pointer to texel array

glTexImage2D(GL_TEXTURE_2D, 0, 3, 512, 512, 0, GL_RGB, GL_UNSIGNED_BYTE, my_texels);

Specifying a 2D Texture
• void glTexImage2D ( GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
• target- target texture (it must be GL_TEXTURE_2D for OpenGL release 1.0)
• level - resolution level (it is used for specifying multiple levels-of-detail)
• internalformat- internal storage format of the texture (it must be 1, 2, 3, 4, or one of a number of symbolic constants;

Specifying a 2D Texture

width - width of the texture image (it must be 2m+2*(border) for some integer m)

height - height of the texture image (it must be 2m+2*(border) for some integer m)

border - the width of the border (either 0 or 1)

format - format of the pixel data (GL_RGBA)

type - data type of the pixel data (GL_UNSIGNED_BYTE)

pixels - pointer to the image data in memory

What if the Texture is the Wrong Size？

glTexImage2D() requires a texture whose pixel dimensions are powers of two

If necessary, use the OpenGL utility routine gluScaleImage() to scale the image

Pass the scaled image to glTexImage2D()

Converting A Texture Image

OpenGL requires texture dimensions to be powers of 2

If dimensions of image are not powers of 2

gluScaleImage( format, w_in, h_in, type_in, *data_in, w_out, h_out, type_out, *data_out );

data_inis source image

data_outis for destination image

Image interpolated and filtered during scaling

Scaling Texture Images
• GLint gluScaleImage( GLenum format, GLsizei widthin, GLsizei heightin, GLenum typein, const void *datain, GLsizei widthout, GLsizei heightout, GLenum typeout, void *dataout )
• format specifies the format of the pixel data
• widthin, heightin specify the dimensions of the source image to be scaled
• datain specifies a pointer to the source image
• typeinand typeout specify the data type for datain and dataout, respectively
Texture Coordinates
• Texture coordinates are part of the data that is associated with each vertex.
• A 2D texture is treated as a 1x1 square whose texture coordinates go from 0.0 to 1.0 in each dimension.
• Texture coordinates are homogeneous (s, t, r, q)
• r is unused and q is 1.0
• Assigned explicitly or generated automatically
• Texture coordinates are interpolated as a polygon is filled.
• Filters control how the interpolation is performed
Setting Texture Coordinates Explicitly
• void glTexCoord2fv( const GLfloat *v )
• v Specifies a pointer to an array of two, which in turn specify the s, t, r, and q texture coordinates
Typical Code

glBegin(GL_POLYGON);

glColor3f(r0, g0, b0); //if no shading used

glNormal3f(u0, v0, w0); // if shading used

glTexCoord2f(s0, t0);

glVertex3f(x0, y0, z0);

glColor3f(r1, g1, b1);

glNormal3f(u1, v1, w1);

glTexCoord2f(s1, t1);

glVertex3f(x1, y1, z1);

.

.

glEnd();

Note that we can use vertex arrays to increase efficiency

Texture Parameters

OpenGL has a variety of parameters that determine how texture is applied

Wrapping parameters determine what happens if s and t are outside the (0,1) range

Filter modes allow us to use area averaging instead of point samples

Mipmapping allows us to use textures at multiple resolutions

Environment parameters determine how texture mapping interacts with shading

Wrapping Mode

Clamping: if s,t > 1 use 1, if s,t <0 use 0

Wrapping: use s,t modulo 1

glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )

glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT )

t

s

GL_CLAMP

wrapping

GL_REPEAT

wrapping

texture

OpenGL中，指定的纹理坐标可以在（0，1）区间之外

GL_REPEAT

（0.3，0.6）.

GL_CLAMP

（1.0，0.0）

Magnification and Minification
• One texel rarely corresponds to one pixel on the final screen image.
• Magnification and Minification Filter
• Texture information must be magnified or minified
Magnification and Minification

Texture

Polygon

Texture

Polygon

Magnification

Minification

More than one texel can cover a pixel (minification) or

more than one pixel can cover a texel (magnification)

Can use point sampling (nearest texel) or linear filtering

( 2 x 2 filter) to obtain texture values

Filter Modes P254

Modes determined by

glTexParameteri( target, type, mode )

glTexParameteri(GL_TEXTURE_2D, GL_TEXURE_MAG_FILTER,

GL_NEAREST);

glTexParameteri(GL_TEXTURE_2D, GL_TEXURE_MIN_FILTER,

GL_LINEAR);

Note that linear filtering requires a border of an

extra texel for filtering at edges (border = 1)

Mipmapped Textures (后面详细讨论)

Mipmapping allows for prefiltered texture maps of decreasing resolutions

Lessens interpolation errors for smaller textured objects

Declare mipmap level during texture definition

glTexImage2D( GL_TEXTURE_*D, level,… )

GLU mipmap builder routines will build all the textures from a given image

gluBuild*DMipmaps( … )

Specifying Filters
• void glTexParameterf( GLenum target, GLenum pname, const GLfloat param )
• target specifies the type of the target texture
• GL_TEXTURE_1D or GL_TEXTURE_2D
• pname specifies which filter to set
• GL_TEXTURE_MAG_FILTER or GL_TEXTURE_MIN_FILTER
• GL_NEAREST to choose the texel nearest to the texture coordinate computed for the pixel.
• GL_LINEAR to use the weighted average of the four texels nearest to the texture coordinate computed for the pixel.
How Filters Work（1）
• Magnification
• Pixels map to less than one texel.
• If GL_NEAREST is specified, then texel 10 is applied to the pixel.
• If GL_LINEAR is specified, the weighted average of texels 9, 10, 13 and 14 is applied to the pixel.

How Filters Work（2）

• Minification
• Pixels map to more than one texel.
• If GL_NEAREST is specified, then texel 17 is applied to the pixel.
• If GL_LINEAR is specified, the weighted average of texels 12, 13, 17 and 18 is applied to the pixel.
Enabling Texture Mapping（注意！）
• void glEnable( GLenum mode )
• Set mode to GL_TEXTURE_1D if one-dimensional texturing is performed using glTexImage1D()
• Set mode to GL_TEXTURE_2D if two-dimensional texturing is performed using glTexImage2D()
• Set mode to GL_TEXTURE_3D_EXT if three-dimensional texturing is performed using glTexImage3DEXT()
Texture.C

This program reads in a single image from a .rgb file, and uses it as a texture. It applies the image to a polygon using explicit texture coordinates. The polygon is then made to "swim" across the window.

The name of the file containing the image can be specified on the command line. If no file is specified, the program attempts to open the file fish.rgba in the current directory.

After reading in the image, the program initializes the texture parameters and loads the texture in initTexture(). Before loading the texture, initTexture() determines whether the image is a power of two in each dimension. If not, it uses the utility routine gluScaleImage() to scale the image. Next it sets both the minification and magnification filter to perform nearest neighbor interpolation. Lastly, it calls glTexImage2D() to load the image into texture memory, and enables 2D texturing.

It then applies the texture to a rectangular polygon using explicit texture coordinates.

The function drawScene() simply uses glTexCoord2fv(), to explicitly assign the texture coordinates to the polygon.

Texture Objects 纹理对象

How to Use Texture Object

• Generate texture names.
• glGenTextures()
• Initially bind (create) texture objects to texture data, including the image arrays and texture properties.
• glBindTexture（）
• Bind and rebind texture objects, making their data currently available for rendering textured models.
• glBindTexture（）
void glGenTextures (GLsize n, GLuint *texnames)

Returns n currently unused names for texture objects in the array textureNames. The names returned in textureNames do not have to be a contiguous set of integers.

The names in textureNames are marked as used, but they acquire texture state and dimensionality (1D or 2D) only when they are first bound.

Zero is a reserved texture name and is never returned as a texture name by glGenTextures().

void glBindTexture (GLenum target, GLuint texname)
• glBindTexture() does three things
• When using textureName of an unsigned integer other than zero for the first time, a new texture object is created and assigned that name.
• When binding to a previously created texture object, that texture object becomes active.
• When binding to a textureName value of zero, OpenGL stops using texture objects and returns to the unnamed default texture.

Other related functions

• void glPrioritizeTextures(GLsize n, const GLuint *texnames, const GLclampf *priorities)
• Set texture residence priority
• void glDeleteTextures ( sizei n, uint *textures )
• Delete texture objects when you are finished with them
Texture1.C

ch10.html

Multiple Levels of Detail P247
• Objects with textures can be viewed at different distances from the viewpoint
• You can specify a series of pre-filtered texture maps of decreasing resolution called mipmaps
• OpenGL automatically determines which texture map to use based on the object's size (in pixels)
As the viewpoint changes, the texture must increase or decrease in size with the size of the object. For example, in texture.c, as the image moves farther away, another sized texture might be more appropriate, rather than trying to filter a large texture down.

If only one resolution of the image is specified, OpenGL has to filter the texture up or down to the appropriate size. A mipmap is an ordered set of pixel arrays representing the same image at progressively lower resolutions.

Using mipmaps allows you to reduce the amount of details on smaller sized objects.

You want to design the mipmaps in such a way that the transition from one to the next is smooth, so that you do not get shimmering and flashing effects

Creating Mipmaps Automatically

You can use the OpenGL Utility routine gluBuild2DMipmaps() to build and load mipmaps automatically.

GLint gluBuild2DMipmaps( GLenum target, GLint internalformat, GLsizei width, GLint height, GLenum format, GLenum type, void *data )

GLint gluBuild2DMipmaps（(GLenum target, GLint internalformat, GLsizei width, GLint height, GLenum format, GLenum type, void *data )

• target specifies the target texture
• internalformat internal storage format of the texture
• width, height specify the dimensions of the texture
• format specifies the format of the pixel data
• type specifies the data type for data
• data specifies a pointer to the image data in memory

void glTexParameterf( target, GL_TEXTURE_MIN_FILTER, param )

Solutions：glTexEnv()函数

void glTexEnv( GLenum target, GLenum pname, const GLfloatparam)
• Specifies how the texture colors interact with the original polygon colors.
• targetis GL_TEXTURE_ENV
• If pname is GL_TEXTURE_ENV_MODE, param specifies a texture function
• GL_MODULATE (default), GL_DECAL, GL_BLENDGL_ADD，or GL_REPLACE
• 表示纹理值如何与被处理的片段颜色值混合
• If pname is GL_TEXTURE_ENV_COLOR, param is a pointer to the RGBA values used with the GL_BLEND texture function
• Default is ( 0, 0, 0, 0 )
Texture Environment and Transparency
• Modulate
• Cv = Ct * C f
• Av = At * Af
• Use a white polygon, so the resulting color equals the color of the texture
• The resulting alpha value will be zero where the texture has a zero alpha
• Use alpha test to remove fragments with alpha close to zero

Replace

• Cv = Ct
• Av = At
• Polygon color does not matter
• Both the color and alpha values will be replaced by the texture values

texenv.c

Choose an appropriate texture environment (GL_MODULATE or GL_REPLACE)

Enable alpha testing to remove alpha values that are close to zero glAlphaFunc( GL_GREATER, 0.1 ); glEnable( GL_ALPHA_TEST );

Set the blending function and enable blending to create smooth edges glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND);a

Automatic Texture Coordinate Generations
• OpenGL can automatically generate three types of texture coordinates:
• Object Linear: the texture image remains fixed to an object
• Eye Linear: a moving object appears to swim through a texture
• Sphere Map: used for environment mapping
Generating Texture Coordinates
• There are three steps to having OpenGL generate texture coordinates automatically
• First, specify the texture coordinate generation functions for S and T:
• GL_OBJECT_LINEAR
• GL_EYE_LINEAR
• GL_SPHERE_MAP

glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR ); glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR );

Second, enable texture coordinate generation: glEnable( GL_TEXTURE_GEN_S ); glEnable( GL_TEXTURE_GEN_T );

Texgen1.c

Third, generate the texture coordinates. For object or eye linear, they are based on a reference plane: static GLfloat sgenparams[] = { 2, 0, 0, 0 }; static GLfloat tgenparams[] = { 0, 1, 0, 0 };glTexGenfv( GL_S, GL_OBJECT_PLANE, sgenparams );glTexGenfv( GL_T, GL_OBJECT_PLANE, tgenparams );

Mapping Textures Smoothly onto 3D Objects

Automatic texture coordinate generation has limits, since it is mapping relative to a plane

You need to provide explicit texture coordinates to improve the mapping

3D modeling and animation software generally create these for you

GLU, the OpenGL Utility library, can map a texture smoothly onto its quadric objectsGLUquadricObj* gluNewQuadric( void )