0% found this document useful (0 votes)
11 views27 pages

CG Unit - Iii

Unit III of the document covers graphics programming, focusing on various color models such as RGB, YIQ, CMY, and HSV, and their applications in computer graphics. It also discusses computer animation techniques, including keyframe specifications, object definitions, and the generation of in-between frames for smooth transitions. The document highlights the importance of color perception and animation design in creating visually appealing graphics and animations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views27 pages

CG Unit - Iii

Unit III of the document covers graphics programming, focusing on various color models such as RGB, YIQ, CMY, and HSV, and their applications in computer graphics. It also discusses computer animation techniques, including keyframe specifications, object definitions, and the generation of in-between frames for smooth transitions. The document highlights the importance of color perception and animation design in creating visually appealing graphics and animations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

UNIT – III GRAPHICS PROGRAMMING

UNIT III - GRAPHICS PROGRAMMING

Color Models – RGB, YIQ, CMY, HSV – Animations – General Computer Animation,
Raster, Keyframe - Graphics programming using OPENGL – Basic graphics primitives –
Drawing three dimensional objects - Drawing three dimensional scenes

1. COLOR MODELS

Color Model is a method for explaining the properties or behavior of color within some
particular context. No single color model can explain all aspects of color, so we make use of
different models to help describe the different perceived characteristics of color.

Properties of Light
Light is a narrow frequency band within the electromagnetic system.

Other frequency bands within this spectrum are called radio waves, micro waves, infrared waves
and x-rays. The below fig shows the frequency ranges for some of the electromagnetic bands.

Each frequency value within the visible band corresponds to a distinct color.

At the low frequency end is a red color (4.3*10 14 Hz) and the highest frequency is a violet color
(7.5 *1014Hz)

Spectral colors range from the reds through orange and yellow at the low frequency end to
greens, blues and violet at the high end.

Since light is an electro magnetic wave, the various colors are described in terms of either the
frequency for the wave length λ of the wave.

The wave length ad frequency of the monochromatic wave are inversely proportional to each
other, with the proportionality constants as the speed of light C where C = λ f

A light source such as the sun or a light bulb emits all frequencies within the visible range to
produce white light. When white light is incident upon an object, some frequencies are reflected

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

and some are absorbed by the object. The combination of frequencies present in the reflected
light determines what we perceive as the color of the object.

If low frequencies are predominant in the reflected light, the object is described as red. In this
case, the perceived light has the dominant frequency at the red end of the spectrum. The
dominant frequency is also called the hue, or simply the color of the light.

Brightness is another property, which in the perceived intensity of the light.

Intensity in the radiant energy emitted per limit time, per unit solid angle, and per unit projected
area of the source.

Radiant energy is related to the luminance of the source.

The next property in the purity or saturation of the light.


- Purity describes how washed out or how pure the color of the light appears.

- Pastels and Pale colors are described as less pure.


The term chromaticity is used to refer collectively to the two properties, purity and dominant
frequency.

Two different color light sources with suitably chosen intensities can be used to produce a range
of other colors.

If the 2 color sources combine to produce white light, they are called complementary colors.
E.g., Red and Cyan, green and magenta, and blue and yellow.

Color models that are used to describe combinations of light in terms of dominant frequency use
3 colors to obtain a wide range of colors, called the color gamut.

The 2 or 3 colors used to produce other colors in a color model are called primary colors.

2. STANDARD PRIMARIES

XYZ COLOR MODEL


The set of primaries is generally referred to as the XYZ or (X,Y,Z) color model where X,Y and
Z represent vectors in a 3D, additive color space.

Any color Cλ is expressed as

Cλ = XX + YY + ZZ-------------(1)

Where X,Y and Z designates the amounts of the standard primaries needed to match Cλ.

It is convenient to normalize the amount in equation (1) against luminance (X + Y+ Z).


Normalized amounts are calculated as,
x = X/(X+Y+Z), y = Y/(X+Y+Z), z = Z/(X+Y+Z) with x + y + z = 1

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

Any color can be represented with just the x and y amounts. The parameters x and y are called
the chromaticity values because they depend only on hue and purity.

If we specify colors only with x and y, we cannot obtain the amounts X, Y and Z. so, a complete
description of a color in given with the 3 values x, y and Y.
X = (x/y)Y, Z = (z/y)Y Where z = 1-x-y.

INTUITIVE COLOR CONCEPTS


Color paintings can be created by mixing color pigments with white and black pigments to form
the various shades, tints and tones.

Starting with the pigment for a „pure color‟ the color is added to black pigment to produce
different shades. The more black pigment produces darker shades.

Different tints of the color are obtained by adding a white pigment to the original color, making
it lighter as more white is added.

Tones of the color are produced by adding both black and white pigments.

2.1. RGB COLOR MODEL


Based on the tristimulus theory of version, our eyes perceive color through the stimulation of
three visual pigments in the cones on the retina.

These visual pigments have a peak sensitivity at wavelengths of about 630 nm (red), 530 nm
(green) and 450 nm (blue).

