OOP&CG GDP Lab Manual
OOP&CG GDP Lab Manual
OOP&CG GDP Lab Manual
Department of
Computer Engineering
LABORATORY MANUAL
OOP and Computer graphics Lab
Examination TW:25
Scheme Practical:25
Credits 02
Write a program in C++ to use map associative container. The keys will be
7.
the names of states and the values will be the populations of the states.
When the program runs, the user is prompted to type the name of a state.
The program then looks in the map, using the state name as an index and
returns the population of the state.
Group B
8. Write C++ program to draw the pattern. Use DDA line and Bresenham‗s
circle drawing algorithm. Apply the concept of encapsulation.
9. Write C++ program to draw a concave polygon and fill it with desired color
using scan fill algorithm. Apply the concept of inheritance.
Write C++ program to implement Cohen Southerland line clipping
10.
algorithm.
11. Write C++ program to draw 2-D object and perform following basic
transformations a )Scaling b) Translation c) Rotation. Apply the concept of
operator overloading.
12. Write C++ program to generate Hilbert curve using concept of fractals.
14. Write a C++ program to implement bouncing ball using sine wave form.
Apply the concept of polymorphism.
15. Design and implement game / animation clip / Graphics Editor using open
source graphics library. Make use of maximum features of Object Oriented
Programming.
Mission
Our mission is to create self-disciplined, physically fit, mentally robust and morally
strong engineers and technocrats with high degree of integrity and sense of purpose
who are capable to meet challenges of ever advancing technology for the benefit of
mankind and nature.
We, the management, the faculty and staff, therefore promise to strive hard and
commit ourselves to achieve this objective through a continuous process of learning
and appreciation of needs of time.
Vision
To serve the needs of society through excellent technical education, promoting
Industry-Institute Interaction and develop competent and cultured Computer
Engineers.
Mission
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.
QUALITY POLICY
QUALITY OBJECTIVES
To strive hard for academic excellence and synergizing spiritual & moral values.
To improve overall development of student.
To enhance industry-institute interaction.
To provide assistance for placement & entrepreneurship development.
To promote and encourage R&D activities.
Aim: Implement a class Complex which represents the Complex Number data
type. Implement the following operations:
1. Constructor (including a default constructor which creates the complex
number0+0i).
2. Overload operator+ to add two complex numbers.
3. Overload operator* to multiply two complex numbers.
4. Overload << and >> to print and read Complex Numbers.
Software Requirements:
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12 public:
// required constructors
Distance ( ) {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
void displayDistance() // method to display distance
{
cout<< "F: " << feet << " I:" << inches <<endl;
}
Distance operator- () // overloaded unary minus (-) operator
{
feet = -feet; inches = -inches;
return Distance(feet, inches); } };
int main()
{
Distance D1(11, 10), D2(-5, 11);
-D1;
D1.displayDistance(); // displayD1
-D2;
D2.displayDistance(); // displayD1
return 0;
}
2. Binary Operator:
Overloading with a single parameter is called binary operator overloading. Similar to
unary operators, binary operators can also be overloaded. Binary operators require
two operands, and they are overloaded by using member functions and friend
functions.
Example:
using namespace std; class temp
{
ALGORITHM:
1. Start.
2. Create class complex with data members x and y and member functions accept(),
display().
3. Initialize 3 objects c1, c2, c3 and k in main().
4. Define default constructor to initialize variables to 0+0i.
5. Define operator overloaded functions to add, subtract, multiply and divide two
complex numbers.
Input :
Enter 2 complex and any 1 operator.
Output :
Desired arithmetic operation on complex no (i.e.+,-,*, /).
Questions:
1. Write class student with suitable data and create object for class.
2. Write different constructors for student class.
3. What is Operator Overloading? Explain with example
4. Write Rules of Operator overloading?
5. What is Friend Function? Explain Syntax.
Software Requirements:
1) Constructor is used for Initializing the values to the data members of the Class.
2) Constructor is that whose name is same as name of class.
3) Constructor gets automatically called when an object of class is created.
4) Constructors never have a Return Type even void.
5) Constructor is of Default, Parameterized and Copy Constructors.
The various types of Constructor are as follows:-
Constructors can be classified into 3 types
1 Default Constructor
2 Parameterized Constructor
3 Copy Constructor
Default Constructor:- Default Constructor is also called as Empty Constructor which
has no arguments and It is Automatically called when we creates the object of class
but Remember name of Constructor is same as name of class and Constructor never
declared with the help of Return Type.
Parameterized Constructor: - This is another type constructor which has some
Arguments and same name as class name but it uses some Arguments So For this
We have to create object of Class by passing some Arguments at the time of creating
object with the name of class. When we pass some Arguments to the Constructor then
this will automatically pass the Arguments to the Constructor and the values will
retrieve by the Respective Data Members of the Class.
Copy Constructor: - This is also another type of Constructor. In this Constructor we
pass the object of class into the Another Object of Same Class. As name Suggests you
Copy, means Copy the values of one Object into the another Object of Class .This is
used for Copying the values of class object into an another object of class So we call
them as Copy Constructor and For Copying the values We have to pass the name of
object whose values we wants to Copying and When we are using or passing an
Object to a Constructor then we must have to use the & Ampersand or Address
Operator.
Destructor:
As we know that Constructor is that which is used for Assigning Some Values to
data Members and For Assigning Some Values this May also used Some Memory so
that to free up the Memory which is Allocated by Constructor, destructor is used which
gets Automatically Called at the End of Program and we doesn‘t have to Explicitly Call
a Destructor and Destructor Cant be Parameterized or a Copy This can be only one
Means Default Destructor which Have no Arguments. For Declaring a Destructor we
have to use ~tiled Symbol in front of Destructor.
Static members
A class can contain static members, either data or functions. A static member variable
has following properties:
It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
Only one copy of that member is created for the entire class and is shared by all
the objects of that class.
It is the visible only within the class but its lifetime is the entire program.
Static data members of a class are also known as "class variables", because there is
only one unique value for all the objects of that same class. Their content is not
different from one object static members have the same properties as global variables
but they enjoy class scope. For that reason, and to avoid them to be declared several
times, we can only include the prototype (its declaration) in the class declaration but
not its definition (its initialization). In order to initialize a static data-member we must
include a formal definition outside the class, in the global scope of this class to
another. Because it is a unique variable value for all the objects of the same class, it
can be referred to as a member of any object of that class or even directly by the class
name (of course this is only valid for static members.
Friend functions:
In principle, private and protected members of a class cannot be accessed from
outside the same class in which they are declared. However, this rule does not affect
friends. Friends are functions or classes declared as such. If we want to declare an
external function as friend of a class, thus allowing this function to have access to the
private and protected members of this class, we do it by declaring a prototype of this
external function within the class, and preceding it with the keyword friend.
2. Since it is not in the scope of the class, it cannot be called using the object of
that class It can be invoked like a normal function w/o the help of any object.
3. It can be declared in private or in the public part of the class.
4. Unlike member functions, it cannot access the member names directly and has
to use an object name and dot operator with each member name.
// friend functions
#include<iostream>
using namespace std;
class CRectangle {
int width, height; public:
void set_values (int, int);
int area () {
return (width * height);
}
friend CRectangle duplicate (CRectangle);
};
void CRectangle::set_values (int a, int b)
{
width = a; height = b;
}
CRectangle duplicate (CRectangle rectparam)
{
CRectangle rectres;
rectres.width = rectparam.width*2;
rectres.height = rectparam.height*2; return (rectres);
}
int main()
{
CRectangle rect, rectb;
rect.set_values(2,3);
rectb = duplicate (rect);
cout<<rectb.area(); return 0;
}
The duplicate function is a friend of CRectangle. From within that function we have
been able to access the members width and height of different objects of type
CRectangle, which are private members. Notice that neither in the declaration of
duplicate() nor in its later use in main() have we considered duplicate a member of
class CRectangle.
Friend classes
Just as we have the possibility to define a friend function, we can also define a class
as friend of another one, granting that second class access to the protected and
private members of the first one.
Pointers:
A pointer is a derived data type that refers to another data variable by storing the
variables memory address rather than data.
Pointers to objects:
Consider the following eg
item X; // where item is class and X is object Similarly we can define a pointer it_ptr of
type item as follows Item *it_ptr ;
Object pointers are useful in creating objects at runtime. We can also access public
members of the class usingpointers.
Eg item X;
item *ptr = &X;
the pointer ptr is initialized with address of X.
we can access the member functions and data using pointers as follows
ptr-> getdata();
ptr->show();
this pointer:
C++ uses a unique keyword called this to represent an object that invokes a member
function. this is a pointer that points to the object for which this function was called.
This unique pointer is automatically passed to a member function when it is called.
Important notes on this pointer:
this pointer stores the address of the class instance, to enable pointer access
of the members to the member functions of the class.
this pointer is not counted for calculating the size of the object
this pointers are not accessible for static member functions.
this pointers are not modifiable.
Algorithm:
1. Start
2. Read personnel information such as Name, Roll number, Class, division, Date of
Birth, Blood group, Contact address, telephone number, driving license no.etc
3. Print all information from database.
4. Stop
Input:
Personnel information such as Name, Roll number, Class, division, Date of Birth,
Blood group, Contact address, telephone number, driving licence no. etc
.
Output:
Display personnel information from database. The result in following format:
QUESTIONS:-
1) What is Friend Function? Syntax.
2) What is Static Data Member and its Properties?
3) What is Dynamic Memory Allocation? Explain new and delete.
Aim: Imagine a publishing company which does marketing for book and audio
cassette versions. Create a class publication that stores the title (a string) and price
(type float) of a publication. From this class derive two classes: book, which adds a
page count (type int), and tape, which adds a playing time in minutes (type float).Write
a program that instantiates the book and tape classes, allows user to enter data and
displays the data members. If an exception is caught, replace all the data member
values with zero values.
Software Requirements:
Types of Inheritance
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid Inheritance
There are three types of class inheritance: public, private and protected The protected
access specifier is similar to private. Its only difference occurs in fact with inheritance.
When a class inherits from another one, the members of the derived class can access
the protected members inherited from the base class, but not its private members.
Difference between public, private and protected
A member (either data member or member function) declared in a private
section of a class can only be accessed by member functions and friends of
that class.
A member (either data member or member function) declared in a protected
section of a class can only be accessed by member functions and friends of
that class, and by member functions and friends of derived classes.
A member (either data member or member function) declared in a public section
of a class can be accessed by anyone.
What a derived class inherits
Every data member defined in the parent class (although such members may not
always be accessible in the derived class!)
Every ordinary member function of the parent class (although such members
always be accessible in the derived class!)
What a derived class doesn't inherit
The base class's constructors and destructor
The base class's assignment operator
#include<iostream>
#include<string.h> using namespace std;
class publication //Abstract class
{public:
float price;
string title;
void getpdata();
void displaypdata();
void setdata();
void displaybdata();
void displaytdata();
void publication::getpdata() //outside the class implementation
{cout<<"enter the title and price of book"<<endl;
cin>>title>>price;
}
Void publication::displaypdata() //outside the class implementation
{cout<<"title is="<<title<<endl;
cout<<"price="<<price<<endl;
}
book b;
tape t;
b.getpdata(); //class publication property.
b.setdata(); //class book property.
t.setdata(); //class tape property.
b.displaypdata();//class publication property.
b.displaybdata();//class book property.
t.displaytdata(); //class tape property.
return 0;
}
Algorithm:
1. Start
2. Read information i.book title(string),price(float), pagecount,
3. Print all information from database.
4. Stop
Input:
Base class publication which consist data members name of book(type string) and
price (type float)etc. two derived classes Book which contains data members page
count (type int)and Tape class consist playing time in minutes (type float).
Output:
1. Display table containing all data Member
2. Insert a new entry
Conclusion: Thus , students are able to apply inheritance and use of exception
handling.
QUESTIONS
1. What is Exception Handling with Example?
2. What is Abstract Class? explain in detail.
3. What is multi-level inheritance?
Experiment No: 4 Demonstrate various file operations using C++. Page 1/4
Aim: Write a C++ program that creates an output file, writes information to it, closes
the file and open it again as an input file and read the information from the file.
Software Requirements:
Experiment No: 4 Demonstrate various file operations using C++. Page 2/4
To perform file processing in C++, header files <iostream> and <fstream> must be
included in your C++ source file.
Opening a File:
A file must be opened before you can read from it or write to it. Either the ofstream or
fstream object may be used to open a file for writing and ifstream object is used to
open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream,
ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Here, the first argument specifies the name and location of the file to be opened and
the second argument of the open() member function defines the mode in which the file
should be opened.
ModeFlag Description
ios::app Append mode. All output to that file to be appended to the end.
ios::ate Open a file for output and move the read/write control to the end
of the file.
ios::in Open a file for reading.
Experiment No: 4 Demonstrate various file operations using C++. Page 3/4
Experiment No: 4 Demonstrate various file operations using C++. Page 4/4
Algorithm:
1. Include required header file like iostream (for keyboard input and output), fstream
(for file reading and writing), and cstdlib (for exit()).
2. In main(), read name of file from user.
3. Open file using ofstream for writing.
4. If file does not exist, new file will be created or existing file will be overwritten.
5. If any error occurs in creating or opening file, exit
6. Otherwise, open file.
7. Read string from user.
8. Check if given termination string is entered. (Here we will use ^D to end reading
contents from keyboard).
9. If ^D is entered, stop reading from keyboard.
10. Otherwise, read line from keyboard and write in file using <<.
11. Close the file.
12. Open the same file for reading.
13. Check if file opened for reading or display error message and exit.
14. In while loop, start reading from file line by line and display output on the terminal.
15. If end of file is reached, exit loop.
16. End program.
Questions:-
1. Explain fstream, ifstream, and ofstream.
2. What are the modes in file handling?
3. Advantages and Disadvantages of File Handling?
Experiment No: 5 Demonstrate function template for sorting algorithm. Page 1/4
Aim: Write a function template selection Sort. Write a program that inputs, sorts and
outputs an integer array and a float array.
Software Requirements:
Experiment No: 5 Demonstrate function template for sorting algorithm. Page 2/4
we could use:
template <class myType>
myType GetMax (myType a, myType b)
{
return (a>b?a:b);
}
Here we have created a template function with myType as its template parameter.
This template parameter represents a type that has not yet been specified, but that
can be used in the template function as if it were a regular type. As you can see, the
function template GetMax returns the greater of two parameters of this still-undefined
type.
Here in this program we have written a function for Selection sort and we have added
a template tag before the function so that, the parameter will be of the data type Name.
Everything is same except some variable data types. Take a look at the below
program, you‟ll get a clear idea.
In the main function we are passing some predefined values into the Selection
function by calling the function Selection(a,6) where a is the array containing integers
and 6 is the size of array. After passing the values into the function we are displaying
the sorted order. You can also rewrite the main function in a way that the user will
enter the data and size of the array.
Selection sort
The algorithm divides the input list into two parts: the sublist of items already sorted,
which is built up from left to right at the front (left) of the list, and the sublist of items
remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is
empty and the unsorted sublist is the entire input list. The algorithm proceeds by
finding the smallest (or largest, depending on sorting order) element in the unsorted
sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in
sorted order), and moving the sublist boundaries one element to the right.
Experiment No: 5 Demonstrate function template for sorting algorithm. Page 3/4
int i, j;
for (j = 0; j < n-1; j++)
{
int iMin = j;
for ( i = j+1; i < n; i++) { if (a[i] <a[iMin])
{
iMin = i;
}
}
if(iMin != j)
{
swap (a[j], a[iMin]);
}
}
Selection sort is not difficult to analyze compared to other sorting algorithms since
none of the loops depend on the data in the array. Selecting the lowest element
requires scanning all n elements (this takes n − 1 comparisons) and then swapping it
into the first position. Finding the next lowest element requires scanning there n−1
elements and soon, for (n−1)+(n−2)+...+ 2 + 1 = n(n - 1) / 2, Θ(n2) comparisons. Each
of these scans requires one swap for n − 1 elements (the final element is already in
place).
Algorithm Selection Sort:
Selection (A, N)
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list Step 3 − Swap with value at location
MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
Experiment No: 5 Demonstrate function template for sorting algorithm. Page 4/4
Algorithm:
1. Start
2. Read the numbers as integers or characters.
3. Sort them according to ascending order.
4. Print values as output.
Input:
Integer values, Float values.
Output:
Sorted order of integers as well as floats.
Conclusion: Thus, students will implement sorting of integer and float numbers.
Questions:
1. What is Function Template?
2. What is Sorting? Enlist Sorting Methods.
3. What is Container, Algorithm ,Iterator? Advantages of STL?
Experiment No: 6 Personnel information system using sorting and Page 1/5
searching for STL and vector.
Aim: Write C++ program using STL for sorting and searching user defined records
such as personal records (Name, DOB, Telephone number etc) using vector container.
OR
Write C++ program using STL for sorting and searching user defined records such as
Item records (Item code, name, cost, quantity etc) using vector container.
Software Requirements:
Experiment No: 6 Personnel information system using sorting and Page 2/5
searching for STL and vector.
Algorithms
The algorithm defines a collection of functions especially designed to be
used on ranges of elements. They act on containers and provide means for
various operations for the contents of the containers.
• Algorithm
• Sorting
• Searching
Important STL Algorithms
• Useful Array algorithms
• Partition Operations
• Numeric
Containers
Containers or container classes store objects and data. There are in total seven
standard ―first- class‖ container classes and three container adaptor classes and only
seven header files that provide access to these containers or container adaptors.
Sequence Containers: implement data structures which can be accessed in a
sequential manner.
vector
list
deque
arrays
priority_queue
stack
Experiment No: 6 Personnel information system using sorting and Page 3/5
searching for STL and vector.
set
multiset
map
multimap
unordered_multiset
unordered_map
unordered_multimap
Functions
The STL includes classes that overload the function call operator. Instances of such
classes are called function objects or functors. Functors allow the working of the
associated function to be customized with the help of parameters to be passed.
Iterators
As the name suggests, iterators are used for working upon a sequence of values. They
are the major feature that allow generality in STL.
Utility Library
Defined in header <utility>.
pair
Sorting:
It is one of the most basic functions applied to data. It means arranging the data in a
particular fashion, which can be increasing or decreasing. There is a built in function in
C++ STL by the name of sort(). This function internally uses IntroSort. In more details it
is implemented using hybrid of QuickSort, Heap Sort and Insertion Sort.By default, it
uses Quick Sort but if Quick Sort is doing unfair partitioning
and taking more than N*log N time, it switches to Heap Sort and when the array size
becomes really small, it switches to Insertion Sort.
Experiment No: 6 Personnel information system using sorting and Page 4/5
searching for STL and vector.
Searching:
It is a widely used searching algorithm that requires the array to be sorted before
search is applied. The main idea behind this algorithm is to keep dividing the array in
half (divide and conquer) until the element is found, or all the elements are exhausted.
It works by comparing the middle item of the array with our target, if it matches, it
returns true otherwise if the middle term is greater than the target, the search is
performed in the left sub-array. If the middle term is less than target, the search is
performed in the right sub-array.
Experiment No: 6 Personnel information system using sorting and Page 5/5
searching for STL and vector.
Conclusion:
Hence, we have successfully studied the concept of STL (Standard Template Library)
and how it makes many data structures easy. It briefs about the predefined functions of
STL and their uses such a search() and sort()
Questions:
1. What is STL? What are four components of STL?
2. What is Sorting and Searching?
3. What is vector container?
Aim: Write a program in C++ to use map associative container. The keys will be the
names of states and the values will be the populations of the states. When the
program runs, the user is prompted to type the name of a state. The program then
looks in the map, using the state name as an index and returns the population of the
state
Software Requirements:
Theory:
Examples:
#include <map>
#include <iostream>
#include<string>
using namespace std;
int main()
{
// map declaration
string s;
map<string,int>mymap;
map<string,int>::iterator i;
// mapping integers to strings
mymap.insert(pair<string,int>("maharastra",12));
mymap.insert(pair<string,int>("gujrat",10));
mymap.insert(pair<string,int>("goa",3));
mymap.insert(pair<string,int>("bihar",9));
mymap.erase("goa");
for(i=mymap.begin();i!=mymap.end();i++)
{
cout<<(*i).first<<" "<<(*i).second<<endl;
}
//cout<<"enter the sate name"<<endl;
//cin>>s;
cout<<"population of state="<<"is"<<"="<<mymap["goa"];
return 0;
}
Algorithm:
1. Start.
2. Give a header file to map associative container.
3. Insert states name so that we get values as population of that state.
4. Use population Map.insert().
5. Display the population of states.
6. End.
Input:
Information such as state name to map associative container.
Output:
Size of population Map: 5
Brasil: 193 million
China: 1339 million
India: 1187million
Indonesia: 234 million
Pakistan: 170 million
Indonesia's populations is 234 million
Conclusion:
Hence, successfully studied the concept of map associative container
Questions:
1. What is an associative container in C++?
2. What is map in C++? How to do declare a map?
3. Explain Associative mapping with example?
Aim: Write C++ program to draw the pattern. Use DDA line and Bresenham‗s circle
drawing algorithm. Apply the concept of encapsulation.
Software Requirements:
Inscribed Circle: When the circle is drawn inside any shape is called inscribed circle.
Circumscribed Circle: Drawing any shape inside circle is called circumscribed circle.
When a circle is placed outside a polygon and each vertex of the polygon lies on the
circle
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 is the s i m p l e s t line drawing algorithm in computer graphics. It
works on incremental method. It plots the points from starting point of line to end
point of line by incrementing in X and Y direction in each iteration.
Step 1: Get coordinates of both the end points (X1, Y1) and (X2, Y2) from user.
Step 2: Calculate the difference between two end points 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.
Steps = absolute(dx);
else
Steps = absolute(dy);
X1 = X1 + Xincrement;
Y1 = Y1 + Yincrement;
Circle is an eight-way symmetric figure. The shape of circle is the same in all quadrants.
In each quadrant, there are two octants. If the calculation of the point of one octant is
done, then the other seven points can be calculated easily by using the concept of
eight-way symmetry.
Bresenham‘s Circle Drawing Algorithm is a circle drawing algorithm that selects the
nearest pixel position to complete the arc. The unique part of this algorithm is that
is uses only integer arithmetic which makes it significantly faster than other algorithms
using floating point arithmetic.
Step 5:
do {
putpixel(centx+x, centy-y, ColorName);
if (p<0)
p = p+(4*x)+6;
else
{
p=p+[4*(x-y)]+10;
y=y-1;
}
x=x+1;
} while(x<y)
Here in step 5, putpixel() function is used which will print Octant-1 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() function
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, coordinates of common center and radius of both the
circles is required. Take coordinates of circle and radius of one of the circle from
user. Then using the properties of an equilateral triangle, find all 3 vertices of
equilateral triangle and radius of other circle. As shown in example, read common
center coordinate (x, y) of circumscribed and inscribed circle. Input radius r1 and r2of
circumscribed and inscribed circle respectively. Calculate coordinates of equilateral
triangle using following formula.
Once all these parameters are calculated, call DDA line drawing and Bresenham‘s
circle drawing algorithms by passing appropriate parameters to get required pattern.
Main Algorithm:
1. Start
2. Input center coordinates of circle
3. Input radius r1 and r2of circumscribed and inscribed circle respectively
4. Find out coordinates of equilateral triangle.
5. Draw inscribed circle using Bresenham‘s circle drawing algorithm (Algorithm-2).
6. Draw circumscribed circle using Bresenham‘s circle drawing algorithm
(Algorithm-2).
7. Draw equilateral triangle using DDA line generation algorithm (Algorithm-1).
8. Stop
Conclusion: Thus implemented program to draw pattern using DDA line drawing
algorithm and Bresenham‘s circle drawing algorithm.
Questions:
1. Explain the derivation of decision parameters in Bresenham‘s circle drawing algorithm.
2. What is slope? What are different types of slopes
3. What is difference between DDA and Bresenham‘s line drawing algorithm?
Aim: Write C++ program to draw a concave polygon and fill it with desired color using
scan fill algorithm. Apply the concept of inheritance.
Software Requirements:
Polygon:
A polygon is a closed planar path composed of a finite number of sequential line
segments. A polygon is a two-dimensional shape formed with more than three
straight lines. When starting point and terminal point is same then it is called
polygon.
Types of Polygons
1. Concave
2. Convex
3. Complex
Complex Polygon
We assume that the vertex list for the polygon is already stored and proceed as
follows.
1. Draw any point outside the range Xmin and Xmax and Ymin and Ymax. Draw a
scan line through P up to a point A under study
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.
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.
It is an image space algorithm. It processes one line at a time 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 endpoints. Active Edge List (AEL) contain edges a
given scan line intersects during its sweep. The active edge list (AEL) should be
sorted in increasing order of x. The AEL is dynamic, growing and shrinking.
Algorithm
1. Enter values in Active edge list (AEL) in sorted order using y as value
3. When one polygon flag is on, and this is for surface S1enter color intensity as I1into
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.
Conclusion: Hence concave polygon is implemented and filled with scan line
algorithm
Questions:
1. Which are the different approaches to fill a polygon?
2. What are advantages and drawbacks of scan line polygon fill algorithm?
3. Explain flood fill algorithm .
Experiment No: 10 Implement Cohen Southerland line clipping algorithm. Page 1/4
Aim: Write C++ program to implement Cohen Southerland line clipping algorithm..
Software Requirements:
Experiment No: 10 Implement Cohen Southerland line clipping algorithm. Page 2/4
Algorithm
Following image illustrates the 9 regions: 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).
Experiment No: 10 Implement Cohen Southerland line clipping algorithm. Page 3/4
Pseudocode
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 region codes.
Step 3.1: If the result is not 0000, then given line is completely outside.
given rectangle.
Experiment No: 10 Implement Cohen Southerland line clipping algorithm. Page 4/4
Questions:
3. What is windowing?
Aim: Write C++ program to draw 2-D object and perform following basic
transformations a )Scaling b) Translation c) Rotation. Apply the concept of operator
overloading.
Software Requirements:
This translation is achieved by adding the translation coordinates to the old coordinates of
the object as-
Xnew = Xold + Tx (This denotes translation towards X axis)
2) Rotation:
In rotation, we rotate the object at particular angle θ (theta) from its original position.
Consider
- Initial coordinates of the object O = (Xold, Yold)
- Initial angle of the object O with respect to origin = Φ
- Rotation angle = θ
Xnew = Xold x cosθ – Yold x sinθ Ynew = Xold x sinθ + Yold x cosθ
3) Scaling:
Homogeneous Coordinates:
Matrix multiplication is easier to implement in hardware and software as compared to
matrix addition. Hence we want to replace matrix addition by multiplication while
performing transformation operations. So the solution is homogeneous coordinates,
which allows us t o express all transformations (including translation) as matrix
multiplications.
Consider that coordinates of vertices of rhombus are (X1,Y1), (X2,Y2), (X3,Y3) and
(X4,Y4) applying basic transformations, we will get corresponding coordinates as
(X1‘,Y1‘), (X2‘,Y2‘), (X3‘,Y3‘) and (X4‘,Y4‘) respectively. Following multiplication will
give the translation on this rhombus:
Questions:
1. How to rotate any 2-D object about an arbitrary point? Explain in brief.
2. Explain shearing transformation.
3. Give difference between parallel and perspective projections?
Aim: Write C++ program to generate Hilbert curve using concept of fractals.
Software Requirements:
The Hilbert curve is a space filling curve that visits every point in a square grid with a
size of 2×2, 4×4, 8×8, 16×16, or any other power of 2. It was first described by David
Hilbert in 1892. Applications of the Hilbert curve are in image processing:
especially image compression and dithering. It has advantages in those operations
where the coherence between neighbouring pixels is important. The Hilbert curve is
also a special version of a quadtree; any image processing function that benefits from
the use of quadtrees may also use a Hilbert curve.
The basic elements of the Hilbert curves are what I call "cups" (a square with one
open side) and "joins" (a vector that joins two cups). The "open" side of a cup can be
top, bottom, left or right.
In addition, every cup has two end-points, and each of these can be the "entry" point
or the "exit" point. So, there are eight possible varieties of cups. In practice, a
Hilbert curve uses only four types of cups. In a similar vein, a join has a direction: up,
down, left or right.
A first order Hilbert curve is just a single cup (see the figure on the left). fills a 2×2
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 cup and
a join has been marked with a fat dot in the figure). Every next order repeats the
process or replacing each cup by four smaller cups and three joins.
The function presented below (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.
Questions:
1. What is the importance of curves and fractals in computer graphics?
2. What are applications of curves and fractals?
3. What is blending function?
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 Syntax
Experiment No: Draw 3-D cube and perform basic transformations on it using
Page 4/8
13 OpenGL.
OpenGL primitives
Drawing two lines
glBegin(GL_LINES);
glVertex3f(_,_,_); // start point of line 1
glVertex3f(_,_,_); // end point of line 1
glVertex3f(_,_,_); // start point of line 2
glVertex3f(_,_,_); // end point of line 2 glEnd();
We can replace GL_LINES with GL_POINTS, GL_LINELOOP, GL_POLYGON etc.
OpenGL states
o glCullFace( Mode )
Mode: GL_FRONT, GL_BACK, GL_FRONT_AND_BACK
o glFrontFace( Vertex_Ordering )
o Vertex Ordering: GL_CW or GL_CCW
Viewing transformation
glMatrixMode ( Mode )
o Mode: GL_MODELVIEW, GL_PROJECTION, or GL_TEXTURE
glLoadIdentity()
glTranslate3f(x,y,z)
glRotate3f(angle,x,y,z)
glScale3f(x,y,z)
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
begin with glu, and constants begin with GLU.
GLUT, the OpenGL Utility Toolkit, provides a system for setting up callbacks 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.
Writing an OpenGL Program with GLUT
An OpenGL program using the three libraries listed above must include the appropriate
headers. This requires the following three lines:
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
Before OpenGL rendering calls can be made, some initialization has to be done.
With GLUT, this consists of initializing the GLUT library, initializing the display mode,
creating the window, and setting up callback functions. The following lines initialize a
full color, double buffered display: glutInit(&argc, argv);
glutInitDisplayMode(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:
glutInitWindowPosition(px, py);
glutInitWindowSize(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 is called. For animation,
an idle event handler that takes no arguments can be created to call the display
function to constantly redraw the scene with glutIdleFunc. Once all the callbacks
have been set up, a call to glutMainLoop 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 be any color:
glClear(GL_COLOR_BUFFER_BIT);
The next line sets the current rendering color to blue. OpenGL behaves like a state
machine, so certain state such as the rendering color is saved by OpenGL and used
automatically later as it is needed.
glBegin(GL_LINES);
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 be drawn from the point at ( x0, y0) to (x1, y1).
Questions:
Experiment No: 14 Implement bouncing ball using sine wave form. Page 1/5
Aim: Write a C++ program to implement bouncing ball using sine wave form. Apply the
concept of polymorphism.
Software Requirements:
Theory:
What is animation?
Animation is the process of designing, drawing, making layouts and preparation of
photographic sequences which are integrated in the multimedia and gaming products.
Animation involves the exploitation and management of still images to generate the
illusion of movement. Animation is the process of creating a continuous motion and shape
change[Note 1] illusion by means of the rapid display of a sequence of static images that
minimally differ from each other. The illusion—as in motion pictures in general—is thought
to rely on the phi phenomenon.
Experiment No: 14 Implement bouncing ball using sine wave form. Page 2/5
Animations can be recorded on either analogue media, such as a flip book, motion picture
film, video tape, or on digital media, including formats such as animated GIF, Flash
animation or digital video. To display it, a digital camera, computer, or projector are used.
Animation creation methods include the traditional animation creation method and those
involving stop motion animation of two and three-dimensional objects, such as paper
cutouts, puppets and clay figures. Images are displayed in a rapid succession, usually 24,
25, or 30 frames per second.
Experiment No: 14 Implement bouncing ball using sine wave form. Page 3/5
How to move an element to left, right, up and down using arrow keys?
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.
#include<ncurses.h> int main()
{
int ch;
/* Curses Initialisations */ initscr();
raw();
keypad(stdscr, TRUE); noecho();
printw("Welcome - Press # to Exit\n"); while((ch = getch()) != '#')
{
switch(ch)
{
case KEY_UP: printw("\nUp Arrow");
break;
case KEY_DOWN: printw("\nDown Arrow"); break;
case KEY_LEFT: printw("\nLeft Arrow"); break;
case KEY_RIGHT: printw("\nRight Arrow"); break;
default:
{
printw("\nThe pressed key is ");
attron(A_BOLD);
printw("%c", ch); attroff(A_BOLD);
}
}
}
Experiment No: 14 Implement bouncing ball using sine wave form. Page 4/5
Experiment No: 14 Implement bouncing ball using sine wave form. Page 5/5
Algorithm:
Step 1: Start
Step 9: Stop.
Conclusion: Thus with the use of graphics functions, bouncing ball animation in sine
wave form is created.
Questions:
1 Which packages are used for animation?
2 Explain animation of tic-tac –toe game.
3 What is segment table?
Aim: Design and implement game / animation clip / Graphics Editor using open source
graphics library. Make use of maximum features of Object Oriented Programming.
Software Requirements:
Types of Animation
Computer animation
2D animation
3D animation
Nowadays, animation can be seen in many area around us. It is used in a lot of
movies, films and games, education, e-commerce, computer art, training etc. It is a big
part of entertainment area as most of the sets and background is all build up through
VFX and animation.
Methods/Techniques:
2. Procedural:
In Procedural method, set of rules are used to animate the objects. Animator
defines or specify the initial rules and procedure to process and later runs
simulations. Many of the times rules or procedure are based on real world.s
physical rule which are shown by mathematical equations.
3. Behavioral:
According to this method/technique, to a certain extent the character or object
specifies/determines it‘s own actions which helps / allows the character to improve
later, and in turn, it frees the animator in determining each and every details of the
character‘s motion.
4. KeyFraming:
A key frame in computer animation is a frame where we define changes in an
animation. According to key framing, a storyboard requirement is must as the
animator/artist draws the major frames (frames in which major/important changes can
be made later) of animation from it. In key framing, character‘s or object‘s key position
are the must and need to be defined by the animator, because the missing frames are
filled in those key position via computer automatically.
5. MotionCapture:
This method of animation uses the live action/motion footage of a living human
character which is recorded to the computer via video cameras and markers and later,
that action or motion is used/applied to animate the character which gives the real feel
to the viewers as if the real human character has been animated. Motion Capture is
quite famous among the animators because of the fact that the human action or
motion can be captured with relative ease.
6. Dynamics:
In this method, simulations are used in order to produce a quite different sequence
while maintaining the physical reality. Physics‘s laws are used in simulations to create
the motion of pictures/characters. High level of interactivity can be achieved in this
method, via the use of real-time simulations, where a real person performs the action
or motions of a simulated character.
Game Programming
Before we actually jump into game programming, we need to know something called
event driven programming. Event driven programming refers to that style of
programming wherein the user of the application is free to choose from several options
rather than be confined to a predetermined sequence of interactions with the program.
Game programming is one common example of event driven programming. A game is
a closed, i.e., complete and self sufficient formal system that represents a subset of
reality. A game is a perfect combination of actions-reactions or event-responses where
every response is based on the most-recently occurred event.
Elements of Game Programming
In general, a computer game has five elements: Graphics, Sound, Interface,
Gameplay, Story
Graphics
Graphics consists of any images that are displayed and any effects that are performed
on them. This includes 3D objects, textures, 2D tiles, 2D full screen shots, Full Motion
Video (FMV) and anything else that the player will see.
Sound
Sound consists of any music or sound effects that are played during the game. This
includes starting music, CD music, MIDI or MOD tracks, Foley effects (environment
sounds), and sound effects.
Interface
Sound consists of any music or sound effects that are played during the game. This
includes starting music, CD music, MIDI or MOD tracks, Foley effects (environment
sounds), and sound effects.
Gameplay
It encompasses how fun the game is, how immense it is, and the length of playability.
Story
The game's story includes any background before the game starts, all information the
player gains during the game or when they win and any information they learn about
character in the game. A story is an element of a game. The difference between a
story and a game is that a story represents the facts in an immutable (i.e., fixed)
sequence, while a game represents a branching tree of sequences and allows the
player to create his own story by making choice at each branch point.
Game Design Sequence
Since game design requires one to explore one's artistic abilities, it cannot be
formulated in a step by step process. However, there are certain technical steps that
one needs to follow in one way or another. These are:
2. Develop Interface.
3. Develop Interface.
Interface is composed of input and output. While developing interface, the programmer
should develop the static display screens and dynamic display screen. Static
display is the screen which remains unaffected by the player's actions i.e., the input
by the player. The dynamic display, on the other hand, is the screen which is
governed by the player's actions i.e., the input by the player. Examples of some static
display screens are:
Game selection screens
What options are available to the player on the game startup? This describes what
options are on the menu, how and where it appears on what screen, how the player
gets there, and how he gets out.
What does the screen looks like at the beginning of the game, what are the startup
parameters, where are the characters, etc? What messages, if any are on screen, and
where? Intro music? etc.Since the dynamic screen vary as per the input given by the
player, their descriptions are too many to be listed here. Some examples:
Message Screens
While developing interfaces, you also need to work on screens in response to legal
actions of the player, by intimating that he/she is on the right track. Also, you need to
work on the screens required to warn the player in case he/she commits an illegal
move or action.
End of game message
These screens include messages and responses to questions like: What happens
when the player loses? What happens when the player wins? What happens when the
player get the high score? Where does the player go when the game is over? How
does he start a new game?
This step involves developing a proper logic for gameplay. This requires the game-
programmer to answer many questions in the form of program-code. These questions
include: How is game played? What are the controls? What is the Game Goal? How is
the player going to achieve the game goal? etc. In other words, we must say that since
game represents an event-driven situation, the game-programmer i.e., you must
specify or program everything that includes:
While writing a game program, after selecting the goal-of-game, one needs to
determine its initial requirements. For instance, to write a game program for
guessing a number, you need to decide about a way to generate the number,
number of players involved, number of chances allowed to the player, a scoring
methodology etc. Here we are not aiming at making you a professional game
programmer, rather we are concentrating more at giving you an idea of writing
simple or elementary game programs.
Developing logic for the scoring purposes is a subset of developing logic for the game
play. For this, you must first decide the scoring policy that you're going to follow in your
game. You're going to decide the maximum number of chances allowed, the scoring
mechanism, whether it is tied to time or not, etc. During this phase, the milestone
events are worked out and accordingly scoring (positively or negatively) is carried out.
Questions:
1 Which basic functions used to design animation?
2 What is game board? How to create it?
3 Which are open source tools for gaming and animation