CG
CG
2023-24
Assignment No. 1
Title A concave polygon filling using scan fill algorithm.
Aim/Problem Write C++ program to draw a concave polygon and fill it with desired color
Statement using scan fill algorithm. Apply the concept of inheritance.
Pre-requisite l. Basic programming skills of C++
2. 64-bit Open source Linux/windows
3. Open Source C++ Programming tool Ike G++/GCC
3
6 5
Polygons
Types of Polygons
1.Concave
2.Convex
3.Complex
A convex polygon is a simple Polygon whose interior is a convex set. In a convex polygon, all
interior angles are less than 180 degrees.
Convex Polygons: In a convex polygon, any line segment joining any two inside points lies inside
the polygon. A straight drawn through a convex polygon crosses at most two sides.
A concave polygon will always have an interior angle greater than 180 degrees. It is possible to cut
a concave polygon into a set of convex polygons. You can draw at least one straight line through a
concave polygon that crosses more than two sides.
Lab Manual -CGL
CG Lab Manual SE COMP, Sem-l, AY. 2020-21
Complex polygon is a polygon whose sides cross over each other one or more times.
(Xmin, Ymin)
2. If this scan
1) Does not pass through any of the vertices then its contribution is equal to the number of times it
intersects the edges of the polygon. Say C if
a) C is odd then A lies inside the polygon.
b) C is even then it lies outside the polygon.
i) If it passes through any of the vertices then the contribution of this intersection say V is,
a) Taken as 2 or even. If the other points of the two edges lie on one side of the scan line.
b) Taken as 1 if the other end points of the 2 edges lie on the opposite sides of the scan- line. c)
Here will total contribution is C + V.
Polygon Filling:
For filling polygons with particular colors, you need to determine the pixels falling on the border of the
Polygon and those which fall inside the polygon
A scan-line fill of a region is performed by first determining the intersection positions of the
boundaries of the fill region with the screen scan lines v Then the fill colors are applied to each section
of a scan line that lies within the interior of the fill region v The scan-line fill algorithm identifies the
same interior regions as the odd-even rule.
It is an image space algorithm. It processes one line at a rather than one pixel at a time. It uses the
concept area of coherence. This algorithm records edge list, active edge list. So accurate bookkeeping
is necessary. The edge list or edge table contains the coordinate of two end points. Active Edge List
(AEL) contain edges a given scan line intersects during its sweep. The active edge list (AEL) should
ymn
Algorithm
Step1: Start algorithm
Step2: Initialize the desired data structure
1. Enter values in Active edge list (AEL) in sorted order using y as value
2. Scan until the flag, i.e. F on using a background color
3. When one polygon flag is on, and this is for surface S I enter color intensity as Il into refresh
buffer
4. When two or image surface flag are on, sort the surfaces according to depth and use intensity
value Sn for the nth surface. This surface will have least z depth value
5. Use the concept of coherence for remaining planes.
Step4: Stop Algorithm
Conclusion: Scan Line algorithm can be used for filling the simple as well as complex polygon
efficiently.
Questions:
l. Which are the different approaches to fill a polygon?
2 What are advantages and drawbacks of scan line polygon fill algorithm?
Lab Manual -CGL
CG
Lab
Manual SE COMP, Sem-l, AY. 2020-21
Assignment No. 2
Title Polygon clipping using Cohen Southerland line clipping algorithm
Aim/Problem Write C++ program to implement Cohen Southerland line clipping
Statement algorithm.
CO Mapped CO4
Pre -requisite l. Basic programming skills of C++
2. 64-bit Open source Linux/windows
3. Open Source C++ Programming tool Ike G++/GCC
Algorithm
The algorithm divides a two-dimensional space into 9 regions (eight outside regions and one inside region)
and then efficiently determines the lines and m»rtions of lines that are visible in the central region of intelest
(the viewport).
Following image illustrates the 9 regions:
CG
Lab
Manual 1001SE 1000
COMP, Sem-l,
1010 AY. 2020-21
3 2
above below right left
0001 0010
Region
Code Legend 0101 0100 0110
As you seen each region is denoted by a 4 bit code like 0101 for the bottom right region
Four Bit code is calculated by comparing extreme end point of given line (x,y) by four co-
ordinates x_min, x_max, y_max, y_min which are the coordinates of the area of interest (0000)
Pseudocode
Step 1 : Assign a legion code for two end points of given line
Step 2 : If both endpoints have a region code 0000 then given line is completely inside and we
will keep this line.
Step 3: If step 2 fails, perform the logical AND operation for both legion codes.
Step 3.1 : If the result is not 0000, then given line is completely outside.
Step 3.2 : Else line is partially inside.
Step 3.2.a : Choose an endpoint of the line that is outside the given rectangle.
Step 3.2.b : Find the intersection point of the rectangular boundary(based on region code)
Lab Manual -CGL
CG
Lab
Manual SE COMP, Sem-l, AY. 2020-21
Step 3.2.c : Replace endpoint with the intersection point and upgrade the region code.
Step 3.2.d : Repeat step 2 until we find a clipped lirr either trivially accepted or
rejected.
Step 4: Repeat step 1 for all lines.
Questions:
1. What is the limitation of Cohen Sutherland Line Clipping algorithm?
2. What are the advantages of Cohen Sutherland Line Clipping?
Assignment No. 3
Title Pattern drawing using line and circle.
Aim/Problem Write C++ program to draw a given pattern. Use DDA line and Bresenham's
Statement circle drawing algorithm. I the co of encapsulation.
Pre -requisite l. Basic programming skills of C++
2. 64-bit Open source Linux
3. Open Source C++ Programming tool Ike G++/GCC/windows
Learning To learn and apply DDA line and Bresenham's circle drawing algorithm.
Objective
Theory:
Line is a basic element in graphics. To draw a line, you need two end points between which you can
draw a line. Digital Differential Analyzer (DDA) line drawing algorithm the simplest line drawing
algorithm in computer graphics. It works on incremental method. It plots the pints from starting EX)int
of line to end pint of line by incrementing in X and Y direction each
Step 1: Get coordinates of both the end points (Xl, Y1) and (X2, Y2) from user.
Step 2: Calculate the difference between two end pints in X and Y direction.
dx=X2-X1;
dy=Y2-Y1;
Step 3: Based on the calculated difference in step-2, you need to identify the number of steps to put
pixel. If dx > dy, then you need more steps in x coordinate; otherwise in y coordinate.
} while(x<y)
Here in step 5, putpixel() function is used which will print Octant-I of the circle with radius r after the
completion of all the iterations of do-while loop. Because of the eight-way symmetry property of circle,
we can draw other octants of the circle using following putpixel() functions:
Octant 1: putpixel(centx+x, centy-y, ColorName);
Octant 2: putpixel(centx+y, centy-x, ColorName);
Octant 3: putpixel(centx+y, centy+x, ColorName);
Octant 4: putpixel(centx+x, centy+y, ColorName);
Octant 5: putpixel(centx-x, centy+y, ColorName);
Octant 6: putpixel(centx-y, centy+x, ColorName);
Octant 7.• putpixel(centx-y, centy-x, ColorName);
Octant 8: putpixel(centx-x, centy-y, ColorName);
This pattern is made up of one equilateral triangle and two concentric circles. To draw the triangle, we
require coordinates of 3 vertices forming an equilateral triangle. To draw two concentric circles, we
require coordinates of common center and radius of both the circles.
We will take coordinates of circle and radius of one of the circle from user. Then using the
properties of an equilateral triangle, we can find all 3 vertices of equilateral triangle and radius of other
circle. Once we get all these parameters, we can call DDA line drawing and Bresenham's circle
drawing algorithm by passing appropriate parameters to get required pattern.
Conclusion: Circle can be drawn using eight-way symmetry. Midpoint & Bresenham' s circle
algorithms are implemented.
CG
Lab
Manual SE COMP, Sem-l, AY. 2020-21
Assignment No. 4
Title Basic 2-D Transformations.
Aim/Problem a) Write C++ program to draw 2-D object and perform following basic
Statement transformations: Scaling, Translation, Rotation. Apply the concept of operator
overloading.
OR
b) Write program to implement translation, rotation and scaling
transformations on equilateral triangle and rhombus. Apply the concept of
operator overloading.
CO Mapped CO4
Pre -requisite l. Basic programming skills of C++
2. 64-bit Open source Linux/windows
3. Open Source C++ Programming tool Ike G++/GCC
1) Translation:
A translation moves an object to a different position on the screen. You can translate a in 2D by
adding translation coordinate or translation vector (TX, Ty) to the original coordinates. Consider
Initial coordinates of the object O = (Xold, Yold)
New coordinates of the object O after translation = (X
Translation vector or Shift vector = (TX, Ty)
This translation is achieved by adding the translation coordinates to the old coordinates of the object
Translation Matrix
2) Rotation:
In rotation. we rotate the obiect at particular angle (theta) from its original position. Consider
Initial coordinates of the obiect O (Xold, Yold)
Initial angle of the object O with respect to origin =
Rotation angle =
New coordinates of the object O after rotation = (Xnew,Ynew)
Rotation
cos9 -
sine sine x
cose
Rotation Matrix
3) Scaling:
Scaling transformation is used to change the size of an object. In the scaling process, you either
expand or compress the dimensions of the object. Scaling can achieved by multiplying the original
coordinates of the object with the scaling factor (Sx,Sy). If scaling factor > l, then the
CG Lab Manual SE AIDS, Sem-l, AY. 2023-24
object size increased. If scaling factor < l, then the object size reduced. Consider
Initial coordinates of the object O — (Xold, Yold)
Scaling Matrix
Homogeneous Coordinates:
Matrix multiplication is easier to in hardware and software as compared to nutrix addition
Hence we want to replace matrix addition by multiplication while performing transformation
operations. So the solution is homogeneous coordinates , which allows us to express all
transformations (including translation) as matrix multiplications.
To obtain homogeneous coordinates we have to represent transformation matrices in 3x3 matrices
instead of 2x2. For this we add dummy coordinate. Each 2 dimensional position (x,y) can
represented by homogeneous coordinate as (x,y, 1 ).
1 0x
o
Similarly we can apply rotation and scaling on rhombus.
Questions:
3. How to rotate any 2-D object about an arbitrary point? Explain in brief.
4. Explain the concept of operator overloading with example.
Assignment No. 5
Title Curves and fractals
Aim/Problem a) Write C++ program to generate snowflake using concept of fractals.
Statement OR
b) Write C++ program to generate curve using concept of fractals.
OR
c) Write C++ program to generate fractal patterns by using Kochcurves.
Pre -requisite Basic programming skill of C++.
2. 64-bit Open source Linux/Windows
3. Open Source C++ Programming tool Ike G++/GCC
Iteration O
Iteration 1 Iteration 2
Iteration 3 Iteration 4
Step 3: In iteration 2, you will repeat step 2 for every segment obtained in iterations1.
In this way, you can generate Koch curve for any number of iterations.
A first order Hilbert curve is just a single cup (see the figure
on the left). It fills a 2x2 space. The second order Hilbert curve
replaces that cup by four (smaller) cups, which are linked
together by three joins (see the figure on the right; the link
between a cu and a join has been marked with a fat dot in the
figure). Ever next order repeats the process or replacing each cup by four
smaller cups and three joins.
The function presented (in the "C" language) computes the Hilbert curve. Note that the curve is
symmetrical around the vertical axis. It would therefore be sufficient to draw half of the Hilbert curve.
Snowflake curve:
Snowflake curve is drawn using koch curve iterations. In koch curve, we just have a single line in the
starting iteration and in snowflake curve, we have an equilateral triangle. Draw an equilateral triangle
and repeat the Steps of Koch curve generation for all three segments of an equilateral triangle.
Iteration O
Iteration I
Iteration 2 Iteration 3
Assignment No. 6
Title Implementation of OpenGL functions
Aim/Problem a) Design and simulate any data structure like stack or queue
Statement visualization using graphics. Simulation should include all operations
performed on designed data structure. Implement the same using OpenGL
OR
b) Write C++ program to draw 3-D cube and perform following
transformations on it using OpenGL i) Scaling ii) Translation iii) Rotation
about an axis (X/Y/Z).
OR
c) Write OpenGL program to draw Sun Rise and Sunset.
Pre -requisite l. Basic programming skills of and OpenGL
2. 64-bit Open source Linux/windows
3. Open Source C++ Programming tool Ike GH/GCC, OpenGL
Development: It an evolving API and Khronos Group regularly releases its new version having
some extended feature compare to previous one. GPU vendors may also provide additional
functionality in the form of extension.
Associated Libraries: The earliest version released with a companion library called OpenGL
utility library. But since OpenGL is quite a complex process. So in order to make it easier other library
such as OpenGL Utility Toolkit is added which is later superseded by freeglut. Later included library
were GLEE, GLEW and glbinding.
OpenGL provides a consistent interface to the underlying graphics hardware. abstraction allows a single
program to run a different graphics hardware easily. A program written with OpenGL can even be run
in software (slowly) on machines with no graphics acceleration. OpenGL function names always with
gl, such as glClear(), and they may end with characters that indicate the types of the parameters, for
example glColor3f(GLfloat red, GLfloat green, GLfloat blue) takes three floating-point color
parameters and glColor4dv(const GLdouble *v) takes a pointer to an array that contains 4 double
precision floating-EX)int values. OpenGL constants with GL, such as GL DEPTH. OpenGL also uses
special names for types that are passed to its functions, such as GLfloat or GLint, the corresponding C
types are compatible, that is float and int respectively.
GLU is the OpenGL utility library. It contains useful functions at a higher level than those provided
by OpenGL for example, to draw complex shapes or set up cameras. All GLU functions are written
on top of OpenGL Like OpenGL GLU function names with glu, and constants with GLU.
GLUT, the OpenGL Utility Toolkit, provides a system for setting up call backs for interacting with
the user and functions for dealing with the windowing system. This abstraction allows a program to
run on different operating systems with only a recompile. Glut follows the convention of
prepending function names with glut and constants with GLUT.
#include
#include
#include
Before OpenGL rendering calls can be made, some initialization has to be done. With GLUT, this
consists of initializing the GLUT library, initializing the mode, creating the window, and
setting up callback functions. The following lines initialize a full color, double buffered
display: glutlnit (&argc, argv); glut1nitDisp1ay Mode(GLUT DOUBLE / GLUT RGB);
Double buffering means that there are two buffers, a front buffer and a back buffer. The front buffer
is displayed to the user, while the back buffer is used for rendering operations. This prevents flickering
that would occur if we rendered directly to the front buffer.
Next, a window is created with GLUT that will contain the viewport which displays the OpenGL
front buffer with the following three lines:
glutlnitWindowPosition(px, py);
glutlnirWindowSize(sx, sy);
glutCreateWindow(name);
To register callback functions, we simply pass the name of the function that handles the event to
the appropriate GLUT function.
glutReshapeFunc(reshape);
glutDisplayFunc(display);
Here, the functions should have the following prototypes:
void reshape(int width, int height);
void display();
In this example, when the user resizes the window, reshape is called by GLUT, and when the display
needs to be refreshed, the display function called. For animation, an idk event handler that takes no
arguments can be created to call the display function to constantly redraw the scene with glutldleFunc.
Once all the callbacks have been set up, a call to glurMainLoop allows the program to run.
In the display function, typically the image buffer is cleared, primitives are rendered to it, and the
results are presented to the user. The following line clears the image buffer, setting each pixel color
to the clear color, which can be configured to any color:
BIT);
The next line sets the current rendering color to blue. OpenGL behaves Ike a state machine, so
certain state such as the rendering color is saved by OpenGL and used automatically later as it is
needed.
To render a primitive, such as a point, line, or polygon, OpenGL requires that a call to glBegin is
made to specify the type of primitive rendered.
Only a subset of OpenGL commands is available after a call to glBegin. The main command that is
used is glVertex, which specifies a vertex position. In GL LINES mode, each pair of vertices define
endpoints of a line segment. In this case, a line would drawn from the point at ( xo, yo) to (xl, yl).
A call to glEnd completes rendering of the current primitive. glEnd(); Finally, the back buffer needs
to swapped to the front buffer that the user will see, which GLUT can handle for us:
glutSwapBuffers();
Developer-Driven Advantages
Industry standard
An independent consortium, the (WIGL Architecture Review Board, guides the OpenGL
specification. With broad industry support, (WIGL is the only truly open, vendor-neutral,
multiplatform graphics standard.
Stable
OpenGL have been for more than seven years on a wide variety of platforms.
Additions to the specification are well controlled, and proposed updates are announced in tinæ for
developers to adopt changes. Backward compatibility requirements ensure that existing applications
do not obsolete.
Reliable and portable
All OpenGL applications produce consistent visual display results on any OpenGL API-compliant
hardware, regardless of operating system or windowing system.
Evolving
Because of its thorough and forward-looking design, OpenGL allows new hardware innovations to
be accessible through the API via the OpenGL extension mechanism. In way, innovations appear in
the API in a timely fashion, letting application developers and hardware vendors incorporate new
features into their normal product release cycles.
Scalable
OpenGL API-based applications can run on systems ranging from consumer electronics to PCs,
workstations, and supercomputers. As a result, applications can scale to any class of machine that the
developer chooses to target.
Easy to use
(WIGL is well structured with an intuitive design and logical commands. Efficient OpenGL routines
typically result in applications with fewer lines of code than those that make up programs generated
using other graphics libraries or packages. In addition, OpenGL drivers encapsulate information about
the underlying hardware, freeing the application developer from having to design for hardware
features.
Well-documented:
Numerous books have been published about OpenGL, and a great deal of sample code is readily
available, making information about OpenGL inexpensive and easy to obtain.
Conclusion: OpenGL is free and open-source computer graphics tool used to develop programs.
Questions:
What are the advantages of Open GL over otiær API's? 2
Explain rendering with reference to OpenGL
Assignment No. 7
Title Animation using C++
Aim/Problem a) Write a C++ program to control a ball using arrow
Stateme nt keys. Apply the concept of polymorphism.
OR
Write a C++ program to implement bouncing ball
using sine wave form Apply the concept
polymorphism.
OR
Write C++ program to draw man walking in the rain
with an umbrella. Apply the concept of
polymorphism.
OR
Write a C++ program to implement the game of 8
puzzle. Apply the concept of polymorphism.
OR
Write a C++ program to implement the game Tic
Tac Toe. Apply the concept of polymorphism.
Pre- I. Basic programming skills of C++
requisite 2. 64-bit Open source Linux/windows
3. Open Source C++ Programming tool Ike G++/GCC
To detect which arrow key is pressed, you can use ncurses.h header file. Arrow key's code is
defined as: KEY_UP, KEY_DOWN, KEY_LEFT, KEY RIGHT.
int ch;
/ * Curses Initialisations
initscr ();
raw ();
keypad (stdscr, TRUE);
noecho() ;
while((ch — getch())
switch (ch)
{
case KEY_UP: printw("\nUp Arrow");
break;
return 0;
int main()
/ * increment angle * /
angle+=5;
}
/* deallocate memory allocated for graphics screen
closegraph();
return 0;
A game of 8 puzzle:
An 8 puzzle is a simple game consisting of a 3 x 3 grid (containing 9 squares). One of the squares is
empty. The object to move to squares around into different positions and having the numbers displayed in the
"'goal state". The image to the left can be thought of as an unsolved initial state of the "3 x 3" 8 punk. Eight
digits will in random order. To Olve a puzzle, you have to move blocks by performing translation of blocks.
a draw.
Note: In all above programs, you have to perform translation of an image to show animation effect.