By comparing intensities in a light source, we perceive the color of the light.

This is the basis for displaying color output on a video monitor using the 3 color primaries, red,
green, and blue referred to as the RGB color model. It is represented in the below figure.

The sign represents black, and the vertex with coordinates (1,1,1) in white.

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

Vertices of the cube on the axes represent the primary colors, the remaining vertices represents
the complementary color for each of the primary colors.

The RGB color scheme is an additive model. (i.e.,) Intensities of the primary colors are added to
produce other colors.

Each color point within the bounds of the cube can be represented as the triple (R,G,B) where
values for R, G and B are assigned in the range from 0 to1.

The color Cλ is expressed in RGB component as


Cλ = RR + GG + BB
The magenta vertex is obtained by adding red and blue to produce the triple (1,0,1) and white at
(1,1,1) in the sum of the red, green and blue vertices

Shades of gray are represented along the main diagonal of the cube from the origin (black) to the
white vertex.

2.2. YIQ COLOR MODEL

The National Television System Committee (NTSC) color model for forming the composite
video signal in the YIQ model.

In the YIQ color model, luminance (brightness) information in contained in the Y parameter,
chromaticity information (hue and purity) is contained into the I and Q parameters.

A combination of red, green and blue intensities are chosen for the Y parameter to yield the
standard luminosity curve.

Since Y contains the luminance information, black and white TV monitors use only the Y signal.

Parameter I contain orange-cyan hue information that provides the flash-tone shading and
occupies a bandwidth of 1.5 MHz.

Parameter Q carries green-magenta hue information in a bandwidth of about 0.6 MHz.

An RGB signal can be converted to a TV signal using an NTSC encoder which converts RGB
values to YIQ values, as follows

An NTSC video signal can be converted to an RGB signal using an NTSC encoder which
separates the video signal into YIQ components, the converts to RCB values, as follows:

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

2.3. CMY COLOR MODEL


A color model defined with the primary colors cyan, magenta, and yellow (CMY) in useful for
describing color output to hard copy devices.

It is a subtractive color model (i.e.,) cyan can be formed by adding green and blue light. When
white light is reflected from cyan-colored ink, the reflected light must have no red component.
i.e., red light is absorbed or subtracted by the link.

Magenta ink subtracts the green component from incident light and yellow subtracts the blue
component.

In CMY model, point (1,1,1) represents black because all components of the incident light are
subtracted.

The origin represents white light.

Equal amounts of each of the primary colors produce grays along the main diagonal of the cube.

A combination of cyan and magenta ink produces blue light because the red and green
components of the incident light are absorbed.

The printing process often used with the CMY model generates a color point with a collection of
4 ink dots; one dot is used for each of the primary colors (cyan, magenta and yellow) and one dot
in black.

The conversion from an RGB representation to a CMY representation is expressed as

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

= -

Where the white is represented in the RGB system as the unit column vector.

Similarly the conversion of CMY to RGB representation is expressed as

Where black is represented in the CMY system as the unit column vector.

2.4. HSV COLOR MODEL


The HSV model uses color descriptions that have a more interactive appeal to a user.

Color parameters in this model are hue (H), saturation (S), and value (V).

The 3D representation of the HSV model is derived from the RGB cube. The outline of the cube
has the hexagon shape.

The boundary of the hexagon represents the various hues, and it is used as the top of the HSV
hexcone.

In the hexcone, saturation is measured along a horizontal axis, and value is along a vertical axis
through the center of the hexcone.

Hue is represented as an angle about the vertical axis, ranging from 00 at red through 3600.
Vertices of the hexagon are separated by 600 intervals.

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

Yellow is at 600, green at 1200 and cyan opposite red at H = 1800. Complementary colors are
1800 apart.

Saturation S varies from 0 to 1. the maximum purity at S = 1, at S = 0.25, the hue is said to be
one quarter pure, at S = 0, we have the gray scale.

Value V varies from 0 at the apex to 1 at the top.


- the apex representation black.
At the top of the hexcone, colors have their maximum intensity.

When V = 1 and S = 1 we have the „pure‟ hues.

White is the point at V = 1 and S = 0.

2.5. HLS COLOR MODEL

Another model based on intuitive color parameters is the HLS system used by Tektronix. This
model has the double-cone representation. The three color parameters in this model are called
hue (H), lightness (L), and saturation 6).
Hue has the same meaning as in the HSV model. It specifies an angle about the vertical
axis that locates a chosen hue. In this model, H = 0' corresponds to blue. The remaining colors
are specified around the perimeter of the cone in the same order as in the HSV model. Magenta

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

is at 60•‹. red is at 120•‹, and cyan is located at H = 180". Again, complementary colors are 180"
apart on the double cone.

The vertical axis in this model is called


lightness, L. At L = 0, we have black, and whitc is
at L = 1. Gray scale is along the L axis, and the
"pure hues" lie on the L = 0.5 plane.
Saturation parameter S again specifies relative
purity of a color. This parameter varies from 0 to
1, and pure hues are those for which S = 1 and L
= 0.5. As S decreases, the hues are said to be less
pure. At S = 0, we have the gray scale.

