Uploaded by xyz004514

18CSL67 CG LAB Manual

advertisement
ATME COLLEGE OF ENGINEERING
13th KM Stone, Bannur Road, Mysore - 560 028
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
(ACADEMIC YEAR 2022-23)
LABORATORY MANUAL
SUBJECT: COMPUTER GRAPHICS LABORATORY WITH MINI PROJECT
SUBJECT CODE: 18CSL67
SEMESTER: VI
2018 CBCS Scheme
Prepared By
Mr. Rajiv
Programmer
Verified By
Dr. Mahesha Y
Mr. Sandesh R
Faculty Co-Ordinators
Approved By
Dr. Puttegowda D
Professor & Head, CSE
INSTITUTIONAL MISSION AND VISION
Objectives

To provide quality education and groom top-notch professionals, entrepreneurs
and leaders for different fields of engineering, technology and management.

To open a Training-R & D-Design-Consultancy cell in each department, gradually
introduce doctoral and postdoctoral programs, encourage basic & applied research
in areas of social relevance, and develop the institute as a center of excellence.

To develop academic, professional and financial alliances with the industry as
well as the academia at national and transnational levels.

To develop academic, professional and financial alliances with the industry as
well as the academia at national and transnational levels.

To cultivate strong community relationships and involve the students and the staff
in local community service.

To constantly enhance the value of the educational inputs with the participation of
students, faculty, parents and industry.
Vision

Development of academically excellent, culturally vibrant, socially responsible
and globally competent human resources.
Mission.

To keep pace with advancements in knowledge and make the students competitive
and capable at the global level.

To create an environment for the students to acquire the right physical,
intellectual, emotional and moral foundations and shine as torch bearers of
tomorrow's society.

To strive to attain ever-higher benchmarks of educational excellence.
Department of Computer Science & Engineering
Vision of the Department
 To develop highly talented individuals in Computer Science and Engineering to
deal with real world challenges in industry, education, research and society.
Mission of the Department
 To inculcate professional behavior, strong ethical values, innovative research
capabilities and leadership abilities in the young minds & to provide a teaching
environment that emphasizes depth, originality and critical thinking.
 Motivate students to put their thoughts and ideas adoptable by industry or to pursue
higher studies leading to research.
Program outcomes (POs)
Engineering Graduates will be able to:

PO1. Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems

PO2. Problem analysis: Identify, formulate, review research literature, and
analyze complex engineering problems reaching substantiated conclusions using
first principles of mathematics, natural sciences, and engineering sciences.

PO3. Design/development of solutions: Design solutions for complex
engineering problems and design system components or processes that meet the
specified needs with appropriate consideration for the public health and safety,
and the cultural, societal, and environmental considerations.

PO4. Conduct investigations of complex problems: Use research-based
knowledge and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide valid
conclusions.

PO5. Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the
limitations.

PO6. The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice

PO7. Environment and sustainability: Understand the impact of the
professional engineering solutions in societal and environmental contexts, and
demonstrate the knowledge of, and need for sustainable development.

PO8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.

PO9. Individual and team work: Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.

PO10. Communication: Communicate effectively on complex engineering
activities with the engineering community and with society at large, such as, being
able to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.

PO11. Project management and finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply these to
one’s own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.

PO12. Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change.
Program Educational Objectives (PEO'S):
1. Empower students with a strong basis in the mathematical, scientific and
engineering fundamentals to solve computational problems and to prepare them for
employment, higher learning and R&D.
2. Gain technical knowledge, skills and awareness of current technologies of computer
science engineering and to develop an ability to design and provide novel
engineering solutions for software/hardware problems through entrepreneurial
skills.
3. Exposure to emerging technologies and work in teams on interdisciplinary projects
with effective communication skills and leadership qualities.
4. Ability to function ethically and responsibly in a rapidly changing environment by
Applying innovative ideas in the latest technology, to become effective
professionals in Computer Science to bear a life-long career in related areas.
Program Specific Outcomes (PSOs)
1. Ability to apply skills in the field of algorithms, database design, web design, cloud
computing and data analytics..
2. Apply knowledge in the field of computer networks for building network and
internet based applications.
COMPUTER GRAPHICS LABORATORY WITH MINI PROJECT
Subject Code :
Hours/Week :
Total Hours :
18CSL67
0:2:2
36
CIE Marks :
SEE Marks :
Exam Hours :
40
60
03
Credits - 2
Course objectives: This course (18CSL67) will enable students to:
 Demonstrate simple algorithms using OpenGL Graphics Primitives and attributes.
 Implementation of line drawing and clipping algorithms using OpenGL functions
 Design and implementation of algorithms Geometric transformations on both 2D
and 3D objects.
Descriptions (if any): --
Installation procedure of the required software must be demonstrated, carried
out in groups and documented in the journal.
Programs List:
PART A
Design, develop, and implement the following programs using OpenGL API
1. Implement Brenham's line drawing algorithm for all types of slope.
Refer: Text-1: Chapter 3.5
Refer: Text-2: Chapter 8
2. Create and rotate a triangle about the origin and a fixed point.
Refer: Text-1: Chapter 5-4
3. Draw a colour cube and spin it using OpenGL transformation matrices.
Refer: Text-2: Modelling a Coloured Cube
4. Draw a color cube and allow the user to move the camera suitably to experiment with
perspective viewing.
Refer: Text-2: Topic: Positioning of Camera
5. Clip a line using Cohen-Sutherland algorithm.
Refer: Text-1: Chapter 6.7
Refer: Text-2: Chapter 8
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.
Refer: Text-2: Topic: Lighting and Shading
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.
Refer: Text-2: Topic: sierpinski gasket.
8. Develop a menu driven program to animate a flag using Bezier Curve algorithm.
Refer: Text-1: Chapter 8-10
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 VivaVoce)
Sample Topics:
Simulation of concepts of OS, Data structures, algorithms etc.
Laboratory outcomes: The students should be able to:

Apply the concepts of computer graphics

Implement computer graphics applications using OpenGL

Animate real world problems using OpenGL
Conduction of Practical Examination:

Experiment distribution



For laboratories having only one part: Students are allowed to pick one experiment
from the lot with equal opportunity.
For laboratories having PART A and PART B: Students are allowed to pick one
experiment from PART A and one experiment from PART B, with equal opportunity.
Change of experiment is allowed only once and marks allotted for procedure to be made
zero of the changed part only.

Marks Distribution (Courseed to change in accoradance with university regulations)
 For laboratories having only one part – Procedure + Execution + Viva-Voce:
15+70+15 =100 Marks
 For laboratories having PART A and PART B
i. Part A – Procedure + Execution + Viva = 6 + 28 + 6 = 40 Marks
ii. Part B – Procedure + Execution + Viva = 9 + 42 + 9 = 60 Marks
CONTENT LIST
SL.NO.
EXPERIMENT NAME
PAGE NO.
1
Introduction
1
2
Sample Programs
Program 1: Implement Brenham's line drawing algorithm for all
types of slope.
12
3
4
5
6
7
8
9
10
11
12
13
Program 2: Create and rotate a triangle about the origin and a
fixed point
Program 3: Draw a colour cube and spin it using OpenGL
transformation matrices.
Program 4: Draw a color cube and allow the user to move the
camera suitably to experiment with perspective viewing.
Program 5 Clip a line using Cohen-Sutherland algorithm.
Program 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.
Program 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.
Program 8: Develop a menu driven program to animate a flag
using Bezier Curve
Program 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.
Viva Questions and answers
31
35
39
45
50
57
62
67
72
77
78
Computer Graphics Laboratory With Mini Project
18CSL67
OpenGL
Introduction
OpenGL (Open Graphics Library) is a standard specification defining a cross-language, crossplatform API for writing applications that produce 2D and 3D Computer graphics. The interface
consists of over 250 different function calls which can be used to draw complex three-dimensional
scenes from simple primitives.
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:
 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. GLU routines use the
prefix glu.
 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. Provides
functionality common to all window systems
 Open a window
 Get input from mouse and keyboard
 Menus
 Event-driven
Code is portable but GLUT lacks the functionality of a good toolkit for a specific platform
 No slide bar
 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, highlevel 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.
Rendering Pipeline
Most implementations of OpenGL have a similar order of operations, a series of processing stages
called the OpenGL rendering pipeline. Although this is not a strict rule of how OpenGL is
implemented, it provides a reliable guide for predicting what OpenGL will do. Geometric data
(vertices, line, and polygons) follow a path through the row of boxes that includes evaluators and
per-vertex operations, while pixel data (pixels, images and bitmaps) are treated differently for part
of the process. Both types of data undergo the same final step (rasterization) before the final pixel
data is written to the frame buffer.
DEPT OF CSE, ATMECE
Page 1
Computer Graphics Laboratory With Mini Project
18CSL67
Display Lists: All data, whether it describes geometry or pixels, can be saved in a display list for
current or later use. (The alternative to retaining data in a display list is processing the data
immediately-known as immediate mode.) When a display list is executed, the retained data is sent
from the display list just as if it were sent by the application in immediate mode.
Evaluators: All geometric primitives are eventually described by vertices. Evaluators provide a
method for deriving the vertices used to represent the surface from the control points. The method
is a polynomial mapping, which can produce surface normal, colors, and spatial coordinate values
from the control points.
Per-Vertex and Primitive Assembly: For vertex data, the next step converts the vertices into
primitives. Some types of vertex data are transformed by 4x4 floating-point matrices. Spatial
coordinates are projected from a position in the 3D world to a position on your screen. In some
cases, this is followed by perspective division, which makes distant geometric objects appear
smaller than closer objects. Then view port and depth operations are applied. The results at this
point are geometric primitives, which are transformed with related color and depth 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 form
one of a variety of formats into the proper number of components. Next the data is scaled, biased,
processed by a pixel map, and sent to the rasterization step.
Rasterization: Rasterization is the conversion of both geometric and pixel data into fragments.
Each fragment square corresponds to a pixel in the frame buffer. Line width, point size, shading
DEPT OF CSE, ATMECE
Page 2
Computer Graphics Laboratory With Mini Project
18CSL67
model, and coverage calculations to support antialiasing are taken it to 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. The processed fragment is then drawn into the
appropriate buffer, where it has finally advanced to be a pixel and achieved its final resting place.
Libraries
OpenGL provides a powerful but primitive set of rendering command, and all higher-level
drawing must be done in terms of these commands. There are several libraries that allow you to
simplify your programming tasks, including the following:


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 and rendering surfaces.
OpenGL Utility Toolkit (GLUT) is a window-system-independent toolkit, written by Mark
Kilgard, to hide the complexities of differing window APIs.
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>
Note that glut.h guarantees that gl.h and glu.h are properly included for you so including these
three files is redundant. To make your GLUT programs portable, include glut.h and do not include
gl.h or glu.h explicitly.
The first things you will need are the OpenGL and GLUT header files and libraries for your current
Operating System.
Setting up Compilers
 Install OpenGL on Ubuntu
