CG_Lab Chapters
CG_Lab Chapters
DDA algorithms
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 motherboard or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
DDA (Digital Differential Analyzer) is a line drawing algorithm used in computer
graphics to generate a line segment between two specified endpoints. It is a simple and
efficient algorithm that works by using the incremental difference between the x-
coordinates and ycoordinates of the two endpoints to plot the line.
Consider one point of the line as (X0, Y0) and the second point of the line as (X1, Y1).
/ calculate dx , dy
dx = X1 – X0;
dy = Y1 – Y0;
X = X0;
Y = Y0;
Program: Slope's
Method:
#include <stdio.h>
#include <graphics.h>
getch();
closegraph(); return
0;
}
DDA Algorithm:
#include <stdio.h>
#include <graphics.h>
getch();
closegraph();
return 0; }
Output:
200 180
199 179
198 178
197 177
196 176
195 175
194 174
193 173
192 172
191 171
190 170
189 169
188 168
187 167
186 166
185 165
184 164
183 163
182 162
181 161
CHAPTER 2
Breshenham’s Algorithm
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 motherboard or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
Bresenham’s Line Drawing Algorithm is an integer-based algorithm that determines which
points in a grid should be plotted to form a close approximation to a straight line between two
given points. It operates using only integer addition, subtraction, and bit shifting, avoiding the
use of multiplication and division. This makes it particularly suitable for computer graphics,
where speed and efficiency are critical. Key Concepts
• Rasterization: The process of converting geometric data (like lines) into a raster
image (pixels or dots).
Algorithm:
To understand Bresenham’s Line Drawing Algorithm, consider the task of drawing a line
from point \((x_0, y_0)\) to \((x_1, y_1)\). Without loss of generality, assume that the slope of
the line \(0 \leq m \leq 1\), meaning \(\Delta x \geq \Delta y\). 1. Initialization:
• Calculate the differences: \(\Delta x = x_1 — x_0\) and \(\Delta y = y_1 — y_0\).
• Initialize the decision variable \(d = 2\Delta y — \Delta x\).
• Set the starting point \((x, y) = (x_0, y_0)\).
2. Plotting the Line:
• For each \(x\) from \(x_0\) to \(x_1\):
• Plot the pixel at \((x, y)\).
• If \(d > 0\):
• Increment \(y\) by 1.
• Update \(d\) by subtracting \(2\Delta x\).
• Update \(d\) by adding \(2\Delta y\).
Here is a pseudocode representation of Bresenham’s Line Drawing Algorithm for the case
where \(0 \leq m \leq 1\): plaintext function BresenhamLine(x0, y0, x1, y1):
Δx = x1 — x0 Δy =
y1 — y0 d = 2 *
Δy — Δx y = y0
plot(x, y) if d >
0: y = y + 1 d =
d — 2 * Δx d =
d + 2 * Δy
• Efficiency: The algorithm uses only integer arithmetic, making it faster than
algorithms requiring floating-point calculations.
• Accuracy: The algorithm produces visually appealing lines that closely approximate
the true line.
Applications
Bresenham’s Line Drawing Algorithm is used in various applications within computer
graphics, including:
Programs:
Slope Method:
#include <stdio.h>
#include <graphics.h>
{ putpixel(x, y, color);
y = y1 + slope * (x - x1);
plotPoint(x, y, WHITE);
x2 = tempX; y2 = tempY;
x = x1 + (y - y1) / slope;
plotPoint(x, y, WHITE); }
closegraph(); return 0;
Breshenham’s Method:
while (1)
{ plotPoint(x1, y1,
y1 == y2) break; e2 = 2 *
{ err -= dy; x1
}
int main() { int gd = DETECT, gm;
}
CHAPTER 3
Circle Generation
Objective:
Implementation Of Circle Generation Using the Mid-Point Method and Bresenham’s
Algorithm.
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 motherboard or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
Circle Generation Using Mid-Point Method:
The Mid-Point Circle Drawing Algorithm, also known as Bresenham's Circle Algorithm, is a
method for drawing circles in computer graphics. It's an efficient algorithm that avoids the
need for using trigonometric functions like sine and cosine, making it suitable for
implementation on devices with limited computational resources. Here's how it works:
Initialization:
Given the center coordinates of the circle (x c ,yc ) and its radius r, set the initial values of the
decision parameter and the plotting points: P=5/4−r x=0 y=r
Plotting Points:
Starting from the point (0,r), plot the eight symmetric points of the circle by incrementally
moving along the x-axis:
If P<0, choose the East pixel (x+1,y) and update the decision parameter as P=P+2x+3. If P≥0,
choose the South-East pixel (x+1,y−1) and update the decision parameter as P=P+2x−2y+5.
Repeat this process until x is greater than or equal to y.
Completion:
Once all symmetric points have been plotted, the circle drawing is complete.
Bresenham's Circle Algorithm is another method for drawing circles that is based on the
Bresenham's line drawing algorithm. Here's how it works:
Initialization:
Given the center coordinates of the circle (xc ,yc ) and its radius r, set the initial values of the
decision parameter and the plotting points:
x=0 y=r
P=3−2r
Plotting Points:
Starting from the (0,r), plot the eight symmetric points of the circle by incrementally moving
along the x-axis:
If P<0, choose the East pixel (x+1,y) and update the decision parameter as P=P+4x+6. If
P≥0, choose the South-East pixel (x+1,y−1) and update the decision parameter as
P=P+4(x−y)+10.
Repeat this process until x is greater than or equal to y.
Completion:
Once all symmetric points have been plotted, the circle drawing is complete.
Algorithm:
BresenhamCircle(xc, yc, r):
x=0 y=r P=3-2*r
plotPoints(xc, yc, x, y)
while x <= y:
x=x+1 if
P < 0:
P=P+4*x+6 else:
y=y-1
P = P + 4 * (x - y) + 10
plotPoints(xc, yc, x, y)
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h> #include <math.h> void
EightWaySymmetricPlot(int xc,int yc,int x,int y)
{
putpixel(x+xc,y+yc,RED); putpixel(x+xc,-
y+yc,YELLOW); putpixel(-x+xc,-y+yc,GREEN);
putpixel(-x+xc,y+yc,YELLOW);
putpixel(y+xc,x+yc,12); putpixel(y+xc,-x+yc,14);
putpixel(-y+xc,-x+yc,15);
putpixel(-y+xc,x+yc,6);
}
void BresenhamCircle(int xc,int yc,int r)
{
int x=0,y=r,d=3-(2*r);
EightWaySymmetricPlot(xc,yc,x,y);
while(x<=y)
{ if(d<=0
)
{
d=d+(4*x)+6;
}
else
{
d=d+(4*x)-(4*y)+10;
y=y-1;
}
x=x+1;
EightWaySymmetricPlot(xc,yc,x,y);
}
}
int main(void)
{
/* request auto detection */ int xc,yc,r,gdriver
= DETECT, gmode, errorcode; /* initialize
graphics and local variables */
initgraph(&gdriver, &gmode, "C:\\TURBOC3\\BGI");
getch();
closegraph(); return
0;
}
Output:
#include<conio.h>
#include<stdio.h> void
main()
g_mode,g_driver=DETECT;
clrscr();
initgraph(&g_driver,&g_mode,"C:\\TURBOC3\\BGI"); printf("***********
********\n\n"); printf("\nenter
%d",&x_mid,&y_mid);
scanf("%d",&radius); x=0;
y=radius; dp=1-radius; do
putpixel(x_mid+x,y_mid+y,YELLOW);
putpixel(x_mid+y,y_mid+x,YELLOW); putpixel(x_mid-
y,y_mid+x,YELLOW); putpixel(x_mid-x,y_mid+y,YELLOW);
putpixel(x_mid-x,y_mid-y,YELLOW); putpixel(x_mid-y,y_mid-x,YELLOW);
putpixel(x_mid+y,y_mid-x,YELLOW); putpixel(x_mid+x,y_mid-
y,YELLOW);
if(dp<0) { dp+=(2*x)+1;
} else{ y=y-1;
dp+=(2*x)-(2*y)+1;
} x=x+1;
}while(y>x);
getch();
Output:
Application:
1. Medical Imaging: Circle drawing algorithms are employed in medical imaging
applications for visualizing circular structures such as tumors, organs, and blood
vessels. They assist in generating accurate representations of anatomical features in
Xray, MRI, and CT scan images, aiding in diagnosis and treatment planning.
2. Automotive Engineering: In automotive engineering, circle drawing algorithms are
used in computer-aided engineering (CAE) software for designing vehicle
components, engine parts, and vehicle dynamics simulations. They facilitate the
creation of circular features such as wheels, tires, and cam profiles with precise
dimensions and tolerances.
3. Robotics and Automation: Circle drawing algorithms find applications in robotics and
automation systems for path planning, trajectory generation, and motion control. They
help in creating circular trajectories for robotic arms, manipulators, and autonomous
vehicles, enabling smooth and accurate movement in manufacturing and logistics
environments.
4. Geographic Information Systems (GIS): GIS software utilizes circle drawing
algorithms for visualizing circular geographical features such as lakes, islands, and
natural landmarks. They assist in creating accurate maps, spatial analyses, and
geospatial data visualization for urban planning, environmental monitoring, and
resource management.
CHAPTER 4
Polygon Filling
Objective:
Implementation Of Polygon Filling Using Flood-Fill, Boundary-Fill And Scan- Line
Algorithms.
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 motherboard or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
Polygon filling algorithms are used to fill closed regions or polygons with a specific color in
computer graphics. Here's an overview of three common polygon filling algorithms:
FloodFill, Boundary-Fill, and Scan-Line.
Flood-Fill Algorithm:
Flood-Fill is a recursive algorithm used to fill closed areas with a specific color. It starts from
a seed point inside the polygon and recursively fills adjacent pixels with the desired color
until it encounters a boundary. Here's how it works:
Boundary-Fill Algorithm:
Boundary-Fill is a non-recursive algorithm that fills a closed area by filling pixels between
specified boundary colors. It starts from a seed point inside the polygon and fills pixels until
it encounters the boundary color. Here's how it works:
Scan-Line Algorithm:
Scan-Line is a scan-conversion algorithm that fills polygons by scanning each horizontal scan
line and determining the intersections with polygon edges. It uses an active edge table (AET)
and a global edge table (GET) to track edges and intersections efficiently. Here's how it
works:
Algorithm:
FloodFill(x, y, boundaryColor, fillColor):
if getColor(x, y) != boundaryColor:
return
setColor(x, y, fillColor)
ScanLineFill(polygon):
edges = getEdges(polygon)
sort edges by y-coordinate
// circle function
circle(x, y, radius);
// Function calling
boundaryFill4(x, y, 6, 15);
delay(10000);
getch();
return 0;
}
Output:
#include<conio.h>
#include<graphics.h>
#include<dos.h> void
flood(int,int,int,int);
void main()
intgd=DETECT,gm;
initgraph(&gd,&gm,"C:/TURBOC3/bgi");
rectangle(50,50,250,250); flood(55,55,10,0);
intdefaultColor)
{ if(getpixel(x,y)==defaultCol
or) { delay(1);
putpixel(x,y,fillColor);
flood(x+1,y,fillColor,defaultColor
); flood(x-
1,y,fillColor,defaultColor);
flood(x,y+1,fillColor,defaultColor
); flood(x,y-
1,fillColor,defaultColor);
Output:
Program: Scanline Polygon Filling Algorithm
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
#include<graphics.h> void
main()
int n,i,j,k,gd,gm,dy,dx;
int x,y,temp; int a[20][2],xi[20]; float
for(i=0;i<n;i++) { printf(“\tX%dY
%d:”,i,i); scanf(“%d%d”,&a[i][0],&a[i]
[1]);
} a[n][0]=a[0][0]; a[n][1]=a[0]
[1]; detectgraph(&gd,&gm);
initgraph(&gd,&gm,”c:\\tc\\bgi”);
for(i=0;i<n;i++) {
line(a[i][0],a[i][1],a[i+1][0],a[i+1][1]);
} getch();
for(i=0;i<n;i++)
{ dy=a[i+1][1]-a[i]
[1]; dx=a[i+1][0]-a[i]
[0]; if(dy==0)
slope[i]=1.0;
if(dx==0)
slope[i]=0.0; if((dy!
=0)&&(dx!=0)) {
slope[i]=(float)dx/dy;
for(y=0;y<480;y++)
k=0;for(i=0;i<n;i++)
{
if((a[i][1]<=y)&&(a[i+1][1]>y)){||((a[i][1]>y)&&(a[i+1][1]<=y))xi[k]=(int)(a[i][0]+slope[i]*
(y-a[i] [1]));
k++;
} } for(j=0;j<k-
1;j++)
for(i=0;i<k;i++)
if(xi[i]>xi[i+1])
{ temp=xi[i];
xi[i]=xi[i+1];
xi[i+1]=temp;
} } setcolor(35);
for(i=0;i<k;i+=2)
line(xi[i],y,xi[i+1]+1,y); getch();
}
}
Output:
Application:
1. Flood-fill algorithms can be used to automatically identify and delineate the
boundaries of the tumor, allowing for accurate quantification of tumor volume and
growth over time.
2. Boundary-fill algorithms can be employed to accurately fill these internal features
with different materials or textures, ensuring precise manufacturing specifications are
met during the machining process.
3. scan-line algorithms, autonomous vehicles can make real-time decisions to navigate
safely and avoid obstacles on the road.
CHAPTER 5
2d Transformation
Objective:
Implementation Of 2d Transformation: Translation, Scaling, Rotation.
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 motherboard or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
2D transformations are fundamental operations in computer graphics used to manipulate the
position, size, and orientation of objects in a 2D space. Here's an overview of three common
types of 2D transformations: translation, scaling, and rotation:
Scaling: Scaling involves changing the size of an object in a 2D plane while preserving its
shape and orientation. It is represented by scaling factors s x and sy along the x and y axes,
respectively.
Algorithm:
Translate(x, y, dx, dy):
// Translate point (x, y) by (dx, dy)
x = x + dx y = y + dy
return (x, y)
Rotate(x, y, angle):
// Rotate point (x, y) by the given angle (in radians)
cos_theta = cos(angle) sin_theta = sin(angle)
new_x = x * cos_theta - y * sin_theta new_y = x *
sin_theta + y * cos_theta return (new_x, new_y)
Program: Implementation Of 2d Transformation: Translation
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void main()
{
int graphdriver = DETECT, graphmode, errorcode;
int i;
int x2, y2, x1, y1, x, y;
printf("Enter the 2 line end points:");
printf("x1,y1,x2,y2");
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
initgraph(&graphdriver, &graphmode, "C:\\TURBOC3\\BGI"); line(x1,
y1, x2, y2);
printf("Enter translation co-ordinates ");
printf("x,y");
scanf("%d%d", &x, &y); x1
= x1 + x; y1 = y1 + y; x2
= x2 + x; y2 = y2 + y;
printf("Line after translation");
line(x1, y1, x2, y2);
getch();
closegraph();
}
Output:
Output:
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void main()
{
int graphdriver = DETECT, graphmode, errorcode;
int i;
int x2, y2, x1, y1, x, y, xn, yn;
double r11, r12, r21, r22, th;
clrscr();
printf("Enter the 2 line end points:");
printf("x1,y1,x2,y2");
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
initgraph(&graphdriver, &graphmode, "C:\\TURBOC3\\BGI"); line(x1,
y1, x2, y2);
printf("\n\n\n[ Enter the
angle"); scanf("%lf", &th);
r11 = cos((th *3.1428) / 180);
r12 = sin((th *3.1428) / 180);
r21 = (-sin((th *3.1428) / 180));
r22 = cos((th *3.1428) / 180);
//printf("%lf %lf %lf %lf",r11,r12,r21,r22); xn =
((x2 *r11) - (y2 *r12)); yn = ((x2 *r12) + (y2
*r11));
line(x1, y1, xn, yn);
getch();
closegraph();
}
Output:
Application:
1. Translation transformations allow users to precisely position elements within the
design space, enabling them to achieve the desired visual balance and hierarchy in
their designs.
2. Conversely, when users zoom out, the map is scaled down to provide a broader view
of the geographic area. Scaling transformations ensure that map features, such as
roads, landmarks, and labels, remain legible and accurately represented at different
zoom levels.
3. By applying rotation transformations to the arm's joints, engineers can adjust the
orientation of the end-effector to accurately grasp objects from various angles,
optimizing the efficiency and flexibility of robotic assembly processes.
CHAPTER 6
2d Transformations
Objective:
Implementation Of 2d Transformation: Mirror Reflection And Shearing.
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 mother board or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
Mirror Reflection:
Mirror reflection, also known as a reflection or flip, is a transformation that mirrors an object
across a specified axis. In 2D graphics, mirror reflection can occur horizontally, vertically, or
diagonally.
Shearing:
Shearing is a transformation that distorts an object by shifting its coordinates along one axis
while leaving the other axis unchanged. There are two types of shearing: horizontal (x-shear)
and vertical (y-shear).
1. Horizontal Shearing (x-Shear): In horizontal shearing, each point (x, y) of the object is
shifted horizontally by an amount proportional to its y-coordinate, resulting in a new
point (x + ky, y), where k is the shear factor.
2. Vertical Shearing (y-Shear): In vertical shearing, each point (x, y) of the object is
shifted vertically by an amount proportional to its x-coordinate, resulting in a new
point (x, y + kx), where k is the shear factor.
3. Shearing transformations are commonly used in computer graphics for creating
perspective effects, such as skewing or stretching objects, or for simulating
deformation in animations.
Algorithm:
MirrorReflection(point(x, y), axis):
if axis == "horizontal":
new_x = -x
new_y = y else if axis
== "vertical":
new_x = x
new_y = -y else if
axis == "diagonal":
new_x = y
new_y = x
return point(new_x, new_y)
#include <conio.h>
#include <graphics.h>
#include <stdio.h>
// Driver Code
void main()
{
// Initialize the drivers int
gm, gd = DETECT, ax, x1 = 100; int x2
= 100, x3 = 200, y1 = 100;
int y2 = 200, y3 = 100;
// After reflection
printf("\nAfter Reflection");
Output:
#include<stdio.h>
#include<graphics.h>
#include<conio.h> void
main()
{
int gd=DETECT,gm;
int x,y,x1,y1,x2,y2,shear_f;
initgraph(&gd,&gm,"C:\\TURBOC3\\BGI");
printf("\n please enter first coordinate = "); scanf("%d
%d",&x,&y);
printf("\n please enter second coordinate = "); scanf("%d
%d",&x1,&y1);
printf("\n please enter third coordinate = "); scanf("%d
%d",&x2,&y2);
printf("\n please enter shearing factor x = ");
scanf("%d",&shear_f);
cleardevice(); line(x,y,x1,y1);
line(x1,y1,x2,y2);
line(x2,y2,x,y);
setcolor(RED); x=x+
y*shear_f; x1=x1+
y1*shear_f; x2=x2+
y2*shear_f;
line(x,y,x1,y1);
line(x1,y1,x2,y2);
line(x2,y2,x,y);
getch(); closegraph();
}
Application:
1. Mirror reflections to design buildings with symmetrical facades or interior spaces with
mirrored walls. Similarly, interior designers may incorporate mirrors into room
designs to visually expand small spaces or create balanced compositions.
2. Shearing transformations are commonly used in 3D modeling and animation software
to create perspective effects and simulate deformation.
CHAPTER 7
Ellipse Generation
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 motherboard or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
The Mid-Point Ellipse Algorithm, also known as the Mid-Point Circle Drawing Algorithm, is
a method used to generate points along the perimeter of an ellipse. It is an extension of the
Mid-Point Circle Algorithm and is based on the idea of plotting points within the ellipse's
octant by utilizing symmetry properties to generate the remaining points.
The equation of an ellipse centered at the origin (0, 0) with semi-major axis a along the x-axis
and semi-minor axis b along the y-axis is:
𝑥2 𝑦2
2 + 𝑏2 = 1
𝑎
The Mid-Point Ellipse Algorithm plots points on the perimeter of the ellipse by iterating over
a particular region (usually the first quadrant) and utilizing symmetry to generate points in
other quadrants.
Algorithm:
MidPointEllipse(rx, ry, xc, yc):
// Initialize variables x = 0
y = ry
p1 = ry^2 - rx^2 * ry + 0.25 * rx^2
dx = 2 * ry^2 * x dy = 2 * rx^2 *
y
// Region 1 while
dx < dy: x=x+1
dx = dx + 2 * ry^2
if p1 < 0:
p1 = p1 + dx + ry^2
else:
y=y-1
dy = dy - 2 * rx^2
p1 = p1 + dx - dy + ry^2
PlotEllipsePoints(xc, yc, x, y)
// Region 2
p2 = ry^2 * (x + 0.5)^2 + rx^2 * (y - 1)^2 - rx^2 * ry^2
while y > 0: y=y-1 dy = dy - 2 * rx^2 if
p2 > 0:
p2 = p2 + rx^2 - dy
else:
x=x+1 dx = dx +
2 * ry^2 p2 = p2 + rx^2 -
dy + dx PlotEllipsePoints(xc,
yc, x, y)
Program:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void ellipse(int xc,int yc,int rx,int ry)
{
int gm=DETECT,gd;
int x, y, p;
clrscr();
initgraph(&gm,&gd,"C:\\TC\\BGI");
x=0;
y=ry;
p=(ry*ry)-(rx*rx*ry)+((rx*rx)/4);
while((2*x*ry*ry)<(2*y*rx*rx))
{
putpixel(xc+x,yc-y,WHITE); putpixel(xc-
x,yc+y,WHITE); putpixel(xc+x,yc+y,WHITE);
putpixel(xc-x,yc-y,WHITE);
if(p<0)
{
x=x+1;
p=p+(2*ry*ry*x)+(ry*ry);
}
else {
x=x+1;
y=y-1;
p=p+(2*ry*ry*x+ry*ry)-(2*rx*rx*y);
}
}
p=((float)x+0.5)*((float)x+0.5)*ry*ry+(y-1)*(y-1)*rx*rx-rx*rx*ry*ry;
while(y>=0)
{
putpixel(xc+x,yc-y,WHITE); putpixel(xc-
x,yc+y,WHITE); putpixel(xc+x,yc+y,WHITE);
putpixel(xc-x,yc-y,WHITE);
if(p>0)
{
y=y-1;
p=p-(2*rx*rx*y)+(rx*rx);
}
else
{
y=y-1;
x=x+1;
p=p+(2*ry*ry*x)-(2*rx*rx*y)-(rx*rx);
} }
getch();
closegraph();
}
void main()
{ int
xc,yc,rx,ry;
clrscr();
printf("Enter Xc=");
scanf("%d",&xc);
printf("Enter Yc=");
scanf("%d",&yc);
printf("Enter Rx=");
scanf("%d",&rx);
printf("Enter Ry=");
scanf("%d",&ry);
ellipse(xc,yc,rx,ry);
getch(); }
Output:
Application:
1. Computer Graphics: In graphics software, such as drawing programs or video games,
ellipses are frequently used for creating shapes, curves, and outlines.
2. CAD Software: Computer-aided design (CAD) software often utilizes ellipse drawing
algorithms to create and manipulate ellipses in engineering drawings,
3. Image Processing: In image processing applications, ellipses are used for object
detection, shape recognition, and image analysis.
CHAPTER 8
Line Clipping
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 motherboard or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
The Cohen-Sutherland line clipping algorithm is a method used to clip lines against a
rectangular clipping window in computer graphics. It was developed by Danny Cohen and
Ivan Sutherland in 1967. The algorithm divides the 2D plane into nine regions based on the
clipping window and efficiently determines which parts of a line lie inside, outside, or
partially inside the window. It then clips the line accordingly, producing the portion of the
line that lies within the window.
2. Line Segments: Given a line segment defined by two endpoints (x0, y0) and (x1, y1),
the algorithm computes region codes for both endpoints. If both endpoints have a
region code of 0, it means the entire line segment lies inside the clipping window and
can be accepted without any further processing. If both endpoints lie in the same non-
zero region, the line lies entirely outside the window and can be rejected.
3. Clipping Process: If the line segment is not trivially accepted or rejected, the
algorithm proceeds to clip it against the boundaries of the clipping window. It
iteratively computes intersection points between the line segment and the window
boundaries. The endpoint of the line that lies outside the window is replaced with the
intersection point, and its region code is updated accordingly. This process continues
until the line segment is either completely inside the window, completely outside the
window, or fully clipped against one or more boundaries.
4. Drawing Clipped Lines: After the clipping process is complete, the algorithm can
draw the portion of the line segment that lies inside the clipping window.
5. Efficiency: One of the key advantages of the Cohen-Sutherland algorithm is its
efficiency. By dividing the plane into a small number of regions, it can quickly
determine whether a line lies inside, outside, or partially inside the clipping window
without extensive computations.
Algorithm:
function CohenSutherlandLineClip(x0, y0, x1, y1, xmin, ymin, xmax, ymax):
// Determine region codes for both endpoints code0 =
ComputeRegionCode(x0, y0, xmin, ymin, xmax, ymax) code1 =
ComputeRegionCode(x1, y1, xmin, ymin, xmax, ymax)
// Main loop
while (not done):
// If both endpoints are inside the window, accept the line
if (code0 == 0 and code1 == 0):
accept = true
done = true
// If both endpoints are outside the window and on the same side, reject the line
else if (code0 & code1 != 0): done = true
// If one of the endpoints is inside the window, clip the line against the window boundary
else:
// Choose an endpoint outside the window
outsideCode = if (code0 != 0) then code0 else code1
Program:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<graphics.h>
#include<dos.h>
void drawwindow()
{ line(150,100,450,100);
line(450,100,450,350);
line(450,350,150,350);
line(150,350,150,100);
}
Application:
1. Drawing Boundaries: The drawing area represents the clipping window, defined by its
boundaries (xmin, ymin, xmax, ymax). These boundaries are usually determined by
the size of the viewport or the dimensions of the paper if printing.
2. User Interaction: As you draw lines to represent walls or other features, the CADD
software computes the region codes for the endpoints of each line segment relative to
the clipping window.
3. Clipping: If a line segment extends beyond the boundaries of the clipping window, the
Cohen-Sutherland algorithm is used to clip the line segment against the window
boundaries. The algorithm computes intersection points between the line segment and
the window boundaries and clips the line segment accordingly.
CHAPTER 9
Polygon Clipping
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 motherboard or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
The Sutherland-Hodgman algorithm is a method for clipping polygons against an arbitrary
clipping window in computer graphics. Developed by Ivan Sutherland and Gary Hodgman in
1974, the algorithm iterates through each edge of the clipping window, determining where
each edge intersects with the subject polygon and retaining the portions of the subject
polygon that lie inside the clipping window.
Clipping Window: The clipping window, also known as the clipping polygon or clip polygon,
defines the boundary within which the subject polygon is to be clipped. It is typically defined
by a set of vertices that form a closed, convex polygon.
Subject Polygon: The subject polygon is the polygon that needs to be clipped against the
clipping window. It may have an arbitrary shape and orientation.
Intersection Tests: The algorithm iterates through each edge of the clipping window. For each
edge, it tests whether each edge of the subject polygon intersects with the clipping edge.
Algorithm:
function sutherlandHodgmanClip(subjectPolygon, clipPolygon):
outputList = subjectPolygon
for edge in clipPolygon:
inputList = outputList
outputList = [] S=
inputList[-1] for E in
inputList: if inside(E,
edge): if not inside(S,
edge):
intersection = computeIntersection(S, E, edge)
outputList.append(intersection)
outputList.append(E) elif inside(S, edge):
intersection = computeIntersection(S, E, edge)
outputList.append(intersection)
S=E
return outputList
Program:
#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<stdlib.h> int
main()
{
int gd,gm,n,*x,i,k=0;
//window coordinates int
wx1=220,wy1=140,wx2=420,wy2=140,wx3=420,wy3=340,wx4=220,wy4=340;
int w[]={220,140,420,140,420,340,220,340,220,140};//array for drawing window
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi"); //initializing graphics
printf("Window:-");
setcolor(RED); //red colored window
drawpoly(5,w); //window drawn
printf("Enter the no. of vertices of polygon: ");
scanf("%d",&n);
x = malloc(n*2+1);
printf("Enter the coordinates of points:\n");
k=0;
for(i=0;i<n*2;i+=2) //reading vertices of polygon
{
printf("(x%d,y%d): ",k,k);
scanf("%d,
%d",&x[i],&x[i+1]); k++; }
//assigning the coordinates of first vertex to last additional vertex for the drawpoly method.
x[n*2]=x[0];
x[n*2+1]=x[1];
setcolor(WHITE);
drawpoly(n+1,x);
printf("\nPress a button to clip a polygon..");
getch();
setcolor(RED);
drawpoly(5,w);
setfillstyle(SOLID_FILL,BLACK);
floodfill(2,2,RED);
gotoxy(1,1); //bringing cursor at starting position
printf("\nThis is the clipped polygon..");
getch();
cleardevice();
closegraph();
return 0;
}
Output:
Application:
1. Computer-Aided Design (CAD): CAD software utilizes polygon clipping algorithms
to handle complex shapes and intersections in engineering and architectural drawings.
For example, when editing or manipulating CAD drawings, the Sutherland-Hodgman
algorithm can be used to clip polygons representing architectural elements against the
boundaries of a building's floor plan or a specified viewing area.
2. Collision Detection: In physics simulations and gaming engines, collision detection
between complex objects often involves clipping polygons against each other or
against the boundaries of the simulation environment. The Sutherland-Hodgman
algorithm can be employed as part of the collision detection process to determine the
intersection of two polygons accurately.
3. Virtual Reality (VR) and Augmented Reality (AR): In VR and AR applications, the
Sutherland-Hodgman algorithm can be used to cull objects or parts of objects that are
outside the user's field of view or occluded by other objects. This helps optimize
rendering performance and improve the user's immersive experience.
CHAPTER 10
3d Transformation
Objective:
Implementation Of 3d Geometric Transformations: Translation, Scaling, And Rotation
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 motherboard or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
Translation:
1. Translation is the process of moving an object from one position to another in space.
2. In 3D space, translation involves shifting the coordinates of every point of the object
by a certain distance along the x, y, and z axes.
.
Scaling:
1. Scaling is the process of resizing an object by multiplying its coordinates by scaling
factors along the x, y, and z axes.
2. Scaling can either enlarge (if scaling factors > 1) or shrink (if scaling factors < 1) the
object.
Mathematically, scaling can be represented using a scaling matrix:
Rotation:
1. Rotation is the process of rotating an object about a specified axis or point in space.
2. In 3D space, rotations can be clockwise or counterclockwise around the x, y, or z
axes.
Algorithm:
// Define a Point data structure struct
Point3D {
float x, y, z;
};
// Example usage:
point = Point3D(x: 1, y: 2, z: 3)
translate(point, dx: 2, dy: 3, dz: 4)
scale(point, sx: 2, sy: 2, sz: 2)
rotateX(point, angle: π/2) rotateY(point,
angle: π/4)
rotateZ(point, angle: π/3)
Program: 3d
Translation
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h> int
maxx,maxy,midx,midy;
void axis() { getch();
cleardevice();
line(midx,0,midx,maxy);
line(0,midy,maxx,midy);
} void main() { int
x,y,z,o,x1,x2,y1,y2; int
gd=DETECT,gm;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\tc\\bgi");
//setfillstyle(0,getmaxcolor());
maxx=getmaxx();
maxy=getmaxy(); midx=maxx/2;
midy=maxy/2;
axis();
bar3d(midx+50,midy-100,midx+60,midy-90,10,1);
3d Scaling:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h> int
maxx,maxy,midx,midy;
void axis() { getch();
cleardevice();
line(midx,0,midx,maxy);
line(0,midy,maxx,midy);
} void main() { int
x,y,z,o,x1,x2,y1,y2; int
gd=DETECT,gm;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\tc\\bgi");
//setfillstyle(0,getmaxcolor());
maxx=getmaxx();
maxy=getmaxy();
midx=maxx/2; midy=maxy/2;
axis();
bar3d(midx+50,midy-100,midx+60,midy-90,5,1);
printf("Enter scaling factors");
scanf("%d%d%d", &x,&y,&z);
//axis(); printf("After scaling"); bar3d(midx+(x*50),midy-
(y*100),midx+(x*60),midy-(y*90),5*z,1);
//axis(); getch();
closegraph();
}
3d Rotation:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h> int
maxx,maxy,midx,midy;
void axis() { getch();
cleardevice();
line(midx,0,midx,maxy);
line(0,midy,maxx,midy);
} void main() { int
x,y,z,o,x1,x2,y1,y2; int
gd=DETECT,gm;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\tc\\bgi");
//setfillstyle(0,getmaxcolor());
maxx=getmaxx();
maxy=getmaxy();
midx=maxx/2; midy=maxy/2;
axis();
bar3d(midx+50,midy-100,midx+60,midy-90,5,1);
printf("Enter rotating angle"); scanf("%d",&o);
x1=50*cos(o*3.14/180)-100*sin(o*3.14/180);
y1=50*sin(o*3.14/180)+100*cos(o*3.14/180); x2=60*cos(o*3.14/180)-90*sin(o*3.14/180);
y2=60*sin(o*3.14/180)+90*cos(o*3.14/180);
axis();
printf("After rotation about z axis");
bar3d(midx+x1,midy-y1,midx+x2,midy-y2,5,1);
axis();
printf("After rotation about x axis");
bar3d(midx+50,midy-x1,midx+60,midy-x2,5,1);
axis(); printf("After rotation about
yaxis");
bar3d(midx+x1,midy-100,midx+x2,midy-90,5,1);
getch(); closegraph();
}
Output:
When you run this program in Turbo C, it will display points on the screen representing the
original point and the points after translation, scaling, and rotation. The points will be
projected onto the 2D screen for visualization.
Application:
1. omputer-Aided Manufacturing (CAM): CAM systems utilize geometric
transformations to generate toolpaths for machining operations, such as milling,
drilling, and turning. Translation, scaling, and rotation are applied to the geometric
models of workpieces and tooling to optimize manufacturing processes and ensure
precise machining operations.
2. Geographic Information Systems (GIS): GIS applications use geometric
transformations to manipulate and analyze spatial data, including maps, satellite
imagery, and terrain models. Translation, scaling, and rotation are employed to align,
transform, and overlay geographic datasets, supporting tasks such as map projections,
spatial analysis, and geographic visualization.
3. Augmented Reality (AR) and Virtual Reality (VR): AR and VR technologies rely on
geometric transformations to render virtual objects and environments in 3D space and
integrate them with the real world. Translation, scaling, and rotation enable realistic
rendering and interaction with virtual objects, enhancing user experiences in gaming,
education, training, and simulation applications.
CHAPTER 11
Curve Generation
Objective:
Implementation Of Curve Generation Using Interpolation Methods.
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 motherboard or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
Curve generation using interpolation methods involves creating smooth curves that pass
through a set of specified points. These curves are often used in computer graphics, CAD
software, animation, and other fields where precise and visually pleasing curves are required.
Here's an overview of the theory behind curve generation using interpolation methods:
Interpolation:
1. Interpolation is the process of estimating unknown values within a range based on
known values at specified points. In curve generation, interpolation is used to
determine the intermediate points that define the curve.
2. Given a set of control points (also known as key points or knots), interpolation
methods compute the coordinates of additional points along the curve to create a
smooth curve passing through all the control points.
Linear Interpolation:
1. Linear interpolation (LERP) is the simplest interpolation method where the curve is
approximated by straight line segments between consecutive control points.
2. The coordinates of the intermediate points along the curve are calculated by linearly
interpolating between the coordinates of adjacent control points.
Polynomial Interpolation:
1. Polynomial interpolation involves fitting a polynomial function to the given set of
control points. Commonly used polynomial interpolation methods include Lagrange
interpolation and Newton interpolation.
2. Lagrange interpolation constructs a polynomial that passes through all the control
points by constructing a unique polynomial of degree n that passes through n+1
control points.
3. Newton interpolation represents the interpolating polynomial as a sum of terms based
on divided differences, providing a stable and efficient method for polynomial
interpolation.
4. Spline Interpolation:
Program:
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
float x = x0;
float y = y0;
int points[5][2] = {
{100, 200}, {150, 150}, {200, 250}, {250, 100}, {300, 200}
};
Output:
When you run this program in Turbo C, it will display a smooth curve passing through the
defined points using linear interpolation. Each segment of the curve between two points will
be a straight line.
Application:
1. Font Design: Bezier curves play a crucial role in font design and typography. They are
used to define the shapes of individual characters, letters, and symbols in digital fonts.
Font designers use Bezier curves to create smooth and aesthetically pleasing
letterforms with precise control over curves and contours.
2. Curve Fitting and Data Visualization: Bezier curves can be used for curve fitting and
data visualization tasks. They allow researchers and scientists to interpolate and
approximate smooth curves that best fit experimental data or mathematical models.
Bezier curves are also used in plotting and graphing software for visualizing
functions, curves, and trends in data.
3. Industrial Design and Manufacturing: Bezier curves find applications in industrial
design and manufacturing for creating product prototypes, molds, and tooling. They
are used to define the shapes of 3D objects and components, allowing designers to
visualize and iterate on designs before production. Bezier curves facilitate smooth
transitions and contours in product designs.
CHAPTER 12
Curve generation
Requirements:
Turbo C / C++ compiler that supports graphics.h package Intel Pentium III800 MHz
Processor or higher version, Intel chipset 810 motherboard or higher version, 14’’ color
monitor or greater than that 2GB HDD or greater, 256 MB RAM or greater.
Theory:
B-Spline and Bezier curves are both popular methods for generating smooth curves in
computer graphics, CAD, animation, and other fields. Here's an overview of the theory
behind B-Spline and Bezier curves:
Bezier Curves:
∑𝑃𝑖 ⋅ 𝐵𝑖,𝑛(𝑡)
𝑖=0
Where Pi are the control poimts and Bi,n(t) are the Bernstein basis functions.
4. Bezier curves have some useful properties, such as interpolation of endpoints and
tangent control at endpoints, which make them intuitive and easy to use for curve
design.
B-Spline Curves:
1. B-Spline stands for Basis Splines, and they are a generalization of Bezier curves.
2. B-Spline curves are defined recursively based on a set of control points and a knot
vector.
3. The knot vector defines the parametric domain of the curve and influences the shape
of the curve.
4. Unlike Bezier curves, B-Spline curves can have multiple segments and can be
nonuniform, meaning that the parameter values do not necessarily increase uniformly.
5. B-Spline curves of degree k+1 consecutive control points at each segment.
Algorithm:
// Example usage:
controlPoints = [(0, 0), (1, 2), (3, 1), (4, 3)] knotVector
= [0, 0, 0, 0, 1, 1, 1, 1]
degree = 3
stepSize = 0.01
Program:
Bezier Curve Implementation
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <math.h>
#define MAX_POINTS 4
void drawBezierCurve() {
for (float t = 0; t <= 1; t += 0.001) {
float x = 0, y = 0;
for (int i = 0; i < MAX_POINTS; i++) {
float b = bernsteinPolynomial(i, MAX_POINTS - 1, t);
x += controlPoints[i][0] * b;
y += controlPoints[i][1] * b;
}
putpixel((int)x, (int)y, WHITE);
}
}
#define MAX_POINTS 6
#define KNOTS 10
// Knot vector
float knotVector[KNOTS] = {0, 0, 0, 1, 2, 3, 4, 5, 5, 5};
void drawBSplineCurve() {
for (float t = 0; t <= 5; t += 0.001) {
float x = 0, y = 0;
for (int i = 0; i < MAX_POINTS; i++) {
float b = basisFunction(i, 3, t); x +=
controlPoints[i][0] * b; y +=
controlPoints[i][1] * b;
}
putpixel((int)x, (int)y, WHITE);
}
}
Output:
When you run these programs in Turbo C, they will display the Bezier and B-Spline curves,
respectively. The Bezier curve will be a smooth curve passing through the control points, and
the B-Spline curve will be a smooth curve influenced by the control points but not necessarily
passing through them. Application:
1. Bezier curves are widely used in graphic design software, font design, animation, and
computer-aided design (CAD) for creating smooth curves and paths.
2. B-Spline curves find applications in automotive design, aerospace engineering,
shipbuilding, and industrial design for modeling complex shapes, surfaces, and curves
with precise control.