3. ANIMATION

Computer animation refers to any time sequence of visual changes in a scene. Computer
animations can also be generated by changing camera parameters such as position, orientation
and focal length. Applications of computer-generated animation are entertainment, advertising,
training and education.

Example : Advertising animations often transition one object shape into another.
Frame-by-Frame animation Each frame of the scene is separately generated and stored. Later,
the frames can be recoded on film or they can be consecutively displayed in "real-time playback"
mode.

Design of Animation Sequences An animation sequence in designed with the following steps:

 Story board layout


 Object definitions
 Key-frame specifications
 Generation of in-between frames.

Story board
The story board is an outline of the action.

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

It defines the motion sequences as a set of basic events that are to take place.
Depending on the type of animation to be produced, the story board could consist of a set of
rough sketches or a list of the basic ideas for the motion.

Object Definition
An object definition is given for each participant in the action.
Objects can be defined in terms of basic shapes such as polygons or splines.
The associated movements of each object are specified along with the shape.

Key frame
A key frame is detailed drawing of the scene at a certain time in the animation sequence.
Within each key frame, each object is positioned according to the time for that frame.
Some key frames are chosen at extreme positions in the action; others are spaced so that the time
interval between key frames is not too much.

In-betweens
In betweens are the intermediate frames between the key frames.
The number of in between needed is determined by the media to be used to display the
animation.
Film requires 24 frames per second and graphics terminals are refreshed at the rate of 30 to 60
frames per seconds.
Time intervals for the motion are setup so there are from 3 to 5 in-between for each pair of key
frames.
Depending on the speed of the motion, some key frames can be duplicated.
For a 1 min film sequence with no duplication, 1440 frames are needed.
Other required tasks are
- Motion verification
- Editing
- Production and synchronization of a sound track.

3.1. General Computer Animation Functions

Steps in the development of an animation sequence are,


1. Object manipulation and rendering
2. Camera motion
3. Generation of in-betweens

Animation packages such as wave front provide special functions for designing the animation
and processing individuals objects.
Animation packages facilitate to store and manage the object database.

Object shapes and associated parameter are stored and updated in the database.
Motion can be generated according to specified constraints using 2D and 3D transformations.
Standard functions can be applied to identify visible surfaces and apply the rendering algorithms.
Camera movement functions such as zooming, panning and tilting are used for motion
simulation.

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

Given the specification for the key frames, the in-betweens can be automatically generated.
3.2. Raster Animations

On raster systems, real-time animation in limited applications can be generated using raster
operations.

Sequence of raster operations can be executed to produce real time animation of either 2D or 3D
objects.

We can animate objects along 2D motion paths using the color-table transformations.
- Predefine the object as successive positions along the motion path, set the successive
blocks of pixel values to color table entries.

- Set the pixels at the first position of the object to „on‟ values, and set the pixels at the
other object positions to the background color.

- The animation is accomplished by changing the color table values so that the object is
„on‟ at successive positions along the animation path as the preceding position is set to the
background intensity.

3.3. Computer Animation Languages


Animation functions include a graphics editor, a key frame generator and standard graphics
routines.

The graphics editor allows designing and modifying object shapes, using spline surfaces,
constructive solid geometry methods or other representation schemes.

Scene description includes the positioning of objects and light sources defining the photometric
parameters and setting the camera parameters.

Action specification involves the layout of motion paths for the objects and camera.

Keyframe systems are specialized animation languages designed dimply to generate the in-
betweens from the user specified keyframes.

Parameterized systems allow object motion characteristics to be specified as part of the object
definitions. The adjustable parameters control such object characteristics as degrees of freedom
motion limitations and allowable shape changes.

Scripting systems allow object specifications and animation sequences to be defined with a user
input script. From the script, a library of various objects and motions can be constructed.

3.4. Keyframe Systems


Each set of in-betweens are generated from the specification of two keyframes.
For complex scenes, we can separate the frames into individual components or objects called
cells, an acronym from cartoon animation.

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

3.4.1. Morphing
Transformation of object shapes from one form to another is called Morphing.
Morphing methods can be applied to any motion or transition involving a change in shape. The
example is shown in the below figure.

An edge with vertex positions 1 and 2 in key frame k evolves into two connected edges in key frame k + 1

Linear interpolation for transforming a line segment in key frame k into two connected line segments in key
frame k + 1.

Linear interpolation for transforming a triangle into a quadrilateral

The general preprocessing rules for equalizing keyframes in terms of either the number of
vertices to be added to a keyframe.

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

Suppose we equalize the edge count and parameters Lk and Lk+1 denote the number of line
segments in two consecutive frames. We define,
Lmax = max (Lk, Lk+1)
Lmin = min(Lk , Lk+1)
Ne = Lmax mod Lmin
Ns = int (Lmax/Lmin)

The preprocessing is accomplished by