Here we will be looking at step by step process to install OpenGL:
Run the following commands to install OpenGL.
$ sudo apt-get update
$ sudo apt-get install libglu1-mesa-dev freeglut3-dev mesa-common-dev
To test if OpenGl libraries are working fine on our Linux, we will create a C/C++ program and
test it.
DEPT OF CSE, ATMECE
Page 3
Computer Graphics Laboratory With Mini Project
18CSL67
So create a following C/C++ Program.
Now give the command below to compile your code.
$ g++ sample.cc -lglut -lGLU –lGL
Now run your OpenGl program with following command
$ ./a.out
OUTPUT:
DEPT OF CSE, ATMECE
Page 4
Computer Graphics Laboratory With Mini Project
18CSL67
Initialization
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), where
argcp is a pointer to the program's unmodified argc variable from main. Upon return, the value
pointed to by argcp will be updated, and argv is the program's unmodified argv variable from
main. Like argcp, the data for argv will be updated.
The next thing we need to do is call the glutInitDisplayMode() procedure to specify the display
mode for a window. You must first decide whether you want to use an RGBA (GLUT_RGBA) or
color-index (GLUT_INDEX) color model. The RGBA mode stores its color buffers as red, green,
blue, and alpha color components. The forth color component, alpha, corresponds to the notion of
opacity. An alpha value of 1.0 implies complete opacity, and an alpha value of 0.0 complete
transparancy. Color-index mode, in contrast, stores color buffers in indices. Your decision on color
mode should be based on hardware availability and what you application requires. More colors
can usually be simultaneously represented with RGBA mode than with color-index mode. 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.
Another decision you need to make when setting up the display mode is whether you want to use
single buffering (GLUT_SINGLE) or double buffering (GLUT_DOUBLE). Applications that use
both front and back color buffers are double-buffered. Smooth animation is accomplished by
rendering into only the back buffer (which isn't displayed), then causing the front and back buffers
to be swapped. If you aren't using animation, stick with single buffering, which is the default.
Finally, you must decide if you want to use a depth buffer (GLUT_DEPTH), a stencil buffer
(GLUT_STENCIL) and/or an accumulation buffer (GLUT_ACCUM). The depth buffer stores a
depth value for each pixel. By using a "depth test", the depth buffer can be used to display objects
with a smaller depth value in front of objects with a larger depth value. The second buffer, the
stencil buffer is used to restrict drawing to certain portions of the screen, just as a cardboard stencil
can be used with a can of spray paint to make a printed image. Finally, the accumulation buffer is
used for accumulating a series of images into a final composed image. None of these are default
buffers.
We need to create the characteristics of our window. A call to glutInitWindowSize() will be used
to specify the size, in pixels, of your initial window. The arguments indicate the height and width
(in pixels) of the requested window. Similarly, glutInitWindowPosition() is used to specify the
screen location for the upper-left corner of your initial window. The arguments, x and y, indicate
the location of the window relative to the entire display.
Creating a Window
To actually create a window, the with the previously set characteristics (display mode, size,
location, etc), the programmer uses the glutCreateWindow() command. The command takes a
string as a parameter which may appear in the title bar if the window system you are using supports
it. The window is not actually displayed until the glutMainLoop() is entered.
Display Function
The glutDisplayFunc() procedure is the first and most important event callback function you will
see. A callback function is one where a programmer-specified routine can be registered to be called
in response to a specific type of event. For example, the argument of glutDisplayFunc() is the
function that is called whenever GLUT determines that the contents of the window needs to be
DEPT OF CSE, ATMECE
Page 5
Computer Graphics Laboratory With Mini Project
18CSL67
redisplayed. Therefore, you should put all the routines that you need to draw a scene in this display
callback function.
Reshape Function
The glutReshapeFunc() is a callback function that specifies the function that is called whenever
the window is resized or moved. Typically, the function that is called when needed by the reshape
function displays the window to the new size and redefines the viewing characteristics as desired.
If glutReshapeFunc() is not called, a default reshape function is called which sets the view to
minimize distortion and sets the display to the new height and width.
Main Loop
The very last thing you must do is call glutMainLoop(). All windows that have been created can
now be shown, and rendering those windows is now effective. The program will now be able to
handle events as they occur (mouse clicks, window resizing, etc). In addition, the registered
display callback (from our glutDisplayFunc()) is triggered. Once this loop is entered, it is never
exited!
Geometric Objects used in graphics
Point, Lines and Polygons
Each geometric object is described by a set of vertices and the type of primitive to be drawn. A
vertex is no more than a point defined in three dimensional space. Whether and how these vertices
are connected is determined by the primitive type. Every geometric object is ultimately described
as an ordered set of vertices. We use the glVertex*() command to specify a vertex. The '*' is used
to indicate that there are variations to the base command glVertex().
DEPT OF CSE, ATMECE
Page 6
Computer Graphics Laboratory With Mini Project
18CSL67
Some OpenGL command names have one, two, or three letters at the end to denote the number
and type of parameters to the command. The first character indicates the number of values of the
indicated type that must be presented to the command. The second character indicates the specific
type of the arguments. The final character, if present, is 'v', indicating that the command takes a
pointer to an array (a vector) of values rather than a series of individual agreements.
For example, in the command glVertex3fv(), '3' is used to indicate three arguments, 'f' is used to
indicate the arguments are floating point, and 'v' indicates that the arguments are in vector format.
Points: A point is represented by a single vertex. Vertices specified by the user as two dimensional
(only x- and y-coordinates) are assigned a z-coordinate equal to zero. To control the size of a
rendered point, use glPointSize() and supply the desired size in pixels as the argument. The default
is as 1 pixel by 1 pixel point. If the width specified is 2.0, the point will be a square of 2 by 2
pixels. glVertex*() is used to describe a point, but it is only effective between a glBegin() and a
glEnd() pair. The argument passed to glBegin() determines what sort of geometric primitive is
constructed from the vertices.
Lines: In OpenGL, the term line refers to a line segment, not the mathematician's version that
extends to infinity in both directions. The easiest way to specify a line is in terms of the vertices
at the endpoints. As with the points above, the argument passed to glBegin() tells it what to do
with the vertices. The option for lines includes:
GL_LINES: Draws a series of unconnected line segments drawn between each set of vertices.
An extraneous vertex is ignored.
GL_LINE_STRIP: Draws a line segment from the first vertex to the last. Lines can intersect
arbitrarily.
GL_LINE_LOOP: Same as GL_STRIP, except that a final line segment is drawn from the last
vertex back to the first.
With OpenGL, the description of the shape of an object being drawn is independent of the
description of its color. When a particular geometric object is drawn, it's drawn using the currently
specified coloring scheme. In general, an OpenGL programmer first sets the color, using
glColor*() and then draws the objects. Until the color is changed, all objects are drawn in that
color or using that color scheme.
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 with the
pixels in the interior filled in, but you can also draw them as outlines or a set of points. In OpenGL,
there are a few restrictions on what constitutes a primitive polygon. For example, the edges of a
polygon cannot intersect and they must be convex (no indentations). There are special commands
for a three-sided (triangle) and four-sided (quadrilateral) polygons, glBegin(GL_TRIANGLES)
and glBegin(GL_QUADS), respectively. However, the general case of a polygon can be defined
using glBegin(GL_POLYGON).
Drawing 3-D Objects
GLUT has a series of drawing routines that are used to create three-dimensional models. This
means we don't have to reproduce the code necessary to draw these models in each program. These
routines render all their graphics in immediate mode. Each object comes in two flavors, wire or
solid. Available objects are:
DEPT OF CSE, ATMECE
Page 7
Computer Graphics Laboratory With Mini Project
18CSL67
Transformations
A modeling transformation is used to position and orient the model. For example, you can rotate,
translate, or scale the model - or some combination of these operations. To make an object appear
further away from the viewer, two options are available - the viewer can move closer to the object
or the object can be moved further away from the viewer. Moving the viewer will be discussed
later when we talk about viewing transformations. For right now, we will keep the default
"camera" location at the origin, pointing toward the negative z-axis, which goes into the screen
perpendicular to the viewing plane.
When transformations are performed, a series of matrix multiplications are actually performed to
affect the position, orientation, and scaling of the model. You must, however, think of these matrix
multiplications occurring in the opposite order from how they appear in the code. The order of
transformations is critical. If you perform transformation A and then perform transformation B,
you almost always get something different than if you do them in the opposite order.
Scaling: The scaling command glScale() multiplies the current matrix by a matrix that stretches,
shrinks, or reflects an object along the axes. Each x-, y-, and z-coordinate of every point in the
object is multiplied by the corresponding argument x, y, or z. The glScale*() is the only one of the
three modeling transformations that changes the apparent size of an object: scaling with values
greater than 1.0 stretches an object, and using values less than 1.0 shrinks it. Scaling with a -1.0
value reflects an object across an axis.
Translation: The translation command glTranslate() multiplies the current matrix by a matrix that
moves (translates) an object by the given x-, y-, and z-values.
Rotation: The rotation command glRotate() multiplies the current matrix that rotates an object in
a counterclockwise direction about the ray from the origin through the point (x,y,z). The angle
parameter specifies the angle of rotation in degrees. An object that lies farther from the axis of
rotation is more dramatically rotated (has a larger orbit) than an object drawn near the axis.
Projections in OpenGL
Perspective projection
DEPT OF CSE, ATMECE
Page 8
Computer Graphics Laboratory With Mini Project
18CSL67
void glFrustum(GLdouble left, GLdouble right, GLdouble bottom,GLdouble top, GLdouble near,
GLdouble far);
Orthographic projection
void glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdou-ble near,
GLdouble far)
OBJECTIVE AND APPLICATION OF THE LAB
The objective of this lab is to give students hands on learning exposure to understand and apply
computer graphics with real world problems. The lab gives the direct experience to Visual Basic
Integrated Development Environment (IDE) and GLUT toolkit. The students get a real world
exposure to Windows programming API. Applications of this lab are profoundly felt in gaming
industry, animation industry and Medical Image Processing Industry. The materials learned here
will useful in Programming at the Software Industry.
Setting up GLUT - main() GLUT provides high-level utilities to simplify OpenGL programming,
especially in interacting with the Operating System (such as creating a window, handling key and
mouse inputs). The following GLUT functions were used in the above program:
 glutInit: initializes GLUT, must be called before other GL/GLUT functions. It takes the same
arguments as the main(). void glutInit(int *argc, char **argv)
 glutCreateWindow: creates a window with the given title. int glutCreateWindow(char *title)
 glutInitWindowSize: species the initial window width and height, in pixels. void
glutInitWindowSize(int width, int height)
 glutInitWindowPosition: positions the top-left corner of the initial window at (x, y). The
coordinates (x, y), in term of pixels, is measured in window coordinates, i.e., origin (0, 0) is at the
DEPT OF CSE, ATMECE
Page 9
Computer Graphics Laboratory With Mini Project
18CSL67
top-left corner of the screen; x-axis pointing right and y-axis pointing down. void
glutInitWindowPosition(int x, int y)
 glutDisplayFunc: registers the callback function (or event handler) for handling
window-paint event. The OpenGL graphic system calls back this handler when it receives a
window re-paint request. In the example, we register the function display() as the handler. void
glutDisplayFunc(void (*func)(void))
 glutMainLoop: enters the innite event-processing loop, i.e, put the OpenGL graphics system to
wait for events (such as re-paint), and trigger respective event handlers (such as display()). void
glutMainLoop()
 glutInitDisplayMode: requests a display with the specied mode, such as color
 mode (GLUTRGB, GLUTRGBA, GLUTINDEX ), single/double buering (GLUT SINGLE ,
GLUTDOUBLE ), enable depth (GLUTDEPTH ), joined with a bit OR '|'. void glutInitDisplayMode(unsigned int displayMode)
 void glMatrixMode (GLenum mode); The glMatrixMode function species which matrix is the
current matrix.
 void glOrtho(GLdouble left,GLdouble right,GLdouble bottom,GLdouble top,GLdouble
zNear,GLdouble zFar) The glOrtho function multiplies the current matrix by an orthographic
matrix.
 void glPointSize (GLoat size); The glPointSize function species the diameter of rasterized
