15CSL68 - Computer Graphics Lab Manual: Mr. Shankar R
15CSL68 - Computer Graphics Lab Manual: Mr. Shankar R
15CSL68 - Computer Graphics Lab Manual: Mr. Shankar R
15CSL68 – Computer
Graphics Lab Manual
A comprehensive package
Mr. Shankar R
15CSL68 – Computer Graphics Lab Manual
SYLLABUS
PART A
Design, develop, and implement the following programs using OpenGL API
1. Implement Bresenham’s line drawing algorithm for all types of slope.
2. Create and rotate a triangle about the origin and a fixed point.
3. Draw a colour cube and spin it using OpenGL transformation matrices.
4. Draw a color cube and allow the user to move the camera suitably to experiment with perspective
viewing.
5. Clip a line using Cohen-Sutherland algorithm
6. To draw a simple shaded scene consisting of a tea pot on a table. Define suitably the position and
properties of the light source along with the properties of the surfaces of the solid object used in the
scene.
7. Design, develop and implement recursively subdivide a tetrahedron to form 3D sierpinski gasket.
The number of recursive steps is to be specified by the user.
8. Develop a menu driven program to animate a flag using Bezier Curve algorithm.
9. Develop a menu driven program to fill the polygon using scan line algorithm
PART –B ( MINI-PROJECT)
Student should develop mini project on the topics mentioned below or similar applications using Open
GL API. Consider all types of attributes like color, thickness, styles, font, background, speed etc., while
doing mini project.
(During the practical exam: the students should demonstrate and answer Viva-Voce)
Sample Topics: Simulation of concepts of OS, Data structures, algorithms etc.
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 2
15CSL68 – Computer Graphics Lab Manual
INTRODUCTION
Computer graphics are graphics created using computers and, more generally, the representation and
manipulation of image data by a computer hardware and software. The development of computer graphics,
or simply referred to as CG, has made computers easier to interact with, and better for understanding and
interpreting many types of data. Developments in computer graphics have had a profound impact on many
types of media and have revolutionized the animation and video game industry. 2D computer graphics are
digital images—mostly from two-dimensional models, such as 2D geometric models, text (vector array), and
2D data. 3D computer graphics in contrast to 2D computer graphics are graphics that use a three-
dimensional representation of geometric data that is stored in the computer for the purposes of performing
calculations and rendering images.
OPEN GL
OpenGL is the most extensively documented 3D graphics API(Application Program Interface) to date.
Information regarding OpenGL is all over the Web and in print. It is impossible to exhaustively list all
sources of OpenGL information. OpenGL programs are typically written in C and C++. One can also
program OpenGL from Delphi (a Pascal-like language), Basic, Fortran, Ada, and other langauges. To
compile and link OpenGL programs, one will need OpenGL header files. To run OpenGL programs one
may need shared or dynamically loaded OpenGL libraries, or a vendor-specific OpenGL Installable Client
Driver (ICD).
GLUT
The OpenGL Utility Toolkit (GLUT) is a library of utilities for OpenGL programs, which primarily perform
system-level I/O with the host operating system. Functions performed include window definition, window
control, and monitoring of keyboard and mouse input. Routines for drawing a number of geometric
primitives (both in solid and wireframe mode) are also provided, including cubes, spheres, and cylinders.
GLUT even has some limited support for creating pop-up menus. The two aims of GLUT are to allow the
creation of rather portable code between operating systems (GLUT is cross-platform) and to make learning
OpenGL easier. All GLUT functions start with the glut prefix (for example, glutPostRedisplay marks the
current window as needing to be redrawn).
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 3
15CSL68 – Computer Graphics Lab Manual
Evaluators
All geometric primitives are eventually described by vertices. Parametric curves and surfaces may be
initially described by control points and polynomial functions called basis functions. Evaluators provide a
method to derive the vertices used to represent the surface from the control points. The method is a
polynomial mapping, which can produce surface normal, texture coordinates, colors, and spatial coordinate
values from the control points.
Per-Vertex Operations
For vertex data, next is the "per-vertex operations" stage, which converts the vertices into primitives. Some
vertex data (for example, spatial coordinates) are transformed by 4 x 4 floating-point matrices. Spatial
coordinates are projected from a position in the 3D world to a position on your screen. If advanced features
are enabled, this stage is even busier. If texturing is used, texture coordinates may be generated and
transformed here. If lighting is enabled, the lighting calculations are performed using the transformed vertex,
surface normal, light source position, material properties, and other lighting information to produce a color
value.
Primitive Assembly
Clipping, a major part of primitive assembly, is the elimination of portions of geometry which fall outside a
half-space, defined by a plane. Point clipping simply passes or rejects vertices; line or polygon clipping can
add additional vertices depending upon how the line or polygon is clipped. In some cases, this is followed by
perspective division, which makes distant geometric objects appear smaller than closer objects. Then
viewport and depth (z coordinate) operations are applied. If culling is enabled and the primitive is a polygon,
it then may be rejected by a culling test. Depending upon the polygon mode, a polygon may be drawn as
points or lines.
The results of this stage are complete geometric primitives, which are the transformed and clipped vertices
with related color, depth, and sometimes texture-coordinate values and guidelines for the rasterization step.
Pixel Operations
While geometric data takes one path through the OpenGL rendering pipeline, pixel data takes a different
route. Pixels from an array in system memory are first unpacked from one of a variety of formats into the
proper number of components. Next the data is scaled, biased, and processed by a pixel map. The results are
clamped and then either written into texture memory or sent to the rasterization step If pixel data is read
from the frame buffer, pixel-transfer operations (scale, bias, mapping, and clamping) are performed. Then
these results are packed into an appropriate format and returned to an array in system memory.
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 4
15CSL68 – Computer Graphics Lab Manual
There are special pixel copy operations to copy data in the framebuffer to other parts of the framebuffer or to
the texture memory. A single pass is made through the pixel transfer operations before the data is written to
the texture memory or back to the framebuffer.
Texture Assembly
An OpenGL application may wish to apply texture images onto geometric objects to make them look more
realistic. If several texture images are used, it’s wise to put them into texture objects so that you can easily
switch among them.
Some OpenGL implementations may have special resources to accelerate texture performance. There may
be specialized, high-performance texture memory. If this memory is available, the texture objects may be
prioritized to control the use of this limited and valuable resource.
Rasterization
Rasterization is the conversion of both geometric and pixel data into fragments. Each fragment square
corresponds to a pixel in the framebuffer. Line and polygon stipples, line width, point size, shading model,
and coverage calculations to support antialiasing are taken into consideration as vertices are connected into
lines or the interior pixels are calculated for a filled polygon. Color and depth values are assigned for each
fragment square.
Fragment Operations
Before values are actually stored into the framebuffer, a series of operations are performed that may alter or
even throw out fragments. All these operations can be enabled or disabled.
The first operation which may be encountered is texturing, where a texel (texture element) is generated from
texture memory for each fragment and applied to the fragment. Then fog calculations may be applied,
followed by the scissor test, the alpha test, the stencil test, and the depth-buffer test (the depth buffer is for
hidden-surface removal). Failing an enabled test may end the continued processing of a fragment’s square.
Then, blending, dithering, logical operation, and masking by a bitmask may be performed.Finally, the
thoroughly processedfragment is drawn into the appropriate buffer, where it has finally advanced to be a
pixel and achieved its final resting place.
OpenGL-Related Libraries
OpenGL provides a powerful but primitive set of rendering commands, and all higher-level drawing must be
done in terms of these commands. Also, OpenGL programs have to use the underlying mechanisms of the
windowing system. A number of libraries exist to allow you to simplify your programming tasks, including
the following:
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 5
15CSL68 – Computer Graphics Lab Manual
The OpenGL Utility Library (GLU) contains several routines that use lower-level OpenGL commands to
perform such tasks as setting up matrices for specific viewing orientations and projections, performing
polygon tessellation, and rendering surfaces. This library is provided as part of every OpenGL
implementation. Portions of the GLU are described in the OpenGL
For every window system, there is a library that extends the functionality of that window system to support
OpenGL rendering. For machines that use the X Window System, the OpenGL Extension to the X Window
System (GLX) is provided as an adjunct to OpenGL. GLX routines use the prefix glX. For Microsoft
Windows, the WGL routines provide the Windows to OpenGL interface. All WGL routines use the prefix
wgl. For IBM OS/2, the PGL is the Presentation Manager to OpenGL interface, and its routines use the
prefix pgl.
The OpenGL Utility Toolkit (GLUT) is a window system-independent toolkit, written by Mark Kilgard, to
hide the complexities of differing window system APIs. Open Inventor is an object-oriented toolkit based on
OpenGL which provides objects and methods for creating interactive three-dimensional graphics
applications. Open Inventor, which is written in C++, provides prebuilt objects and a built-in event model
for user interaction, high-level application components for creating and editing three-dimensional scenes,
and the ability to print objects and exchange data in other graphics formats. Open Inventor is separate from
OpenGL.
In addition, since OpenGL drawing commands are limited to those that generate simple geometric primitives
(points, lines, and polygons), GLUT includes several routines that create more complicated three-
dimensional objects such as a sphere, a torus, and a teapot. This way, snapshots of program output can be
interesting to look at. (Note that the OpenGL Utility Library, GLU, also has quadrics routines that create
some of the same three-dimensional objects as GLUT, such as a sphere, cylinder, or cone.)
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 6
15CSL68 – Computer Graphics Lab Manual
GLUT may not be satisfactory for full-featured OpenGL applications, but you may find it a useful starting
point for learning OpenGL. The rest of this section briefly describes a small subset of GLUT routines so that
you can follow the programming examples in the rest of this book.
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 7
15CSL68 – Computer Graphics Lab Manual
glutInitDisplayMode: requests a display with the specified mode, such as color mode
(GLUT_RGB, GLUT_RGBA, GLUT_INDEX), single/double buffering (GLUT_SINGLE,
GLUT_DOUBLE), enable depth (GLUT_DEPTH), joined with a bit OR '|'.
void glutInitDisplayMode(unsigned int displayMode)
void glMatrixMode (GLenum mode);
The glMatrixMode function specifies which matrix is the current matrix.
void
glOrtho(GLdoubleleft,GLdoubleright,GLdoublebottom,GLdoubletop,GLdoublezNear,GLdou
blezFar);
The glOrtho function multiplies the current matrix by an orthographic matrix.
void glPointSize (GLfloat size);
The glPointSize function specifies the diameter of rasterized points.
voidglutPostRedisplay(void);
glutPostRedisplay marks the current window as needing to be redisplayed.
void glPushMatrix (void);
void glPopMatrix (void);
The glPushMatrix and glPopMatrix functions push and pop the current matrix stack.
GLintglRenderMode (GLenum mode);
The glRenderMode function sets the rasterization mode.
void glRotatef (GLfloat angle, GLfloat x, GLfloat y, GLfloat);
The glRotatef functions multiply the current matrix by a rotation matrix.
void glScalef (GLfloat x, GLfloat y, GLfloat z);
The glScalef functions multiply the current matrix by a general scaling matrix.
void glTranslatef (GLfloat x, GLfloat y, GLfloat z);
The glTranslatef functions multiply the current matrix by a translation matrix.
void glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
The glViewport function sets the viewport.
void glEnable, glDisable();
The glEnable and glDisable functions enable or disable OpenGL capabilities.
glutBitmapCharacter();
The glutBitmapCharacter function used for font style.
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 8
15CSL68 – Computer Graphics Lab Manual
OpenGL Primitives
INTRODUCTION TO openGL
OpenGL is an API.OpenGL is nothing more than a set of functions you call from your program (think of as collection
of .h files.
OpenGL Libraries:
OpenGL
Application
Frame Buffer
Display
OpenGL Hierarchy:
Several levels of abstraction are provided
GL
Lowest level: vertex, matrix manipulation
glVertex3f(point.x, point.y, point.z)
GLU
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 9
15CSL68 – Computer Graphics Lab Manual
OpenGL Implementations :
OpenGL IS an API (think of as collection of .h files):
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
Windows, Linux, UNIX, etc. all provide a platform specific implementation.
Windows: opengl32.lib glu32.lib glut32.lib
Linux: -l GL -l GLU –l GLUT
Event Loop:
• OpenGL programs often run in an event loop:
– Start the program
– Run some initialization code
– Run an infinite loop and wait for events such as
• Key press
• Mouse move, click
• Reshape window
• Expose event
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 10
15CSL68 – Computer Graphics Lab Manual
Ten gl Primitives:
GL_POINTS GL_LINES
GL_POLYGON GL_TRIANGLES
GL_QUADS GL_LINE_STRIP
GL_LINE_LOOP GL_QUAD_STRIP
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 11
15CSL68 – Computer Graphics Lab Manual
GL_TRIANGLE_STRIP GL_TRIANGLE_FAN
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 12
15CSL68 – Computer Graphics Lab Manual
Projections in OpenGL
Perspective projection:
void glFrustum(GLdouble left, GLdouble right, GLdouble bottom,GLdouble top, GLdouble near, GLdouble far);
Orthographic projection:
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 13
15CSL68 – Computer Graphics Lab Manual
1. What is Computer Graphics? Answer: Computer graphics are graphics created using computers and, more
generally, the representation and manipulation of image data by a computer.
2. What is OpenGL? Answer: OpenGL is the most extensively documented 3D graphics API (Application Program
Interface) to date. It is used to create Graphics.
3. What is GLUT? Answer: The OpenGL Utility Toolkit (GLUT) is a library of utilities for OpenGL programs, which
primarily perform system-level I/O with the host operating system.
4. What are the applications of Computer Graphics? Answer: Gaming Industry, Animation Industry and Medical
Image Processing Industries. The sum total of these industries is a Multi Billion Dollar Market. Jobs will continue to
increase in this arena in the future.
5. Explain in breif 3D Sierpinski gasket? Answer: The Sierpinski triangle (also with the original orthography
Sierpinski), also called the Sierpinski gasket or the Sierpinski Sieve, is a fractal named after the Polish mathemati-
cian Waclaw Sierpinski who described it in 1915. Originally constructed as a curve, this is one of the basic
examples of self-similar sets, i.e. it is a mathematically generated pattern that can be reproducible at any
magnifcation or reduction.
6. What is Liang-Barsky line clipping algorithm? Answer: In computer graphics, the Liang-Barsky algorithm is a line
clipping algorithm. The Liang-Barsky algorithm uses the parametric equation of a line and inequalities describing
the range of the clipping box to determine the intersections between the line and the clipping box. With these
intersections it knows which portion of the line should be drawn.
7. Explain in brief Cohen-Sutherland line-clipping algorithm? Answer: The Cohen-Sutherland line clipping algorithm
quickly detects and dispenses with two common and trivial cases. To clip a line, we need to consider only its
endpoints. If both endpoints of a line lie inside the window, the entire line lies inside the window. It is trivially
accepted and needs no clipping. On the other hand, if both endpoints of a line lie entirely to one side of the
window, the line must lie entirely outside of the window. It is trivially rejected and needs to be neither clipped nor
displayed.
8. Explain in brief scan-line area flling algorithm? Answer: The scanline fll algorithm is an ingenious way of flling in
irregular polygons. The algorithm begins with a set of points. Each point is connected to the next, and the line
between them is considered to be an edge of the polygon. The points of each edge are adjusted to ensure that
the point with the smaller y value appears frst. Next, a data structure is created that contains a list of edges that
begin on each scanline of the image. The program progresses from the frst scanline upward. For each line, any
pixels that contain an intersection between this scanline and an edge of the polygon are flled in. Then, the
algorithm progresses along the scanline, turning on when it reaches a polygon pixel and turning of when it
reaches another one, all the way across the scanline.
9. Explain Midpoint Line algorithm Answer: The Midpoint line algorithm is an algorithm which determines which
points in an n-dimensional raster should be plotted in order to form a close approximation to a straight line between
two given points. It is commonly used to draw lines on a computer screen, as it uses only integer addition, subtraction
and bit shifting, all of which are very cheap operations in standard computer architectures.
10. What is a Pixel? Answer: In digital imaging, a pixel (or picture element) is a single point in a raster image. The
Pixel is the smallest addressable screen element; it is the smallest unit of picture which can be controlled. Each Pixel
has its address. The address of Pixels corresponds to its coordinate. Pixels are normally arranged in a 2-dimensional
grid, and are often represented using dots or squares.
11. What is Graphical User Interface? Answer: A graphical user interface (GUI) is a type of user interface item
that allows people to interact with programs in more ways than typing such as computers; hand-held devices such as
MP3 Players, Portable Media Players or Gaming devices; household appliances and ofce equipment with images
rather than text commands.
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 14
15CSL68 – Computer Graphics Lab Manual
12. What is the general form of an OpenGL program? Answer: There are no hard and fast rules. The following
pseudocode is generally recognized as good OpenGL form. program entrypoint { // Determine which depth or pixel
format should be used. // Create a window with the desired format. // Create a rendering context and make it current
with the window. // Set up initial OpenGL state. // Set up callback routines for window resize and window refresh. }
handle resize { glViewport(...); glMatrixMode(GL PROJECTION); glLoadIdentity(); // Set projection transform with
glOrtho, glFrustum, gluOrtho2D, gluPerspective, etc. } handle refresh { glClear(...); glMatrixMode(GL MODELVIEW);
glLoadIdentity(); // Set view transform with gluLookAt or equivalent // For each object (i) in the scene that needs to be
rendered: // Push relevant stacks, e.g., glPushMatrix, glPushAttrib. // Set OpenGL state specifc to object (i). // Set
model transform for object (i) using glTranslatef, glScalef, glRotatef, and/or equivalent. // Issue rendering commands
for object (i). // Pop relevant stacks, (e.g., glPopMatrix, glPopAttrib.) // End for loop. // Swap bufers. }
13. What support for OpenGL does Open,Net,FreeBSD or Linux provide? Answer: The X Windows
implementation, XFree86 4.0, includes support for OpenGL using Mesa or the OpenGL Sample Implementation.
XFree86 is released under the XFree86 license. http://www.xfree86.org/
14. What is the AUX library? Answer: The AUX library was developed by SGI early in OpenGL's life to ease
creation of small OpenGL demonstration programs. It's currently neither supported nor maintained. Developing
OpenGL programs using AUX is strongly discouraged. Use the GLUT instead. It's more fexible and powerful and is
available on a wide range of platforms. Very important: Don't use AUX. Use GLUT instead.
15. How does the camera work in OpenGL? Answer: As far as OpenGL is concerned, there is no camera. More
specifcally, the camera is always located at the eye space coordinate (0., 0., 0.). To give the appearance of moving
the camera, your OpenGL application must move the scene with the inverse of the camera transformation.
16. How do I implement a zoom operation? Answer: A simple method for zooming is to use a uniform scale on the
ModelView matrix. However, this often results in clipping by the zNear and zFar clipping planes if the model is scaled
too large. A better method is to restrict the width and height of the view volume in the Projection matrix.
17. What are OpenGL coordinate units? Answer: Depending on the contents of your geometry database, it may
be convenient for your application to treat one OpenGL coordinate unit as being equal to one millimeter or one parsec
or anything in between (or larger or smaller). OpenGL also lets you specify your geometry with coordinates of difering
values. For example, you may fnd it convenient to model an airplane's controls in centimeters, its fuselage in meters,
and a world to fy around in kilometers. OpenGL's ModelView matrix can then scale these diferent coordinate systems
into the same eye coordinate space. It's the application's responsibility to ensure that the Projection and ModelView
matrices are constructed to provide an image that keeps the viewer at an appropriate distance, with an appropriate
feld of view, and keeps the zNear and zFar clipping planes at an appropriate range. An application that displays
molecules in micron scale, for example, would probably not want to place the viewer at a distance of 10 feet with a 60
degree feld of view.
18. What is Microsoft Visual Studio? Answer: Microsoft Visual Studio is an integrated development environment
(IDE) for developing windows applications. It is the most popular IDE for developing windows applications or windows
based software.
19. What does the .gl or .GL fle format have to do with OpenGL? Answer: .gl fles have nothing to do with
OpenGL, but are sometimes confused with it. .gl is a fle format for images, which has no relationship to OpenGL.
20. Who needs to license OpenGL? Who doesn't? Is OpenGL free software? Answer: Companies which will be
creating or selling binaries of the OpenGL library will need to license OpenGL. Typical examples of licensees include
hardware vendors, such as Digital Equipment, and IBM who would distribute OpenGL with the system software on
their workstations or PCs. Also, some software vendors, such as Portable Graphics and Template Graphics, have a
business in creating and distributing versions of OpenGL, and they need to license OpenGL. Applications developers
do NOT need to license OpenGL. If a developer wants to use OpenGL that developer needs to obtain copies of a
linkable OpenGL library for a particular machine. Those OpenGL libraries may be bundled in with the development
and/or run-time options or may be purchased from a third-party software vendor, without licensing the source code or
use of the OpenGLtrademark.
21. How do we make shadows in OpenGL? Answer: There are no individual routines to control neither shadows
nor an OpenGL state for shadows. However, code can be written to render shadows.
22. What is the use of Glutinit? Answer: void glutInit(int *argcp, char **argv); glutInit will initialize the GLUT library
and negotiate a session with the window system. During this process, glutInit may cause the termination of the GLUT
program with an error message to the user if GLUT cannot be properly initialized.
23. Describe the usage of glutInitWindowSize and glutInitWindowPosition? Answer: void glutInitWindowSize(int
width, int height); void glutInitWindowPosition(int x, int y); Windows created by glutCreateWindow will be requested to
be created with the current initial window position and size. The intent of the initial window position and size values is
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 15
15CSL68 – Computer Graphics Lab Manual
to provide a suggestion to the window system for a window's initial size and position. The window system is not
obligated to use this information. Therefore, GLUT programs should not assume the window was created at the
specifed size or position. A GLUT program should use the window's reshape callback to determine the true size of the
window.
24. Describe the usage of glutMainLoop? Answer: void glutMainLoop(void); glutMainLoop enters the GLUT event
processing loop. This routine should be called at most once in a GLUT program. Once called, this routine will never
return. It will call as necessary any callbacks that have been registered.
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 16
15CSL68 – Computer Graphics Lab Manual
#include<GL/glut.h>
#include<stdio.h>
int x1, y1, x2, y2;
if (m < 1)
{
int decision_parameter = 2*dy - dx;
int x = x1; // initial x
int y = y1; // initial y
if (dx < 0) // decide the first point and second point
{
x = x2; // making second point as first point
y = y2;
x2 = x1;
}
draw_pixel (x, y); // plot a point
while (x < x2) // from 1st point to 2nd point
{
if (decision_parameter >= 0)
{
x = x+1;
y = y+1;
decision_parameter = decision_parameter + 2*dy - 2*dx * (y+1 - y);
}
else
{
x = x+1;
y = y;
decision_parameter = decision_parameter + 2*dy - 2*dx * (y - y);
}
draw_pixel (x, y);
}
}
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 6
15CSL68 – Computer Graphics Lab Manual
else if (m > 1)
{
int decision_parameter = 2*dx - dy;
int x = x1; // initial x
int y = y1; // initial y
if (dy < 0)
{
x = x2;
y = y2;
y2 = y1;
}
draw_pixel (x, y);
while (y < y2)
{
if (decision_parameter >= 0)
{
x = x+1;
y = y+1;
decision_parameter = decision_parameter + 2*dx - 2*dy * (x+1 - x);
}
else
{
y = y+1;
x = x;
decision_parameter = decision_parameter + 2*dx - 2*dy * (x- x);
}
draw_pixel(x, y);
}
}
else if (m == 1)
{
int x = x1;
int y = y1;
draw_pixel (x, y);
while (x < x2)
{
x = x+1;
y = y+1;
draw_pixel (x, y);
}
}
}
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 7
15CSL68 – Computer Graphics Lab Manual
void init()
{
glClearColor(1,1,1,1);
gluOrtho2D(0.0, 500.0, 0.0, 500.0); // left ->0, right ->500, bottom ->0, top ->500
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
bresenhams_line_draw(x1, y1, x2, y2);
glFlush();
}
***********************************************************************************
OUTPUT
Case 1: m < 1
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 8
15CSL68 – Computer Graphics Lab Manual
Case 2: m > 1
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 9
15CSL68 – Computer Graphics Lab Manual
Case 3: m == 1
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 10
15CSL68 – Computer Graphics Lab Manual
2. Create and rotate a triangle about the origin and a fixed point.
#include<GL/glut.h>
#include<stdio.h>
int x,y;
int where_to_rotate=0; // don't rotate initially
float rotate_angle=0; // initial angle
float translate_x=0,translate_y=0; // initial translation
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
void init()
{
glClearColor(0,0,0,1); //setting to black
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-800, 800, -800, 800);
glMatrixMode(GL_MODELVIEW);
}
if(option==2)
where_to_rotate=2; // rotate around customer's coordinates
if(option==3)
where_to_rotate=3; // stop rotation
}
glutAddMenuEntry("Stop Rotation",3);
glutAttachMenu(GLUT_RIGHT_BUTTON);
***********************************************************************************
OUTPUT
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 8
15CSL68 – Computer Graphics Lab Manual
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 9
15CSL68 – Computer Graphics Lab Manual
3. Program to draw a color cube and spin it using OpenGL transformation matrices.
#include<stdlib.h>
#include<GL/glut.h>
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 6
15CSL68 – Computer Graphics Lab Manual
void spinCube()
{
theta[axis] += 2; // rotate every 2 degrees
if (theta[axis] > 360) // it the rotation angle crosses 360 degrees, make it 0 degree
theta[axis] -= 360;
if(w<=h)
glOrtho (-2, 2, -2*(GLfloat)h/(GLfloat)w, 2*(GLfloat)h / (GLfloat)w, -10, 10);
else
glOrtho (-2*(GLfloat)w/(GLfloat)h, 2*(GLfloat)w / (GLfloat)h, -2, 2, -10, 10);
glMatrixMode(GL_MODELVIEW);
}
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 7
15CSL68 – Computer Graphics Lab Manual
glColor3f(1, 1, 1);
glutMainLoop();
}
void glEnableClientState (GLenum cap);
cap
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 8
15CSL68 – Computer Graphics Lab Manual
***********************************************************************************
OUTPUT
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 9
15CSL68 – Computer Graphics Lab Manual
4. Program to draw a color cube and allow the user to move the camera suitably to experiment
with perspective viewing.
#include <stdlib.h>
#include <GL/glut.h>
glColor3fv(colors[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glVertex3fv(vertices[d]);
glEnd();
}
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 6
15CSL68 – Computer Graphics Lab Manual
void colorcube(void)
{
polygon (0,3,2,1);
polygon (0,4,7,3);
polygon (5,4,0,1);
polygon (2,3,7,6);
polygon (1,2,6,5);
polygon (4,5,6,7);
}
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt (viewer[0],viewer[1],viewer[2], 0, 0, 0, 0, 1, 0);
glRotatef (theta[0], 1, 0, 0);
glRotatef (theta[1], 0, 1, 0);
glRotatef (theta[2], 0, 0, 1);
colorcube();
glFlush();
glutSwapBuffers();
}
theta[axis] += 2;
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutKeyboardFunc(keys);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}
***********************************************************************************
OUTPUT
Also, press x, X
y, Y
z, Z
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 8
15CSL68 – Computer Graphics Lab Manual
#include <stdio.h>
#include <GL/glut.h>
double xmin = 50, ymin = 50, xmax = 100, ymax = 100; //window coordinates
double xvmin = 200, yvmin = 200, xvmax = 300, yvmax = 300; //viewport coordinates
const int LEFT = 1; // assuming code words for LEFT, RIGHT, BOTTOM & TOP.
const int RIGHT = 2;
const int BOTTOM = 4;
const int TOP = 8;
do
{
if ( ! (outcode0 | outcode1))
{
accept = true; //both the points
done = true; are inside the window
}
else if (outcode0 & outcode1)
done = true; //both are outside
else
{
double x, y;
double m = (y1 - y0) / (x1 - x0);
outcodeOut = outcode0 ? outcode0: outcode1;
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 6
15CSL68 – Computer Graphics Lab Manual
if (outcodeOut == outcode0)
{
x0 = x;
y0 = y;
outcode0 = ComputeOutCode (x0, y0);
}
else
{
x1 = x;
y1 = y;
outcode1 = ComputeOutCode (x1, y1);
}
}
}
while (!done);
if (accept)
Zooming (scaling) the clipping rectangle
{
and the clipped line and show it to the
double sx = (xvmax - xvmin) / (xmax - xmin);
customer. The customer can see both
double sy = (yvmax - yvmin) / (ymax - ymin);
before and after clipping effects. See
double vx0 = xvmin + (x0 - xmin) * sx; the output for better clarity.
double vy0 = yvmin + (y0 - ymin) * sy; sx, sy -> scaling parameters
double vx1 = xvmin + (x1 - xmin) * sx; vx0, vy0, vx1, vy1 -> line coordinates
double vy1 = yvmin + (y1 - ymin) * sy;
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 7
15CSL68 – Computer Graphics Lab Manual
void display()
{
double x0 = 60, y0 = 20, x1 = 80, y1 = 120; // the line coordinates
glClear (GL_COLOR_BUFFER_BIT);
glBegin (GL_LINES);
glVertex2d (x0, y0); // draw the line that has to be clipped
glVertex2d (x1, y1);
glEnd ();
void init()
{
glClearColor (0, 0, 0, 1); //black background colour
gluOrtho2D (0, 500, 0, 500);
}
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 8
15CSL68 – Computer Graphics Lab Manual
init();
glutDisplayFunc(display);
glutMainLoop();
}
***********************************************************************************
OUTPUT
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 9
15CSL68 – Computer Graphics Lab Manual
6. Program to draw a simple shaded scene consisting of a tea pot on a table. Define suitably
the position and properties of the light source along with the properties of the properties of
the surfaces of the solid object used in the scene.
#include<GL/glut.h>
void teapot(GLfloat x, GLfloat y, GLfloat z)
{
glPushMatrix (); //save the current state
glTranslatef (x, y, z); //move your item appropriately
glutSolidTeapot (0.1); //render your teapot
glPopMatrix (); //get back your state with the recent changes that you have done
}
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 6
15CSL68 – Computer Graphics Lab Manual
wall (0, 0, wallP); //Create 2nd wall pname specifies one of ten light
glRotatef (90, 0, 1, 0); source parameters, again by
symbolic name.
wall (0, 0, wallP); //Create 3rd wall params is either a single value or
a pointer to an array that
glFlush (); // show the output to the user contains the new values.
}
void init()
{
glClearColor (0, 0, 0, 1); // black colour background
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho (-1, 1, -1, 1, -1, 10);
glMatrixMode (GL_MODELVIEW);
}
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 7
15CSL68 – Computer Graphics Lab Manual
init();
glutDisplayFunc(display);
glutMainLoop();
}
***********************************************************************************
OUTPUT
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 8
15CSL68 – Computer Graphics Lab Manual
#include<stdlib.h>
#include<stdio.h>
#include<GL/glut.h>
if(n>0)
{
for(j=0; j<3; j++)
v1[j] = (a[j]+b[j])/2; // calculate mid-point between a and b
divide_triangle(c,v2,v3,n-1);
divide_triangle(b,v3,v1,n-1);
else
triangle (a,b,c);// draw triangle
}
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 6
15CSL68 – Computer Graphics Lab Manual
void tetrahedron(int n)
{
glColor3f(1, 0, 0); // assign color for each of the side
divide_triangle(v[0], v[1], v[2], n); // draw triangle between a, b, c
glColor3f(0, 1, 0);
divide_triangle(v[3], v[2], v[1], n);
glColor3f(0, 0, 1);
divide_triangle(v[0], v[3], v[1], n);
glColor3f(0, 0, 0);
divide_triangle(v[0], v[2], v[3], n);
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
tetrahedron(n);
glFlush(); // show the output
}
void myReshape(int w,int h) // please see the earlier program for explanation on this
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
glOrtho(-2, 2, -2*(GLfloat)h/(GLfloat)w, 2*(GLfloat)h/(GLfloat)w, -10, 10);
else
glOrtho(-2*(GLfloat)w/(GLfloat)h, 2*(GLfloat)w/(GLfloat)h, -2, 2, -10, 10);
glMatrixMode(GL_MODELVIEW);
glutPostRedisplay();
}
glutReshapeFunc(myReshape);
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 7
15CSL68 – Computer Graphics Lab Manual
glClearColor(1, 1, 1, 0);
glutMainLoop();
return 0;
}
***********************************************************************************
OUTPUT
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 8
15CSL68 – Computer Graphics Lab Manual
8. Develop a menu driven program to animate a flag using Bezier curve algorithm.
Bézier curves are parametric curves that are generated with the control points. It is
widely used in computer graphics and other related industry, as they appear reasonably
smooth at all scales. Bézier curves was name after french engineer Pierre Bézier, who
discovered it. Mathematically Bézier curves is represented as –
Bézier curves are of different degree - linear curves, quadratic curve, cubic curve and
high order curve.
Where n = (number_of_control_points - 1)
= 4 – 1
n = 3
t ranges from 0 to 1
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 6
15CSL68 – Computer Graphics Lab Manual
#include<GL/glut.h>
#include<stdio.h>
#include<math.h>
#define PI 3.1416
float theta = 0;
struct point
{
GLfloat x, y, z;
};
float bernstein_polynomial;
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 7
15CSL68 – Computer Graphics Lab Manual
glBegin (GL_LINE_STRIP);
See the above
for(i=0; i<=number_of_bezier_points; i++)
{ explanation to
t=float (i) / float (number_of_bezier_points); understand this
delete [] hold_ncr_values;
}
void display()
{
glClear (GL_COLOR_BUFFER_BIT);
int number_of_control_points= 4, number_of_bezier_points= 20;
point control_points_array[4]= {{100, 400, 0}, {150, 450, 0}, {250, 350, 0},{300, 400, 0}};
glPushMatrix ();
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 8
15CSL68 – Computer Graphics Lab Manual
glPopMatrix();
glLineWidth(5);
glBegin(GL_LINES);
glVertex2f(100,400);
glVertex2f(100,40);
glEnd();
void init ()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,500,0,500);
}
init ();
glutDisplayFunc (display);
glutMainLoop ();
}
***********************************************************************************
OUTPUT
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 10
15CSL68 – Computer Graphics Lab Manual
9. Develop a menu driven program to fill any given polygon using scan-line area filling
algorithm.
Also, define
your polygon
i,e., x1,y1
x2,y2
x3,y3
x4,y4
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 6
15CSL68 – Computer Graphics Lab Manual
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 7
15CSL68 – Computer Graphics Lab Manual
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 8
15CSL68 – Computer Graphics Lab Manual
You remember I had taught all the iterations via debug - breakpoints and an excel sheet which
kinda looked like this after 4th iteration?
and so on….
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 9
15CSL68 – Computer Graphics Lab Manual
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
float x1, x2, x3, x4, y1, y2, y3, y4; // our polygon has 4 lines - so 8 coordinates
void edgedetect(float x1, float y1, float x2, float y2, int *left_edge, int *right_edge)
{
float x_slope, x, temp;
int i;
temp = x1;
x1 = x2;
x2 = temp;
}
x = x1;
if (x > right_edge[i])
right_edge[i] = x;
x = x + x_slope;
}
}
void draw_pixel (int x, int y) // fill the polygon point by point (pixel by pixel)
{
glColor3f (1, 1, 0); // fill the RHOMBUS in yellow colour
glBegin (GL_POINTS);
glVertex2i (x, y);
glEnd ();
}
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 10
15CSL68 – Computer Graphics Lab Manual
void scanfill (float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4)
{
int left_edge[500], right_edge[500];
int i, y;
for (y = 0; y <= 500; y++) // now that you have calculated all values, start filling
{ from left edge to right edge row by row pixel by pixel
if (left_edge[y] <= right_edge[y])
{
for (i = left_edge[y]; i <= right_edge[y]; i++)
{
draw_pixel (i, y);
glFlush ();
}
}
}
}
void display()
{
x1 = 200, y1 = 200; // RHOMBUS coordinates
x2 = 100, y2 = 300;
x3 = 200, y3 = 400;
x4 = 300, y4 = 300;
glClear (GL_COLOR_BUFFER_BIT);
scanfill (x1, y1, x2, y2, x3, y3, x4, y4); // FILL the RHOMBUS
}
void init()
{
glClearColor (1, 1, 1, 1);
gluOrtho2D (0, 499, 0, 499);
}
init ();
glutDisplayFunc (display);
glutMainLoop ();
}
***********************************************************************************
OUTPUT
BMSIT & M, Bengaluru -560064 | Author: Mr. Shankar R, Asst. Prof, CSE 12