1. Dividing Ne edges of keyframemin into Ns+1 section.


2. Dividing the remaining lines of keyframemin into Ns sections.

For example, if Lk = 15 and Lk+1 = 11, we divide 4 lines of keyframek+1 into 2 sections each.
The remaining lines of keyframek+1 are left infact.
If the vector counts in equalized parameters V k and Vk+1 are used to denote the number of
vertices in the two consecutive frames. In this case we define
Vmax = max(Vk,Vk+1), Vmin = min( Vk,Vk+1)
Nls = (Vmax -1) mod (Vmin – 1)
Np = int ((Vmax – 1)/(Vmin – 1 ))

Preprocessing using vertex count is performed by


1. Adding Np points to Nls line section of keyframemin.
2. Adding Np-1 points to the remaining edges of keyframemin.

4. GRAPHICS PROGRAMMING USING OPENGL

OpenGL is a software interface that allows you to access the graphics hardware without
taking care of the hardware details or which graphics adapter is in the system. OpenGL is a low-
level graphics library specification. It makes available to the programmer a small set of
geometric primitives - points, lines, polygons, images, and bitmaps. OpenGL provides a set of
commands that allow the specification of geometric objects in two or three dimensions, using the
provided primitives, together with commands that control how these objects are rendered
(drawn).

Every graphics program begins with some initializations that establish the desired display
mode and set up a coordinate system for specifying points, lines etc.
Graphics commands use a coordinate system that is attached to the window,
Some elementary drawing tools used are setPixel (x,y,col) ,which sets the individual pixel at
location (x, y) to the color specified by col.
To draw a straight line the command used is line (x1, y1, x2, y2) which draws a line between
(x1, y1) and (x2, y2)

Device Independent programming and OPENGL


OPENGL offers a tool for device independent graphics programming. To build a
graphics program it is enough to install the appropriate OPENGL libraries on the new machine.

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

OPENGL is often called an Application Programming Interface (API)-a collection of routines


that the programmer can call along with a model of the routines work together to produce
graphics.
A key feature of the design of OpenGL is the separation of interaction (input and
windowing functions) from rendering.
You can always identify an OpenGL function: all OpenGL function names start with “gl”
Two utility libraries have been developed which extend the low level functionality of OpenGL
 OpenGL Utility Library or GLU
 OpenGL Utility Toolkit or GLUT

GLU provides functions for drawing more complex primitives than those of OpenGL such as
curves and surfaces and also functions to help specify 3D views of scenes. All GLU function
names start with “glu”
GLUT provides the facilities for interaction that the OpenGL lacks. It provides functions for
managing windows on the display screen and handling input events from the mouse and
keyboard. All GLUT function names start with “glut”

Include Files
For all OpenGL applications, you want to include the gl.h header file in every file. Almost all
OpenGL applications use GLU, the aforementioned OpenGL Utility Library, which also requires
inclusion of the glu.h header file. So almost every OpenGL source file begins with:
#include <GL/gl.h>
#include <GL/glu.h>

If you are using the OpenGL Utility Toolkit (GLUT) for managing your window manager
tasks, you should include:
#include <GL/glut.h>

The following files must be placed in the proper folder to run a OpenGL Program

Libraries (place in the lib\ subdirectory of Visual C++)


 [Link]
 [Link]
 [Link]

Include files (place in the include\GL\ subdirectory of Visual C++)


 gl.h
 glu.h
 glut.h

Dynamically-linked libraries (place in the \Windows\System subdirectory)


 [Link]
 [Link]
 [Link]

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

4.1. Working with OpenGL

Opening a window for Drawing


The First task in making pictures is to open a screen window for drawing.
The following five functions initialize and display the screen window in our program.

1. glutInit(&argc, argv)
The first thing we need to do is call the glutInit() procedure. It should be called before
any other GLUT routine because it initializes the GLUT library. The parameters to glutInit()
should be the same as those to main(), specifically main(int argc, char** argv) and
glutInit(&argc, argv).

2. glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
The next thing we need to do is call the glutInitDisplayMode() procedure to specify the
display mode for a window. We must first decide whether we want to use an RGBA
(GLUT_RGB) or color-index (GLUT_INDEX) color model. The RGBA mode stores its color
buffers as red, green, blue, and alpha color components. Color-index mode, in contrast, stores
color buffers in indicates. And for special effects, such as shading, lighting, and fog, RGBA
mode provides more flexibility. In general, use RGBA mode whenever possible. RGBA mode is
the default.

3. glutInitWindowSize(640,480)
A call to glutInitWindowSize() will be used to specify the size, in pixels, of our inital
window. The arguments indicate the height and width (in pixels) of the requested window.

4. glutInitWindowPosition(100,15)
A glutInitWindowPosition() is used to specify the screen location for the upper-left
corner of our initial window. The arguments, x and y, indicate the location of the window
relative to the entire display. This function positioned the screen 100 pixels over from the left
edge and 150 pixels down from the top.

