CG-Practical-Lab-Manual
CG-Practical-Lab-Manual
Institute of Technology
Lohgaon, Pune
Accredited with 'A' Grade by NAAC
Prepared by,
SE COMP
2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
5. 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.
6. 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.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
12. 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.
Course Objectives:
1. To acquaint the learner with the basic concepts of Computer Graphics
2. To learn the various algorithms for generating and rendering graphical figures
3. To get familiar with mathematics behind the graphical transformations
4. To understand and apply various methods and techniques regarding projections,
animation, shading, illumination and lighting
Course Outcomes:
On completion of the course, student will be able to–
1. Apply mathematics and logic to develop Computer programs for elementary
graphics operations like line and circle.
2. Develop scientific and strategic approach to solve complex problems in the domain
of Computer Graphics such as polygon filling, windowing and clipping.
3. Compare different transformations and differentiate between 2-D and 3-D
transformation.
4. Apply the logic to develop animation and gaming programs.
5. Understand the concepts of illumination models, shading algorithms and
hidden surfaces.
6. Explain advanced tools and technologies for enhancement of graphics applications
INDEX
Software Required:
1. 64 bit open source operating system
2. Geany, Qt creator
3. Eclipse version 3.8
Write-ups must include:
● Group:
● Assignment No.
● Title
● Problem Statement
● Prerequisites
● Course Objectives
● Course Outcomes
● Theory(in brief)
● Algorithm
● Test Cases
● Conclusion
● FAQs:
PREREQUISITES:
COURSE OBJECTIVE:
THEORY:
● Text Editor:
A text editor is a type of program used for editing plain text files.
Text editors are often provided with operating systems or software development packages,
and can be used to change configuration files and programming language source code.
● Graphics Editor :
A raster graphics editor is a computer program that allows users to paint and edit pictures
interactively on the computer screen and save them in one of many popular "bitmap" or
"raster" formats such as JPEG, PNG, GIF and TIFF. Usually an image viewer is preferred
over a raster graphics editor for viewing images .Some editors specialize in the editing of
photo-realistic images such as the popular Adobe Photoshop, while others are more geared to
artist-created illustrations.
Graphics mode Initialization :
First of all we have to call the initgraph function that will initialize the graphics mode on the
computer. Initigraph have the following prototype.
void initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);
Initgraph initializes the graphics system by loading a graphics driver from disk (or validating a
registered driver) then putting the system into graphics mode.Initgraph also resets all graphics
settings(color, palette current position, viewport)to their defaults, then resets graphresult to 0.
*graphdriver Integer that specifies the graphics driver to be used. You can give graphdriver a
value using a constant of the graphics_drivers enumeration type.
*graphmode Integer that specifies the initial graphics mode(unless *graphdriver = DETECT).
If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the
detected driver. You can give *graphmode a value using a constant of the graphics_modes
enumeration type.
*pathtodriver Specifies the directory path where initgraph looks for graphics drivers
(*.BGI) first.
1. If they're not there, initgraph looks in the current directory.
2. If pathtodriver is null, the driver files must be in the current directory.
*graphdriver and *graphmode must be set to valid graphics_drivers and graphics_mode values or
you'll get unpredictable results. (The exception is graphdriver = DETECT.)
Graphics Primitives:
Function Description
It initializes the graphics system by loading the passed graphics driver
then changing the system into graphics mode.
initgraph int gd,gm;
gd=DETECT;
initgraph(&gd,&gm,NULL);
It returns the maximum X & Y coordinate in current graphics mode and
getmaxx driver.
getmaxy Syntax: int getmaxx()
int getmaxy()
It changes the current drawing colour. Default colour is white. Each
color is assigned a number, like BLACK is 0 and RED is 4. Here we are
setcolor
using colour constants defined inside graphics.h header file.
setcolor(int color)
It is used to get intensity of current pixel
getpixel int getpixel(int x, int y)
Ellipse void ellipse(int xCenter, int yCenter, int startAngle, int endAngle, int xRadius,
int yRadius);
It is used to fill a closed area with current fill pattern and fill color. It
floodfill takes any point inside closed area and color of the boundary as input.
floodfill(int x, int y, int color)
It clears the screen, and sets current position to (0, 0).
cleardevice
cleardevice();
It is used to determine whether a key is pressed or not. It returns a non-
kbhit zero value if a key is pressed otherwise zero.
Kbhit()
It is used to suspend execution of a program for a M milliseconds.
delay
delay(miliseconds)
It unloads the graphics drivers and sets the screen back to text mode.
closegraph
closegraph();
PROBLEM STATEMENT A. Write C++ program to draw the following pattern. Use DDAline and
Bresenham‘s circle drawing algorithm. Apply the concept of encapsulation.
PREREQUISITES:
COURSE OBJECTIVE:
COURSE OUTCOME:
1. Apply mathematics and logic to develop Computer programs for elementary graphic
operations
THEORY:
Line is denoted by two points P1(x1, y1) and P2(x2,y2). Mathematical equation for line is
y=mx+b where m is slope and b is intercept.
1. It is the simplest algorithm and it does not require special skills for implementation.
2. It is a faster method for calculating pixel positions than the direct use of equation y=mx + b. It
eliminates the multiplication in the equation by making use of raster characteristics, so that
appropriate increments are applied in the x or y direction to find the pixel positions along the line
path.
Circle
We can reduce our calculation drastically (8th fraction ) by making use of the fact that a circle
has 8 way symmetry. Thus after calculating a pixel position (x,y) to be plotted, we get 7 other
points on the circle corresponding to it. These are:
(x,y);(x,-y);(-x,y);(-x,-y);(y,x);(y,-x);(-y,x);(-y,-x);
1. Accept radius and center co-ordinates from user and plot first point on circumference of
circle (x,y) = (0,r)
3.If we are using octant symmetry property to plot the pixel then until (x<y) we have
If(d<=0)
Update d by d=d+4x+6 and increase x by 1
Else
Update d by d=d+4(x-y)+10 and increase x by 1
and decrease y by 1
5. Move and calculate the pixel position (x,y) on to the circular path .
Test Cases
T_ID T_Name Condition to test Expected outcome Pass/Fail
T_P1 End point Given end points are Output will be
within X max and Y
Checking displayed on the screen
max of screen
CONCLUSION: Hence we have studied and implemented DDA line drawing and Bresenhams circle
drawing algorithms.
FAQ’s
1. Compare DDA and Bresenham’s Line Drawing
Algorithms Ans :
DDA Bresenham’s
Arithmetic DDA algorithm uses floating Bresenhams algorithm uses
fixed points i.e. Integer
points i.e. Real Arithmetic.
Arithmetic.
2. What is Aliasing?
Ans: Stair case or jagged line effect is called aliasing. Minimizing aliasing effect is
called antialiasing. Super sampling and area sampling are techniques for antialiasing.
3. Use of Floor and ceil function in DDA algorithm
Ans: The C library function double floor(double x) returns the largest integer value less than or
equal to x.
The C library function double ceil(double x) returns the smallest integer value greater than or
equal to x.
4. What is Antialising?
Ans: In computer graphics, antialiasing is a technique for minimizing jaggies- stairstep-like.
Aliasing is staircase or jagged line effect.
5. What is 8 way Symmetry?
Ans: Circle can be drawn by drawing 1/8th part. Eight pixels can be drawn by one pixel only.
PREREQUISITES:
2. Basic mathematics
COURSE OBJECTIVE:
1. To acquaint the learner with the basic concepts of Computer Graphics
2. To get familiar with mathematics behind the graphical objects
COURSE OUTCOME:
1. Develop scientific and strategic approach to solve complex problems in the domain of
Computer Graphics
THEORY:
Polygon: polygon is a diagram in which start point and end point is connected.
Convex Polygons: In a convex polygon, any line segment joining any two inside points lies
inside the polygon.
Concave Polygons: In a concave polygon, a line segment connecting any two points may or may
not lie inside the polygon.
Scan Line Polygon Fill Algorithms
● For each scan lines crossing a polygon are then sorted from left to right, and the
corresponding frame buffer positions between each intersection pair are set to the
specified color.
● These intersection points are then sorted from left to right , and the corresponding
frame buffer positions between each intersection pair are set to specified color
● Some scan-Line intersections at polygon vertices require special handling:
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:
Test Cases
T_ID T_Name Condition to test Expected outcome Pass/Fail
T_F1 Seed point Selected pixel is Polygon will fill with given
checking inside the polygon color
Selected pixel is Polygon will not fill
outside the polygon
T_F2 Polygon Polygon of small Get filled
Size testing size
Polygon of large Due to recursive fall
size system error will occur
CONCLUSION: Scan Line algorithm can be used for filling the simple as well as complex
polygon efficiently.
FAQs
1. What are active edges?
Ans: Edges that are inserted by current scan line are called active edges.
2. What is scan line?
Ans: Horizontal line across the y axix
3. What is span?
Ans: pixels between to active edges
4. What is complex polygon?
Ans: intersecting or overlapping polygons
5. Why to sort ymax and y min of polygon edges?
Ans: So algorithm will start at ymin or ymax of polygon instead of ymin and ymax of window.
6. Why to sort xmin and xmax?
Ans: To make pair for filling per active edge
PREREQUISITES:
● Knowledge of windowing
COURSE OBJECTIVE:
COURSE OUTCOME:
1. Develop scientific and strategic approach to solve complex problems in the domain of
Computer Graphics
2. Develop the competency to understand the concepts related to Computer Vision and
Virtual reality
THEORY:
Clipping :
1. Accept (and draw) lines that have both endpoints inside the region
2. Reject (and don’t draw) lines that have both endpoints less than xmin or ymin or
greater than xmax or ymax
3. Clip the remaining lines at a region boundary and repeat steps 1 and 2 on the
clipped line segments
FAQ:
1. What are types clipping algorithms?
Ans: Point clipping, Line Clipping, Polygon Clipping and Text Clipping
2. What is viewing transformation?
Ans: Mapping of picture coordinates to display coordinates is viewing transformation
3. What is windowing?
Ans: The process of selecting and viewing the picture with different views is called windowing.
4. What is window?
Ans: To perform viwing transformation we select a finite world co-ordinate area for display
called a windowing.
5. What is viewport?
Ans: An area on divice to which window is mapped
6. Name polygon clipping algorithm
Ans: Sudherland Hodgman polygon clipping algorithm
AIM: To apply the basic 2D transformations such as translation, Scaling, Rotation for a
given 2D object.
PROBLEM STATEMENT A : Write C++/Java program to draw 2-D object and perform
following basic transformations,
b) Scaling
c) Translation
d) Rotation
Use operator overloading.
PREREQUISITES:
COURSE OBJECTIVE:
1. To acquaint the learner with the basic concepts of Computer Graphics
2. To get familiar with mathematics behind the graphical transformations
COURSE OUTCOME:
1. Develop scientific and strategic approach to solve complex problems in the domain of
Computer Graphics
THEORY:
A. Transformations:
Transformations allow us to uniformly alter the entire picture. The geometric transformations
considered here - translation, scaling and rotation are expressed in terms of matrix multiplication.
Example:
Homogenous Coordinates
To perform a sequence of transformation such as translation followed
by rotation and scaling, we need to follow a sequential process −
To shorten this process, we have to use 3×3 transformation matrix instead of 2×2 transformation
matrix. To convert a 2×2 matrix to 3×3 matrix, we have to add an extra dummy coordinate W.
In this way, we can represent the point by 3 numbers instead of 2 numbers, which is called
Homogenous Coordinate system. In this system, we can represent all the transformation
equations in matrix multiplication.
Scaling
scaling refers to changing the size of the object either by increasing or decreasing. We will
increase or decrease the size of the object based on scaling factors along x and y-axis.
Scaling can be achieved by multiplying the original coordinates of the object with the scaling
factor to get the desired result.
The scaling factor SX, SY scales the object in X and Y direction respectively.
The above equations can also be represented in matrix form as below
−
X’ X Sx 0
Y’ = Y
0 Sy
scaling is performed about the origin (0,0) not about the center of the line/polygon/whatever
uniform scaling: Sx = Sy
differential scaling Sx != Sy -> alters proportions
If we
provide
values
less than 1 to the scaling factor S, then we can reduce the size of the object. If we provide values
greater than 1, then we can increase the size of the object.
Rotation
In rotation, we rotate the object at particular angle θ (theta) from its origin. From the following
figure, we can see that the point P(X, Y) is located at angle φ from the horizontal X coordinate
with distance r from the origin.
X = r cosϕ (1)
Y = r sinϕ (2)
Same way we can represent the point P’ (X’, Y’) as −
x′ = r cos(ϕ+θ) = r cosϕ cosθ − r sinϕ sinθ (3)
y′ = r sin(ϕ+θ) = r cosϕ sinθ + r sinϕ cosθ. (4)
Substituting equation (1) & (2) in (3) & (4) respectively, we will get
x′ = x cosθ –y sinθ
y′ = x sinθ + y cosθ
Representing the above equation in matrix form,
X’ X’
Y’ = Y’
OR P’ = P . R
Where R is the rotation matrix
cos θ sin θ
R= -sin θ cos θ
The rotation angle can be positive and negative.
For positive rotation angle, we can use the above rotation matrix.
However, for negative angle rotation, the matrix will change as shown
below −
Translation
A translation moves an object to a different position on the screen. You can translate a point in
2D by adding translation coordinate (tx, ty) to the original coordinate (X, Y) to get the new
coordinate (X’, Y’).
Translation Distance: It is nothing but by how much units we should shift the object from one
location to another along x, y-axis.
From the above figure, you can write that −
X’ = X + tx
Y’ = Y + ty
The pair (tx, ty) is called the translation vector or shift vector. The above equations can also be
represented using the column vectors.
P = [X] / [Y]
p' = [X′] / [Y′]
T = [tx] / [ty]
We can write it as - P’ = P + T
Shear
A transformation that slants the shape of an object is called the shear transformation. There are
two shear transformations X-Shear and Y-Shear. One shifts X coordinates values and other shifts
Y coordinate values. However; in both the cases only one coordinate changes its coordinates and
other preserves its values. Shearing is also termed as Skewing.
X-Shear
The X-Shear preserves the Y coordinate and changes are made to X coordinates, which causes
the vertical lines to tilt right or left as shown in below figure.
1 Shy 0
0 1 0
Ysh =
0 0 1
Y’ = Y + Shy . X
X’ = X
Reflection
Reflection in computer graphics is used to emulate reflective objects like mirrors and shiny
surfaces.
Homogeneous Matrices:
Translation Scaling
Sx 0 0
1 0 0
0 Sy 0
0 1 0
0 0 1
Tx Ty 1
cosθ sinθ 0 -1 0 0
0 -1 0
-sinθ cosθ 0
0 0 1
0 0 1
X- Shear Y-Shear
1 0 0 1 Shy 0
Shx 1 0 0 1 0
0 0 1 0 0 1
Algorithm:
1. Read input object in the form of matrix
2. Multiply input matrix with transformation matrix
3. Repeat same for all transformations
4. Display transformed object
5. Stop
OOP’s concepts used
1. Class
2. Operator Overloading
FAQs:
1. Perform a counterclockwise 450 rotation of triangle A(2,3), B(5,5), C(4,3) about
point (1,1).
2. A point (4,3) is rotated counterclockwise by an angle of 450. Find the rotation matrix
and the resultant point.
3. Translate the polygon with co-ordinates A(2,5), B(7,10) and C(10,2) by 3 units in
x direction and 4 units in y direction.
4. Scale the polygon with co-ordinates A(2,5), B(7,10) and C(10,2) by 2 units in x
direction and 2 units in y direction.
5. Give a 3*3 homogeneous co-ordinate transformation matrix for each of
following translations
a) Shift image to right 3 units
b) Shift image up 2 units
c) Move image down 1 units
PROBLEM STATEMENT: Write C++ program to generate fractal patterns by using Koch
curves.
PREREQUISITES:
COURSE OBJECTIVE:
1. Develop the competency to understand the concepts related to Computer Vision and
Virtual reality
THEORY:
Fractals : Fractals are very complex pictures generated by a computer from a single formula.
They are created using iterations. This means one formula is repeated with slightly different
values over and over again, taking into account the results from the previous iteration.
Fractals are used in many areas such as −
Koch curve :
The Koch curve is also known as snowflake curve. It is drawn by dividing line into 4 equal
segments with scaling factor 1/3 & middle 2 segments are so adjusted that they form adjacent
sides of equilateral triangle. Repeat same process for each of the 4 segments. Each repetition
increases length by factor 4/3.
Fractal dimension:
4=3D
D= log34= log 4/ log 3 = 1.2618
Therefore for Koch curve topological dimension is 1, but fractal dimension is 1.2618 hence Koch
curve is fractal.
Algorithm
1. Divide line into 4 equal segments with scaling factor 1/3.
2. Adjust middle 2 segments that they form adjacent sides of equilateral triangle.
5. Stop
FAQs:
PROBLEM STATEMENT: Write OpenGL program to draw Sun Rise and Sun Set
PREREQUISITES:
1. Basic programming skills of OpenGL
2. Graphics Primitive for OpenGL
COURSE OBJECTIVE:
COURSE OUTCOME:
THEORY:
OpenGL
e.g. include<gl/GL.h>
2. GLUT: GL utility toolkit. Related with managing windows, menu and events
e.g. include<gl/GLUT.h>
3. GLU: Involves high level routines to handle matrix operation , drawing 3D
surfaces.
e.g. include<gl/GLU.h>
4. GLUI: User interface library. Control and menus can be added to application.
OpenGL Primitives: Following are the graphics primitives present in OpenGL:
Vertex Primitives: Command for vertex representation is explained below.
e.g. glVertex2i(..)
gl: library Vertex: Basic command 2: no. of arguments i: datatype
Point Primitives: This will cause OpenGL to interpret each individual vertex in the stream as a
point.
● GL_POINTS
Line Primitives:
There are 3 kinds of line primitives, based on different interpretations of a vertex stream.
FAQs:
PROBLEM STATEMENT: Write C++ program to draw man walking in the rain with an umbrella. Apply
the concept of polymorphism.
PREREQUISITES:
1. Basic programming skills of C++
2. Graphics Primitive for C++
3. Basic steps to generate animation
COURSE OBJECTIVE:
COURSE OUTCOME:
THEORY:
Animation means giving life to any object in computer graphics. Computer-assisted animation
and computer-generated animation are two categories of computer animation. It can be presented
via film or video.
The basic idea behind animation is to play back the recorded images at the rates fast enough to
fool the human eye into interpreting them as continuous motion. Animation can be used in many
areas like entertainment, computer aided-design, scientific visualization, training, education, e-
commerce, and computer art.
Animation Techniques
Animators have invented and used a variety of different animation techniques. Basically there
are six animation techniques which we would discuss one by one in this section.
Traditionally most of the animation was done by hand. All the frames in an animation had to be
drawn by hand. Since each second of animation requires 24 frames (film), the amount of efforts
required to create even the shortest of movies can be tremendous.
2. Keyframing
In this technique, a storyboard is laid out and then the artists draw the major frames of the
animation. Major frames are the ones in which prominent changes take place. They are the key
points of animation. Keyframing requires that the animator specifies critical or key positions for
the objects. The computer then automatically fills in the missing frames by smoothly
interpolating between those positions.
3. Procedural
4. Behavioral
In behavioral animation, an autonomous character determines its own actions, at least to a certain
extent. This gives the character some ability to improvise, and frees the animator from the need
to specify each detail of every character's motion.
Another technique is Motion Capture, in which magnetic or vision-based sensors record the
actions of a human or animal object in three dimensions. A computer then uses these data to
animate the object.
This technology has enabled a number of famous athletes to supply the actions for characters in
sports video games. Motion capture is pretty popular with the animators mainly because some of
the commonplace human actions can be captured with relative ease. However, there can be
serious discrepancies between the shapes or dimensions of the subject and the graphical
character and this may lead to problems of exact execution.
Unlike key framing and motion picture, simulation uses the laws of physics to generate motion
of pictures and other objects. Simulations can be easily used to produce slightly different
sequences while maintaining physical realism. Secondly, real-time simulations allow a higher
degree of interactivity where the real person can maneuver the actions of the simulated character.
In contrast the applications based on key-framing and motion select and modify motions form a
pre-computed library of motions. One drawback that simulation suffers from is the expertise and
time required to handcraft the appropriate controls systems.
• Goal-Directed Systems : We can specify the motions that are to take place in general
terms that abstractly describe the actions. These systems are referred to as goal directed
because they determine specific motion parameters given the goals of the animation.
For example, We could specify that we want an object to "walk " or to "run" to a particular
destination. Or We could state that we want an object to "pick up " some other specified
object.
FAQs:
1. List down films based on animation
PREREQUISITES:
COURSE OBJECTIVE:
THEORY:
Blender is a professional free and open-source 3D computer graphics software product used for
creating animated films, visual effects, art, 3D printed models, interactive 3D applications and
video games. Blender's features include 3D modeling, UV unwrapping, texturing, raster graphics
editing, rigging and skinning, fluid and smoke simulation, particle simulation, soft body
simulation, sculpting, animating, match moving, camera tracking, rendering, video editing and
compositing.
Features
Official releases of Blender for Microsoft Windows, Mac OS X, and Linux, as well as a port for
FreeBSD, are available in both 32-bit and 64-bit versions.
● Support for a variety of geometric primitives, including polygon meshes, fast subdivision
surface modeling, Bezier curves, NURBS surfaces, metaballs, multi-res digital sculpting
(including dynamic topology, maps baking, remeshing, resymetrize, decimation..),
outline font, and a new n-gon modeling system called B-mesh.
● Keyframed animation tools including inverse kinematics, armature (skeletal), hook, curve
and lattice-based deformations, shape keys (morph target animation), non-linear
animation, constraints, and vertex weighting
Algorithm:
1) Take UVSphere on Mesh from Add-> Mesh->UVSphere toolbar
2) Add key frame style movement to the ball. With the ball selected press i to insert a
location key frame. Now press the up arrow we will see the number of key frames
increase on the bottom of the screen 51 represents the number of frames. Go up to 75 key
frames so that the ball has a smooth 3 second bounce.
3) Save the location of ball in every keyframe, press s.
4) Run the Animation ,click on start button or Press P Button from Keyboard
CONCLUSION:
● Blender is free and open-source 3D computer graphics software product used for creating
animations.
● Screen Saver is created as a part of content beyond syllabus
FAQs:
Ans: Maya 3D animation, modeling, simulation and rendering software offers artists a
comprehensive creative tool set.
2. List Open Source Software for creating Animation
3. What is animation?
4. What is fps?