Autocad, 3D Max Opengl Opengl Opengl Open Graphic Library: Opengl Rendering Opengl Opengl
Autocad, 3D Max Opengl Opengl Opengl Open Graphic Library: Opengl Rendering Opengl Opengl
OpenGl
OpenGL
Open Graphic Library OpenGL
OpenGL
OpenGL
OpenGL
OpenGL rendering
OpenGL
OpenGL
OpenGL
OS/2 Linux Windows OpenGL
OpenGL
Graphical Device Interface GDI OpenGL
GDI32.DLL GDI
GDI
GLU32.DLL OpenGL
OpenGL32.DLL
OpenGL
gl OpenGL
glClearColor opengl32.lib
GL OpenGL
GL _ COLOR_ BUFFER_BIT Underscore
3 glColor3f() 3f
OpenGL f
OpenGL c
GLbyte Signed char 8 Bit b
GLshort short 16 Bit s
GLint , GLsizei Long 32 Bit i
GLfloat,GLclampf Float 32 Bit f
GLdouble , GLclamped double 64 Bit d
GLubyte , GLboolean Unsigned char 8 Bit ub
GLushort Unsigned short 16 Bit us
GLunit , GLenum , Unsigned long 32 Bit ui
GLbitfield
2
Computer Graphics CS 330 Spring 2011
Chapter 1,
Introduction to Computer Graphics (C.G.)
Image processing task is to improve or alter images that were created elsewhere. Processing can remove
specks, enhance the contrast, and sharpen its image and highlight, as in Fig 1.2.
3. Monitoring a process
Complex systems (factories, power plants,..) must be monitored to watch out (by human) for impending
trouble, as in Fig 1.3.
4. Displaying Simulations
A variety of systems can be profitably simulated. These systems might be exist, never be built, or exist
only as equations and algorithms. Flight simulator as shown in Fig. 1.4
Fig 1.4, A woman wear a head-mounted display and data gloves to interact with a virtual world
5. Computer-Aided Design
A number of disciplines use computer graphics to facilitate the design of system or product. The
computer holds a model of device in memory, and a picture based on the model is displayed for user to
examine.
Computer-aided Architectural Design
C.G. can help architects design buildings. Architect can make adjustments to the floor plan, moving a
wall, adjusting a window.
Fig 1.7, Mathematical displays of (a) a complex mathematical surface and (b) a mathematical defined
solid object.
The basic objects of pictures are composed are called output primitives, such as polylines, text, filled
region, and raster images.
The attributes of a graphic primitive are the characteristics that affect how it appears, such as color and
thickness.
1. Polylines
A polylines is a connected sequence of straight lines.
Fig 1.8, (a) A polyline drawing of a dinosaur, (b) A plot of a mathematical function,
(c) A wire-frame rendering of three dimensional object.
Polylines can appear as a smooth curve, Fig 1.9. shows a blowup of a curve, revealing its underlying
short line segments.
A polyline need not form a closed figure, but if the first and last points are connected by an edge, the
polyline is a polygon, as in Fig. 1.11
2. Text
There are two display modes:
Text mode: used for simple input and output of characters to control the operating system or edit the
code in a program. A built-in character generating alphabetic, numeric, and punctuation characters
Graphics mode offers a richer set of character shapes than text mode, as in Fig 1.14
drawstring (x, y, string);
Text Attributes
font (type face), color, size, spacing, and orientation. Font is a specific
set of character shapes in a particular style and size, as in Fig 1.15.
The shape of character can be defined by a polyline or by an arrangement of dots, as in Fig 1.16.
Fig 1.16, A character shape defined by (a) a polyline and (b) a pattern of dots.
3. Filled Regions
The filled region (fill area) primitive is a shape filled with some color or pattern. The boundary is a polygon
as in Fig. 1.17.
4. Raster Image
cell
pixel see the individual cells; instead, it blends them together and
synthesizes an overall picture.
Fig 1.19, (a) A raster image of a chess. (b) A blowup of the image.
A raster image is stored in a computer as an array of numerical values. Each value represents the value
of the pixel stored there pixel map bitmap
figure represented as a bit map, (b) shows the numerical values of the pixel map for the upper left 6x8
portion.
An algorithm is used to render a scene, which might be modeled abstractly in computer memory.
For example a scene might consist of a single yellow, smooth sphere illuminated by a light source
that emanates orange light.
3. Scanned Image
A photograph or television image can be digitized. A grid is placed over the original image, and at
each grid point, the closest
thereby created is then stored in a file for later use.
When the pixels in a gray-scale image take on more than two values. Gray-scale are classified in
terms of their pixel depth, the number of bits needed to represent their gray levels. There are 2n
gray levels in an image with pixel depth n. the common values:
Two bits per pixel produce 4 gray levels.
Dr Taleb Obaid 1 / 10
Computer Graphics CS 330 Spring 2011
Fig 1.31, A common correspondence between color value and perceived color.
Dr Taleb Obaid 1 / 11
The highest quality images, known as true-color images, have a color depth of 24 and so use a byte for
each component.
1. Line-Drawing Display
The pen plotter is an example, which moves a pen invisibly over a piece of paper to some spot that is
specified by the computer, puts the pen down, and then sweeps the pen across to another spot, leaving
of a line drawing is related to the precision with which the pen
is positioned and the sharpness of the lines are drawn.
Kinds of pen plotter:
Flatbed Plotter, move the pen in two dimensions over a stationary sheet of paper.
Drum Plotter, move the paper back and forth at the top of the drum to provide the other direction.
There are also video displays vector random-scan calligraphic
line drawings. These devices have internal circuitry to sweep an electronic beam from point to point
leaving a glowing trail.
Vector displays cannot show smoothly-shaded regions, so is usually simulated by cross-hatching with
different line pattern, as in Fig 1.33.
Fig 1.35, The built-in coordinate system for the surface of a raster display.
Dr Taleb Obaid 1 / 12
Computer Graphics CS 330 Spring 2011
Raster displays are connected to a frame buffer, a region of memory sufficiently large to hold all of the
pixel values, (i.e., to hold the bit map of the image). Figure 1.36 suggests how an image is created and
display
In this figure, the graphics program is stored in system memory and executed instruction by instruction
by CPU. The program computes the values (color) for each pixel and loads the values into the frame
buffer. A
appropriate physical spot on the display surface. The convector takes a pixel value and converts it to the
corresponding quantity that produce a spot of the color on the display.
The Scanning Process
Figure 1.37 provide details of the scanning process. Main issue is how each pixel value in the frame buffer
Fig 1.37, Scanning out an image from the frame buffer to the display surface.
In this figure, each pixels in frame buffer have 2-D address (x, y) and have a specific memory location
mem [x][y]. the scan controller send logical address (x, y) to the frame buffer and simultaneously,
Dr Taleb Obaid 1 / 13
physical (geometric) position (x, y) on the display surface. The value mem [x][y] is
converted to a color and sent to the proper physical position.
Video Monitors
Based on a cathode-ray tube (CRT). Figure 1.38 adds some details on the conversion process from pixel
Fig
green,
and blue components use a pair of bits. The pairs are fed to three Digital-to-Analog Convectors which
convert logical values like 01 into actual voltage.
The red, green, and blue components of a pixel each use a pair of bits. The pairs are fed to three digital-
to-analog converters (DACs) , which convert logical values like 01 into actual voltages, as in Fig 1.39,
where max is the largest voltage level the DAC can produce.
The scan controller addresses one pixel value, mem[x][y], in the frame buffer at the same time
Dr Taleb Obaid 1 / 14
Computer Graphics CS 330 Spring 2011
coils. The glow of a phosphor dot quickly fades when the stimulus is removed, a CRT image must be
refreshed to prevent disturbing flicker.
Scanning proceeds row by row through the frame buffer, each row providing pixel values for one
scan line across the CRT. The order of scanning is usually from left to right along a scan line and from
top to bottom.
The expensive systems have a frame buffer that supports 24 planes of memory. Each of the DACs has
eight input bits, so there are 256 levels of red, 256 of green, and 256 of blue, the total 224 = 16 million
colors.
The monochrome video display a single color in different intensities. The CRT has only on type of
phosphor; so, produce various intensities of one color.
In fig 1.38, the pixel values 001101 send
The color depth is six bits stored in each pixel. These bits are used as an index into a table of 64 (=26)
values,
In Fig 1.40, LUT[39] contains the 15-
5 others drive
under program control, using some system routine such as setPalette()
setPalette (39, 17, 25, 4);
would set the value in LUT [39] to 15-bit quantity 10001 11001 00100 (since 17 is 10001 in binary, 25 is
11001, and 4 is 00100).
drawDot (479, 532, 39); // set pixel at (479, 532) to value 39
Dr Taleb Obaid 1 / 15
Suppose that a raster display system has a color depth of b bits and that each LUT entry is w bits wide.
Then the system can display 2w colors, any 2b at one time.
To compare the costs of two systems, one with an LUT and one without, Fig 1.41 shows an example of
two 1,024-by-1,280-pixel displays (1.3 million pixel).
System 1 (expensive) The first system has a 24-bit-per-pixel frame buffer and no LUT, so each of its 1.3
million pixel (=224) colors. The amount of memory required for the frame buffer in this system is
1,024x1,280x24 bits (6 megabytes).
System 2 (inexpensive) The second has an 8-bit-per-pixel frame buffer along with an LUT, and the LUT is
24 bits wide. The system can display 224 different colors, but only 256 at a time. The amount of memory
is 1,024x1,280x8 (1 megabyte).
Active matrix panels are LCD panels that have a tiny transistor at each pixel location. The transistor
responds to the electric field to allowing the display of different levels of brightness. This transistor has
memory that holds the crystals in their adjusted state , so that the display need not be refreshed.
The plasma panel displays has similar to Fig 1.42, but the material in the effective places a tiny neon bulb
at pixel location. This bulb is turned on or off.
Dr Taleb Obaid 1 / 16
Computer Graphics CS 330 Spring 2011
Dot matrix prints place dots at a density of 70 dots per inch (dpi). Laser produce densities of 600 dpi, so
produce very high-quality graphics.
Dr Taleb Obaid 1 / 17
Joystick and Trackball, Joystick has a lever that can be pivoted in any direction to indicate position. The
trackball has a large ball that can be rotated in any direction with the thumb to alter the position of the
cursor.
Knobs, used for interactive design of three-dimensional objects. The user can rotate a displayed object
in three dimensions by adjusting the position of three separate knobs.
Space Ball and Data Glove, Both are designed to give a user explicit control over several variables at
once, by performing hand and finger motions.
Dr Taleb Obaid 1 / 18
Computer Graphics CS 330 Spring 2011
Fig 1.50,
Dr Taleb Obaid 1 / 19
Chapter 2,
Getting Started; Drawing Figures
Goals
Writing programs that produce pictures.
Learn the basic ingredients found in every OpenGL program.
Develop some elementary graphics tools for drawing lines, polylines, and polygons.
Develop tools that allow the user to control a program with mouse and keyboard.
Fig 2.1(a), entire screen is used foe drawing. Coordinates x and y are measured in pixels, with x increasing
to the right and y in creasing downward.
Fig. 2.1(b), different rectangular windows on the display screen at one time. Initialization involves creating
and opening a new window for graphics.
Fig 2.1(c),
upward.
line (x1, y1, x2, y2); draws a line between (x1, y1) and (x 2, y2).
2. Windows-based Programming
Many graphics systems are windows based and manage the display of multiple overlapping windows. The
user can move windows around and resize them.
Event-driven Programming
Means that the program responds to various events, such as click a mouse, press a key, resize a window.
The programmer organizes a program as a collection of callback functions that are executed when events
occur.
void main ( ) {
initialize things
create a screen window
glutDisplayFunc (myDisplay) ; // register the redraw function
glutReshapeFunc (myReshape) ; // register the reshape function
glutMouseFunc (myMouse) ; // register the mouse action function
glutKeyboardFunc (myKeyboard) ; // register the keyboard action function
perhaps initialize other things
glutMainLoop ();
}
all of the callback functions are defined here
There are
glutDisplayFunc (myDisplay);
event. This happens when the window is first opened and when the window is exposed by moving
another window off of it. The function myDisplay () is registered as the callback function for a
redraw event.
glutReshapeFunction (myReshap); screen windows can be reshaped by the user, dragging a corner
of the window to new position with mouse. myReshape () is registered with the reshape events,
and automatically passed arguments that report the new width and height of the reshape window.
glutMouseFunc (myMouse); when one mouse buttons is pressed or released, a mouse event
occurs. The function myMouse () is automatically passed arguments that describe the location of
the mouse and nature of the action.
If a program does not make use of a mouse (or keyboard), the corresponding callback function need not
be registered or written. The mouse click (or key pressed) have no effect in the program.
Fig 2.3, Code using the OpenGL Utility Toolkit to open the initial window for drawing.
The first five calls use the OpenGL Utility Toolkit to open a window for drawing.
glutInit (&argc, argv); This function initialize the OpenGL Utility Toolkit. Its arguments are the
standard ones for passing information about the command lines.
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); specifies how the display should be initialized.
The built-in constants GLUT_SINGLE and GLUT_RGB, which are ORed together, indicate that a
single display buffer should be allocated and that colors are specified.
glutInitWindowSize (640,480); specifies the screen window should initially be 640 pixel wide by
480 pixel high. You may resize the window as desired.
OpenGL provides tools for drawing all of the output primitives. To draw object, you pass a list of vertices.
The list occurs between two functions glBegin () and glEnd ().
glBegin (GL_POINTS);
glVertex2i (100, 50);
glVertex2i (100, 130);
glVertex2i (150, 130);
glEnd ();
The constant GL_POINTS is built-into OpenGL. To draw other primitives, you replace GL_POINTS with
GL_LINES, GL_POLYGON, etc.
The function glVertex2i () have several variations, that distinguish the number and type of arguments
passed to the function, as in Fig 2.6.
indicates a function from OpenGL library. Then basic command root, followed by the number of
arguments sent to the function (3 and 4), the argument i for integer, f or d for a floating-point value).
Fig
2.7,
-bit integer, when your use 16-bit integer, this caused a problem
as in the following code.
The background color is set with glClearColor (red, green, blue, alpha) , where alpha specifies a degree of
transparency. To clear the entire window to the background color, use
glClear (GL_COLOR_BUFFER_BIT).
The argument GL_COLOR_BUFFER_BIT is a constant.
myDisplay
void myDisplay(void {
glClear (GL_COLOR_BUFFER_BIT); // clear the screen
glBegin (GL_POINTS);
glVertex2i(100, 50); // draw three points
glVertex2i(100, 130);
glVertex2i(150, 130);
glEnd ()
glFlush(); // send all output to display
main
void main (int argc, char** argv {
glutInit (&argc, argv); // initialize the toolkit
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize (640,480); // set window size
glutInitWindowPosition (100, 150); // set window position on screen
glutCreateWindow ("my first attempt"); // open the screen window
glutDisplayFunc (myDisplay); // register redraw function
myInit ();
glutMainLoop (); // go into a perpetual loop
}
Fig 2.12, the Sierpinski Gasket Fig 2.13 Building the Sierpinski Gasket
We define a simple class GLintPoint, that describes a point whose coordinates areintegers.
class GLintPoint {
public:
GLint x, y ;
};
Initialize the array T of three points:
GLintPoint T[3] = { {10, 10}, {300, 30}, {200, 300} }.
We use i = random (3) to choose one points T[i] random, so returns one of the values 0, 1, 2. defined as
random (int m) {
return rand ( ) % m;
}
Fig 2.14, the algorithm, which generates 1000 points of Sierpinski gasket.
void Sierpinski(void) {
GLintPoint T[3]= {{10,10},{300,30},{200, 300}};
int index = random(3); // 0, 1, or 2 equally likely
GLintPoint point = T[index]; // initial point
drawDot(point.x, point.y); // draw initial point
for(int i = 0; i < 1000; i++) // draw 1000 dots
{
index = random(3);
point.x = (point.x + T[index].x) / 2;
point.y = (point.y + T[index].y) / 2;
drawDot (point.x, point.y); }
glFlush();
}
Plot of function
f(x) = e-xcos (2 x)
for values of x between 0 and 4.
glBegin (GL_POINTS)
for (Gldouble x = 0; x < 4.0; x += 0.005)
glVsrtix2d (x, f(x));
glEnd ();
glFlush ();
-xcos (2 x) versus x.
Scaling x, if the range 0 to 4 be scaled so that it covers the entire width of the screen window is screenWidth
pixel. S0,
sx = x * screenWidth / 4.0.
scaling and shifting y The values of f(x) lie between 1 and 1. Let the screen height of screenHeight pixels,
so
sy = (y + 1.0) * screenHeight / 2.0.
note that the conversions from x to sx and from y to sy are of the form
sx = Ax + B and
sy = Cy + D.
Fig 2.15 given the values of A, B, C, and D,
Gldouble A, B, C, D, x;
A = screenWidth / 4.0;
B = 0.0;
C = screenHeight / 2.0;
D = C;
glBegin (GL_POINTS)
for (Gldouble x = 0; x < 4.0; x += 0.005)
glVsrtix2d (A*x + B, C*f(x) + D);
glEnd ();
glFlush ();
void drawLineInt (Glint x1, Glint y1, Glint x2, Glint y2) {
glBegin (GL_LINES); // use contsatnt GL_LINES here
glVertex2i (x1, y1);
glVertex2i (x2, y2);
glEnd ();
}
To make the polylie into a polygon, replace GL_LINE-STRIP with GL_LINE_LOOP as in Fig 2.18 b
Dr Taleb Obaid 2 / 10
The following cod read from file dino.dat and draw dinosaur.
Dr Taleb Obaid 2 / 11
Computer Graphics CS 330 Spring 2011
2.23 shows a simple house, the routine hardwireHouse () , can draw only one house in one size and one
location.
Dr Taleb Obaid 2 / 12
glBegin(GL_LINE_STRIP);
glVertex2i(50, 100); // draw the chimney
glVertex2i(50, 120);
glVertex2i(60, 120);
glVertex2i(60, 110);
glEnd();
We can draw families of objects by different parameter values, as in routine parameterizedHouse (), Fig
2.26
Dr Taleb Obaid 2 / 13
Computer Graphics CS 330 Spring 2011
Fig 2.28 shows implementation of polyline-drawing routine. The routine takes a parameter closed . The
value of closed sets the argument of glBegin ().
Fig 2.28 A linked list data type and drawing a polyline or polygon
#include <windows.h>
#include <GL\GL.h>
class GlintPoint {
public:
GLint x, y;
};
// draw the line
Dr Taleb Obaid 2 / 14
flurry
(a). Checkerboard in (b),
Dr Taleb Obaid 2 / 15
Computer Graphics CS 330 Spring 2011
glFlush();
}
void drawFlurry (int num, int numColors, int Width, int Height) {
for (int i = 0; i < num; i++) {
GLint x1 = random (Width); // place corner randomly
GLint y1 = random (Height);
GLint x1 = random (Width); // pick the size so it fits
GLint y1 = random (Height);
Glfloat lev = random ( ); // random value, in range 0 to 1
GlColor3f (lev, lev, lev); // set the gray level
glRecti (x1, y1, x2, y2); }
glFlush (); }
Dr Taleb Obaid 2 / 16
PRACTIC EXERCISES
2.3.1 Drawing the checkerboard
2.3.2 Alternative ways to specify a rectangle
Instead of two opposite corners, there are:
Its center point, height, and width.
Its upper left corner, width, and aspect ratio.
Dr Taleb Obaid 2 / 18
Convex polygon: A polygon is convex if a line connecting any two points of the polygon lines entirely
within it.
The polygon will be filled in the current color. It can also be filled with a stipple pattern, and paint images
into polygons (texture).
Dr Taleb Obaid 2 / 19
Computer Graphics CS 330 Spring 2011
Dr Taleb Obaid 2 / 20
Dr Taleb Obaid 2 / 21
Computer Graphics CS 330 Spring 2011
GL_LINE_LOOP
GL_TRIANGLES
GL_TRIANGLE_STRIP
Dr Taleb Obaid 2 / 22
The x value is the number of pixels from the left of the window. The y value is the number of pixel down
the top of the window.
Dr Taleb Obaid 2 / 23
Computer Graphics CS 330 Spring 2011
glFlush();
}
Dr Taleb Obaid 2 / 24
The callback function must take two parameters myMoveMouse (int x, int y); x and y are the mouse
position when the event occurred.
The callback function myMoveMouse () designed to draw a square at the current mouse position.
void myMovedMouse (int mouseX, int mouseY) {
Glint x = mouseX ; // grab the mouse position
Glint y = screenHeight mousey ; // flip it as usual
Glint brushSize = 5;
glRecti (x, y, x + brushSize, y + brushSize );
glFlush () ;
}
break;
case GLUT_KEY_LEFT : List [++last].x = x; // add a point
List [ last] . y = y;
Dr Taleb Obaid 2 / 25
Computer Graphics CS 330 Spring 2011
break;
exit(-1); // terminate the program
default :
break ; // do nothing
}
}
Dr Taleb Obaid 2 / 26
Chapter 3,
More Drawing Tools
Goals
Introduce viewports and clipping.
Develop the window-to-viewport transformation.
Develop a classical clipping algorithm.
Create tools to draw in world coordinates.
Develop ways to select windows and viewports for optimum viewing.
Draw complex pictures using relative drawing and turtle graphics.
Build figures based on regular polygons and their offspring.
Draw arcs and circles.
Describe parametrically defined curves and to see how to draw them.
INTRODUCTION
In Ch 2, our drawings used the basic coordinate system of the screen window:
Coordinates are in pixels, from zero to screenWidth-1 in x, and from zero to sereenHeight-1 in y. This
means that we can use only positive values of x and y. But, we may not want to think in terms of pixels:
It may think in terms of x varying from, say, -1 to 1, and y varying from -100.0 to 20.0. In this
chapter, we develop methods that let the programmer describe objects in whatever coordinate
system, and automatically scale and shift the picture of an object so that it "comes out right" in the
screen window. The space in which objects are described is called world coordinates, which are the
Cartesian xy-coordinates.
We define a rectangular world window , in world coordinates. The world window specifies which
part of the "world" should be drawn, i.e., whatever lies inside the window should be drawn and
whatever lies outside should be clipped away and not drawn.
We define also a rectangular viewport in the screen window. A mapping (consisting of scaling
and shifting) between the world window and the viewport is established so that when all the objects
in the world are drawn, the parts that lie inside the world window are automatically mapped to the
inside of the viewport. So, the programmer thinks in terms of "looking through a window" at the
objects being drawn and placing a "snapshot" of whatever is seen in that window into the viewport
on the display. This window-viewport approach makes it much easier to do natural things like
"zooming in" on a detail in a scene or "panning around" the scene.
Fig e
The key issue here is how the various (x, y) values become scaled and shifted so that the picture
appears properly in the screen window. We accomplish the proper scaling and shifting by setting up
a world window and viewport and then establishing a suitable mapping between them.
Fig 3.2 is an example of a world window and a viewport. The notion is that whatever lies in the world
window is scaled and shifted so that it appears in the viewport; everything else is clipped off and not
displayed.
The world window and viewport do not have to have the same aspect ratio, although distortion results
if their aspect ratios differ, as in Fig 3.4.
Fig 3.5
Proportionality In mapping x to sx
The window-to-viewport transformation,
sx = Ax + C and sy = By + D.
with
A = (V.r V.l) / ( W.r W.l),
C = V.l AW.l
B = (V.t - V.b) / (W.t W.b) ,
D = V.b BW.b.
The mapping can be used with any point (x, y) inside or outside the window. Points inside the window
map to points inside the viewport, and points outside the window map to points outside the viewport.
Ex 3.2.1
Consider the window and viewport of Figure 3.6. The window has (W.l, W.r, W.b, W.t) = (0, 2.0 ,0 ,1.0),
and the viewport has(V.l, V.r, V.b, V.l) = (40, 400, 60, 300).
Doing It in OpenGL
OpenGL makes it very easy, for 2D drawing, the world window is set by the function gluOrtho2D(),
and viewport is set by the function gIViewport () .These functions have the prototypes:
void gluOrtho2D (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top) ;
Dr Taleb Obaid 3/4
Which sets the window to have a lower left corner of (left, bottom) and an upper right corner of (right,
top), and
void gIViewport (GLint x, GLint y, GLint width, GLint height)
which sets the viewport to have a lower left corner of (x, y) and an upper right corner of (x + width, y
+ height).
By default, the viewport is the entire screen window: Lower left corner (0, 0) and upper right corner
(W, H).
Because OpenGL uses matrices to set up all its transformations, glu0rtho2D () must be preceded by
two "setup" functions: glMatrixMode (GL_PROJECT) and gILoadIdentity ().
Thus, to establish the window and viewport used in Example 3.2.1, we would use the following code:
glMatrixMode (GL_PROJECTION);
gILoadIdentity ();
gluOrtho2D (0.0, 2.0, 0.0, 1.0); // sets the window
gIViewport (40, 60, 360, 240); // sets the viewport
We will make programs more readable if we encapsulate the commands that set the window into a
function setWindow () and Viewport, as in Fig 3.7.
void myDisplay (void) { // plot the sine function, using world coordinates
setWindow (-5.0, 5.0, -0.3, 1.0) ; // set the window a little wider
setViewport (0, 640, 0, 480) ; // set the viewport
glBegin(GL_LINE_STRIP);
for (GLfloat x = -4.0; x < 4.0; x += 0.1) // draw the plot
glVertex2f (x, sin (3.14159 * x) / (3.14159 * x));
glEnd():
glFlush();
}
Fig 3.8 Plotting the sine function
Ex 3.2.4
Tiling the screen window with the dinosaur motif
Laying lots of copies of the same thing side by side to cover the entire screen window is called tiling
the window. The picture that is copied at different positions is often called a motif.
Tiling a screen window is easily achieved by using a different viewport for each instance of the motif.
Fig 3.10a shows a tiling involving 25 copies of the motif generated by the following code:
setWindow (0, 640.0, 0, 440.0) ; // set a fixed window
for (int 1=0; i < 5; i++) // for each column
for (int j=0; j < 5 ; j++) { // for each row
glViewport (i * 64, j * 44, 64, 44) ;
drawPolylineFile ("dino.dat") ; // draw it again
}
Figure 3.10(b) shows another tiling, motifs are flipped upside down to produce an intriguing effect.
This was done by flipping the window upside down every other iteration: interchanging the top and
bottom values in setWindow(). The code for the double loop was changed to the following:
A picture can be clipped, by proper setting of the window. OpenGL automatically clips off parts of
objects that lie outside the world window, as in Fig 3.11.
void setWindow ( double left, double right, double bottom, double top) {
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluOrtho2D (left, right, bottom, top);
}
void hexSwirl (void) {
GLdouble Pi = 3.14159, Thi = 0.0, Xc = 200., Yc = 200., R = 2.;
GLdouble Ang, XX, YY;
// glClear (GL_COLOR_BUFFER_BIT);
for (int i = 0; i < 30; i++) {
R += 5;
Thi += 0.05;
glBegin (GL_LINE_STRIP);
for (double k = 0; k <= 6; k++){
Ang = Thi + k * Pi/3.;
XX = R * cos ( Ang );
YY = R * sin ( Ang );
glVertex2d (Xc + XX, Yc + YY );
}
glEnd();
}
glFlush(); // send all output to display
}
The problem is that the user sees the line-by-line creation of the new frame, which can be distracting.
What the user would like to see is:
The trick is to draw the new figure "somewhere else" and then to move the completed new figure
onto the user's display. OpenGL offers double buffering to accomplish this task. Memory is set aside
for an extra screen window that is not visible on the actual display, and all drawing is done to that
window, or buffer. The command glutSwapBuffers () then causes the image in the buffer to be
transferred onto the screen window.
OpenGL reserve a separate buffer using GLUT_DOUBLE rather than GLUT_SINGLE.
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
The command glutSwapBuffers () would be placed directly after hexSwirl () in the code.
The extent can be computed by finding the extreme values of the x- and y-coordinates in the array
p[i]. The left side of the extent is the smallest of the values pt[i].x. Once the extent is known, the
window can be made identical to it. Automatic Setting of the Viewport to Preserve the Aspect Ratio
To draw the largest undistorted version of a figure that will fit in the screen window:
You need to specify a viewport that has the same aspect ratio as the world window. A common wish
is to find the largest such viewport that will fit inside the screen window on the display.
Suppose the aspect ratio of the world window is R and the screen widow has width W and height H.
There are two distinct situations:
The world window may have a larger aspect ratio than the screen window (R > W/H), or it may have
a smaller aspect ratio (R < W/H). The two situations are shown in Figure 3.16.
Fig 3.16 Possible aspect ratios for the world and screen windows
Case (a): R > W/H. Here the world window is short and stout relative to the screen window. The
viewport will have width W and height W/R, so it is set with the following command:
setViewport (O, W, 0, W/R);
Case (b): R < W/H. Here the world window is tall and narrow relative to the screen
Window. The viewport will have height H, but width HR, so it is set with the command:
setViewport(0, H * R, 0, H);
Dr Taleb Obaid 3 / 10
Fig 3.17 Using a reshape function to set the largest matching viewport upon a resize event.
#include <gl/glut.h>
#include <math.h>
double W = 400., H = 400., left = 0.0, right = 300.,
bottom = 0.0, top = 300., R = right/top ;
//<<<<<<<<<<<< setWindow >>>>>>>>>>>>>>>>>>>>>
void setWindow ( double left, double right, double bottom, double top) {
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluOrtho2D (left, right, bottom, top);
}
Dr Taleb Obaid 3 / 11
Computer Graphics CS 330 Fall 2009
glutDisplayFunc(myDisplay);
glutReshapeFunc (myReshape);
Dr Taleb Obaid 3 / 12
class IntRect {
public:
IntRect () {l=0; r = 100; b = 0; t = 100;} // constructors
IntRect (int left, int right, int bottom, int top) {
l = left; r = right; b = bottom; t = top; }
void set (int left, int right, int bottom, int top) {
l = left; r = right; b = bottom; t = top; }
void draw (void); // draw this rectangle using OpenGL
private:
int l, r , b , t; };
Dr Taleb Obaid 3 / 13
Computer Graphics CS 330 Fall 2009
class Canvas{
public
Canvas (int width, int height, char* windowTitle) ; // constructor
void setWindow (float 1, float r, float b, float t
void setViewport (int 1, int r, int b, int t)
IntRect getViewport (void) ; // divulge the viewport data
RealRect getWindow(void) ; // divulge the window data
float getWindowAspectRatio (void)
void clearScreen ()
void setBackgroundColor (float r, float g, float b) ;
void setColor (float r, float g, float b) ;
void lineTo (float x, float y) ;
void lineTo (Point2 p) ;
void moveTo (float x. float y) ;
void moveTo (Point2 p) ;
others later
private
Point2 CP // current position in the world
IntRect viewport // the current window
RealRect window // the current viewport
others later
};
Figure 3.26 shows how the Canvas class might typically be used in an application.
Canvas cvs (640, 480, "try out Canvas") ; // global canvas object
//«««««««««««««« display »»»»»»»»»»»
void display (void) {
cvs.clearScreen () ; // clear screen
cvs.setWindow (-10.0, 10.0, -10.0, 10.0) ;
cvs.setViewport (10, 460, 10, 460) ;
cvs .moveTo (0, -10.0) ; // draw a line
cvs.lineTo (0, 10.0) ;
RealRect box ( -2.0, 2.0, -1.0, 1.0) ; // construct a box
box.draw () ; // draw the box
//««««««««««« main »»»»»»»>»»»»»»»»
void main (void) {
// the window is opened in the Canvas constructor
cvs . setBackgroundColor (1.0, 1.0, 1.0) ; // background is white
cvs. setColor (0.0, 0.0, 0.0) ; // set drawing color
glutDisplayFunc (display) ;
glutMainLoop () ;
}
Dr Taleb Obaid 3 / 14
The main () routine does no initialization: This has all been done in the Canvas constructor. The
routine main () simply sets the drawing and background colors, registers the function display (), and
enters the main event loop.
Figure 3.28 shows the implementation of some of the Canvas members functions, such as moveTo (),
lineTo ().
//«««««««««««««««««««« moveTo ««««««««««««««««««««
void Canvas:: moveTo (float x, float y) {
CP.set (x, y);
}
//«««««««««««««««««««« lineTo ««««««««««««««««««««
void Canvas:: lineTo (float x, float y) {
glEegin (GL_LINES);
glVertex2f ((GLfloat) CP.x, (GLfloat) CP.y);
glVertex2f ((GLfloat) x, (GLfloat) y); // draw the line
glEnd () ;
CP.set (x, y); // update the CP
gIFlush ();
}
//«««««««««««««««««« set Window »««««««««««««««««««
void Canvas:: setWindow (float 1, float r, float b, float t) {
gIMatrixMode (GL_PROJECTION);
gILoadIdentity ();
gluOrtho2D ((GLdouble) 1, (GLdouble) r, (GLdouble) b, (GLdouble) t)) ;
window.set (1, r, b, t);
Dr Taleb Obaid 3 / 15
Computer Graphics CS 330 Fall 2009
Dr Taleb Obaid 3 / 16
Figure 3.31 shows an arrow-shaped marker, drawn using the routine in Figure 3.32. The arrow is
positioned with its uppermost point at the CP. For flexibility, the arrow shape is parameterized
through the four size parameters f, h, t, and w as shown.
void arrow (float f, float h, float t, float w) {
// assumes global Canvas object: cvs
cvs.lineRel (-w - t / 2, -f); // down the left side
cvs.lineRel (w, 0);
cvs.lineRel (0, -h);
cvs.lineRel (t, 0); // across
cvs.lineRel (0, h); // back up
cvs.lineRel (w, 0);
cvs.lineRel (-w - t / 2, f);
}
Dr Taleb Obaid 3 / 17
Computer Graphics CS 330 Fall 2009
glFlush ();
CPX = X; CPY = Y; } // update CPX and CPY
//<<<<<<<<<<<<<<<<< Arrow >>>>>>>>>>>>>>>>>>>>>
void Arrow (void) {
GLdouble f = 40., h = 40., t = 40., w = 40.;
CPX = 0.; CPY = 0.;
RelTo (-w-t/2., -f);
RelTo (w, 0); RelTo (0, -h);
RelTo (t, 0); RelTo (0, h);
RelTo (w, 0); RelTo (-w-t/2, f);
}
Dr Taleb Obaid 3 / 18
1. turnTo (float angle). This function turns the turtle to the given angle and is implemented as
void Canvas:: turnTo (float angle) {
CD=angle;
}
2. turn (float angle). This routine turns the turtle through angle degrees counterclockwise:
void Canvas:: turn (angle) {
CD += angle;
}
We use a negative argument to make a right turn. Note that a turn is a relative change in direction;
3. forward (float dist, int isVisible) .This instruction moves the turtle forward in a straight line from
the CP through a distance dist in the current direction CD and updates the CP. If isVisible is nonzero,
a visible line is drawn; otherwise nothing is drawn.
Figure 3.33 shows that, in going forward in the direction CD, the turtle just moves in the x direction a
distance dist cos ( CD/180) and in the y direction a distanced dis*sin ( CD/180), so the
implementation of forward () is immediate:
Dr Taleb Obaid 3 / 19
Computer Graphics CS 330 Fall 2009
Dr Taleb Obaid 3 / 20
Ex 3.5.3 Polyspirals
A polyspiral is a polyline wherein each successive segment is larger (or smaller) than its predecessor
by a fixed amount and is oriented at some fixed angle to the predecessor.
Each time a line is drawn, both its length and direction are incremented. If increment is 0, the figure
neither grows nor shrinks. Figure 3.35 shows several polyspirals.
The vertices of an n-gon lie on a circle, the so-called parent circle of the n-gon, and their locations are
easily calculated. Fig 3.42, the vertices lie equispaced every 60o around the circle. The parent circle of
radius R is centered at the origin, and the first vertex P 0 has been placed on the positive x-axis. The
other vertices follow accordingly, as
Pi = (R cos(ia), R sin(ia)), for i = 1,..., 5, where a is /3 radians. Similarly, the vertices of the general n-
gon lie at
Pi = (R cos (2 i/n),R sin (2 i/n)), for i = 0,..., n-1.
Dr Taleb Obaid 3 / 21
Computer Graphics CS 330 Fall 2009
It is simple to implement a routine that draws an n-gon, as shown in Figure 3.43. The n-gon is drawn
centered at (cx, cy), with radius radius, and is rotated through rotAngle degrees.
void ngon (int n, float ex, float cy, float radius, float rotAngle) { // assumes global Canvas object,
cvs
if (n < 3) return; // bad number of sides
double angle = rotAngle * 3.14159265 / 180; // initial angle
double angleinc = 2 * 3.14159265 /n; //angle increment
cvs. moveTo (radius * cos(angle) + ex, radius * sin(angle) + cy);
for(int k = 0; k < n; k++) { // repeat n times
angle += angleinc;
cvs.lineTo(radius * cos(angle) + ex, radius * sin(angle) + cy);
}
}
Fig 3.43 Building an n-gon in memory.
FIGURE 3.45 A 7-gon and its offspring, (a) The 7-gon, (b) A stellation, (c) A "7-rosette
Dr Taleb Obaid 3 / 22
Figure 3.48 shows some shapes built upon two concentric parent circles, the outer of radius R and the
inner of radius fR for some fraction f. Each figure uses a variation of an n-gon whose radius alternates
between the inner and outer radii.
Parts (a) and (b) show familiar company logos based on 6-gons and 10-gons. Part (c) is based on the
14-gon, and part (d) shows the inner circle explicitly.
Dr Taleb Obaid 3 / 23
Computer Graphics CS 330 Fall 2009
Drawing a circle is equivalent to drawing an n-gon that has a large number of vertices. The routine
draw Circle () shown in Figure 3.55 draws a 50-sided n-gon.
With drawArc ( ) in hand, it is a simple matter to build the routine drawCircle (Point2 center, float
radius)
that draws an entire circle by specifying a center and radius. but there are other ways to describe a
circle:
1. The center is given, along with a point on the circle. If c is the center and p is the given point on the
circle, the radius is simply the distance from c to p, found using the usual Pythagorean theorem.
2. Three points are given through which the circle must pass. It is known that a unique circle passes
through any three points that do not lie in a straight line.
EXAMPLES
Dr Taleb Obaid 3 / 24
Fig 3.59 The yin-yang symbol. Fig 3.60 The seven circle Fig 3.61 A famous logo
Fig 3.62 Blending arcs to form smooth curves (clock) Fig 3.64 Shape based on arcs
Fig 3.65 The teardrop and its construction Fig 3.66 Some figures based on the teardrop
The implicit form describes a curve by a function F(x, y) that provides a relationship between the x and
y coordinates: The point (x, y) lies on the curve if and only if it satisfies the equation
F(x,y) = 0. (3.7)
For example, the straight line through the points A and B has the implicit form
and the circle with radius R centered at the origin has the implicit form
F(x, y)= x 2 + y2 - R2 (3.9)
Dr Taleb Obaid 3 / 25
Computer Graphics CS 330 Fall 2009
You can easily test whether a given point lies on the curve: Simply evaluate F(x, y) at the point. For
certain classes of curves, it is meaningful to speak of an inside and an outside of the curve.
Thus, the point P(t) = (x(t), y(t)) sweeps through all of the points on the line between A and B as t
varies from 0 to 1. (Check this out!). Another classic example is the ellipse, a slight generalization of
the circle. The ellipse is described parametrically by
x(t) = Wcos (t) (3.13)
and
y(t) = Wsin (r), for 0 t 2 .
where W is the "half width" and H the "half height" of the ellipse. When W and H are equal, the ellipse
is a circle of radius W. Figure 3.69 shows an ellipse, along with the
component functions x(.) and y(.).
Dr Taleb Obaid 3 / 26
How do we find the implicit form from the parametric form? The basic step is to combine the two
equations for x(t) and y(t) to somehow eliminate the variable t. For the ellipse we can square both
x/W and y/H and use equation (3-13) to obtain the familiar equation for an ellipse:
(x/W)2 + (y/H)2 =1 (3.14)
Dr Taleb Obaid 3 / 27
Computer Graphics CS 330 Fall 2009
Archimedean spiral: f( ) = K .
The conic sections (the ellipse, parabola, and hyperbola) all share the polar form
f( ) = 1 / (1 ± e cos( ))
where e is the eccentricity of the section. For e = 1, the shape is a parabola; for 0 e < 1, it is an ellipse;
and for e > 1, it is a hyperbola. From practice exercises page 122, the eccentricity , e = c / W, where
c is the focus of the ellipse, W the width.
Dr Taleb Obaid 3 / 28
Chapter 5,
Transformations of Objects
Goals of the Chapter
To develop tools for transforming one picture into another
To introduce the fundamental concepts of affine transformations, which perform
combinations of rotations, scaling, and translations
To develop functions that applies affine transformations to objects in computer
programs
To develop tools for transforming coordinate frames
To see how to set up a camera to render a 3D scene using OpenGL
To learn to design scenes in the Scene Design language SDL, and to write programs that
read SDL files and draw the scenes they describe
INTRODUCTION TO TRANSFORMATIONS
Figure 5.1 (a) shows two versions of a simple house, drawn before and after each of its points
has been transformed. In this case the house has been scaled down in size, rotated a small
amount, and then moved up and to the right.
The overall transformation is a combination of three elementary ones: scaling, rotation, and
translation. Figure 5.1(b) shows a 3D house before and after it is similarly transformed: Each 3D
point in the house is subjected to a scaling, a rotation, and a translation by the transformation
Fig 5.1, Drawings of Objects before and after they are transformed
a. We can compose a "scene" out of a number of objects, as in Figure 5.2. The scene is
b. The
fashion the whole shape by appropriate reflections, rotations, and transformations of
the motif.
c. A designer may want to view an object from different vantage points and make a picture
from each one. The scene can be rotated and viewed with same camera, but it is more
natural to leave the scene alone and move the camera.
Figure 5,7 shows a simplified view of the OpenGL graphics pipeline. An application sends the
pipeline a sequence of points P1, P2, P3,... using commands like,
glBegin (GL_LINES);
glVertex3f (...); // send PI through the pipeline
glVertex3f (...): // send P2 through the pipeline
glVertex3f (...); // send P3 through the pipeline
glEnd ():
These points first encounter a transformation called the "current transformation" (CT), which
alters their values into a different set of points, say Q1, Q2, Q3 i
describe some geometric object, the points Q i, describe the Transformed version of the same
object. These points are then sent through additional steps and ultimately are used lo draw the
final image on the display.
As the figure illustrates, an arbitrary point P in the plane is mapped to another point Q. We say
that Q is the image of P under the mapping T. More formally, if S is a set of points, its image T(S)
is the set of all points T(P) , where P is some point in S.
We take the 2D case first, in whichever coordinate frame we are using, points P and Q have the
representations
Px Qx
P = Py and Q = Qy
1 1
1 1
Affine transformations have a simple form. The coordinates of Q are linear combinations of those
of P.
Qx m11 Px + m12Py + m13
Qy = m21 Px + m12Py + m23
1 1
Example 5.2.1
An affine transformation is specified by the matrix
3 0 5
-2 1 2
0 0 1
Translation
To translate a picture into a different position on a graphics display
Qx 1 0 m 13 Px
Qy = 0 1 m 23 Py
1 0 0 1 1
or simply
Qx Px + m13
Qy = Py + m23
1 1
Example
If the offset vector is (2, 3), every point will be altered into a new point that is two units farther
to right and three units above. The point (1, -5), for instance, is transformed into (3, -2), and the
point (0, 0) is translated into (2, 3).
Scaling
Scaling changes the size of a picture and involves two scale factors, Sx, Sy, for the x- and y-
coordinates.
(Qx, Qy) = (SxPx, SyPy).
The matrix is
Sx 0 0
0 Sy 0
0 0 1
This is called scaling about the origin, because each point P is moved Sx times farther from the
origin in the x-direction and Sy times farther from the origin in the y-direction.
If a scale factor is negative, then there is also a reflection about a coordinate axis. Fig 5.11, the
scaling (Sx, Sy) = (-1, 2) is applied to a collection of points. Each point is both reflected about the
y-axis and scaled by 2 in the y-direction.
1.
If the two factors are the same (Sx = Sy = S) , is a uniform scaling. If S is negative, there are
reflection about both axes.
Rotation
A fundamental graphics operation is the rotation of a figure about a given point through some
angle, as in Fig.
As When T() is a rotation about the origin, the offset vector d is zero and Q = T(P) the form
In terms of its matrix form, a pure rotation about the origin is given by
Qx cos( ) -sin( ) 0 Px
Qy = sin( ) cos( ) 0 Py
1 0 0 1 1
and
sin( + ) = sin( )cos( ) + cos( )sin( )
and use
Px = Rcos( + ) and Py = Rsin( + ) to obtain eq. 5.9.
1 0 0
g 1 0
0 0 1
If point P is mapped into point Q according to Q = MP, we simply pre-multiply both sides by the
inverse of M denoted by M-1, and write
m22 -m12
M-1 = 1 .
det M -m21 m11
1. Scaling
1/Sx 0 0
M-1 = 0 1/Sy 0
0 0 1
2. Rotation
cos( ) sin( ) 0
M-1 = -sin( ) cos( ) 0
0 0 1
3. Shearing
1 -h 0
M-1 = 0 1 0
0 0 1
4. Translations
1 0 -m13
M-1 = 0 1 -m23
0 0 1
The process of applying several transformations in succession to form one overall transformation
is called composing the transformations. Fig 5.16 T1() maps P into Q, and T2() maps Q into W. The
nature of W = T2(Q)=T2(T1(P))
Suppose the two transformations are represented by the matrices M 1 and M2. P is transformed
to the point M1P, which is then transformed to M2(M1P). So, the later just (M 2M1)P, and we have
W = MP.
Where M = M2M1.
Notice that the matrices appear in reverse order.
Dr Taleb Obaid 5 / 10
Creating a matrix for each elementary transformation and multiplying the matrices out produces
1 0 Vx cos( ) -sin( ) 0 1 0 -Vx cos( ) -sin( ) d x
0 1 Vy sin( ) cos( ) 0 0 1 -Vy = sin( ) cos( ) dy
0 0 1 0 0 1 0 0 1 cos( ) 0 1
where
dx = -cos( )Vx + sin( )Vy + Vx
dy = -sin( )Vx - cos( )Vy + Vy
Example 5.2.6
Scaling and shearing about arbitrary
-transform-
Dr Taleb Obaid 5 / 11
Computer Graphics CS 330 Spring 2011
We want to develop the transformation that reflects any point P about the line, called the axis
of reflection, to produce point Q.
1. A rotation through the angle (the axis of reflection coincides with the x-axis).
2. A reflection about the x-axis.
3. A rotation back through
The over all transformation is given by the product of the following three matrices:
c s 0 1 0 0 c -s 0 c2-s2 -2sc 0
-s c 0 0 -1 0 s c 0 = -2cs s2-c2 0
0 0 1 0 0 1 0 0 1 0 0 1
cos(2 ) sin(2 ) 0
sin(2 ) - cos(2 ) 0 (a reflection about the axis at angle
0 0 1
Px
P = Py .
Pz
1
Qx Px
Qy = M P y
Qz Pz
1 1
Dr Taleb Obaid 5 / 12
Scaling
The matrix is
Sx 0 0 0
0 Sy 0 0
0 0 Sz 0
0 0 0 1
Shearing
The matrix for the simplest elementary shear is the identity matrix with one zero term replaced
by some value, as in
1 0 0 0
f 1 0 0
0 0 1 0
0 0 0 1
Rotations
We often want to rotate an object or a camera in order to obtain different views. We must specify
an axis about which the rotation occurs, rather than just a single point.
The simplest rotation is a rotation about one of the coordinate axes. We call a rotation about the
x-axis an "x-roll," a rotation about the y-axis a "y-roll," and a rotation about the z-axis a "z-roll."
The rotation is through an angle , about the given axis. We define positive angles using a
"looking inward" convention:
Positive values of cause a counterclockwise (CCW) rotation about an axis as one looks inward
from a point on the positive axis toward the origin.
Dr Taleb Obaid 5 / 13
Computer Graphics CS 330 Spring 2011
2. A y-roll
c 0 s 0
0 1 0 0
R y( ) = 0 -s c 0
0 0 0 1
3. A z-roll
c -s 0 0
s c 0 0
R z( ) = 0 0 1 0
0 0 0 1
Suppose you have a routine house () that draws house #1 in Fig 5.34. But you wish instead to
draw house #2, shown rotated through -30° and then translated through (32, 25). This is a
frequently encountered situation; An object is defined at a convenient size and position, but we
want to draw it (perhaps many times) at different sizes, orientations, and locations.
Dr Taleb Obaid 5 / 14
After drawing house #, how do we arrange matters so that house #2 is drawn instead? There are
tow ways:
The routine produces Q=MP, then apply the transformation to each point V [i] in house ().
The window-to-viewport mapping is "quietly" applied to each vertex as part of moveTo () and
lineTo(). We can have an additional transformation, the current transformation, CT. We enhance
move-To () and linsTo () so that they first quietly apply CT to the argument vertex and then apply
the window-to-viewport mapping.
As in Fig 5.35, When glVertex2d () is called with the argument V, the vertex V is first transformed
by the CT to form point Q, which is then passed through the window to-viewport mapping to
form point S in the screen window.
Fig 5.35 The current transformation is applied to vertices.
How do we extend moveTo () and lineTo () so that they quietly carry out this additional mapping?
If you are not using OpenGL, you must write code that actually performs the transformation.
If you are using OpenGL, the transformation is done automatically! OpenGL maintains a so-called
modelview matrix, and every vertex that is passed down the graphics pipeline is multiplied by
this matrix.
We need only set up the modelview matrix to embody the desired transformation
OpenGL works entirely in 3D, so its modelview matrix produces 3D transformations.
The principal routines for altering the modelview matrix are glRotated(), glScaled (), and
glTranslated (), (d indicated to double). These do not set the CT directly; instead, each
Dr Taleb Obaid 5 / 15
Computer Graphics CS 330 Spring 2011
postmultiplies the CT (the modelview matrix) by a particular matrix, say, M, and puts the result
back into the CT. That is, each of the routines creates a matrix M required for the new
transformation and performs the operation
CT = CT* M
The following are OpenGL routines for applying transformations in the 2D case;
Since these routines only compose a transformation with the CT, we need some way to get
started:
to initialize the CT to the identity transformation. For that purpose OpenGL provides the routine
gILoadIdentity (). And because the functions listed can be set to work on any of the matrices that
OpenGL supports, we must inform OpenGL which matrix we are altering. This is accomplished
using
gIMatrixMode (GL_MODELV1EW).
Dr Taleb Obaid 5 / 16
Dr Taleb Obaid 5 / 17
Computer Graphics CS 330 Spring 2011
A reflection about the x-axis is achieved by the use of scale 2D (l, -l), so the motif plus its reflection
can be drawn using the following code:
flakeMotif () ; // draw the top half
cva.scals2D(1.0, -1.0) : // flip it vertically
flakeMotif (); // draw the bottom half
cvs.scalc2D(1.0, 1.0); // restore the original axis
To draw the entire snowflake just execute this code six times, with an intervening rotation of 60°:
void drawFlake () {
for (int count = 0; count < 6; count++) {
flakeMotif () ;
cvs.scale2D (l.0. -1.0) :
flakeMotif () ;
cvs.sca1e2D (l .0 , -1,0);
cvs.rotatc2D (60.0);
}
}
The implementation of pushCT () and popCT () is simple with OpenGL, which has routines
glPushMatrix () and glPopMatrix () to manage several different slacks of matrices as in Figure
5.44.
Dr Taleb Obaid 5 / 18
Fig 5.45 A tiling based on a Motif. (a) The motif, (b) The tiling
Dr Taleb Obaid 5 / 19
Computer Graphics CS 330 Spring 2011
Dr Taleb Obaid 5 / 20
Dr Taleb Obaid 5 / 21
Computer Graphics CS 330 Spring 2011
Dr Taleb Obaid 5 / 22
if (state == GLUT_DOWN)
glutIdleFunc (spinDisplay_CW);
break;
case GLUT_RIGHT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc (spinDisplay_CCW);
else
glutIdleFunc (NULL);
break;
default:
break;
}
}
int main (int argc, char**argv) {
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize (600, 600);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc (display);
glutReshapeFunc (reshape);
glutMouseFunc (mouse);
glutMainLoop();
return 0;
}
Dr Taleb Obaid 5 / 23
Computer Graphics CS 330 Spring 2011
Points lying inside the view volume are projected onto the window along lines parallel to the z-
axis, i.e. ignoring the z-components of those points, so 3D point (x1, y1, z1) projects to (x1, y1, 0).
Points lying outside the view volume are clipped off.
Fig 5.51 shows such a camera immersed in a scene. The scene consists of a block, part of which
lies outside the view volume.
Dr Taleb Obaid 5 / 24
The modelview matrix provides what we have calling the CT. It combines two effects: the
sequence of modeling transformation applied to objects and the transformation that orients and
positions the camera.
Dr Taleb Obaid 5 / 25
Computer Graphics CS 330 Spring 2011
The V matrix used to rotate and translate the block into a new position. The specific
transforma
with the eye at the origin and view volume aligned with z-axis, as in Part (c).
In the (eye) coordinate, the edges of the view volume are parallel to the x-,y-, and z-
axes. The volume extends from left to right in x, from bottom to top in y, and from near to -far
in z.
The projection matrix scales and shifts each vertex in a particular way, so that all those vertices
that lie inside the view volume will lie inside a standard cube that extends from 1 to 1 in each
dimension.
Dr Taleb Obaid 5 / 26
The following functions are normally used to modify the modelview matrix, which is first made
"current" by executing: gIMatrixMode (GL_MODELVIEW)
glRotated(angle, ux , uy , uz);
Postmultiply the current matrix by a matrix that performs a rotation through angle degrees about
the axis that passes through the origin and the point (ux, uy, uz). Put the result back in the
current matrix.
Dr Taleb Obaid 5 / 27
Computer Graphics CS 330 Spring 2011
The torus is determined by the inner radius inRad and outer radius outRad.
The sphere and torus are approximated by polygonal faces, and you can adjust the parameters
nSlices and nStacks to specify how many faces to use in the approximation. nSlices is the number
of subdivisions around the z-axis, and nStacks is the number of "bands" along the z-axis, as if the
shape were a stack of nStacks disks.
The functions used to render four of the Platonic solids are as follows:
tetrahedron: glutWireTetrahedron();
octahedron: glutWireOctahedron ();
dodecahedron: glutWireDodecahedron ();
icosahedron: glutWireIcosahedron ();
All of the preceding shapes are centered at the origin. We also have the following solids:
cone: glutWireCone (GLdouble baseRad, GLdouble height, GLint nSlices, GLint nStacks)
glu Quadrics
Dr Taleb Obaid 5 / 28
The axes of the cone and tapered cylinder coincide with the z-axis. Their bases rest on the z = 0
plane and extend to z = height along the z-axis. The radius of the
cone and tapered cylinder at z = 0 is given by baseRad. The radius of the tapered cylinder at z =
height is topRad.
When topRad is 1, there is no taper, and we have the classic right circular cylinder. When topRad
is 0,the tapered cylinder is identical to the cone.
Note that drawing the tapered cylinder in OpenGL requires some extra work. To draw it, you
must;
EXAMPLE 5.6.2
A scene composed of wire-frame objects Figure 5.59 shows a scene with several objects disposed
at the corners of a unit cube, which itself has one corner at the origin.
The camera is given a view volume that extends from -2 to 2 in y. with an aspect ratio of 640/480.
The near plane is at N = 0.1, the far plane at F = l00. This is accomplished using
The camera is positioned with eye = (2, 2, 2), lookAt = (0, 0, 0), and up = (0, 1, 0) (parallel lo the
y-axis), using
gluLookAt (2.0, 2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
Dr Taleb Obaid 5 / 29
Computer Graphics CS 330 Spring 2011
glutWireDodecahedron (); glRotated (ang + 15, 0.5, 0.5, 0.5); glutWireTeapot (1.);
Dr Taleb Obaid 5 / 30
Dr Taleb Obaid 5 / 31
Computer Graphics CS 330 Spring 2011
glPopMatrix ();
}
glPushMatrix ();
glTranslated (0.5, 0.5, 0.5); // big cube at (0.5, 0.5, 0.5)
glutWireCube (1.0);
glPopMatrix ();
glPushMatrix ();
glTranslated (1.0,1.0,0); // sphere at (1,1,0)
glutWireSphere (0.25, 10, 8);
glPopMatrix ();
glPushMatrix ();
glTranslated (1.0,0,1.0); // cone at (1,0,1)
glutWireCone (0.2, 0.5, 10, 8);
glPopMatrix ();
glPushMatrix ();
glTranslated (1,1,1);
glutWireTeapot (0.2); // teapot at (1,1,1)
glPopMatrix ();
glPushMatrix ();
glTranslated (0, 1.0 ,0); // torus at (0,1,0)
glRotated (90.0, 1,0,0);
glutWireTorus (0.1, 0.3, 10,10);
Dr Taleb Obaid 5 / 32
glPopMatrix ();
glPushMatrix ();
glTranslated (1.0, 0 ,0); // dodecahedron at (1,0,0)
glScaled (0.15, 0.15, 0.15);
glutWireDodecahedron ();
glPopMatrix ();
glPushMatrix ();
glTranslated (0, 1.0 ,1.0); // small cube at (0,1,1)
glutWireCube (0.25);
glPopMatrix ();
glPushMatrix ();
glTranslated (0, 0 ,1.0); // cylinder at (0,0,1)
GLUquadricObj * qobj;
qobj = gluNewQuadric ();
gluQuadricDrawStyle (qobj,GLU_LINE);
gluCylinder (qobj, 0.2, 0.2, 0.4, 8, 8);
glPopMatrix ();
glFlush ();
}
Dr Taleb Obaid 5 / 33
Computer Graphics CS 330 Spring 2011
The main () routine initializes a 640-by-480 pixel screen window, sets the viewport and
background color, and specifies displayWire ().
In displayWire (), the shape and position of the camera are established first. Then each object is
drawn in turn.
Also shown in the figure are the x-, y-, and z-axes, drawn with conical arrow-heads. Displaying
the underlying coordinate system can help to orient the viewer. To draw the x-axis, the z-axis is
rotated 90o about the y-axis to form a rotated system, and the x-axis is redrawn in its new
orientation. Note that this axis is drawn without immersing it in a glPushMaLrix (), glPopMatrix ()
pair, so the next rotation to produce the y-axis takes place in the already rotated coordinate
system.
Fig 5.61 A simple 3D scene a) using a large view volume, b) using a small view volume
Dr Taleb Obaid 5 / 34
Two views of a scene are shown in Figure 5.61. Both views use a camera set by
Part (a) uses a large view volume that encompasses the whole scene;
Part (b) uses a small view volume that encompasses only a small portion of the scene, thereby
providing a close-up view.
The scene contains three objects resting on a table in the corner of a "room." Each of the three
walls is made by flattening a cube into a thin sheet.
The jack is composed of three stretched spheres oriented at right angles to each other, plus six
small spheres at their ends.
The table consists of a tabletop and four legs. Each of the table's five pieces is a cube that has
been scaled to the desired size and shape. The layout for the table is shown in Figure 5.62 and is
based on Four parameters that characterize the size of its parts: topWidth, topThick, 1egLen, and
legThick. A routine tableLeg () draws each leg and is called four times within the routine table ().
Always, a glPushMatrix (), glPopMatrix () pair surrounds the modeling functions to isolate their
effect
#include <windows.h>
Dr Taleb Obaid 5 / 35
Computer Graphics CS 330 Spring 2011
#include <gl/Gl.h>
#include <gl/Glu.h>
#include <gl/glut.h>
// <<<<<<<<<< wall >>>>>>>>>>>
void wall (double thickness ) {
// draw thin wall with top = xz-plane, corner at origin
glPushMatrix () ;
glTranslated (0.5, 0.5 * thickness, 0.5);
glScaled (1.0, thickness, 1.0);
glutSolidCube (1.0);
glPopMatrix ();
}
// <<<<<<<<<< tablfeLeg >>>>>>>>>>
void tableLeg (double thick, double len) {
glPushMatrix () ;
glTranslated (0, len/2, 0);
glScaled (thick, len, thick);
glutSolidCube (1.0) ;
glPopMatrix ();
}
//<<<<<<<<<< jack part >>>>>>>>>>>>
void jackPart () {
// draw one axis of the unit jack - a stretched sphere
glPushMatrix ();
glScaled (0.2,0.2, 1.0);
glutSolidSphere (1, 15, 15);
glPopMatrix () ;
glPushMatrix () ;
glTranslated (0, 0.1, 2) ; // ball on one end
glutSolidSphere (0.2, 15, 15) ;
glTranslated (0, 0, -2.4);
glutSolidSphere (0.2, 15, 15); // ball on the other end
glPopMatrix ();
}
//<<<<<<<<<<<<< jack >>>>>>>>>>>
void jack() {
// draw a unit jack out of spheroids
glPushMatrix () ;
jackPart ();
glRotated (90.0, 0, 1, 0);
jackPart ();
glRotated (90.0, 1, 0, 0);
jackPart () ;
glPopMatrix () ;
}
Dr Taleb Obaid 5 / 36
Dr Taleb Obaid 5 / 37
Computer Graphics CS 330 Spring 2011
Dr Taleb Obaid 5 / 38
glutMainLoop () ;
}
Dr Taleb Obaid 5 / 39
Computer Graphics CS 330 Spring 2011
gluLookAt(2.3, 1.3, 2, 0, 0.25, 0, 1.0, 0.0, 0.0); gluLookAt(2.3, 1.3, 2, 0, 0.25, 0, 0.0,
0.0,1.0);
What changes should be made in Figure 5.63 to place the jack on the floor and the sphere
perched on top of the teapot?
Dr Taleb Obaid 5 / 40
Menus
The windowing systems support a set of widgets, which are special types of windows with which
the user can interact. Widgets sets include menus, buttons, slides bars, and dialog boxes. GLUT
provides limited capabilities, such as menu.
Suppose that we want to use the right mouse button to pop up a menu that will have two entries:
Clear the screen.
End the program.
glutCreateMenu (mymenu);
glutAddMenuEntr
glutAttachMenuEntry (GLUT_RIGHT_BUTTON);
Dr Taleb Obaid 5 / 41
Computer Graphics CS 330 Spring 2011
When a window is created, it becomes the current window, the primitive are rendered to the
current window. We can change this window by:
We can also create sub-windows of any window. Each sub-window is defined to be a sub-
rectangle of its parent using:
int glutCreateSubWindow (int parant, int x, int y, int width, int height ) ;
Creates a sub-window of parent and returns its ID. The sub-window has its origin at (x, y) and has
size width by height in pixels. The sub-window becomes the current window.
Dr Taleb Obaid 5 / 42
Some Functions:
void glutIdleFunc (void (*f) (void)) ;
The function f() is executed whenever no other events are to be handled. When we want to
eliminate a callback, we call glutIdelFunction ().
// Menu Program
#include <GL/glut.h>
#include <stdlib.h>
GLsizei ww = 500, wh = 500;
int fill, r=1.0, g=1.0, b=1.0;
void fill_menu (int );
void color_menu (int );
void right_menu (int );
void display (void) {
glClearColor (0.0, 0.0, 0.0, 0.0);
glClear (GL_COLOR_BUFFER_BIT);
glColor3f(r, g, b);
if (fill == 1)
glBegin (GL_POLYGON);
else
glBegin (GL_LINE_LOOP);
glVertex3f (100.0, 200.0, 0.0);
glVertex3f (200.0, 200.0, 0.0);
glVertex3f (200.0, 300.0, 0.0);
glVertex3f (100.0, 300.0, 0.0);
glEnd();
glFlush ();
}
void init (void) {
glClearColor (0.3, 0.5, 0.3, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
}
void fill_menu (int id) {
if (id == 1)
fill = 1;
else
fill = 0;
glutPostRedisplay();
}
Dr Taleb Obaid 5 / 43
Computer Graphics CS 330 Spring 2011
c_menu = glutCreateMenu(color_menu);
glutAddMenuEntry ("Red", 1);
glutAddMenuEntry ("Green", 2);
glutAddMenuEntry ("Blue", 3);
glutCreateMenu (right_menu);
glutAddSubMenu("Colors", c_menu);
glutAddSubMenu("Fill", f_menu);
glutAttachMenu (GLUT_RIGHT_BUTTON);
init ();
glutMainLoop();
return 0;
}
Dr Taleb Obaid 5 / 44