5. glutCreateWindow(“Example”)
The command takes a string as a parameter which may appear in the title bar.

6. glutMainLoop()
The window is not actually displayed until the glutMainLoop() is entered. The very last
thing is we have to call this function

4.2. Event Driven Programming

The method of associating a call back function with a particular type of event is called as
event driven programming. OpenGL provides tools to assist with the event management. There
are four Glut functions available

[Link](mydisplay)
The glutDisplayFunc() procedure is the first and most important event callback function.
the function that is called whenever GLUT determines that the contents of the window needs to

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

be redisplayed. Therefore, we should put all the routines that you need to draw a scene in this
display callback function.

2. glutReshapeFunc(myreshape)
The glutReshapeFunc() is a callback function that specifies the function that is called
whenever the window is resized or moved.

3. glutKeyboardFunc(mykeyboard)
GLUT interaction using keyboard inputs is handled. The command glutKeyboardFunc()
is used to run the callback function specified and pass as parameters, the ASCII code of the
pressed key, and the x and y coordinates of the mouse cursor at the time of the event.

GLUT_KEY_UP Up Arrow
GLUT_KEY_RIGHT Right Arrow
GLUT_KEY_DOWN Down Arrow
GLUT_KEY_PAGE_UP Page Up
GLUT_KEY_PAGE_DOWN Page Down
GLUT_KEY_HOME Home
GLUT_KEY_END End
GLUT_KEY_INSERT Insert

4. glutMouseFunc(mymouse)
GLUT supports interaction with the computer mouse that is triggered when one of the
three typical buttons is presses. This buttons are defined as either GL_LEFT_BUTTON,
GL_RIGHT_BUTTON, or GL_MIDDLE_BUTTON and the states for that button are either
GLUT_DOWN (when pressed) or GLUT_UP (when released). Finally, x and y callback
parameters indicate the location (in window-relative coordinates) of the mouse at the time of the
event.

Example : Skeleton for OpenGL Code


int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(465, 250);
glutInitWindowPosition(100, 150);
glutCreateWindow("My First Example");
glutDisplayFunc(mydisplay);
glutReshapeFunc(myreshape);
glutMouseFunc(mymouse);
glutKeyboardFunc(mykeyboard);
myinit();
glutMainLoop();
return 0;
}

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

5. BASIC GRAPHICS PRIMITIVES

OPENGL provides tools for drawing all the output primitives such as points, lines,
polylines, and polygons. To draw such objects using OPENGL must pass a list of vertices. The
list occurs between the two OPENGL function calls glBegin() and glEnd().
Every time to draw a primitive on the screen first call glBegin specifying what kind of primitive
to draw in the mode parameter of glBegin and then list all the vertices one by one and finally
call glEnd to tell that drawing picture is over.

My First Attempt

The above figure shows 3 points drawn in a window 640 pixels wide and 480 pixels high

The command sequence to draw the points as shown in above figure is

glBegin(GL_POINTS);

glVertex2i(100, 50);

glVertex2i(100, 130);

glVertex2i(150, 130);

glEnd( );

To draw other primitive replace GL_POINTS with GL_LINES, GL_POLYGON etc.


The main function is function named glvertex. This function defines a point in 3D world and it
can vary from receiving 2 up to 4 coordinates. The function glvertex have several variations that
determines the number and type of arguments passed as shown below

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

Format of glVertex Command

For floating point values replace i with f.

glvertex2f(100.0f, 150.0f)-defines a point at x=100 y=150 z=0. This function takes only two
parameters z is always 0. Glvertex2f can be used in special cases and won’t be used a lot unless
you’re working pseudo 2D sprites or triangles and points that always have to be constrained by
the depth coordinate.

glvertex3f(100.0f, 150.0f,-25.0f)-defines a point x=100 y=150 z=-25. This function takes 3


parameters, defining a fully 3D point in your world. This function will be used a lot to define any
kind of shapes you will possibly want.

glvertex4f(100.0f, 150.0f,-25.0f,1.0f)-this is same as the glvertex3f, the only difference is in the


last coordinate that specifies a scaling factor. The scaling factor is set to 1.0f by default. It can be
used to make your 3D points look thicker than one pixel.

5.1. OpenGL Datatypes

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

A function to draw a dot by passing two integers


Void drawDot(Glint x, Glint y)
{
glBegin(GL_POINTS);
glVertex2i (x,y)
glEnd( );
}

//the following code plots three dots


glBegin(GL_POINTS);
glVertex2i(100, 50);
glVertex2i(100, 130);
glVertex2i(150, 130);
glEnd( );

// the following code draws a triangle


glBegin(GL_TRIANGLES);
glVertex3f(100.0f, 100.0f, 0.0f);
glVertex3f(150.0f, 100.0f, 0.0f);
glVertex3f(125.0f, 50.0f, 0.0f);
glEnd( );

// the following code draw a lines


glBegin(GL_LINES);
glVertex3f(100.0f, 100.0f, 0.0f); // origin of the line
glVertex3f(200.0f, 140.0f, 5.0f); // ending point of the line
glEnd( );

