Mod 1
Mod 1
1 OpenGL
If you create an act, you create a habit. If you create a habit, you create a character. If you
create a character, you create a destiny.
Reputation is what men and women think of us. Character is what God and the angels know of
us.
✔ An early application for computer graphics is the display of simple data graphs usually
plotted on a character printer. Data plotting is still one of the most common graphics
application.
✔ Graphs & charts are commonly used to summarize functional, statistical, mathematical,
engineering and economic data for research reports, managerial summaries and other
types of publications.
✔ Typically examples of data plots are line graphs, bar charts, pie charts, surface graphs,
contour plots and other displays showing relationships between multiple parameters in
two dimensions, three dimensions, or higher-dimensional spaces
b. Computer-Aided Design
✔ CAD, computer-aided design or CADD, computer-aided drafting and design methods are
now routinely used in the automobiles, aircraft, spacecraft, computers, home appliances.
✔ Circuits and networks for communications, water supply or other utilities are
✔ Animations are often used in CAD applications. Real-time, computer animations using
wire-frame shapes are useful for quickly testing the performance of a vehicle or
system.
c. Virtual-Reality Environments
✔ With virtual-reality systems, designers and others can move about and interact with
✔ With a special glove, we can even “grasp” objects in a scene and turn them over or move
✔ Producing graphical representations for scientific, engineering and medical data sets and
Module Computer Graphics and
1 processes is another fairly new application of computer OpenGL
graphics, which is generally
referred to as scientific visualization. And the term business visualization is used in
connection with data sets related to commerce, industry and other nonscientific areas.
Module Computer Graphics and
1 OpenGL
✔ There are many different kinds of data sets and effective visualization schemes depend on
the characteristics of the data. A collection of data can contain scalar values, vectors or
higher-order tensors.
diagram as shown in the figure, can help trainees to understand the operation of a system.
specialized systems are the simulators for practice sessions ,aircraft pilots,air traffic-
control personnel.
✔ Some simulators have no video screens,for eg: flight simulator with only a control panel
✔ The picture is usually painted electronically on a graphics tablet using a stylus, which can
✔ Fine artists use a variety of other computer technologies to produce images. To create
✔ Commercial art also uses theses “painting” techniques for generating logos & other
designs, page layouts combining text & graphics, TV advertising spots & other
applications.
g. Entertainment
graphics methods.
✔ Sometimes graphics images are combined a live actors and scenes and sometimes
the films are completely generated a computer rendering and animation techniques.
Module Computer Graphics and
1 OpenGL
✔ Some television programs also use animation techniques to combine computer generated
figures of people, animals, or cartoon characters with the actor in a scene or to transform
an actor’s face into another shape.
h. Image Processing
✔ Methods used in computer graphics and image processing overlap, the two areas
✔ Image processing methods are used to improve picture quality, analyze images,
✔ Image processing methods are often used in computer graphics, and computer graphics
✔ Medical applications also make extensive use of image processing techniques for picture
✔ It is common now for applications software to provide graphical user interface (GUI).
Module Computer Graphics and
1 OpenGL
✔ A major component of graphical interface is a window manager that allows a user to
✔ Each screen display area can contain a different process, showing graphical or non-
graphical information, and various methods can be used to activate a display window.
✔ Using an interactive pointing device, such as mouse, we can active a display window on
some systems by positioning the screen cursor within the window display area and
pressing the left mouse button.
✔ Historically, the operation of most video monitors was based on the standard
✔ In recent years, flat-panel displays have become significantly more popular due to
✔ A beam of electrons, emitted by an electron gun, passes through focusing and deflection
systems that direct the beam toward specified positions on the phosphor-coated screen.
✔ The phosphor then emits a small spot of light at each position contacted by the electron
beam and the light emitted by the phosphor fades very rapidly.
✔ One way to maintain the screen picture is to store the picture information as a charge
✔ The most common method now employed for maintaining phosphor glow is to redraw
the picture repeatedly by quickly directing the electron beam back over the same screen
points. This type of display is called a refresh CRT.
✔ The frequency at which a picture is redrawn on the screen is referred to as the refresh
rate.
✔ The primary components of an electron gun in a CRT are the heated metal cathode and
a control grid.
✔ The heat is supplied to the cathode by directing a current through a coil of wire, called
✔ Inside the CRT envelope, the free, negatively charged electrons are then
✔ Intensity of the electron beam is controlled by the voltage at the control grid.
✔ Since the amount of light emitted by the phosphor coating depends on the number of
electrons striking the screen, the brightness of a display point is controlled by varying the
voltage on the control grid.
✔ The focusing system in a CRT forces the electron beam to converge to a small cross
section as it strikes the phosphor and it is accomplished with either electric or magnetic
fields.
✔ With electrostatic focusing, the electron beam is passed through a positively charged
metal cylinder so that electrons along the center line of the cylinder are in equilibrium
position.
✔ Deflection of the electron beam can be controlled with either electric or magnetic fields.
✔ Cathode-ray tubes are commonly constructed with two pairs of magnetic-deflection coils
✔ One pair is mounted on the top and bottom of the CRT neck, and the other pair is
✔ The magnetic field produced by each pair of coils results in a traverse deflection force
that is perpendicular to both the direction of the magnetic field and the direction of travel
of the electron beam.
✔ Horizontal and vertical deflections are accomplished with these pair of coils
✔ When electrostatic deflection is used, two pairs of parallel plates are mounted inside the
CRT envelope where, one pair of plates is mounted horizontally to control vertical
deflection, and the other pair is mounted vertically to control horizontal deflection.
✔ Spots of light are produced on the screen by the transfer of the CRT beam energy to the
phosphor.
✔ When the electrons in the beam collide with the phosphor coating, they are stopped and
Module Computer Graphics and
1 their kinetic energy is absorbed by the phosphor. OpenGL
✔ Part of the beam energy is converted by the friction in to the heat energy, and the
✔ After a short time, the “excited” phosphor electrons begin dropping back to their stable
ground state, giving up their extra energy as small quantum of light energy called
photons.
✔ What we see on the screen is the combined effect of all the electrons light emissions: a
glowing spot that quickly fades after all the excited phosphor electrons have returned to
their ground energy level.
✔ The frequency of the light emitted by the phosphor is proportional to the energy
difference between the excited quantum state and the ground state.
✔ Lower persistence phosphors required higher refresh rates to maintain a picture on the
✔ The maximum number of points that can be displayed without overlap on a CRT is
referred to as a resolution.
❖ The electron beam is swept across the screen one row at a time from top to bottom.
❖ As it moves across each row, the beam intensity is turned on and off to create a pattern
of illuminated spots.
❖ The refreshing rate, called the frame rate, is normally 60 to 80 frames per second,
or described as 60 Hz to 80 Hz.
❖ This frame buffer stores the intensity values for all the screen points. Each screen point
❖ Property of raster scan is Aspect ratio, which defined as number of pixel columns
✔ On black and white systems, the frame buffer storing the values of the pixels is called
a bitmap.
Module Computer Graphics and
1 OpenGL
✔ Each entry in the bitmap is a 1-bit data which determine the on (1) and off (0) of
❖ On color systems, the frame buffer storing the values of the pixels is called a pixmap
❖ Each entry in the pixmap occupies a number of bits to represent the color of the pixel. For
a true color display, the number of bits for each entry is 24 (8 bits per red/green/blue
channel, each channel 28=256 levels of intensity value, ie. 256 voltage settings for each
of the red/green/blue electron guns).
✔ When operated as a random-scan display unit, a CRT has the electron beam directed
✔ Pictures are generated as line drawings, with the electron beam tracing out the
✔ For this reason, random-scan monitors are also referred to as vector displays (or
✔ The component lines of a picture can be drawn and refreshed by a random-scan system
on that system.
memory referred to as the display list, refresh display file, vector file, or display
program
✔ To display a specified picture, the system cycles through the set of commands in
✔ After all line-drawing commands have been processed, the system cycles back to the
✔ Random-scan displays are designed to draw all the component lines of a picture 30 to
60 times each second, with up to 100,000 “short” lines in the display list.
✔ When a small set of lines is to be displayed, each refresh cycle is delayed to avoid
very high refresh rates, which could burn out the phosphor.
✵
Module Computer Graphics and
1 OpenGL
Module Computer Graphics and
1 OpenGL
Raster-Scan Systems
🡺 In addition to the central processing unit (CPU), a special-purpose processor, called the
video controller or display controller, is used to control the operation of the display
device.
🡺 Here, the frame buffer can be anywhere in the system memory, and the video controller
Video controller:
✔ The figure below shows a commonly used organization for raster systems.
✔ A fixed area of the system memory is reserved for the frame buffer, and the
Cartesian coordinates.
package to set coordinate positions for displayed objects relative to the origin of the
✔ The coordinate origin is referenced at the lower-left corner of a screen display area by the
software commands, although we can typically set the origin at any convenient location
for a particular application.
Module Computer Graphics and
1 OpenGL
Working:
✔ Figure shows a two-dimensional Cartesian reference frame with the origin at the
✔ The screen surface is then represented as the first quadrant of a two-dimensional system
with positive x and y values increasing from left to right and bottom of the screen to the
top respectively.
✔ Pixel positions are then assigned integer x values that range from 0 to xmax across the
screen, left to right, and integer y values that vary from 0 to ymax, bottom to top.
✔ Initially, the x register is set to 0 and the y register is set to the value for the top scan line.
✔ The contents of the frame buffer at this pixel position are then retrieved and used to set
✔ Then the x register is incremented by 1, and the process is repeated for the next pixel on
✔ This procedure continues for each pixel along the top scan line.
✔ After the last pixel on the top scan line has been processed, the x register is reset to 0 and
the y register is set to the value for the next scan line down from the top of the screen.
✔ After cycling through all pixels along the bottom scan line, the video controller resets the
registers to the first pixel position on the top scan line and the refresh process starts over
a.Speed up pixel position processing of video controller:
✔ Since the screen must be refreshed at a rate of at least 60 frames per second,the simple
procedure illustrated in above figure may not be accommodated by RAM chips if the
cycle time is too slow.
✔ To speed up pixel processing, video controllers can retrieve multiple pixel values from
✔ When group of pixels has been processed, the next block of pixel values is retrieved from
✔ For various applications, the video controller can retrieve pixel values from
✔ In addition, the video controller often contains a lookup table, so that pixel values in the
frame buffer are used to access the lookup table. This provides a fast method for changing
screen intensity values.
Module Computer Graphics and
1 OpenGL
✔ Finally, some systems are designed to allow the video controller to mix the framebuffer
image with an input image from a television camera or other input device
✔ Figure shows one way to organize the components of a raster system that contains a
✔ The purpose of the display processor is to free the CPU from the graphics chores.
provided.
Scan conversion:
application program into a set of pixel values for storage in the frame buffer.
🡺 Graphics commands specifying straight lines and other geometric objects are scan
Module Computer Graphics and
1 converted into a set of discrete points, corresponding to screen pixel positions.
OpenGL
🡺 The array size for character grids can vary from about 5 by 7 to 9 by 12 or more for
higher-quality displays.
🡺 A character grid is displayed by superimposing the rectangular grid pattern into the frame
Using outline:
🡺 For characters that are defined as outlines, the shapes are scan-converted into the frame
🡺 These functions include generating various line styles (dashed, dotted, or solid),
🡺 Display processors are typically designed to interface with interactive input devices, such
as a mouse.
🡺 In an effort to reduce memory requirements in raster systems, methods have been devised
Module Computer Graphics and
1 for organizing the frame buffer as a linked list and encodingOpenGL
the color information.
🡺 One organization scheme is to store each scan line as a set of number pairs.
Module Computer Graphics and
1 OpenGL
🡺 Encoding methods can be useful in the digital storage and transmission of picture
information
i) Run-length encoding:
✵ The first number in each pair can be a reference to a color value, and the second
numbercanspecify the number of adjacent pixels on the scan line that are to be displayed in
that color.
✵Thistechnique,calledrun-lengthencoding,canresultinaconsiderablesaving in storagespace if
apictureistobeconstructedmostlywithlongrunsofasinglecoloreach.
✵Anotherapproachistoencodetherasterasasetofrectangularareas(cellencoding).
Disadvantages of encoding:
❖ The disadvantages of encoding runs are that color changes are difficult to record
❖ In addition, it is difficult for the display controller to process the raster when many
❖ Moreover, the size of the frame buffer is no longer a major concern, because of
✔ Most graphics monitors today operate as raster-scan displays, and both CRT and flat
specialized features.
Module Computer Graphics and
1 OpenGL
✔ Multi-panel display screens are used in a variety of applications that require “wall-sized”
viewing areas. These systems are designed for presenting graphics displays at meetings,
conferences, conventions, trade shows, retail stores etc.
✔ A multi-panel display can be used to show a large view of a single scene or several
individual images. Each panel in the system displays one section of the overall picture
✔ A large, curved-screen system can be useful for viewing by a group of people studying a
✔ A 360 degree paneled viewing system in the NASA control-tower simulator, which is
used for training and for testing ways to solve air-traffic and runway problems at airports.
Graphics Software
Coordinate Representations
✔ If coordinate values for a picture are given in some other reference frame
✔ Several different Cartesian reference frames are used in the process of constructing
and displaying
✔ First we define the shapes of individual objects, such as trees or furniture, These
✔ Then we place the objects into appropriate locations within a scene reference
✔ After all parts of a scene have been specified, it is processed through various output-
device reference frames for display. This process is called the viewing pipeline.
✔
The scene is then stored in normalized coordinates. Which range from 1 to 1 or from 0 to 1 Normalized c
Module Computer Graphics and
1 OpenGL
✔ The coordinate systems for display devices are generally called device coordinates, or
screen coordinates.
NOTE: Geometric descriptions in modeling coordinates and world coordinates can be given in
Module Computer Graphics and
1 OpenGL
floating-point or integer values.
Graphics Functions
🡺 It provides users with a variety of functions for creating and manipulating pictures
🡺 The basic building blocks for pictures are referred to as graphics output primitives
transformations
🡺 Viewing transformations are used to select a view of the scene, the type of projection to
🡺 Input functions are used to control and process the data flow from these interactive
🡺 Graphics package contains a number of tasks .We can lump the functions for carrying out
✔ In 1984, Graphical Kernel System (GKS) was adopted as the first graphics
✔ The graphics workstations from Silicon Graphics, Inc. (SGI), came with a set of
Introduction To OpenGL
✔ OpenGL basic(core) library :-A basic library of functions is provided in OpenGL for
🡺 Function names in the OpenGL basic library (also called the OpenGL core library) are
GL_POLYGON, GL_AMBIENT_AND_DIFFUSE.
Module Computer Graphics and
1 OpenGL
🡺 The OpenGL functions also expect specific data types. For example, an OpenGL function
parameter might expect a value that is specified as a 32-bit integer. But the size of an
integer specification can be different on different machines.
🡺 To indicate a specific data type, OpenGL uses special built-in, data-type names, such as
Related Libraries
Header Files
✔ In all graphics programs, we will need to include the header file for the OpenGL
core library.
Module Computer Graphics and
1 OpenGL
✔ In windows to include OpenGL core libraries and GLU we can use the following
header files:-
#include <windows.h> //precedes other header files for including Microsoft windows ver
of OpenGL libraries
#include<GL/gl.h>
#include <GL/glu.h>
✔ The above lines can be replaced by using GLUT header file which ensures gl.h and
✔ #include <GLUT/glut.h>
a picture.
Step 1: initialization of GLUT
✵ WeareusingtheOpenGLUtilityToolkit,ourfirststepistoinitializeGLUT.
✵Thisinitializationfunctioncouldalsoprocessanycommandlinearguments, butwe
display-window title.
Module Computer Graphics and
1 Step 3: Specification of the display window OpenGL
GLUT routine glutDisplayFunc, which assigns our picture to the display window.
Module Computer Graphics and
1 OpenGL
calledlineSegment.
✵ Then the following function call passes theline-segment descriptionto hte dsipalywindow:
glutDisplayFunc (lineSegment);
Step 4: one more GLUT function
✵ WeneedonemoreGLUTfunctiontocompletethewindow-processingoperations.
✵ After execution of the following statement, all display windows that we have creaetd,including their
program into an infinite loop that checks for input from devices such as a mouse or
keyboard.
Step 5: these parameters using additional GLUT functions
🡺 We use the glutInitWindowPosition function to give an initial location for the upper left
🡺 This position is specified in integer screen coordinates, whose origin is at the upper-left
🡺 We can also set a number of other options for the display window, such as buffering and a
🡺 Example: the following command specifies that a single refresh buffer is to be used for the
display window and that we want to use the color mode which uses red, green, and blue
(RGB) components to select color values:
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
🡺 The values of the constants passed to this function are combined using a logical or
operation.
🡺 Actually, single buffering and RGB color mode are the default options.
🡺 But we will use the function now as a reminder that these are the options that are set for
our display.
🡺 Later, we discuss color modes in more detail, as well as other display options, such as
double buffering for animation applications and selecting parameters for viewing
threedimensional scenes.
🡺 There are still a few more tasks to perform before we have all the parts that we need for a
complete program.
Step 1: to set background color
🡺 Using RGB color values, we set the background color for the display window to be
the value 1.0, giving us a white background color for the display window.
🡺 If, instead of 1.0, we set each of the component colors to 0.0, we would get a black
background.
Module Computer Graphics and
1 OpenGL
🡺 The fourth parameter in the glClearColor function is called the alpha value for the
specified color. One use for the alpha value is as a “blending” parameter
🡺 When we activate the OpenGL blending operations, alpha values can be used to
🡺 An alpha value of 0.0 indicates a totally transparent object, and an alpha value of 1.0
🡺 Although the glClearColor command assigns a color to the display window, it does not
🡺 To get the assigned window color displayed, we need to invoke the following OpenGL
function:
glClear (GL_COLOR_BUFFER_BIT);
🡺 The argument GL COLOR BUFFER BIT is an OpenGL symbolic constant specifying that
it is the bit values in the color buffer (refresh buffer) that are to be set to the values
indicated in the glClearColor function. (OpenGL has several different kinds of buffers
that can be manipulated.
🡺 In addition to setting the background color for the display window, we can choose a
🡺 For our initial programming example, we will simply set the object color to be a dark
green
glColor3f (0.0, 0.4, 0.2);
🡺 The suffix 3f on the glColor function indicates that we are specifying the three RGB
🡺 To do this, we need to tell OpenGL how we want to “project” our picture onto the display
🡺 So, although we only want to produce a very simple two-dimensional line, OpenGL
🡺 We can set the projection type (mode) and other viewing parameters that we need with the
twodimensional rectangular area of world coordinates to the screen, and that the x-
coordinate values within this rectangle range from 0.0 to 200.0 with y-coordinate values
ranging from 0.0 to 150.0.
🡺 Whatever objects we define within this world-coordinate rectangle will be shown within
🡺 Therefore, the GLU function gluOrtho2D defines the coordinate reference frame within the
display window to be (0.0, 0.0) at the lower-left corner of the display window and (200.0,
150.0) at the upper-right window corner.
🡺 For now, we will use a world-coordinate rectangle with the same aspect ratio as the display
🡺 Finally, we need to call the appropriate OpenGL routines to create our line segment.
🡺 init: We place all initializations and related one-time parameter settings in function init.
function lineSegment, which is the function that will be referenced by the GLUT function
glutDisplayFunc.
🡺 main function main function contains the GLUT functions for setting up the display
🡺 glFlush: This is simply a routine to force execution of our OpenGL functions, which are
🡺 The procedure lineSegment that we set up to describe our picture is referred to as a display
callback function.
✵Example:Wedefineastraight-linesegmentwithtwoendpointpositions,and a polygonis
✵Thesecoordinatepositionsarestoredinthescenedescriptionalongwithother nifoabouthe
each object.
✵Ex:Fora2Dfigure,thecoordinateextentsaresometimescalleditsboundingrectangle.
Module Computer Graphics and
1 OpenGL
✵Objectsarethendisplayedbypassingthescenedescriptiontotheviewingroutines
locations in the frame buffer, and then the scene is displayed on the output device.
Screen co-ordinates:
✔ Scan-line algorithms for the graphics primitives use the coordinate descriptions to
✔ Example: given the endpoint coordinates for a line segment, a display algorithm must
calculate the positions for those pixels that lie along the line path between the
endpoints.
✔ Since a pixel position occupies a finite area of the screen, the finite size of a pixel
✔ For the present, we assume that each integer screen position references the centre of
a pixel area.
✔ Once pixel positions have been identified the color values must be stored in the
frame buffer
● stores the current color setting into the frame buffer at integer position(x, y), relative
to the position of the screen-coordinate origin
ii) getPixel (x, y, color);
● Parameter color receives an integer value corresponding to the combined RGB bit
codes stored for the specified pixel at position (x,y).
⮚ So far, the coordinate references that we have discussed are stated as absolute coordinate
values.
⮚ This means that the values specified are the actual positions within the coordinate system
in use.
Relative coordinates:
⮚ However, some graphics packages also allow positions to be specified using relative
coordinates.
⮚ This method is useful for various graphics applications, such as producing drawings with
pen plotters, artist’s drawing and painting systems, and graphics packages for publishing
and printing applications.
⮚ Taking this approach, we can specify a coordinate position as an offset from the last
reference frames.
⮚ The arguments for this function are the four values defining the x and y coordinate
sure that the coordinate values are placed in the OpenGL projection matrix.
⮚ In addition, we could assign the identity matrix as the projection matrix before
⮚ This would ensure that the coordinate values were not accumulated with any values
⮚ Thus, for our initial two-dimensional examples, we can define the coordinate frame for
Module Computer Graphics and
1 the screen display window with the following statements OpenGL
glMatrixMode
(GL_PROJECTION);
glLoadIdentity ( );
gluOrtho2D (xmin, xmax, ymin, ymax);
Module Computer Graphics and
1 OpenGL
⮚ The display window will then be referenced by coordinates (xmin, ymin) at the lower-left
corner and by coordinates (xmax, ymax) at the upper-right corner, as shown in Figure
below
⮚ We can then designate one or more graphics primitives for display using the coordinate
⮚ If the coordinate extents of a primitive are within the coordinate range of the display
⮚ Otherwise, only those parts of the primitive within the display-window coordinate limits
will be shown.
⮚ Also, when we set up the geometry describing a picture, all positions for the OpenGL
primitives must be given in absolute coordinates, with respect to the reference frame
defined in the gluOrtho2D function.
OpenGL Functions
Geometric Primitives:
⮚ These primitives pass through geometric pipeline which decides whether the primitive is
visible or not and also how the primitive should be visible on the screen etc.
Module Computer Graphics and
⮚ The geometric transformations such rotation, scaling etc can be applied on the primitives
1 OpenGL
which are displayed on the screen.The programmer can create geometric primitives as
shown below:
Module Computer Graphics and
1 OpenGL
where:
⮚ The type within glBegin() specifies the type of the object and its value can be as follows:
GL_POINTS
⮚ Then this coordinate position, along with other geometric descriptions we may have
⮚ Unless we specify other attribute values, OpenGL primitives are displayed with a
⮚ The default color for primitives is white, and the default point size is equal to the size of
⮚ we could specify the coordinate values for the preceding points in arrays such
⮚ specifying two point positions in a three dimensional world reference frame. In this
⮚ Successive pairs of vertices are considered as endpoints and they are connected to
⮚ Note that successive segments usually are disconnected because the vertices
⮚ we obtain one line segment between the first and second coordinate positions and
Module Computer Graphics and
1 another line segment between the third and fourth positions.OpenGL
⮚ if the number of specified endpoints is odd, so the last coordinate position is ignored.
Module Computer Graphics and
1 OpenGL
Case 1: Lines
glBegin (GL_LINES);
glVertex2iv
(p1);
glVertex2iv
(p2);
glVertex2iv
(p3);
glVertex2iv
(p4);
glVertex2iv
(p5);
glEnd ( );
Case 2: GL_LINE_STRIP:
Successive vertices are connected using line segments. However, the final vertex is not
connected to the initial vertex.
glBegin
(GL_LINES_STRIP);
glVertex2iv (p1);
glVertex2iv (p2);
glVertex2iv (p3);
glVertex2iv (p4);
glVertex2iv (p5);
glEnd ( );
Case 3: GL_LINE_LOOP:
Successive vertices are connected using line segments to form a closed path or loop i.e., final
vertex is connected to the initial vertex.
glBegin
(GL_LINES_LOOP);
glVertex2iv (p1);
glVertex2iv (p2);
Module Computer Graphics and
1 glVertex2iv (p3); OpenGL
glVertex2iv (p4);
glVertex2iv (p5);
glEnd ( );
Module Computer Graphics and
1 OpenGL
Point Attributes
🡺 Basically, we can set two attributes for points: color and size.
🡺 In a state system: The displayed color and size of a point is determined by the current
🡺 Color components are set with RGB values or an index into a color table.
🡺 For a raster system: Point size is an integer multiple of the pixel size, so that a large point
🡺 The displayed color of a designated point position is controlled by the current color
🡺 Also, a color is specified with either the glColor function or the glIndex function.
Size:
glPointSize (size);
and the point is then displayed as a square block of pixels.
🡺 The number of horizontal and vertical pixels in the display of the point is determined by
parameter size.
🡺 Thus, a point size of 1.0 displays a single pixel, and a point size of 2.0 displays a 2×2
pixel array.
🡺 If we activate the antialiasing features of OpenGL, the size of a displayed block of pixels
Example program:
🡺 Example: the following code segment plots three points in varying colors and sizes.
Module Computer Graphics and
1 OpenGL
🡺 The first is a standard-size red point, the second is a double-size green point, and the third
Ex:
glColor3f (1.0, 0.0, 0.0);
glBegin (GL_POINTS);
glVertex2i (50, 100);
glPointSize (2.0);
glColor3f (0.0, 1.0, 0.0);
glVertex2i (75, 150);
glPointSize (3.0);
glColor3f (0.0, 0.0, 1.0);
glVertex2i (100, 200);
glEnd ( );
🡺 In OpenGL straight-line segment with three attribute settings: line color, line-width, and
line style.
🡺 OpenGL provides a function for setting the width of a line and another function for
specifying a line style, such as a dashed or dotted line.
🡺 We assign a floating-point value to parameter width, and this value is rounded to the
🡺 If the input value rounds to 0.0, the line is displayed with a standard width of 1.0, which
widths, and some might not support widths other than 1.0.
Module Computer Graphics and
1 OpenGL
🡺 That is, the magnitude of the horizontal and vertical separations of the line endpoints,
deltax and deltay, are compared to determine whether to generate a thick line using
vertical pixel spans or horizontal pixel spans.
🡺 But we can also display dashed lines, dotted lines, or a line with a combination of dashes
and dots.
🡺 We can vary the length of the dashes and the spacing between dashes or dots.
🡺 We set a current display style for lines with the OpenGL function:
Pattern:
🡺 Parameter pattern is used to reference a 16-bit integer that describes how the line should
be displayed.
🡺 1 bit in the pattern denotes an “on” pixel position, and a 0 bit indicates an “off” pixel
position.
🡺 The pattern is applied to the pixels along the line path starting with the low-order bits in
the pattern.
🡺 The default pattern is 0xFFFF (each bit position has a value of 1),which produces a solid
line.
repeatFactor
🡺 Integer parameter repeatFactor specifies how many times each bit in the pattern is to be
🡺 With a polyline, a specified line-style pattern is not restarted at the beginning of each
segment.
Module Computer Graphics and
1 OpenGL
🡺 It is applied continuously across all the segments, starting at the first endpoint of the
polyline and ending at the final endpoint for the last segment in the series.
Example:
🡺 For line style, suppose parameter pattern is assigned the hexadecimal representation
🡺 This would display a dashed line with eight pixels in each dash and eight pixel positions
🡺 Also, since low order bits are applied first, a line begins with an eight-pixel dash starting
🡺 This dash is followed by an eight-pixel space, then another eight-pixel dash, and so forth,
⮚ Before a line can be displayed in the current line-style pattern, we must activate the line-
⮚ If we forget to include this enable function, solid lines are displayed; that is, the
glDisable (GL_LINE_STIPPLE);
⮚ This replaces the current line-style pattern with the default pattern (solid lines).
Example Code:
typedef struct { float x, y; } wcPt2D;
wcPt2D dataPts [5];
void linePlot (wcPt2D dataPts [5])
{
int k;
Module Computer Graphics and
1 glBegin (GL_LINE_STRIP); OpenGL
for (k = 0; k < 5; k++)
glVertex2f (dataPts [k].x, dataPts [k].y);
Module Computer Graphics and
1 OpenGL
glFlush ( );
glEnd ( );
}
/* Invoke a procedure here to draw coordinate axes. */
glEnable (GL_LINE_STIPPLE); /* Input first set of (x, y) data values. */
glLineStipple (1, 0x1C47); // Plot a dash-dot, standard-width polyline.
linePlot (dataPts);
/* Input second set of (x, y) data values. */
glLineStipple (1, 0x00FF); / / Plot a dashed, double-width polyline.
glLineWidth (2.0);
linePlot (dataPts);
/* Input third set of (x, y) data values. */
glLineStipple (1, 0x0101); // Plot a dotted, triple-width polyline.
glLineWidth (3.0);
linePlot (dataPts);
glDisable (GL_LINE_STIPPLE);
Curve Attributes
🡺 Parameters for curve attributes are the same as those for straight-line segments.
🡺 We can display curves with varying colors, widths, dot-dash patterns, and available pen
or brush options.
🡺 Raster curves of various widths can be displayed using the method of horizontal or
Method 3:The pixel masks discussed for implementing line-style options could also be used in
raster curve algorithms to generate dashed or dotted patterns
Method 4: Pen (or brush) displays of curves are generated using the same techniques discussed
for straight-line segments.
the segment.
✔ To display the line on a raster monitor, the graphics system must first project the
endpoints to integer screen coordinates and determine the nearest pixel positions along
the line path between the two endpoints then the line color is loaded into the frame buffer
at the corresponding pixel coordinates
y=m * x +b >(1)
with m as the slope of the line and b as the y intercept.
✔ Given that the two endpoints of a line segment are specified at positions (x0,y0) and
✔ We determine values for the slope m and y intercept b with the following equations:
✔ Algorithms for displaying straight line are based on the line equation (1) and
✔ For given x interval δx along a line, we can compute the corresponding y interval δy
from eq.(2) as
δy=m. δx >(4)
δx=δy/m >(5)
✔ These equations form the basis for determining deflection voltages in analog displays,
such as vector-scan system, where arbitrarily small changes in deflection voltage are
possible.
🡺 |m|<1, δx can be set proportional to a small horizontal deflection voltage with the
🡺 |m|>1, δy can be set proportional to a small vertical deflection voltage with the
🡺 A line is sampled at unit intervals in one coordinate and the corresponding integer values
nearest the line path are determined for the other coordinate
🡺 DDA Algorithm has three cases so from equation i.e.., m=(yk+1 - yk)/(xk+1 - xk)
Case1:
if m<1,x increment in unit intervals i.e..,xk+1=xk+1
then, m=(yk+1 - yk)/( xk+1 - xk)
m= yk+1 - yk
yk+1 = yk + m >(1)
🡺 where k takes integer values starting from 0,for the first point and increases by 1 until
final endpoint is reached. Since m can be any real number between 0.0 and 1.0,
Case2:
if m>1, y increment in unit intervals i.e.., yk+1 = yk + 1
then, m= (yk + 1- yk)/( xk+1 - xk)
m(xk+1 - xk)=1
xk+1 =(1/m)+ xk (2)
Case3:
if m=1,both x
and y increment
in unit intervals
i.e..,xk+1=xk + 1
and yk+1 = yk + 1
Equations (1) and (2) are based on the assumption that lines are to be processed from the left
endpoint to the right endpoint. If this processing is reversed, so that the starting endpoint is at the
right, then either we have δx=-1 and
yk+1 = yk- m (3)
or(when the slope is greater than 1)we have δy=-1 with
xk+1 = xk- (1/m) (4)
Module Computer Graphics and
1 OpenGL
🡺 Similar calculations are carried out using equations (1) through (4) to determine the pixel
positions along a line with negative slope. thus, if the absolute value of the slope is less
than 1 and the starting endpoint is at left ,we set δx==1 and calculate y values with eq(1).
🡺 when starting endpoint is at the right(for the same slope),we set δx=-1 and obtain y
🡺 This algorithm is summarized in the following procedure, which accepts as input two
🡺 if m<1,where x is incrementing by 1
yk+1 = yk + m
starting point .
o Illuminate pixel(x, round(y))
o x1= x+ 1 , y1=y + 1
o Illuminate pixel(x1,round(y1))
o x2= x1+ 1 , y2=y1 + 1
o Illuminate pixel(x2,round(y2))
o Till it reaches final point.
🡺 if m>1,where y is incrementing by 1
xk+1 =(1/m)+ xk
starting point .
o Illuminate pixel(round(x),y)
o x1= x+( 1/m) ,y1=y
o Illuminate pixel(round(x1),y1)
o x2= x1+ (1/m) , y2=y1
o Illuminate pixel(round(x2),y2)
o Till it reaches final point.
🡺 The DDA algorithm is faster method for calculating pixel position than one that directly
Module Computer Graphics and
1 implements . OpenGL
Module Computer Graphics and
1 OpenGL
increments are applied in the x or y directions to step from one pixel position to another
along the line path.
🡺 The accumulation of round off error in successive additions of the floating point increment,
however can cause the calculated pixel positions to drift away from the true line path for
long line segments. Furthermore ,the rounding operations and floating point arithmetic in
this procedure are still time consuming.
🡺 we improve the performance of DDA algorithm by separating the increments m and 1/m
into integer and fractional parts so that all calculations are reduced to integer operations.
#include <stdlib.h>
#include <math.h>
inline int round (const float a)
{
return int (a + 0.5);
}
void lineDDA (int x0, int y0, int xEnd, int yEnd)
{
int dx = xEnd - x0, dy = yEnd - y0, steps, k;
float xIncrement, yIncrement, x = x0, y = y0;
if (fabs (dx) > fabs (dy))
steps = fabs (dx);
else
steps = fabs (dy);
xIncrement = float (dx) / float (steps);
yIncrement = float (dy) / float (steps);
setPixel (round (x), round (y));
for (k = 0; k < steps; k++) {
x += xIncrement;
y += yIncrement;
setPixel (round (x), round (y));
}
Module Computer Graphics and
1 OpenGL
}
Bresenham’s Algorithm:
🡺 It is an efficient raster scan generating algorithm that uses incremental integral calculations
🡺 To illustrate Bresenham’s approach, we first consider the scan-conversion process for lines
🡺 Pixel positions along a line path are then determined by sampling at unit x intervals.
Starting from the left endpoint (x0, y0) of a given line, we step to each successive column
(x position) and plot the pixel whose scan-line y value is closest to the line path.
p0 = 2y x
4. At each xk along the line, starting at k = 0, perform the following test:
If pk < 0, the next point to plot is (xk + 1, yk ) and
pk+1 = pk + 2y
Otherwise, the next point to plot is (xk + 1, yk + 1) and
pk+1 = pk + 2y 2x
5. Repeat step 4 x 1 more times.
Note:
If |m|>1.0
Then
p0 = 2x y
and
Module Computer Graphics and
1 OpenGL
If pk < 0, the next point to plot is (xk , yk +1) and
pk+1 = pk + 2x
Otherwise, the next point to plot is (xk + 1, yk + 1) and
pk+1 = pk + 2x 2y
Code:
#include <stdlib.h>
#include <math.h>
/* Bresenham line-drawing procedure for |m| < 1.0. */
void lineBres (int x0, int y0, int xEnd, int yEnd)
{
int dx = fabs (xEnd - x0), dy = fabs(yEnd - y0);
int p = 2 * dy - dx;
int twoDy = 2 * dy, twoDyMinusDx = 2 * (dy - dx);
int x, y;
/* Determine which endpoint to use as start position. */
if (x0 > xEnd) {
x = xEnd;
y = yEnd;
xEnd = x0;
}
else {
}
x = x0; y = y0;
setPixel (x, y);
while (x < xEnd) {
x++;
if (p < 0)
p += twoDy;
Module Computer Graphics and
1 OpenGL
else {
y++;
p += twoDyMinusDx;
}
setPixel (x, y);
}
}
Properties of Circles
🡺 A circle is defined as the set of points that are all at a given distance r from a center
position (xc , yc ).
🡺 For any circle point (x, y), this distance relationship is expressed by the Pythagorean
🡺 We could use this equation to calculate the position of points on a circle circumference by
stepping along the x axis in unit steps from x c r to x c +r and calculating the
corresponding y values at each position as
🡺 One problem with this approach is that it involves considerable computation at each step.
🡺 We could adjust the spacing by interchanging x and y (stepping through y values and
calculating x values) whenever the absolute value of the slope of the circle is greater than
1; but this simply increases the computation and processing required by the algorithm.
🡺 Another way to eliminate the unequal spacing is to calculate points along the circular
🡺 Expressing the circle equation in parametric polar form yields the pair of equations
Module Computer Graphics and
1 OpenGL
Midpoint Circle Algorithm
🡺 Midpoint circle algorithm generates all points on a circle centered at the origin by
🡺 The strategy is to select which of 2 pixels is closer to the circle by evaluating a function
🡺 To summarize, the relative position of any point (x, y) can be determined by checking the
🡺 Therefore ,if we determine the curve positions in the first quadrant ,we can generate the
🡺 The circle sections in the third and fourth quadrant can be obtained from sections in the
🡺 Conside the circle centered at the origin,if the point ( x, y) is on the circle,then we can
🡺 Our decision parameter is the circle function evaluated at the midpoint between these
two pixels:
🡺 We obtain a recursive expression for the next decision parameter by evaluating the circle
🡺 The initial decision parameter is obtained by evaluating the circle function at the start
p0 = 1 r (for r an integer)
because all increments are integers.
Code:
void draw_pixel(GLint cx, GLint cy)
{
glColor3f(0.5,0.5,0.0);
glBegin(GL_POINTS);
glVertex2i(cx, cy);
glEnd();
}