points.
 void glutPostRedisplay(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 ras-terization
mode.
 void glRotatef (GLoat angle, GLoat x, GLoat y, GLoat); The glRotatef functions multiply the
current matrix by a rotation matrix.
void glScalef (GLoat x, GLoat y, GLoat z); The glScalef functions multiply the current matrix by
a general scaling matrix.
void glTranslatef (GLoat x, GLoat y, GLoat z); The glTranslatef functions multiply the current
matrix by a translation matrix.
void glViewport (GLint x, GLint y, GLsizei width, GLsizei height); The glView-port function
sets the viewport.
void glEnable, glDisable(); The glEnable and glDisable functions enable or dis-able OpenGL
capabilities.
DEPT OF CSE, ATMECE
Page 10
Computer Graphics Laboratory With Mini Project
18CSL67
glutBitmapCharacter(); The glutBitmapCharacter function used for font style.
Sample Programs
Creating a Window:
#include<GL/glut.h>
void display () /* callback function which is called when OpenGL needs to update the display */
{
DEPT OF CSE, ATMECE
Page 11
Computer Graphics Laboratory With Mini Project
18CSL67
glClearColor (1.0,1.0,0.0,0.0);/*default color –black…….. Now set to YELLOW */
glClear (GL_COLOR_BUFFER_BIT);/*Clear the window-set the color of pixels in buffer*/
glFlush(); /* Force update of screen */
}
void main (int argc, char **argv)
{
glutInit (&argc, argv); /* Initialise OpenGL */
glutCreateWindow ("Example1"); /* Create the window */
glutDisplayFunc (display); /* Register the "display" function */
glutMainLoop (); /* Enter the OpenGL main loop */
}
Activity 1:
Change the window size to 500, 500
Change the window position to 100, 100
Change the window color to CYAN
#include<GL/glut.h>
void display (void)
{
DEPT OF CSE, ATMECE
Page 12
Computer Graphics Laboratory With Mini Project
18CSL67
glClearColor (0.0,1.0,1.0,0.0);
glClear (GL_COLOR_BUFFER_BIT);
glFlush();
}
void main (int argc, char **argv)
{
glutInit (&argc, argv); /* Initialise OpenGL */
glutInitWindowSize(500,500);
glutInitWindowPosition(100,100);
glutCreateWindow ("Activity1"); /* Create the window */
glutDisplayFunc (display); /* Register the "display" function */
glutMainLoop (); /* Enter the OpenGL main loop */
}
Drawing pixels/points :
#include<GL/glut.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
glVertex2i(100,300);
DEPT OF CSE, ATMECE
Page 13
Computer Graphics Laboratory With Mini Project
18CSL67
glVertex2i(201,300);
glEnd();
glFlush();
}
void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);// set the window color to white
glColor3f(1.0,0.0,0.0);// set the point color to red (RGB)
glPointSize(5.0);// set the pixel size
gluOrtho2D(0.0,500.0,0.0,500.0);// coordinates to be used with the
viewport(left,right,bottom,top)
}
void main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);// sets the initial display mode, GLUT
single-default
glutInitWindowSize(300,300);
glutInitWindowPosition(0,0);
glutCreateWindow("Example2");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Activity 2
Change the window color to BLUE
Change the point color to CYAN
Change the point width to 10
Draw FIVE points: at 4 corners of the window and one more at the Centre of the window.
DEPT OF CSE, ATMECE
Page 14
Computer Graphics Laboratory With Mini Project
18CSL67
#include<GL/glut.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POINTS);
glVertex2i(10,10);
glVertex2i(250,250);
glVertex2i(10,490);
glVertex2i(490,490);
glVertex2i(490,10);
glEnd();
glFlush();
}
void myinit()
{
glClearColor(0.0,0.0,1.0,0.0);// set the window color to blue
glColor3f(0.0,1.0,1.0);// set the point color to cyan (RGB)
glPointSize(10.0);
gluOrtho2D(0.0,500.0,0.0,500.0);// coordinates to be used with the viewport
(left,right,bottom,top)
}
void main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Activity2");
DEPT OF CSE, ATMECE
Page 15
Computer Graphics Laboratory With Mini Project
18CSL67
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Drawing lines :
#include<GL/glut.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0); //draw the line with red color
glLineWidth(3.0); // Thickness of line
glBegin(GL_LINES);
glVertex2d (50,50);
// to draw horizontal line in red color
glVertex2d (150,50);
glColor3f(0.0,0.0,1.0); //draw the line with blue color
glVertex2d (200,200); // to draw vertical line in blue color
glVertex2d (200,300);
glEnd();
glFlush();
}
void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
glPointSize(1.0);
gluOrtho2D(0.0,500.0,0.0,500.0);
DEPT OF CSE, ATMECE
Page 16
Computer Graphics Laboratory With Mini Project
18CSL67
}
void main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(100,100);
glutCreateWindow("LINE");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Activity 3
Change the window color to MAGENTA
Change the line color to YELLOW
Change the line width to width to 4
Draw a square using 4 lines
#include<GL/glut.h>
DEPT OF CSE, ATMECE
Page 17
Computer Graphics Laboratory With Mini Project
18CSL67
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,1.0,0.0);
glLineWidth(4.0);
glBegin(GL_LINES);
glVertex2d (50, 100);
glVertex2d (100, 100);
glVertex2d (100, 100);
glVertex2d (100, 150);
glVertex2d (100, 150);
glVertex2d (50, 150);
glVertex2d (50, 150);
glVertex2d (50, 100);
glEnd();
glFlush();}
void myinit()
{
glClearColor(1.0,0.0,1.0,1.0);
gluOrtho2D(0.0,200.0,0.0,200.0);
}
void main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(10,100);
DEPT OF CSE, ATMECE
Page 18
Computer Graphics Laboratory With Mini Project
18CSL67
glutCreateWindow("Square");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Drawing a square using LINE_LOOP:
#include<GL/glut.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 1.0);
glLineWidth(3.0);
glBegin(GL_LINE_LOOP); // If you put GL_LINE_LOOP, it is only boundary.
glVertex2f(50, 50);
glVertex2f(200, 50);
glVertex2f(200, 200);
glVertex2f(50, 200);
glEnd();
glFlush();
}
void myinit()
{
glClearColor(1.0,1.0,0.0,1.0);
gluOrtho2D(0.0,499.0,0.0,499.0);
}
void main(int argc, char** argv)
DEPT OF CSE, ATMECE
Page 19
Computer Graphics Laboratory With Mini Project
18CSL67
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(300,300);
glutInitWindowPosition(0,0);
glutCreateWindow("LINE LOOP");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Activity 4
Change the window color to PURPLE
Change the line color to GREEN
Change the line width to width to 3
Draw a square using GL_POLYGON
#include<GL/glut.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 1.0, 0.0);// set line color to green
glLineWidth(3.0);
glBegin(GL_POLYGON);
glVertex2f(50, 50);
glVertex2f(200, 50);
glVertex2f(200, 200);
glVertex2f(50, 200);
glEnd();
}
DEPT OF CSE, ATMECE
Page 20
Computer Graphics Laboratory With Mini Project
18CSL67
void myinit()
{
glClearColor(0.5,0.0,0.5,1.0); // set window color to purple
gluOrtho2D(0.0,499.0,0.0,499.0);
}
void main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(300,300);
glutInitWindowPosition(0,0);
glutCreateWindow("POLYGON");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Drawing a right angled triangle using GL_TRINGLES
#include<GL/glut.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 1.0, 0.0);// set line color to green
glLineWidth(3.0);
glBegin(GL_POLYGON);
DEPT OF CSE, ATMECE
Page 21
Computer Graphics Laboratory With Mini Project
18CSL67
glVertex2f(50, 50);
glVertex2f(200, 50);
glVertex2f(200, 200);
glVertex2f(50, 200);
glEnd();
glFlush();
}
void myinit()
{
glClearColor(0.0,0.0,0.0,0.0);
gluOrtho2D(0.0,499.0,0.0,499.0);
}
void main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(300,300);
glutInitWindowPosition(0,0);
glutCreateWindow("TRIANGLE");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
Writing Text
#include<GL/glut.h>
void output(GLfloat x,GLfloat y,char *text)
{
char *p;
glPushMatrix();
glTranslatef(x,y,0);
DEPT OF CSE, ATMECE
Page 22
Computer Graphics Laboratory With Mini Project
18CSL67
glScaled(0.2,0.2,0);
for(p=text;*p;p++)
glutStrokeCharacter(GLUT_STROKE_ROMAN,*p);
glPopMatrix();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
output(10,300,"ATME COLLEGE OF ENGINEERING");
glFlush();
}
void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
gluOrtho2D(0.0,499.0,0.0,499.0);
}
void main(int argc,char ** argv)
{
glutInit(&2wargc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("ATME");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
DEPT OF CSE, ATMECE
Page 23
Computer Graphics Laboratory With Mini Project
18CSL67
Drawing colored line and writing Text
#include<GL/glut.h>
#include<string.h>
char *str= "GRAPHICS";
void display()
{
int i;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glLineWidth(10.0);
glBegin(GL_LINES);
glVertex2f(0.0,0.0);
glColor3f(0.0,1.0,0.0);
glVertex2f(0.0,0.8);
glEnd();
glColor3f(0.0,1.0,1.0);
glRasterPos2f(-0.2,-0.1);
//font type character to be displayed
for(i=0;i<strlen(str);i++)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,str[i]);
glFlush();
}
void myinit()
{
glClearColor(0.0,0.0,0.0,0.0);
gluOrtho2D(-1.0,1.0,-1.0,1.0);
}
DEPT OF CSE, ATMECE
Page 24
Computer Graphics Laboratory With Mini Project
18CSL67
void main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("Coloured Line");
myinit();
glutDisplayFunc(display);
glutMainLoop();
}
Activity 5
Change the window color to BLACK
Set the font to GLUT_STROKE_MONO_ROMAN
Display “GRAPICS IS FUN!” in YELLOW color
Display “REALLY FUN!” in RED color in the next line
#include<GL/glut.h>
void output(GLfloat x,GLfloat y,char *text)
{
char *p;
glPushMatrix();
glTranslatef(x,y,0);
glScaled(0.2,0.2,0);
for(p=text;*p;p++)
glutStrokeCharacter( GLUT_STROKE_MONO_ROMAN,*p);
DEPT OF CSE, ATMECE
Page 25
Computer Graphics Laboratory With Mini Project
18CSL67
glPopMatrix();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
output(70,300,"GRAPHICS IS FUN!");
glColor3f(1.0,0.0,0.0);
output(120,250,"REALLY FUN!");
glFlush();
}
void myinit()
{
glClearColor(0.0,0.0,0.0,0.0);
glColor3f(1.0,1.0,0.0);
gluOrtho2D(0.0,499.0,0.0,499.0);
}
void main(int argc,char ** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("STROKE TEXT”);
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
DEPT OF CSE, ATMECE
Page 26
Computer Graphics Laboratory With Mini Project
18CSL67
Drawing a colored square
#include<GL/glut.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 1.0, 0.0); // Green
glBegin(GL_POLYGON);
glVertex2f(100, 100);
glColor3f(1.0,0.0,0.0); // Red
glVertex2f(300, 100);
glColor3f(0.0,0.0,1.0); // Blue
glVertex2f(300, 300);
glColor3f(1.0,1.0,0.0); // Yellow
glVertex2f(100, 300);
glEnd();
glFlush();
}
void myinit()
{
glClearColor(0.0,0.0,0.0,1.0);
glColor3f(1.0,0.0,0.0);// Red
gluOrtho2D(0.0,499.0,0.0,499.0);
}
void main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
DEPT OF CSE, ATMECE
Page 27
Computer Graphics Laboratory With Mini Project
18CSL67
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("COLORED SQUARE");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
DEPT OF CSE, ATMECE
Page 28
Computer Graphics Laboratory With Mini Project
18CSL67
Creating 2 view ports
#include<GL/glut.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glViewport (5,-150,400,400);
glBegin(GL_POLYGON);
glColor3f(1.0,0.0,0.0);
glVertex2f(90,250);
glColor3f(0.0,1.0,0.0);
glVertex2f(250,250);
glColor3f(0.0,0.0,1.0);
glVertex2f(175,400);
glEnd();
glViewport (300,300,400,400);
glBegin(GL_POLYGON);
glColor3f(1.0,0.0,0.0);
glVertex2f(50,50);
glColor3f(0.0,1.0,0.0);
glVertex2f(250,50);
glColor3f(0.0,0.0,1.0);
glVertex2f(250,250);
glColor3f(0.0,1.0,1.0);
glVertex2f(50,250);
glEnd();
glFlush();
}
DEPT OF CSE, ATMECE
Page 29
Computer Graphics Laboratory With Mini Project
18CSL67
voidmyinit()
{
glClearColor(0.0,0.0,0.0,1.0);
gluOrtho2D(0.0,499.0,0.0,499.0);
}
void main(intargc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("2 VIEW PORTS");
glutDisplayFunc(display);
myinit();
glutMainLoop();
}
DEPT OF CSE, ATMECE
Page 30
Computer Graphics Laboratory With Mini Project
18CSL67
1. PART A
Design, develop, and implement the following programs in C/C++ using OpenGL API.
1.1 Bresenham's Line Drawing
Implement Brenham's line drawing algorithm for all types of slope.
1.1.1 PREAMBLE
Bresenham's line algorithm is an algorithm that determines the points of an n-dimensional raster
that should be selected in order to form a close approximation to a straight line between two points.
It is commonly used to draw line primitives in a bitmap image (e.g. on a computer screen), as it
uses only integer addition, sub-traction and bit shifting, all of which are very cheap operations in
standard computer architectures.
It is an incremental error algorithm. It is one of the earliest algorithms developed in the field of
computer graphics. An extension to the original algorithm may be used for drawing circles.
While algorithms such as Wu's algorithm are also frequently used in modern computer graphics
because they can support antialiasing, the speed and simplicity of Bresenham's line algorithm
means that it is still important.
The algorithm is used in hardware such as plotters and in the graphics chips of modern graphics
cards. It can also be found in many software graphics libraries. Because the algorithm is very
simple, it is often implemented in either the rmware or the graphics hardware of modern graphics
cards.
Concepts Used:
 Line equations
 Interger arithmetic