5.2. OpenGl State

OpenGl keeps track of many state variables, such as current size of a point, the current
color of a drawing, the current background color, etc.
The value of a state variable remains active until new value is given.

glPointSize() : The size of a point can be set with glPointSize(), which takes one floating point
argument
Example : glPointSize(4.0);

glClearColor() : establishes what color the window will be cleared to.


The background color is set with glClearColor(red, green, blue, alpha), where alpha specifies a
degree of transparency
Example : glClearColor (0.0, 0.0, 0.0, 0.0); //set black background color

To clear the entire window to the background color, we use glClear


(GL_COLOR_BUFFER_BIT).
The argument GL_COLOR_BUFFER_BIT is another constant built into OpenGL
Example : glClear(GL_COLOR_BUFFER_BIT)

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

glColor3f() : establishes to use for drawing objects. All objects drawn after this point use this
color, until it‟s changed with another call to set the color.
Example:
glColor3f(0.0, 0.0, 0.0); //black
glColor3f(1.0, 0.0, 0.0); //red
glColor3f(0.0, 1.0, 0.0); //green
glColor3f(1.0, 1.0, 0.0); //yellow

gluOrtho2D(): specifies the coordinate system in two dimension


void gluOrtho2D (GLdouble left, GLdouble right, GLdouble bottom,GLdouble top);
Example : gluOrtho2D(0.0, 640.0, 0.0, 480.0);

glOrtho() : specifies the coordinate system in three dimension


Example : glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);

glFlush() : ensures that the drawing commands are actually executed rather than stored in a
buffer awaiting (ie) Force all issued OpenGL commands to be executed

5.3. Establishing the coordinate system

myInit() function is used to set up the coordinate system. OPENGL routinely perfoms large
number of transformation which uses matrices.
OpenGL supports three types of geometric primitives: points, line segments, and closed
polygons.

POINTS
GL_POINTS: Each vertex defines a point
glpointsize can be used to set the size
void glPointSize (GLfloat sizeInPixels)// where size is measured in pixels with default of 1.0

LINE SEGMENTS
Three types
GL_LINES: Each successive pair of vertices specifies a line segment.
GL_LINE_STRIP: First pair of vertices specifies the first line segment. The end point of the
previous line segment and the next vertex from the next segment and so on.
GL_LINE_LOOP: Similar to GL_LINE_STRIP except that the last vertex is joined to the first
vertex to form a closed loop.

The following functions can be used to set the line’s attributes:


glLineWidth: Set the width of the line segment in pixels(default is 1.0)
void glLineWidth (GLfloat widthInPixels)

CLOSED POLYGONS
There are 6 filled polygonal primitives
GL_POLYGON: The vertices form one closed polygon.

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

GL_TRIANGLES: Each group of 3 vertices defines a triangle.


GL_TRIANGLE_STRIP: The first three vertices define the first triangle. The last two vertices
of the previous triangle plus the next vertex form the next triangle, and so on.
GL_TRIANGLE_FAN: the first three defines the first triangle. The first vertex, last vertexof
the previous triangle and the next vertex in the list form the next triangle and so on.

GL_QUADS: Each group of 4 vertices defines a quad.


GL_QUAD_STRIP: the first 4 vertices form the first quad. The last 2 vertices of the previous
quad plus the next 2 vertices from the list form the next quad, and so on.

Example : OpenGL Program to draw three dots (2-Dimension)


#include "stdafx.h"
#include "gl/glut.h"
#include <gl/gl.h>
void myInit(void)
{
glClearColor (1.0, 1.0, 1.0, 0.0);
glColor3f (0.0, 0.0, 0.0);
glPointSize(4.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
void Display(void)
{
glClear (GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
glVertex2i(100, 50);
glVertex2i(100, 130);
glVertex2i(150, 130);
glEnd( ); glFlush();
}
int main (int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(640,480);
glutInitWindowPosition(100,150);
glutCreateWindow("Example");
glutDisplayFunc(Display);
myInit();
glutMainLoop();
return 0;
}

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

Example : White Rectangle on a Black Background (3-Dimension co-ordinates)


#include "stdafx.h"
#include "gl/glut.h"
#include <gl/gl.h>
void Display(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
glBegin(GL_POLYGON);
glVertex3f (0.25, 0.25, 0.0);
glVertex3f (0.75, 0.25, 0.0);
glVertex3f (0.75, 0.75, 0.0);
glVertex3f (0.25, 0.75, 0.0);
glEnd();
glFlush();
}
int main (int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(640,480);
glutCreateWindow("Intro");
glClearColor(0.0,0.0,0.0,0.0);
glutDisplayFunc(Display);
glutMainLoop();
return 0;
}

5.4. Making Line Drawings


OpenGL makes it easy to draw a line: use GL_LINES as the argument to glBegin(), and pass it
the two end points as vertices.
Thus to draw a line between (40,100) and (202,96) use:

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

glBegin(GL_LINES); // use constant GL_LINES here


glVertex2i(40, 100);
glVertex2i(202, 96);
glEnd();

 To draw thicker lines use glLineWidth(4.0). The default thickness is 1.0


 To make stippled (dotted or dashed) lines, you use the command glLineStipple() to define
the stipple pattern, and then we enable line stippling with glEnable()
glLineStipple(1, 0x3F07);
glEnable(GL_LINE_STIPPLE);

5.5. Drawing Polylines and Polygons


Polyline is a collection of line segments joined end to end. It is described by an ordered list of
points,

P0=(X0,Y0), P1=(X1,Y1), ……….. Pn=(Xn,Yn)

In OpenGL a polyline is called a “line strip”, and is drawn by specifying the vertices in turn
between glBegin(GL_LINE_STRIP) and glEnd().
For example, the code:

glBegin(GL_LINE_STRIP); // draw an open polyline


(or)
glBegin(GL_LINE_LOOP); // draw an polygon
glVertex2i(20,10);
glVertex2i(50,10);
glVertex2i(20,80);
glVertex2i(50,80);
glEnd();
glFlush();

5.6. Drawing Aligned Rectangles


A special case of a polygon is the aligned rectangle, so called because its sides are aligned with
the coordinate axes.
OpenGL provides the ready-made function:
glRecti(GLint x1, GLint y1, GLint x2, GLint y2);

// draw a rectangle with opposite corners (x1, y1) and (x2, y2);
// fill it with the current color;
glClearColor(1.0,1.0,1.0,0.0); // white background
glClear(GL_COLOR_BUFFER_BIT); // clear the window
glColor3f(0.6,0.6,0.6); // bright gray
glRecti(20,20,100,70);
glColor3f(0.2,0.2,0.2); // dark gray
glRecti(70, 50, 150, 130);
aspect ratio = width/height;

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

5.7. Polygons
Polygons are the areas enclosed by single closed loops of line segments, where the line
segments are specified by the vertices at their endpoints. Polygons are typically drawn by filling
in all the pixels enclosed within the boundary, but you can also draw them as outlined polygons
or simply as points at the vertices. A filled polygon might be solidly filled, or stippled with a
certain pattern.
OpenGL also supports filling more general polygons with a pattern or color. To draw a
convex polygon based on vertices (x0, y0), (x1, y1), …, (xn, yn) use the usual list of vertices,
But place them between a glBegin(GL_POLYGON) and an glEnd():

glBegin(GL_POLYGON);
glVertex2f(x0, y0);
glVertex2f(x1, y1);
. . . . ..
glVertex2f(xn, yn);
glEnd();

The following list explains the function of each of the five constants:

GL_TRIANGLES: takes the listed vertices three at a time, and draws a separate triangle for
each;

GL_QUADS: takes the vertices four at a time and draws a separate quadrilateral for each

GL_TRIANGLE_STRIP: draws a series of triangles based on triplets of vertices: v0, v1, v2,
then v2, v1, v3, then v2, v3, v4, etc. (in an order so that all triangles are “traversed” in the same
way;e.g. counterclockwise).

GL_TRIANGLE_FAN: draws a series of connected triangles based on triplets of vertices: v0,


v1, v2, then v0, v2, v3, then v0, v3, v4, etc.

GL_QUAD_STRIP: draws a series of quadrilaterals based on foursomes of vertices: first v0,


v1, v3, v2, then v2, v3, v5, v4, then v4, v5, v7, v6 (in an order so that all quadrilaterals are
“traversed” in the same way; e.g. counterclockwise).

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

5.8. Simple Interaction with the mouse and keyboard


When the user presses or releases a mouse button, moves the mouse, or presses a
keyboard key, an event occur. Using the OpenGL Utility Toolkit (GLUT) the programmer can
register a callback function with each of these events by using the following commands:

glutMouseFunc(myMouse) which registers myMouse() with the event that occurs when the
mouse button is pressed or released;
glutMotionFunc(myMovedMouse) which registers myMovedMouse() with the event that
occurs when the mouse is moved while one of the buttons is pressed;
glutKeyboardFunc(myKeyboard) which registers myKeyBoard() with the event that occurs
when a keyboard key is pressed.

Mouse interaction

void myMouse(int button, int state, int x, int y);


When a mouse event occurs the system calls the registered function, supplying it with
values for these parameters. The value of button will be one of:
GLUT_LEFT_BUTTON
GLUT_MIDDLE_BUTTON
GLUT_RIGHT_BUTTON,

with the obvious interpretation, and the value of state will be one of: GLUT_UP or
GLUT_DOWN. The values x and y report the position of the mouse at the time of the event.

Keyboard interaction
As mentioned earlier, pressing a key on the keyboard queues a keyboard event. The
callback function myKeyboard() is registered with this type of event through
glutKeyboardFunc(myKeyboard).
It must have prototype: void myKeyboard(unsigned int key, int x, int y);

The value of key is the ASCII value12 of the key pressed. The values x and y report the
position of the mouse at the time that the event occurred. (As before y measures the number of
pixels down from the top of the window.)

6. DRAWING THREE DIMENSIONAL OBJECTS

GLUT provides several 3D objects: a sphere, a cone, a torus, the five platonic solids and the
teapot.
Each is available as a wireframe model and as a solid model with faces that can be shaded.
All are drawn by default centered at the origin.
To use the solid version replace wire by solid in the functions.

 Cube: glutWireCube (GLdouble size);


Each side is of length size

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

 Sphere: glutWireSphere (GLdouble radius,Glint nslices, Glint nstacks);


nslices is the number of “orange sections” and nstacks is the numbe of disks.
Alternately nslices boundaries are longitude lines and nstacks boundaries are latitude lines.

 Torus: glutWireTorus (GLdouble inRad, GLdouble outRad, Glint nslices, Glint nstacks);

 Teapot: glutWireteapot (GLdouble size);

 Tetrahedron: glutWireTetrahedron();

 Octahedron: glutWireOctahedron();

 Dodecahedron: glutWireDodecahedron();

 Icosahedron: glutWireIsosahedron();

 Cone: glutWireCone(GLdouble baseRad, GLdouble height, Glint nslices, Glint nStacks);

 Tapered Cylinder: gluCylinder (GLUquadricObj *qobj, GLdouble baseRad, GLdouble


topRad, GLdouble height, Glint nslices, Glint nstacks);

7. 3D TRANSFORMATION IN OPENGL

glTranslate () : multiply the current matrix by a translation matrix

glTranslated(GLdouble x, GLdouble y, GLdouble z);


void glTranslatef(GLfloat x, GLfloat y, GLfloat z);

x, y, z - Specify the x, y, and z coordinates of a translation vector.


If the matrix mode is either GL_MODELVIEW or GL_PROJECTION, all objects drawn after a
call to glTranslate are translated. Use glPushMatrix and glPopMatrix to save and restore the
untranslated coordinate system.

glRotate() : multiply the current matrix by a rotation matrix

void glRotated(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);


void glRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);

angle : Specifies the angle of rotation, in degrees.


x, y, z : Specify the x, y, and z coordinates of a vector, respectively.

glScale() : multiply the current matrix by a general scaling matrix

voidglScaled(GLdouble x, GLdouble y, GLdouble z);


void glScalef(GLfloat x, GLfloat y, GLfloat z); x, y, z :
Specify scale factors along the x, y, and z axes, respectively.

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

8. DRAWING THREE DIMENSIONAL SCENES

 The main purpose of transforming objects using 3D is to orient and position them as
desired in 3D scenes.

 All the work is done with matrices.

 OpenGL provide the necessary function to build the required matrices.

 The matrix structure maintained by openGL makes it easy to set up a transformation for
one object and then “back up” to a previous transformation.

 It is easy to build a program that draws different scenes using a collection of 3D


transformation

 It improves the ability to visualize.

Fig: OpenGL pipeline

OpenGL has separate transformation matrices for different graphics features

glMatrixMode(GLenum mode), where mode is one of:


GL_MODELVIEW - for manipulating model in scene
GL_PROJECTION - perspective orientation
GL_TEXTURE - texture map orientation

glLoadIdentity() : loads a 4-by-4 identity matrix into the current matrix


glPushMatrix() : push current matrix stack
glPopMatrix() : pop the current matrix stack
glMultMatrix () : multiply the current matrix with the specified matrix
glViewport() : set the viewport
Example : glViewport(0, 0, width, height);
gluPerspective() : function sets up a perspective projection matrix.
Format : gluPerspective(angle, asratio, ZMIN, ZMAX);
Example : gluPerspective(60.0, width/height, 0.1, 100.0);
gluLookAt() : view volume that is centered on a specified eyepoint
Example : gluLookAt(3.0, 2.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glutSwapBuffers () : glutSwapBuffers swaps the buffers of the current window if double
buffered.

CS2401 – COMPUTER GRAPHICS


UNIT – III GRAPHICS PROGRAMMING

Three Matrices

1. The Modelview Matrix


Basically provides CT. It combines two effects:
 The sequence of modeling transformations applied to objects.
 Transformation that orients and positions the camera in space.
Although it is a single matrix in the actual pipeline, it is easier to think of it as the product of two
matrices.
– a modeling matrix M
- a viewing matrix V
The modeling matrix is applied first and then the viewing matrix, so modelview matrix is in fact
the product VM.

2. The Projection Matrix


The projection matrix scales and translates each vertex in a particular way, so that all
those that lie inside the view volume will lie inside a standard cube that extends from -1 to 1 in
each dimension. This matrix effectively squashes the view volume into the cube centered at the
origin.

3. The Viweport Matrix


This matrix maps the surviving portion of the block into a 3D viewport. This matrix maps
the standard cube into a block shape whose x- and y- values extend across the viewport and
whose z- component extends from 0 to 1 and retains a measure of the depth of each point.

CS2401 – COMPUTER GRAPHICS

You might also like