Algorithm:
Pseudo Code OpenGL commands Familiarised :
 glutInit
 glutInitDisplayMode
 glClearColor
 glColor
 glPointSize
 glOrtho
DEPT OF CSE, ATMECE
Page 31
Computer Graphics Laboratory With Mini Project
18CSL67
Program 1: Implement Brenham’s line drawing algorithm for all types of slope.
Program Objective:



creation of 2D objects
Implement GLU and GLUT functions
To have the detailed knowledge of the graphics Brenham's line algorithm.
/* Brenham's line */
#include<GL/glut.h>
#include<stdio.h>
int x1,x2,y1,y2;
void myInit()
{
glClearColor(0.0,0.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,500,0,500);
}
void draw_pixel(int x,int y)
{
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
}
void draw_line(int x1,int x2,int y1,int y2)
{
int dx,dy,i,e;
int incx,incy,inc1,inc2;
int x,y;
dx=x2-x1;
dy=y2-y1;
if(dx<0)
dx=-dx;
if(dy<0)
dy=-dy;
incx=1;
if(x2<x1)
incx=-1;
incy=1;
if(y2<y1)
incy=-1;
x=x1;
y=y1;
if(dx>dy)
{
draw_pixel(x,y);
e=2*dy-dx;
DEPT OF CSE, ATMECE
Page 32
Computer Graphics Laboratory With Mini Project
18CSL67
inc1=2*(dy-dx);
inc2=2*dy;
for(i=0;i<dx;i++)
{
if(e>=0)
{
y+=incy;
e+=inc1;
}
else
e+=inc2;
x+=incx;
draw_pixel(x,y);
}
}
else
{
draw_pixel(x,y);
e=2*dx-dy;
inc1=2*(dx-dy);
inc2=2*dx;
for(i=0;i<dy;i++)
{
if(e>=0)
{
x+=incx;
e+=inc1;
}
else
e+=inc2;
y+=incy;
draw_pixel(x,y);
}
}
}
void myDisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
draw_line(x1,x2,y1,y2);
glFlush();
}
int main(int argc,char **argv)
{
printf("enter x1,x2,y1,y2\n");
scanf("%d%d%d%d",&x1,&x2,&y1,&y2);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("win");
DEPT OF CSE, ATMECE
Page 33
Computer Graphics Laboratory With Mini Project
18CSL67
glutDisplayFunc(myDisplay);
myInit();
glEnable(GL_DEPTH_TEST);
glClearColor(0.0,0.0,0.0,0.0);
glutMainLoop();
}
RUN:
gcc 1.c -lglut -lGL –lGLU
./a.out
Enter x1, x2, y1, y2
40 140
40 280
SAMPLE OUTPUT:
Program Outcome:



Ability to Design and develop 2D objects for different graphics applications.
Use matrix algebra in computer graphics and implement Brenham's line algorithm.
Analyze and evaluate the use of openGL methodss in practical applications of 2D
representations.
DEPT OF CSE, ATMECE
Page 34
Computer Graphics Laboratory With Mini Project
18CSL67
1.2 Triangle Rotation
Create and rotate a triangle about the origin and a fixed point.
1.2.1 PREAMBLE
In linear algebra, a rotation matrix is a matrix that is used to perform a rotation in Euclidean
space. For example the matrix rotates points in the xy-Cartesian plane counterclockwise
through an angle about the origin of the Cartesian coordinate system. To perform the rotation
using a rotation matrix R, the position of each point must be represented by a column vector v,
containing the coordinates of the point.
A rotated vector is obtained by using the matrix multiplication Rv. Since matrix multiplication
has no effect on the zero vector (i.e., on the coordinates of the origin), rotation matrices can
only be used to describe rotations about the origin of the coordinate system.
Rotation matrices provide a simple algebraic description of such rotations, and are used
extensively for computations in geometry, physics, and computer graphics. In 2-dimensional
space, a rotation can be simply described by an angle of rotation, but it can be also represented
by the 4 entries of a rotation matrix with 2 rows and 2 columns. In 3-dimensional space, every
rotation can be interpreted as a rotation by a given angle about a single fixed axis of rotation
(see Euler's rotation theorem), and hence it can be simply described by an angle and a vector
with 3 entries. However, it can also be represented by the 9 entries of a rotation matrix with 3
rows and 3 columns.
The notion of rotation is not commonly used in dimensions higher than 3; there is a notion of
a rotational displacement, which can be represented by a matrix, but no associated single axis
or angle.
Concepts Used: Algorithm: Pseudo Code OpenGL commands Familiarised:
glutInit
glutInitDisplayMode
glClearColor
glColor
glPointSize
glOrtho
DEPT OF CSE, ATMECE
Page 35
Computer Graphics Laboratory With Mini Project
18CSL67
Program 2: Create and rotate a triangle about the origin and a fixed point.
Program Objective:



creation of 2D objects
Create 2D Triangle with basic transformation operations like rotation.
Use mathematical and theoretical principles i.e transformation matrices of computer
graphics to draw and rotate Triangle object.
/* Triangle Rotation */
#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 draw_pixel(float x1, float y1)
{
glPointSize(5);
glBegin(GL_POINTS);
glVertex2f(x1,y1);
// plot a single point
glEnd();
}
void triangle(int x, int y)
{
glColor3f(1,0,0);
glBegin(GL_POLYGON); // drawing a Triangle
glVertex2f(x,y);
glVertex2f(x+400,y+300);
glVertex2f(x+300,y+0);
glEnd();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glColor3f(1,1,1);
draw_pixel(0,0);
// mark origin point as white dot
// plot origin - white colour
if (where_to_rotate == 1) //Rotate Around origin
{
translate_x = 0;
// no translation for rotation around origin
translate_y = 0;
rotate_angle += 1;
// the amount of rotation angle
}
DEPT OF CSE, ATMECE
Page 36
Computer Graphics Laboratory With Mini Project
18CSL67
if (where_to_rotate == 2) //Rotate Around Fixed Point
{
translate_x = x;
// SET the translation to wherever the customer says
translate_y = y;
rotate_angle += 1; // the amount of rotation angle
glColor3f(0,0,1);
// mark the customer coordinate as blue dot
draw_pixel(x,y);
// plot the customer coordinate - blue colour
}
glTranslatef(translate_x, translate_y, 0); // ACTUAL translation +ve
glRotatef(rotate_angle, 0, 0, 1);
// rotate
glTranslatef(-translate_x, -translate_y, 0); // ACTUAL translation -ve
triangle(translate_x,translate_y);
glutPostRedisplay();
glutSwapBuffers();
// what to rotate? - TRIANGLE
// call display function again and again
// show the output
}
void init()
{
glClearColor(0,0,0,1); //setting to black
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-800, 800, -800, 800);
glMatrixMode(GL_MODELVIEW);
}
void rotateMenu (int option)
{
if(option==1)
where_to_rotate=1;
// rotate around origin
if(option==2)
where_to_rotate=2;
// rotate around customer's coordinates
if(option==3)
where_to_rotate=3;
// stop rotation
}
int main(int argc, char **argv)
{
printf( "Enter Fixed Points (x,y) for Rotation: \n");
scanf("%d %d", &x, &y);
// getting the user's coordinates to rotate
glutInit(&argc, argv);
// initialize the graphics system
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB); // SINGLE also works
glutInitWindowSize(800, 800); // 800 by 800 size..you can change it
glutInitWindowPosition(0, 0);
// where do you wanna see your window
glutCreateWindow("Create and Rotate Triangle"); // title
init();
DEPT OF CSE, ATMECE
// initialize the canvas
Page 37
Computer Graphics Laboratory With Mini Project
glutDisplayFunc(display);
18CSL67
// call display function
glutCreateMenu(rotateMenu); // menu items
glutAddMenuEntry("Rotate around ORIGIN",1);
glutAddMenuEntry("Rotate around FIXED POINT",2);
glutAddMenuEntry("Stop Rotation",3);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
// run forever
}
RUN:
g++ 2.cc -lglut -lGL -lGLU
./a.out
Enter Fixed Points (x,y) for Rotation:
100
100
SAMPLE OUTPUT:
DEPT OF CSE, ATMECE
Page 38
Computer Graphics Laboratory With Mini Project
18CSL67
Program Outcome:




Ability to Design and develop 2D objects for different graphics applications.
Use matrix algebra in computer graphics and implement fundamental transformations
involved in transformation operation.
Ability to draw objects like Triangle using basic objects like points and lines.
Analyze and evaluate the use of openGL methodss in practical applications of 2D
representations.
DEPT OF CSE, ATMECE
Page 39
Computer Graphics Laboratory With Mini Project
18CSL67
1.3 Color cube and spin
Draw a color cube and spin it using OpenGL transformation matrices.
1.3.1 PREAMBLE
Concepts Used:
Data structures for representing a cube
Rotation Transformation
Algorithm:
Modeling a color cube with simple data structures
Define vertices with centre of cube as origin
Define normals to identify faces
Define colors
Rotating the cube
Define angle of rotation [or accept it as input]
Define/Input rotation axis
Use swap-buffer to ensure smooth rotation
Using callback functions to indicate either or both of the following:
 Angle of rotation
 Axis of rotation
1. Define global arrays for vertices and colors
GLfloat vertices [][3] = {{-1.0,-1.0,-1.0}, {1.0,-1.0,-1.0}, {1.0,1.0,-1.0}, {-1.0,1.0,-1.0},
{-1.0,-1.0, 1.0}, {1.0,-1.0, 1.0}, {1.0, 1.0, 1.0}, {-1.0, 1.0, 1.0}};
GLfloat colors[][3] = {{0.0,0.0,0.0},{1.0,0.0,0.0}, {1.0,1.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0},
{1.0,0.0,1.0}, {1.0,1.0,1.0}, {0.0,1.0,1.0}};
2. Draw a polygon from a list of indices into the array vertices and use color corresponding to first
index
void polygon(int a, int b, int c, int d)
{
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glVertex3fv(vertices[b]);
glVertex3fv(vertices[c]);
glVertex3fv(vertices[d]);
glEnd();
}
3. Draw cube from faces.
void colorcube( )
{
polygon(0,3,2,1);
polygon(2,3,7,6);
polygon(0,4,7,3);
DEPT OF CSE, ATMECE
Page 40
Computer Graphics Laboratory With Mini Project
18CSL67
polygon(1,2,6,5);
polygon(4,5,6,7);
polygon(0,1,5,4);
}
4. Define the Display function to clear frame buffer, Z-buffer, rotate cube and draw, swap buffers.
void display(void)
{
/* display callback, clear frame buffer and z buffer,
rotate cube and draw, swap buffers */
glLoadIdentity();
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
colorcube();
glutSwapBuffers();
}
5. Define the spin cube function to spin cube 2 degrees about selected axis.
6. Define mouse callback to select axis about which to rotate.
7. Define reshape function to maintain aspect ratio.
void myReshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho(-2.0, 2.0, -2.0 * (GLfloat) h / (GLfloat) w,2.0 * (GLfloat) h / (GLfloat) w, -10.0, 10.0);
else
glOrtho(-2.0 * (GLfloat) w / (GLfloat) h,2.0 * (GLfloat) w / (GLfloat) h, -2.0, 2.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
}
8. Define main function to create window and to call all function.
DEPT OF CSE, ATMECE
Page 41
Computer Graphics Laboratory With Mini Project
18CSL67
OpenGL Commands Familiarized:
glRotate
glMatrixMode
glMouseFunc. and/or glKeyboardFunc
glEnable
glutSwapBuffer
glutIdleFunc
DEPT OF CSE, ATMECE
Page 42
Computer Graphics Laboratory With Mini Project
18CSL67
Program 3: Draw a color cube and spin it using OpenGL transformation matrices.
Program Objective:



creation of 3D objects
Create 3D-color cube with basic transformation operations like rotation.
Use mathematical and theoretical principles i.e transformation matrices of computer graphics
to draw the color cube object.
/* Color cube and spin */
#include<GL/glut.h>
#include<stdio.h>
GLfloat vertices[][3]={{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},{1.0,1.0,-1.0},{-1.0,1.0,-1.0},
{-1.0,-1.0,1.0},{1.0,-1.0,1.0},{1.0,1.0,1.0},{-1.0,1.0,1.0}};
GLfloat colors[][3]={{0.0,0.0,0.0},{0.0,0.0,1.0},{0.0,1.0,0.0},{0.0,1.0,1.0},{1.0,0.0,0.0},
{1.0,0.0,1.0},{1.0,1.0,0.0},{1.0,1.0,1.0}};
static GLfloat theta[]={0.0,0.0,0.0};
static GLint axis=2;
static GLdouble viewer[]={0,0,5};
void polygon(int a,int b,int c,int d)
{
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glColor3fv(colors[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube()
{
polygon(0,3,2,1);
polygon(2,3,7,6);
polygon(1,2,6,5);
polygon(0,4,5,1);
polygon(4,5,6,7);
polygon(0,3,7,4);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(theta[0],1.0,0.0,0.0);
glRotatef(theta[1],0.0,1.0,0.0);
glRotatef(theta[2],0.0,0.0,1.0);
colorcube();
DEPT OF CSE, ATMECE
Page 43
Computer Graphics Laboratory With Mini Project
18CSL67
glFlush();
glutSwapBuffers();
}
void spincube()
{
theta[axis]+=2.0;
if(theta[axis]>360.0)
theta[axis]-=360.0;
glutPostRedisplay();
}
void mouse(int btn,int state,int x,int y)
{
if(btn==GLUT_LEFT_BUTTON&&state==GLUT_DOWN)
axis=0;
if(btn==GLUT_MIDDLE_BUTTON&&state==GLUT_DOWN)
axis=1;
if(btn==GLUT_RIGHT_BUTTON&&state==GLUT_DOWN)
axis=2;
spincube();
}
void myreshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
glOrtho(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w,-10.0,10.0);
else
glOrtho(-2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,-2.0,2.0,-10.0,10.0);
glMatrixMode(GL_MODELVIEW);
glutPostRedisplay();
}
int main(int argc,char**argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutCreateWindow("Color cube");
glutReshapeFunc(myreshape);
glutDisplayFunc(display);
glutIdleFunc(spincube);
glutMouseFunc(mouse);
glEnable(GL_DEPTH_TEST);
glClearColor(0.0,0.0,0.0,0.0);
glutMainLoop();
}
DEPT OF CSE, ATMECE
Page 44
Computer Graphics Laboratory With Mini Project
18CSL67
RUN:
gcc 3.c -lglut -lGL -lGLU
./a.out
SAMPLE OUTPUT:
Program Outcome:



Ability to Design and develop 3D objects for different graphics applications.
Use matrix algebra in computer graphics and implement fundamental transformations involved
in transformation operation.
Ability to draw objects like cube using basic objects like points and lines.
DEPT OF CSE, ATMECE
Page 45
Computer Graphics Laboratory With Mini Project
18CSL67
1.4 Color cube with perspective viewing
Draw a color cube and allow the user to move the camera suitably to experiment with perspective
viewing.
1.4.1PREAMBLE
Concepts Used:
 Data structures for representation of a cube
 Perspective viewing
 Defining and moving the camera
 Input functions using Keyboard and mouse
Algorithm:
1. Modeling a color cube with simple data structures
Define vertices with centre of cube as origin
Define normals to identify faces
Define colors
2. Camera Manipulations
Define initial camera position - take care to define outside the cube.
3. Callback Function
 Handling mouse inputs - use the 3 mouse buttons to define the 3 axes of rotation
Handling Keyboard Inputs - use the 3 pairs of keys to move the viewer along +ive and
-ive directions of the X and Y axes respectively.
Pseudo Code
1. Define global arrays for vertices and colors
GLfloat vertices[][3] = {{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0}, {1.0,1.0,-1.0},
{-1.0,1.0,-1.0}, {-1.0,-1.0,1.0}, {1.0,-1.0,1.0}, {1.0,1.0,1.0}, {1.0,1.0,1.0}};
GLfloat
colors[][3]
=
{{0.0,0.0,0.0},{1.0,0.0,0.0},
{1.0,1.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}, {1.0,0.0,1.0},
{1.0,1.0,1.0}, {0.0,1.0,1.0}};
2. Draw a polygon from a list of indices into the array vertices and use color corresponding to first
index
void polygon(int a, int b, int c, int d)
{
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glVertex3fv(vertices[b]);
glVertex3fv(vertices[c]);
glVertex3fv(vertices[d]);
glEnd();
}
3. Draw cube from faces.
void colorcube( )
{
polygon(0,3,2,1);
DEPT OF CSE, ATMECE
Page 46
Computer Graphics Laboratory With Mini Project
18CSL67
polygon(2,3,7,6);
polygon(0,4,7,3);
polygon(1,2,6,5);
polygon(4,5,6,7);
polygo n(0,1,5,4);
}
4. Intialize the theta value and initial viewer location and axis static GLfloat theta[]={0.0,0.0,0.0}
static Glint axis =2;
static GLdouble viewer[]={0.0,0.0,5,0}
5. Define display function to upadate viewer position in model view matrix
void display(void)
{
/* display callback, clear frame buffer and z buffer,
rotate cube and draw, swap buffers */
glLoadIdentity();
gluLookAt(viewer[0],viewer[1],viewer[2],0.0,0.0,0.0,0.0,1.0,0.0);
glRotatef(theta[0], 1.0, 0.0, 0.0);
glRotatef(theta[1], 0.0, 1.0, 0.0);
glRotatef(theta[2], 0.0, 0.0, 1.0);
colorcube();
glutSwapBuffers();
}
6. Define mouse callback function to rotate about axis.
7. Define key function to move viewer position .use x,X,y,Y z,Z keys to move viewer
position.
8. Define reshape function to maintain aspect ratio and then use perspective view.
9. Define main fuction to create window and to call all function.
OpenGL Commands Familiarized:
glutInit
glutInitDisplayMode
glClearColor
glColor
glPointSize
gluOrtho2D
DEPT OF CSE, ATMECE
Page 47
Computer Graphics Laboratory With Mini Project
18CSL67
Program 4: Draw a color cube and allow the user to move the camera suitably to experiment
with perspective viewing.
Program Objective:




creation of 3D objects
Create 3D-color cube with basic transformation operations like rotation.
Use mathematical and theoretical principles i.e transformation matrices of computer graphics
to draw and rotate the color cube object.
Use matrix algebra in computer graphics and implement fundamental algorithms and
transformations involved in viewing models.
/* Color cube with perspective viewing */
#include<GL/glut.h>
#include<stdio.h>
GLfloat vertices[][3]={{-1.0,-1.0,-1.0},
{1.0,-1.0,-1.0},
{1.0,1.0,-1.0},
{-1.0,1.0,-1.0},
{-1.0,-1.0,1.0},
{1.0,-1.0,1.0},
{1.0,1.0,1.0},
{-1.0,1.0,1.0}};
GLfloat colors[][3]={{0.0,0.0,0.0},
{0.0,0.0,1.0},
{0.0,1.0,0.0},
{0.0,1.0,1.0},
{1.0,0.0,0.0},
{1.0,0.0,1.0},
{1.0,1.0,0.0},
{1.0,1.0,1.0}};
static GLfloat theta[]={0.0,0.0,0.0};
static GLint axis=2;
static GLdouble viewer[]={0,0,5};
void polygon(int a,int b,int c,int d)
{
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glColor3fv(colors[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube()
{
polygon(0,3,2,1);
DEPT OF CSE, ATMECE
Page 48
Computer Graphics Laboratory With Mini Project
18CSL67
polygon(2,3,7,6);
polygon(1,2,6,5);
polygon(0,4,5,1);
polygon(4,5,6,7);
polygon(0,3,7,4);
}
void display()
{
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.0,0.0);
glRotatef(theta[1],0.0,1.0,0.0);
glRotatef(theta[2],0.0,0.0,1.0);
colorcube();
glFlush();
glutSwapBuffers();
}
void myreshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
glFrustum(-2,2,-2*(GLfloat)h/(GLfloat)w,2*(GLfloat)h/(GLfloat)w,2,20);
else
glFrustum(-2*(GLfloat)w/(GLfloat)h,2*(GLfloat)w/(GLfloat)h,-2,2,2,20);
glMatrixMode(GL_MODELVIEW);
glutPostRedisplay();
}
void myMouse(int btn,int state,int x,int y)
{
if(btn==GLUT_LEFT_BUTTON&&state==GLUT_DOWN)
axis=0;
if(btn==GLUT_RIGHT_BUTTON&&state==GLUT_DOWN)
axis=1;
if(btn==GLUT_MIDDLE_BUTTON&&state==GLUT_DOWN)
axis=2;
theta[axis]+=2.0;
if(theta[axis]>360.0)
theta[axis]-=360.0;
display();
}
void keys(unsigned char key,int x,int y)
{
if(key=='x') viewer[0]-=1;
if(key=='X') viewer[0]+=1;
if(key=='y') viewer[1]-=1;
if(key=='Y') viewer[1]+=1;
if(key=='z') viewer[2]-=1;
if(key=='Z') viewer[2]+=1;
display();
DEPT OF CSE, ATMECE
Page 49
Computer Graphics Laboratory With Mini Project
18CSL67
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutCreateWindow("colorcube");
glutReshapeFunc(myreshape);
glutDisplayFunc(display);
glutMouseFunc(myMouse);
glutKeyboardFunc(keys);
glEnable(GL_DEPTH_TEST);
glClearColor(0.0,0.0,0.0,0.0);
glutMainLoop();
}
RUN:
gcc 4.c -lglut -lGL -lGLU
./a.out
SAMPLE OUTPUT:
Program Outcome:



Ability to Design and develop 3D objects for different graphics applications.
Use matrix algebra in computer graphics and implement fundamental transformations involved
in viewing models.
Analyze and evaluate the use of openGL methodss in practical applications of 3D
representations.
DEPT OF CSE, ATMECE
Page 50
Computer Graphics Laboratory With Mini Project
18CSL67
1.4 Cohen-Sutherland
Clip a line using Cohen-Sutherland algorithm.
1.5.1 PREAMBLE
The Cohen-Sutherland algorithm uses a divide-and-conquer strategy. The line segment's endpoints
are tested to see if the line can be trivially accepted or rejected. If the line cannot be trivally accepted
or rejected, an intersection of the line with a window edge is determined and the trivial reject/accept
test is repeated.
This process is continued until the line is accepted. To perform the trivial acceptance and rejection
tests, we extend the edges of the window to divide the plane of the window into the nine regions.
Each end point of the line segment is then assigned the code of the region in which it lies.
Concepts Used:
Data structures for representing a square and line
Algorithm:
Every line endpoint is assigned a 4 bit Region code. The appropriate bit is set depending on
location of the endpoint with respect to that window component as shown below:
the
Endpoint Left of window then set bit 1 Endpoint Right of window then set bit 2 Endpoint Below
window then set bit 3 Endpoint Above window then set bit 4
1. Given a line segment with endpoint P1=(x1,y1) and P2=(x2,y2)
2. Compute the 4-bit codes for each endpoint. If both codes are 0000,(bitwise OR of the codes yields
0000 ) line lies completely inside the window: pass the endpoints to the draw routine.
If both codes have a 1 in the same bit position (bitwise AND of the codes is not 0000), the line lies
outside the window. It can be trivially rejected.
3. If a line cannot be trivially accepted or rejected, at least one of the two endpoints must lie outside
the window and the line segment crosses a window edge. This line must be clipped at the window
edge before being passed to the drawing routine.
4. Examine one of the endpoints, say. Read’s 4-bit code in order: Left-to-Right, Bottom-to-Top.
5. When a set bit (1) is found, compute the intersection I of the corresponding window edge with the
line from to. Replace with i and repeat the algorithm.
DEPT OF CSE, ATMECE
Page 51
Computer Graphics Laboratory With Mini Project
18CSL67
1.6
Example1
Can determine the bit code by testing the endpoints with window as follows:
If x is less than Xwmin then set bit 1
If x is greater than Xwmax then set bit 2
If y is less than Ywmin then set bit 3
If y is greater than Ywmax then set bit 4
Note: can use 4 element Boolean matrix and set C [Left] = true / false (1/0). If both endpoints
= 0000 (in window) then display line. If both endpoints have a bit set in same position (P7, P8)
then the line is completely outside the window and is rejected.So: can do logical AND of region
codes and reject if result is 0000 Can do logical OR of region codes and accept if result = 0000
For the rest of the lines we must check for intersection with window. May still be outside, e.g.
P3 - P4 in the above image. If point is to Left of window then compute intersection with Left
window boundary. Do the same for Right, Bottom, and Top.
Then recompute region code restest. So the algorithm is as follows:
1. Compute region code for endpoints
2. Check for trivial accept or reject
3. If step 2 unsuccessful then compute window intersections in order:\\ Left, Right, Bottom,
Top (only do 1)
4. Repeat steps 1, 2,3 until done.
Example2:
I. 1) P1 = 0001 2) no 3) P1 = P'1 P2 = 1000
1) P'1= 0000 2) no 3) P2 = P' 2 P2 = 1000
III. 1) P'1 = 0000 2) Yes - accept & display P'2 = 0000
Look at how to compute the line intersections for
P'1: m = dy/dx = (y1 - y'1)/(x1 - x'1) P1(x1, y1)P'1(x'1, y'1) or y'1 = y1 + m( x'1 - x1)
but for Left boundary x'1 = Xwmin for Right boundary x'1 = Xwmax
Similarly for Top / Bottom, e.g. P'3
x'3 = x3 + (y'3 - y3) / m
For Top y'3 = Ywmax for Bottom y'3 = Ywmin
OpenGL Commands Familiarized :
DEPT OF CSE, ATMECE
Page 52
Computer Graphics Laboratory With Mini Project
18CSL67
glMatrixMode
glLoadIdentity
gluOrtho2D
glFlush
glColor3f
glBegin
DEPT OF CSE, ATMECE
Page 53
Computer Graphics Laboratory With Mini Project
18CSL67
Program 5: Clip a lines using Cohen-Sutherland algorithm
Program Objective:




creation of 2D objects
To have the detailed knowledge of the graphics Cohen-Sutherland line-clipping algorithm.
Use mathematical and theoretical principles of computer graphics to draw the and clip the
line object.
Implement GLU and GLUT functions
/* Cohen-Sutherland */
#include<GL/glut.h>
#include<stdio.h>
#define outcode int
const int L=1,R=2,B=4,T=8;
float x0,y00,x1,y11;
float xmin=50.0,ymin=50.0,xmax=150.0,ymax=150.0,xvmin=200,yvmin=200,xvmax=300,
yvmax=300;
outcode compute(float x,float y)
{
outcode code=0;
if(y>ymax) code=T;
else if(y<ymin) code=B;
else if(x>xmax) code=R;
else if(x<xmin) code=L;
return code;
}
void cohen(float x0,float y00,float x1,float y11)
{
outcode outcode0,outcode1,outcodeout;
int accept=0,done=0;
outcode0=compute(x0,y00);
outcode1=compute(x1,y11);
do
{
if(!(outcode0| outcode1))
{
accept=1,done=1;
}
else if(outcode0&outcode1)
done=1;
else
{
outcodeout=outcode0?outcode0:outcode1;
float x,y;
if(outcodeout&T)
{
x=x0+(ymax-y00)*(x1-x0)/(y11-y00);
DEPT OF CSE, ATMECE
Page 54
Computer Graphics Laboratory With Mini Project
18CSL67
y=ymax;
}
else if(outcodeout&B)
{
x=x0+(ymin-y00)*(x1-x0)/(y11-y00);
y=ymin;
}
else if(outcodeout&R)
{
y=y00+(xmax-x0)*(y11-y00)/(x1-x0);
x=xmax;
}
else
{
y=y00+(xmin-x0)*(y11-y00)/(x1-x0);
x=xmin;
}
if(outcodeout==outcode0)
{
x0=x;
y00=y;
outcode0=compute(x0,y00);
}
else
{
x1=x,y11=y;
outcode1=compute(x1,y11);
}
}
}
while(!done);
if(accept)
{
float sx,sy,vx0,vx1,vy00,vy11;
sx=(xvmax-xvmin)/(xmax-xmin);
sy=(yvmax-yvmin)/(ymax-ymin);
vx0=xvmin+(x0-xmin)*sx;
vy00=yvmin+(y00-ymin)*sy;
vx1=xvmin+(x1-xmin)*sx;
vy11=yvmin+(y11-ymin)*sy;
glColor3f(0.0,1.0,0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xvmin,yvmin);
glVertex2f(xvmax,yvmin);
glVertex2f(xvmax,yvmax);
glVertex2f(xvmin,yvmax);
glEnd();
glColor3f(0.0,0.0,1.0);
glBegin(GL_LINES);
glVertex2f(vx0,vy00);
glVertex2f(vx1,vy11);
glEnd();
DEPT OF CSE, ATMECE
Page 55
Computer Graphics Laboratory With Mini Project
18CSL67
}
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xmin,ymin);
glVertex2f(xmax,ymin);
glVertex2f(xmax,ymax);
glVertex2f(xmin,ymax);
glEnd();
glColor3f(0.0,0.0,1.0);
glBegin(GL_LINES);
glVertex2f(x0,y00);
glVertex2f(x1,y11);
glEnd();
cohen(x0,y00,x1,y11);
glFlush();
}
void init(){
glClearColor(0.0,0.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
}
int main(int argc,char **argv){
printf("Enter the line coordinates\n");
scanf("%f%f%f%f",&x0,&y00,&x1,&y11);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("cohen");
glutDisplayFunc(display);
init();
glutMainLoop();
}
RUN:
DEPT OF CSE, ATMECE
Page 56
Computer Graphics Laboratory With Mini Project
18CSL67
gcc 5.c -lglut -lGL -lGLU
./a.out
Enter the line coordinates
20 40
120 180
SAMPLE OUTPUT:
Program Outcome:



Ability to Design and develop 2D objects for different graphics applications.
Use matrix algebra in computer graphics and implement Cohen-Sutherland line-clipping
algorithm. .
Analyze and evaluate the use of openGL methodss in practical applications of 2D
representations.
DEPT OF CSE, ATMECE
Page 57
Computer Graphics Laboratory With Mini Project
18CSL67
1.6 Tea pot
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.
1.6.1 PREAMBLE
Concepts Used:
Translation, Scaling
Material Properties, Light Properties
Depth in 3D Viewing
Using predefined GLU library routines
Algorithm:
Algorithm[High Level]:
1. Recognise the objects in the problem domain and their components
 Teapot
 Table
Table top
4Legs
 Walls
Left wall
Right wall
Floor
2. If depth testing is NOT used ensure that the background is drawn first
3. Enable lighting first - since lighting is applied at the time objects are drawn.
4. Draw the objects.
Algorithm[Low Level]:
Main Function:
Initialization for Display, Mode , Window
Enable lighting, shading, depth test
Register display and callback function
 Define viewport appropriately
Call mainloop
Display function:
Define Material properties
Define lighting properties
Set the camera by defining
projection parameters
camera parameters
Plan the required centre position for each of the components
Draw each component using translation, scaling and rotation as required
DEPT OF CSE, ATMECE
Page 58
Computer Graphics Laboratory With Mini Project
18CSL67
Pseudo Code
1. Include glut header files.
2. Define wall function as following
void wall(double thickness)
{
glPushMatrix();
glTranslated(0.5,0.5*thickness,0.5);
glScaled(1.0,thickness,1.0);
glutSolidCube(1.0);
gPopMatrix();
}
3. Draw one tableleg using tableLeg function as following
void tableLeg(double thick,double len)
{
glpushMatrix();
glTranslated(0,len/2,0);
glScaled(thick,len,thick);
glutsolidCube(1.0);
glPopMatrix();
}
4. Draw the table using table function.
i) draw the table top using glutSolidCube(1.0) function.Before this use gltranslated and glScaled
function to fix table in correct place.
ii) Draw four legs by calling the function tableleg .before each call use gltranslated function to
fix four legs in correct place.
5. Define the function displaySolid
i) Initialize the properties of the surface material and set the light source properties.
ii) Set the camera position.
iii)Draw the teapot using glutSolidTeapot(0.08).before this call gltranslated and glRotated.
iv) Call table function and wall function
v) Rotate wall about 90 degree and then call wall function.
vi) Rotate wall about -90 degree and then call wall function.
6. Define the main function to create window and enable lighting function using
glEnable(GL_LIGHTING)
OpenGL Commands Familiarized :
glPushMatrix, glPopMatrix
glTranslate, glScale, glRotate
glMaterial, glLight
gluLookAt
glutSolidTeapot, glutSolidCube
DEPT OF CSE, ATMECE
Page 59
Computer Graphics Laboratory With Mini Project
18CSL67
Program 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.
Program Objective:



creation of 3D objects
Use 3D teapot objects to draw a simple shaded scene consisting of a tea pot on a table.
Use matrix algebra in computer graphics and implement fundamental algorithms and
transformations involved in viewing models.
/* Tea pot */
#include<GL/glut.h>
void wall(double thickness)
{
glPushMatrix();
glTranslated(0.5,0.5*thickness,0.5);
glScaled(1.0,thickness,1.0);
glutSolidCube(1.0);
glPopMatrix();
}
void tableleg(double thick,double len)
{
glPushMatrix();
glTranslated(0,len/2.0,0);
glScaled(thick,len,thick);
glutSolidCube(1.0);
glPopMatrix();
}
void table(double topwid,double topthick,double legthick,double leglen)
{
glPushMatrix();
glTranslated(0,leglen,0);
glScaled(topwid,topthick,topwid);
glutSolidCube(1.0);
glPopMatrix();
double dist=0.95*topwid/2-legthick/2;
glPushMatrix();
glTranslated(dist,0,dist);
tableleg(legthick,leglen);
glTranslated(0,0,-2*dist);
tableleg(legthick,leglen);
glTranslated(-2*dist,0,2*dist);
tableleg(legthick,leglen);
glTranslated(0,0,-2*dist);
tableleg(legthick,leglen);
glPopMatrix();
}
DEPT OF CSE, ATMECE
Page 60
Computer Graphics Laboratory With Mini Project
18CSL67
void display()
{
GLfloat mat_ambient[]={0.7f,0.7f,0.7f,1.0f};
GLfloat mat_diffuse[]={0.5f,0.5f,0.5f,1.0f};
GLfloat mat_specular[]={1.0f,1.0f,1.0f,1.0f};
GLfloat mat_shininess[]={50.0f};
glMaterialfv(GL_FRONT,GL_AMBIENT,mat_ambient);
glMaterialfv(GL_FRONT,GL_DIFFUSE,mat_diffuse);
glMaterialfv(GL_FRONT,GL_SPECULAR,mat_specular);
glMaterialfv(GL_FRONT,GL_SHININESS,mat_shininess);
GLfloat Lightintensity[]={1.0f,1.0f,1.0f,1.0f};
GLfloat Lightposition[]={2.0f,6.0f,3.0f,0.0f};
glLightfv(GL_LIGHT0,GL_POSITION,Lightposition);
glLightfv(GL_LIGHT0,GL_DIFFUSE,Lightintensity);
double winht=1.0;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-winht*64/48.0,winht*64/48.0,-winht,winht,0.1,100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(2.3,1.3,2.0,0.0,0.25,0.0,0.0,1.0,0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslated(0.5,0.38,0.5);
glRotated(60,0,1,0);
glutSolidTeapot(0.08);
glPopMatrix();
glPushMatrix();
glTranslated(0.4,0,0.4);
table(0.6,0.02,0.02,0.3);
glPopMatrix();
wall(0.02);
glPushMatrix();
glRotated(90.0,0.0,0.0,1.0);
wall(0.02);
glPopMatrix();
glPushMatrix();
glRotated(-90.0,1.0,0.0,0.0);
wall(0.02);
glPopMatrix();
glFlush();
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB |GLUT_DEPTH);
glutCreateWindow("Tea pot");
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutDisplayFunc(display);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
DEPT OF CSE, ATMECE
Page 61
Computer Graphics Laboratory With Mini Project
18CSL67
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glClearColor(0.0,0.0,0.0,0.0);
glutMainLoop();
}
RUN:
gcc 6.c -lglut -lGL -lGLU
./a.out
SAMPLE OUTPUT:
Program Outcome:




Ability to Design and develop 3D objects for different graphics applications.
Use matrix algebra in computer graphics and implement fundamental transformations
involved in viewing models.
Ability to draw objects like table basic objects like points and lines.
Analyze and evaluate the use of openGL methodss in practical applications of 3D
representations.
DEPT OF CSE, ATMECE
Page 62
Computer Graphics Laboratory With Mini Project
18CSL67
1.7 3 D Sierpinski gasket
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.
1.7.1 PREAMBLE
Sierpinski's Triangle is a very famous fractal that's been seen by most advanced math students.
This fractal consists of one large triangle, which contains an infinite amount of smaller triangles
within. The infinite amount of triangles is easily understood if the fractal is zoomed in many
levels. Each zoom will show yet more previously unseen triangles embedded in the visible ones.
Creating the fractal requires little computational power. Even simple graphing calculators can
easily make this image. The fractal is created pixel by pixel, using random numbers; the fractal
will be slightly different each time due to this. Although, if you were to run the program
repeatedly, and allow each to use an infinite amount of time, the results would be always
identical. No one has an infinite amount of time, but the differences in the finite versions are
very small.
A fractal is generally "a rough or fragmented geometric shape that can be split into parts, each
of which is (at least approximately) a reduced-size copy of the whole".
To generate this fractal, a few steps are involved.
We begin with a triangle in the plane and then apply a repetitive scheme of operations to it (when
we say triangle here, we mean a blackened, filled-in' triangle). Pick the midpoints of its three
sides. Together with the old vertices of the original triangle, these midpoints define four
congruent triangles of which we drop the center one. This completes the basic construction step.
In other words, after the first step we have three congruent triangles whose sides have exactly
half the size of the original triangle and which touch at three points which are common vertices
of two contiguous triangles. Now we follow the same procedure with the three remaining
triangles and repeat the basic step as often as desired. That is, we start with one triangle and then
produce 3, 9, 27, 81, 243, triangles, each of which is an exact scaled down version of the triangles
in the preceding step.
Concepts Used:
Data structures for representing 3D vertices
 Tetrahedron sub-division using mid-points
Algorithm:
Input: Four 3D vertices of tetrahedron, no. of divisions
Recursively sub-divide the each triangle by finding the mid-point Pseudo Code
1. Define and initializes the array to hold the vertices as follows:
GLfloatvertices[4][3]={{0.0,0.0,0.0},{25.0,50.0,10.0},{50.0,25.0,25.0},{25.0,10.0,25.0}};
2. Define and initialize initial location inside tetrahedron. GLfloat p[3] = {25.0,10.0,25.0};
3. Define Triangle function that uses points in three dimensions to display one triangle
Use glBegin(GL_POLYGON)
glVertex3fv(a) glVertex3fv(b)
glVertex3fv(c) to display points. glEnd();
4. Subdivide a tetrahedron using divide_triangle function
DEPT OF CSE, ATMECE
Page 63
Computer Graphics Laboratory With Mini Project
18CSL67
i) if no of subdivision(m) > 0 means perform following functions
ii) Compute six midpoints using for loop.
iii)Create 4 tetrahedrons by calling divide_triangle function
iv) Else draw triangle at end of recursion.
5. Define tetrahedron function to apply triangle subdivision to faces of tetrahedron by calling
the function divide_triangle.
6. Define display function to clear the color buffer and to call tetrahedron function.
7. Define main function to create window and to call display function.
OpenGL commands Familiarised :
glutInit
glutInitDisplayMode
glClearColor
glColor
glPointSize
glOrtho
DEPT OF CSE, ATMECE
Page 64
Computer Graphics Laboratory With Mini Project
18CSL67
Program 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.
Program Objective:




creation of 3D objects
Implement GLU and GLUT functions
Create Sierpinski gasket
Implement the concepts of recursion to create Sierpinski gasket
/* 3 D Sierpinski gasket */
#include <GL/glut.h>
#include <stdio.h>
typedef float point[3];
point v[] = {{0.0,0.0,1.0},{0.0,1.0,0.0},{-1.0,-0.5,0.0},{1.0,-0.5,0.0}};
int n;
void triangle(point a, point b, point c)
{
glBegin(GL_POLYGON);
glVertex3fv(a);
glVertex3fv(b);
glVertex3fv(c);
glEnd();
}
void divide(point a, point b, point c,int m)
{
point v1, v2, v3;
int j;
if(m > 0)
{
for(j = 0; j < 3; j++)
v1[j] = (a[j] + b[j]) / 2;
for(j = 0; j < 3; j++)
v2[j] = (a[j] + c[j]) / 2;
for(j=0; j<3; j++)
v3[j] = (b[j] + c[j]) / 2;
divide(a, v1, v2, m - 1);
divide(c, v2, v3, m - 1);
divide(b, v3, v1, m - 1);
}
else(triangle(a, b, c));
}
void tetra(int m)
{
glColor3f(1.0, 0.0, 0.0);
divide(v[0], v[1], v[2], m);
glColor3f(0.0, 1.0, 0.0);
divide(v[3], v[2], v[1], m);
glColor3f(0.0, 0.0, 1.0);
DEPT OF CSE, ATMECE
Page 65
Computer Graphics Laboratory With Mini Project
18CSL67
divide(v[0], v[3], v[1], m);
glColor3f(1.0, 1.0, 1.0);
divide(v[0], v[2], v[3], m);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
tetra(n);
glFlush();
}
void myreshape(int w, int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w <= h)
glOrtho(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w,-10.0,10.0);
else
glOrtho(-2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,-2.0,2.0,-10.0,10.0);
glMatrixMode(GL_MODELVIEW);
glutPostRedisplay();
}
int main(int argc, char **argv)
{
printf("Enter number of divisions");
scanf("%d", &n);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("GASKET");
glutReshapeFunc(myreshape);
glutDisplayFunc(display);
glEnable(GL_DEPTH_TEST);
glClearColor(0.0,0.0,0.0,0.0);
glutMainLoop();
}
DEPT OF CSE, ATMECE
Page 66
Computer Graphics Laboratory With Mini Project
18CSL67
RUN:
gcc 7.c -lglut -lGL -lGLU
./a.out
Enter number of divisions
3
SAMPLE OUTPUT:
Program Outcome:


Analyze and evaluate the use of openGL methodss in practical applications of 3D
representations.
Ability to explain the mathematical principles of recursion and to draw basic Sierpinski
gasket object.
DEPT OF CSE, ATMECE
Page 67
Computer Graphics Laboratory With Mini Project
18CSL67
1.8 Bezier Curve
Develop a menu driven program to animate a flag using Bezier Curve algorithm.
1.8.1 PREAMBLE
Bezier curve is discovered by the French engineer Pierre Bezier. These curves can be generated
under the control of other points. Approximate tangents by using control points are used to
generate curve. The Bezier curve can be represented mathematically as
Where pi is the set of points and Bni(t) represents the Bernstein polynomials which
are given by
Where n is the polynomial degree, i is the index, and t is the variable.
The simplest Bezier curve is the straight line from the point P0 to P1. A quadratic Bezier curve
is determined by three control points. A cubic Bezier curve is deter-mined by four control
points.
Bezier curves generally follow the shape of the control polygon, which consists of the segments
joining the control points and always pass through the first and last control points. They are
contained in the convex hull of their defining control points. The degree of the polynomial
defining the curve segment is one less that the number of defining polygon point. Therefore,
for 4 control points, the degree of the polynomial is 3, i.e. cubic polynomial. A Bezier curve
generally follows the shape of the defining polygon. The direction of the tangent vector at the
end points is same as that of the vector determined by first and last segments. The convex hull
property for a Bezier curve ensures that the polynomial smoothly follows the control points.
No straight line intersects a Bezier curve more times than it intersects its control polygon. They
are invariant under an affine transformation. Bezier curves exhibit global control means
moving a control point alters the shape of the whole curve. A given Bezier curve can be
subdivided at a point t=t0 into two Bezier segments which join together at the point
corresponding to the parameter value t=t0.
Concepts Used: Algorithm: OpenGL Commands Familiarized:
 glMatrixMode
 glLoadIdentity
 gluOrtho2D
 glFlush
 glColor3f
 glBegin
DEPT OF CSE, ATMECE
Page 68
Computer Graphics Laboratory With Mini Project
18CSL67
Program 8: Develop a menu driven program to animate a flag using Bezier Curve
Program Objective:



creation of 2D objects
Use mathematical and theoretical principles of computer graphics to animate a flag using
Bezier Curve algorithm
Implement GLU and GLUT functions
/* Bezier Curve */
#include<GL/glut.h>
#include<stdio.h>
#include<math.h>
#define pi 3.14
struct
{
GLfloat x,y,z;
}
typedef wcpt;
void bino(GLint n,GLint *c)
{
GLint k,j;
for(k=0;k<=n;k++)
{
c[k]=1;
for(j=n;j>=k+1;j--)
c[k]*=j;
for(j=n-k;j>=2;j--)
c[k]/=j;
}
}
void combez(GLfloat u,wcpt *bezpt,GLint nctrpt,wcpt *ctrlpt,GLint *c)
{
GLint k,n=nctrpt-1;
GLfloat blendfunc;
bezpt->x=bezpt->y=bezpt->z=0.0;
for(k=0;k<nctrpt;k++)
{
blendfunc=c[k]*pow(u,k)*pow(1-u,n-k);
bezpt->x+=ctrlpt[k].x*blendfunc;
bezpt->y+=ctrlpt[k].y*blendfunc;
bezpt->z+=ctrlpt[k].z*blendfunc;
}
}
DEPT OF CSE, ATMECE
Page 69
Computer Graphics Laboratory With Mini Project
18CSL67
void bezier(wcpt *ctrlpt,GLint nctrpt,GLint nBezcurpts)
{
wcpt bezcurpt;
GLfloat u;
GLint *c,k;
c=new GLint[nctrpt];
bino(nctrpt-1,c);
glBegin(GL_LINE_STRIP);
for(k=0;k<=nBezcurpts;k++)
{
u=GLfloat(k)/GLfloat(nBezcurpts);
combez(u,&bezcurpt,nctrpt,ctrlpt,c);
glVertex2f(bezcurpt.x,bezcurpt.y);
}
glEnd();
delete[]c;
}
void display()
{
GLint nctrpt=4,nBezcurpts=20;
static float theta=0;
wcpt ctrlpt[4]={{20,100,0},{30,110,0},{50,90,0},{60,100,0}};
ctrlpt[1].x+=10*sin(theta*pi/180);
ctrlpt[1].y+=5*sin(theta*pi/180);
ctrlpt[2].x-=10*sin((theta+30)*pi/180);
ctrlpt[2].y-=10*sin((theta+30)*pi/180);
ctrlpt[3].x-=4*sin(theta*pi/180);
ctrlpt[3].y-=sin((theta+30)*pi/180);
theta+=3;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,1.0,1.0);
glPushMatrix();
glLineWidth(5);
glColor3f(1,0,0.15);
for(int i=0;i<8;i++)
{
glTranslatef(0,-0.8,0);
bezier(ctrlpt,nctrpt,nBezcurpts);
}
glColor3f(1,1,1);
for(int i=0;i<8;i++)
{
glTranslatef(0,-0.8,0);
bezier(ctrlpt,nctrpt,nBezcurpts);
}
glColor3f(0,1,0);
for(int i=0;i<8;i++)
{
glTranslatef(0,-0.8,0);
bezier(ctrlpt,nctrpt,nBezcurpts);
}
DEPT OF CSE, ATMECE
Page 70
Computer Graphics Laboratory With Mini Project
18CSL67
glPopMatrix();
glColor3f(0.7,0.5,0.3);
glLineWidth(5);
glBegin(GL_LINES);
glVertex2f(20,100);
glVertex2f(20,40);
glEnd();
glFlush();
glutPostRedisplay();
glutSwapBuffers();
}
void Reshape(GLint w,GLint h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,130,0,130);
glutPostRedisplay();
glFlush();
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("bazier");
glutDisplayFunc(display);
glutReshapeFunc(Reshape);
glClearColor(0.0,0.0,0.0,0.0);
glutMainLoop();
}
RUN:
g++ 8.cc -lglut -lGL –lGLU
./a.out
SAMPLE OUTPUT
DEPT OF CSE, ATMECE
Page 71
Computer Graphics Laboratory With Mini Project
18CSL67
Program Outcome:



Ability to Design and develop 2D objects for different graphics applications.
Use matrix algebra in computer graphics and implement Bezier Curve algorithm.
Analyze and evaluate the use of openGL methodss in practical applications of 2D
representations.
DEPT OF CSE, ATMECE
Page 72
Computer Graphics Laboratory With Mini Project
18CSL67
1.9 Scan-line
Develop a menu driven program to fill the polygon using scan line algorithm.
1.9.1 PREAMBLE
The scan conversion algorithm works as follows
i. Intersect each scanline with all edges
ii. Sort intersections in x
iii. Calculate parity of intersections to determine in/out iv. Fill the "in" pixels
Special cases to be handled: i. Horizontal edges should be excluded ii. For vertices lying on
scanlines, i. count twice for a change in slope. ii. Shorten edge by one scanline for no change
in slope
 Coherence between scanlines tells us that
 Edges that intersect scanline y are likely to intersect y + 1
 X changes predictably from scanline y to y + 1
We have 2 data structures: Edge Table and Active Edge Table
Traverse Edges to construct an Edge Table
Eliminate horizontal edges
Add edge to linked-list for the scan line corresponding to the lower vertex.
Store the following:
yupper : last scanline to consider
xlower: starting x coordinate for edge
1/m: for incrementing x; compute
Construct Active Edge Table during scan conversion. AEL is a linked list of active edges
on the current scanline, y. Each active edge line has the following information
yupper : last scanline to consider
xlower: edge's intersection with current y
1/m: x increment
The active edges are kept sorted by x Concepts Used:
Use the straight line equation y2-y1=m(x2-x1) to compute the x values
corresponding to lines increment in y value.
Determine which are the left edge and right edges for the the closed
polygon.for each value of y within the polygon.
Fill the polygon for each value of y within the polygon from x=left edge
to x=right edge.
Algorithm:
1. Set y to the smallest y coordinate that has an entry in the ET; i.e, y for the first nonempty
bucket.
2. Initialize the AET to be empty.
3. Repeat until the AET and ET are empty:
3.1 Move from ET bucket y to the AET those edges whose y_min = y (entering edges).
3.2 Remove from the AET those entries for which y = y_max (edges not
involved in the next scanline), the sort the AET on x (made easier because ET is
presorted).
DEPT OF CSE, ATMECE
Page 73
Computer Graphics Laboratory With Mini Project
18CSL67
3.3 Fill in desired pixel values on scanline y by using pairs of x coordinates
from AET.
3.4 Increment y by 1 (to the coordinate of the next scanline).
3.5 For each nonvertical edge remaining in the AET, update x for the new y.
Extensions:
1. Multiple overlapping polygons - priorities
2. Color, patterns Z for visibility
// Function scanfill
Inputs: vertices of the polygon.
Output: filled polygon.
Processing :
1. Initialize array LE to 500 and RE to 0 for all values of y(0-->499)
2. Call function EDGEDETECT for each edge of the polygon one by one to set the value of x
for each value of y within that line.
3. For each value of y in the screen draw the pixels for every value of x provided. It is greater
than right edge value of x.
//function Display
Inputs: Globally defined vertices of Polygon
Output: Filled polygon display
Processing:
1. Draw the polygon using LINE,LOOP
2. Fill the polygon using SCANFILL
//Function EDGEDETECT:
Inputs:
1. End co-ordinates of edge
2. Address of LE and RE
3. Output: The updated value of x for left edge of the polygon and the right edge of the
Polygon.
Processing:
1. Find the inverse of the slope.
2. Starting from the lesser integer value of y to the greater integer value of y.
3. Compute the value of x for left edge and right edge and update the value of
x for both the edges.
OpenGL Commands Familiarized:
glutInit
glutInitDisplayMode
glClearColor
glColor
glPointSize
gluOrtho2D
DEPT OF CSE, ATMECE
Page 74
Computer Graphics Laboratory With Mini Project
18CSL67
Program 9: Develop a menu driven program to fill the polygon using scan line
algorithm
Program Objective:




creation of 2D objects
To have the detailed knowledge of the graphics scan-line area filling algorithm
Use mathematical and theoretical principles of computer graphics to draw and fill colors
to the object.
Implement GLU and GLUT functions
/* Scan-line */
#include<GL/glut.h>
float x1,x2,x3,x4,y1,y2,y3,y4;
void draw_pixel(int x,int y)
{
glColor3f(1.0,0.0,1.0);
glPointSize(1.0);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
}
void edgedetect(float x1,float y1,float x2,float y2,int *le,int *re)
{
float temp,x,mx;
int i;
if(y1>y2)
{
temp=x1,x1=x2,x2=temp;
temp=y1,y1=y2,y2=temp;
}
if(y1==y2)
mx=x2-x1;
else
mx=(x2-x1)/(y2-y1);
x=x1;
for(i=(int)y1;i<(int)y2;i++)
{
if(x<(float)le[i])
le[i]=(int)x;
if(x>(float)re[i])
re[i]=(int)x;
x+=mx;
}
}
void Scanfill(float x1,float y1,float x2,float y2,float x3,float y3,float x4,float y4)
{
int le[500],re[500],i,j;
for(i=0;i<500;i++)
le[i]=500,re[i]=0;
edgedetect(x1,y1,x2,y2,le,re);
DEPT OF CSE, ATMECE
Page 75
Computer Graphics Laboratory With Mini Project
18CSL67
edgedetect(x2,y2,x3,y3,le,re);
edgedetect(x3,y3,x4,y4,le,re);
edgedetect(x4,y4,x1,y1,le,re);
for(j=0;j<500;j++)
{
if(le[j]<=re[j])
for(i=le[j];i<re[j];i++)
draw_pixel(i,j);
}
}
void filloption(GLint selectedoption)
{
switch(selectedoption)
{
case 1:
Scanfill(x1,y1,x2,y2,x3,y3,x4,y4);
break;
case 2:
exit(0);
break;
}
}
void Reshape(GLint w,GLint h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,500,0,500);
glutPostRedisplay();
glFlush();
}
void display()
{
x1=250.0,y1=200.0,x2=150.0,y2=300.0,x3=250.0,y3=400.0,x4=350.0,y4=300.0;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0,0.0,1.0);
glBegin(GL_LINE_LOOP);
glVertex2f(x1,y1);
glVertex2f(x2,y2);
glVertex2f(x3,y3);
glVertex2f(x4,y4);
glEnd();
glFlush();
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("polygon");
DEPT OF CSE, ATMECE
Page 76
Computer Graphics Laboratory With Mini Project
18CSL67
glutDisplayFunc(display);
glutCreateMenu(filloption);
glutAddMenuEntry("Scanfill",1);
glutAddMenuEntry("exit",2);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutReshapeFunc(Reshape);
glClearColor(0.0,0.0,0.0,0.0);
glutMainLoop();
}
RUN:
gcc 9.c -lglut -lGL -lGLU
./a.out
SAMPLE OUTPUT
Program Outcome:



Ability to Design and develop 2D objects for different graphics applications.
Use matrix algebra in computer graphics and implement scan-line area filling algorithm.
Analyze and evaluate the use of openGL methodss in practical applications of 2D
representations.
DEPT OF CSE, ATMECE
Page 77
Computer Graphics Laboratory With Mini Project
18CSL67
PART B
Develop a suitable Graphics package to implement the skills learnt in the theory and the exercises
indicated in PART A. Use the OpenGL. Criteria for CG Project Students per batch should be
THREE or less.
One Three-Dimensional OpenGL Graphics Project using features from at least THREE
CATEGORIES listed below:
Category I
 Input and Interaction
 Menus, Display Lists
Category II
 Transformations
 Camera Movement
Category III
 Coloring
 Texturing
 Lighting/ Shading
Category IV
 Animation
 Hidden Surface Removal
DEPT OF CSE, ATMECE
Page 78
Computer Graphics Laboratory With Mini Project
18CSL67
Viva questions and answers
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 Pro-gram
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 magnication or reduction.
6. What is Liang-Barsky line clipping algorithm?
Answer: In computer graphics, the Liang-Barsky algorithm is a line clipping algorithm. The LiangBarsky 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 filling algorithm?
Answer: The scanline ll algorithm is an ingenious way of filling 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 first. 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 first
DEPT OF CSE, ATMECE
Page 79
Computer Graphics Laboratory With Mini Project
18CSL67
scanline upward. For each line, any pixels that contain an intersection between this scanline and an
edge of the polygon are filled in. Then, the algorithm progresses along the scanline, turning on
when it reaches a polygon pixel and turning o 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 ndimensional 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 o-ce
equipment with images rather than text commands.
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();
DEPT OF CSE, ATMECE
Page 80
Computer Graphics Laboratory With Mini Project
//
//
//
//
//
//
//
//
//
}
18CSL67
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 specic 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 buers.
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 in-stead. It's more exible
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 specically, 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 diering values. For example, you may nd it convenient to model an airplane's
controls in centimeters, its fuselage in meters, and a world to y around in kilometers. OpenGL's
ModelView matrix can then scale these dierent coordinate sys-tems 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 eld of view, and keeps the zNear and zFar clipping planes at an appropriate range. An
DEPT OF CSE, ATMECE
Page 81
Computer Graphics Laboratory With Mini Project
18CSL67
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 eld of view.
18. What is Microsoft Visual Studio?
Answer: Microsoft Visual Studio is an integrated development environment (IDE) for devel-oping
windows applications. It is the most popular IDE for developing windows applications or windows
based software.
19. What does the .gl or .GL le format have to do with OpenGL?
Answer: .gl les have nothing to do with OpenGL, but are sometimes confused with it. .gl is a le
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 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 specied 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?
DEPT OF CSE, ATMECE
Page 82
Computer Graphics Laboratory With Mini Project
18CSL67
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.
DEPT OF CSE, ATMECE
Page 83
Download