You are on page 1of 54

1. Implement Brenham’s line drawing algorithm for all types of slope.

#include <GL/glut.h>
#include<math.h>
#include<stdio.h>
//Input vairables
GLint xOne, yOne, xTwo, yTwo;
//Funtion declaration
void resize(int, int);
void setPixel(GLint, GLint);
void lineBres_L1(GLint, GLint, GLint, GLint, GLfloat) ;
void lineBres_GE1(GLint, GLint, GLint, GLint, GLfloat);
void display();
int main(int argc, char**argv)
{
printf("****Bresenham's Line Drawing Algorithm *****");
printf("\nEnter starting vertex (x1, y1):");
scanf("%d%d",&xOne, &yOne);
printf("\nEnter ending vertex (x2, y2):");
scanf("%d%d",&xTwo, &yTwo);
glutInit(&argc,argv); //initialize GLUT
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); //initialize display mode
glutInitWindowSize(400,400); //set display-window width & height
glutInitWindowPosition(800,50); //set display-window upper-left position
//create display-window with a title
glutCreateWindow("Bresenhams Line Drawing Algorithm");
glutDisplayFunc(display); //call graphics to be displayed on the window
glutReshapeFunc(resize); //calls whenever frame buffer window is resized
glutMainLoop(); //display everything and wait
return 0;
}

1
void resize(int w, int h)
{
//set projection paramaters
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,w,0.0,h);
glViewport(0.0, 0.0, w, h);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
GLfloat m;
m=(float)(yTwo-yOne)/(xTwo-xOne); //compute slope
//call required function based on value of slope
if(fabs(m)>=1)
lineBres_GE1(xOne,yOne,xTwo,yTwo,m);
else
lineBres_L1(xOne, yOne, xTwo,yTwo, m);
}
//Bresenham line-drawing procedure for |m| < 1.0
void lineBres_L1(GLint x0, GLint y0, GLint xEnd, GLint yEnd, GLfloat m)
{
GLint dx = abs(xEnd - x0);
GLint dy = abs(yEnd - y0);
GLint p = 2 * dy - dx;
GLint twoDy = 2 * dy;
GLint twoDyMinusDx = 2 * (dy-dx);
GLint x=x0,y=y0;
// determine which point to use as start position
if (x0 > xEnd)

2
{
x = xEnd;
y = yEnd;
xEnd = x0;
}
else
{
x = x0;
y = y0;
}
setPixel(x,y);
while(x<xEnd)
{
x++;
if(p<0)
p += twoDy;
else
{
if(m<0)
y--;
else
y++;
p += twoDyMinusDx;
}
setPixel(x,y);
}
}
//Bresenham line-drawing procedure for |m| >= 1.0
void lineBres_GE1(GLint x0, GLint y0, GLint xEnd, GLint yEnd, GLfloat m)
{

3
GLint dx = abs(xEnd - x0);
GLint dy = abs(yEnd - y0);
GLint p=2*dx-dy;
GLint twoDx = 2*dx;
GLint twoDxMinusDy=2*(dx-dy);
GLint x=x0,y=y0;
// determine which point to use as start position
if (y0 > yEnd)
{
x = xEnd;
y = yEnd;
yEnd = y0;
}
else
{
x = x0;
y = y0;
}
setPixel(x,y);
while(y<yEnd)
{
y++;
if(p<0)
p+=twoDx;
else
{
if(m<0)
x--;
else
x++;

4
p+=twoDxMinusDy;
}
setPixel(x,y);
}
}
void setPixel(GLint xCoordinate, GLint yCoordinate)
{
glBegin(GL_POINTS);
glVertex2i(xCoordinate,yCoordinate);
glEnd();
glFlush(); //executes all OpenGL functions as quickly as possible.
}
Output:

5
2. Create and rotate a triangle about the origin and a fixed point.
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Set initial display-window size. */
GLsizei winWidth = 800, winHeight = 800;
/* Set range for world coordinates. */
GLfloat xwcMin = -255.0, xwcMax = 225.0;
GLfloat ywcMin = -255.0, ywcMax = 225.0;
GLfloat degree;
class wcPt2D {
public:
GLfloat x, y;
};
wcPt2D fixedpt;
typedef GLfloat Matrix3x3 [3][3];
Matrix3x3 matComposite;
const GLdouble pi = 3.14159;
void init (void)
{
/* Set color of display window to white. */
glClearColor (1.0, 1.0, 1.0, 0.0);
}
/* Construct the 3 x 3 identity matrix. */
void matrix3x3SetIdentity (Matrix3x3 matIdent3x3)
{
GLint row, col;
for (row = 0; row < 3; row++)
for (col = 0; col < 3; col++)

6
matIdent3x3 [row][col] = (row == col);
}
void matrix3x3PreMultiply (Matrix3x3 m1, Matrix3x3 m2)
{
GLint row, col;
Matrix3x3 matTemp;
for (row = 0; row < 3; row++)
for (col = 0; col < 3 ; col++)
matTemp [row][col] = m1 [row][0] * m2 [0][col] + m1 [row][1] * m2 [1][col] + m1 [row][2]
* m2 [2][col];
for (row = 0; row < 3; row++)
for (col = 0; col < 3; col++)
m2 [row][col] = matTemp [row][col];
}
void rotate2D (wcPt2D pivotPt, GLfloat theta)
{
Matrix3x3 matRot;
/* Initialize rotation matrix to identity. */
matrix3x3SetIdentity (matRot);
matRot [0][0] = cos (theta);
matRot [0][1] = -sin (theta);
matRot [0][2] = -pivotPt.x * cos (theta) +
pivotPt.y * sin (theta)+pivotPt.x;
matRot [1][0] = sin (theta);
matRot [1][1] = cos (theta);
matRot [1][2] = -pivotPt.y * cos (theta) -
pivotPt.x * sin (theta)+pivotPt.y;
/* Concatenate matRot with the composite matrix. */
matrix3x3PreMultiply (matRot, matComposite);
}
/* Using the composite matrix, calculate transformed coordinates. */

7
void transformVerts2D (GLint nVerts, wcPt2D * verts)
{
GLint k;
GLfloat temp;
for (k = 0; k < nVerts; k++) {
temp = matComposite [0][0] * verts [k].x + matComposite [0][1] *
verts [k].y + matComposite [0][2];
verts [k].y = matComposite [1][0] * verts [k].x + matComposite [1][1] *
verts [k].y + matComposite [1][2];
verts [k].x = temp;
}
}
void triangle (wcPt2D *verts)
{
GLint k;
glBegin (GL_TRIANGLES);
for (k = 0; k < 3; k++)
glVertex2f (verts [k].x, verts [k].y);
glEnd ( );
}
void displayFcn ()
{
/* Define initial position for triangle. */
GLint nVerts = 3;
wcPt2D verts [3] = { {50.0, 25.0}, {150.0, 25.0}, {100.0, 100.0} };
/* Calculate position of triangle centroid. */
GLint k, xSum = 0, ySum = 0;
GLdouble theta = degree*pi/180;
glClear (GL_COLOR_BUFFER_BIT); // Clear display window.
glColor3f (0.0, 0.0, 1.0); // Set initial fill color to blue.

8
triangle (verts); // Display blue triangle.
/* Initialize composite matrix to identity. */
matrix3x3SetIdentity (matComposite);
/* Construct composite matrix for transformation sequence. */
rotate2D (fixedpt, theta); // Second transformation: Rotate
/* Apply composite matrix to triangle vertices. */
transformVerts2D (nVerts, verts);
glColor3f (1.0, 0.0, 0.0); // Set color for transformed triangle.
triangle (verts);
glFlush ( );
}
void winReshapeFcn (GLint newWidth, GLint newHeight)
{
glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
gluOrtho2D (xwcMin, xwcMax, ywcMin, ywcMax);
glClear (GL_COLOR_BUFFER_BIT);
}
int main (int argc, char ** argv)
{
printf("Enter the angle\n");
scanf("%f",&degree);
printf("Enter the fixed point\n");
scanf("%f %f",&fixedpt.x,&fixedpt.y);
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (50, 50);
glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("Geometric Transformation Sequence");
init ( );

9
glutDisplayFunc (displayFcn);
glutReshapeFunc (winReshapeFcn);
glutMainLoop ( );
return 0;
}
Output:

10
3. Draw a colour cube and spin it using OpenGL transformation matrices.
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
/* Defining global variables for vertices, colors, normals and cube Indices */

GLfloat vertices[ ]={ -1.0,-1.0,-1.0,


1.0,-1.0,-1.0,
1.0, 1.0,-1.0,
- 1.0, 1.0,-1.0,
- 1.0,-1.0, 1.0,
1.0,-1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0 };
GLfloat normals[ ]={ -1.0,-1.0,-1.0,
1.0,-1.0,-1.0,
1.0, 1.0,-1.0,
-1.0, 1.0,-1.0,
-1.0,-1.0, 1.0,
1.0,-1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0 };
GLfloat
colors[ ]={ 0.0,0.0,0.0,
1.0,0.0,0.0,
1.0,1.0,0.0,
0.0,1.0,0.0,
0.0,0.0,1.0,
1.0,0.0,1.0,
1.0,1.0,1.0,
0.0,1.0,1.0};

11
/* These numbers represent faces of a cube */

GLubyte cubeIndices[]={0,3,2,1,
2,3,7,6,
0,4,7,3,
1,2,6,5,
4,5,6,7,
0,1,5,4 };
static GLfloat theta[]={0.0,0.0,0.0};//Initializing the theta value
static GLint axis=2; //default z-axis rotation-0(x-axis),1(y-axis),2(z-axis)
static GLdouble viewer[]={0.0,0.0,5.0};//initial viewer location
void display(void)
{
/*Specifies the red, green, blue, and alpha values
used by glClear to clear the color buffers.*/
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
/*Update viewer position in modelview matrix*/
glLoadIdentity();
/* Rotate Cube */
/*glRotatef function computes a matrix that performs a counterclockwise rotation
of angle degrees about the vector from the origin through the point (x, y, z).*/
glRotatef(theta[0],1.0,0.0,0.0);
glRotatef(theta[1],0.0,1.0,0.0);
glRotatef(theta[2],0.0,0.0,1.0);
glDrawElements(GL_QUADS,24,GL_UNSIGNED_BYTE,cubeIndices); //Drawing a cube
glFlush();//Empties the buffers
glutSwapBuffers();//Performs a buffer swap on the layer in use for the current window
}
void mouse(int btn,int state,int x,int y)
{
/*Mouse callback function to rotate about axis */

12
if(btn==GLUT_LEFT_BUTTON && state==GLUT_DOWN)axis=0;
if(btn==GLUT_RIGHT_BUTTON && state==GLUT_DOWN) axis=1;
if(btn==GLUT_MIDDLE_BUTTON && state==GLUT_DOWN) axis=2;
}
void spincube()
{
theta[axis]+=2.0;
if(theta[axis]>360.0)
theta[axis]-=360.0;
glutPostRedisplay();/*Marks the normal plane of current window as needing to be
redisplayed.*/
}
/*Define reshape function to maintain aspect ratio and then use perspective view*/
void myReshape(int w,int h)
{
/*The glViewport function specifies the affine transformation of x and y
from normalized device coordinates to window coordinates. */
glViewport(0,0,w,h);
/*Applies subsequent matrix operations to the projection matrix stack.*/
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
The glOrtho function multiplies the current matrix by an orthographic matrix.
glOrtho(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w,10.0,10.0);
else
glOrtho(-2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,-2.0,2.0,-10.0,10.0);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char **argv)
{

13
glutInit(&argc,argv);//Initialize glut library
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);//sets the initial
display mode
glutInitWindowSize(500,500);//Defining the window size
glutCreateWindow("color cube");//Creates a top-level window
glutReshapeFunc(myReshape);//sets the reshape callback for the current window
glutDisplayFunc(display);//Sets the display callback for the current window.
glutIdleFunc(keys);//Sets Idle callback for the current window.
glutMouseFunc(mouse);//Sets mouse callback for the current window.
glEnable(GL_DEPTH_TEST);//enables depth testing
/*color array is enabled for writing and
and used during rendering when glDrawElements is called. */
glEnableClientState(GL_COLOR_ARRAY);
/*the vertex array is enabled for writing
and used during rendering when glDrawElements is called. */
glEnableClientState(GL_VERTEX_ARRAY);
/*the normal array is enabled for writing and
used during rendering when glDrawElements is called. */
glEnableClientState(GL_NORMAL_ARRAY);
/*glVertexPointer specifies the location and data of
an array of vertex coordinates to use when rendering.*/
glVertexPointer(3,GL_FLOAT,0,vertices);
glColorPointer(3,GL_FLOAT,0,colors);//define an array of colors
glNormalPointer(GL_FLOAT,0,normals);//define an array of normals
glColor3f(1.0,1.0,1.0);//sets the current color
glutMainLoop();//Enters the GLUT event processing loop
}

14
Output:

15
4. Draw a color cube and allow the user to move the camera suitably to experiment with
perspective viewing.
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
/* Defining global variables for vertices, colors, normals and cube Indices */
GLfloat vertices[ ]={ -1.0,-1.0,-1.0,
1.0,-1.0,-1.0,
1.0, 1.0,-1.0,
- 1.0, 1.0,-1.0,
- 1.0,-1.0, 1.0,
1.0,-1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0 };
GLfloat normals[ ] ={ -1.0,-1.0,-1.0,
1.0,-1.0,-1.0,
1.0, 1.0,-1.0,
-1.0, 1.0,-1.0,
-1.0,-1.0, 1.0,
1.0,-1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0};
GLfloat colors[ ]={ 0.0,0.0,0.0,
1.0, 0.0, 0.0,
1.0, 1.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
1.0, 0.0, 1.0,
1.0, 1.0, 1.0,
0.0, 1.0, 1.0};
/* These numbers represent faces of a cube */
GLubyte cubeIndices[]={0,3,2,1,
2,3,7,6,
0,4,7,3,

16
1,2,6,5,
4,5,6,7,
0, 1, 5, 4 };
static GLfloat theta[]={0.0,0.0,0.0};//Intializing the theta value
static GLint axis=2; //default z-axis rotation-0(x-axis),1(y-axis),2(z-axis)
static GLdouble viewer[]={0.0,0.0,5.0};//initial viewer location
void display(void)
{
/*Specifies the red, green, blue, and alpha values
used by glClear to clear the color buffers.*/
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
/*Update viewer position in modelview matrix*/
glLoadIdentity();
gluLookAt(viewer[0],viewer[1],viewer[2],0.0,0.0,0.0,0.0,1.0,0.0);//where
viewer[0],viewer[1],viewer[2] are camera position
/*Rotate cube */
/*glRotatef function computes a matrix that performs a counterclockwise rotation
of angle degrees about the vector from the origin through the point (x, y, z).*/
glRotatef(theta[0],1.0,0.0,0.0);
glRotatef(theta[1],0.0,1.0,0.0);
glRotatef(theta[2],0.0,0.0,1.0);
glDrawElements(GL_QUADS,24,GL_UNSIGNED_BYTE,cubeIndices);//Drawing a cube
glFlush();//Empties the buffers
glutSwapBuffers();//Performs a buffer swap on the layer in use for the current window
}
void mouse(int btn, int state, int x, int y)
{
/*Mouse callback function to rotate about axis */
if(btn==GLUT_LEFT_BUTTON && state==GLUT_DOWN)axis=0;
if(btn==GLUT_RIGHT_BUTTON && state==GLUT_DOWN) axis=1;
if(btn==GLUT_MIDDLE_BUTTON && state==GLUT_DOWN) axis=2;
theta[axis]+=2.0;
if(theta[axis]>360.0)
theta[axis]-=360.0;
17
glutPostRedisplay();//Marks the normal plane of current window as needing to be
redisplayed.
}
void keys(unsigned char key, int x, int y)
{
/* Use x,X,y,Y,z and Z keys to move viewer position */
if(key=='x') viewer[0]-=1.0;
if(key=='X') viewer[0]+=1.0;
if(key=='y') viewer[1]-=1.0;
if(key=='Y') viewer[1]+=1.0;
if(key=='z') viewer[2]-=1.0;
if(key=='Z') viewer[2]+=1.0;
glutPostRedisplay();
}
/*Define reshape function to maintain aspect ratio and then use perspective view*/
void myReshape(int w, int h)
{
/*The glViewport function specifies the affine transformation of x and y
*/ from normalized device coordinates to window coordinates.
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);//Applies subsequent matrix operations to the projection
matrix stack.
glLoadIdentity();// replaces the current matrix with the identity matrix.
if(w<=h)
/*multiply the current matrix by a perspective matrix*/
glFrustum(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w,2.0,20.0);
else
glFrustum(-2.0,2.0,-2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,2.0,20.0);
glMatrixMode(GL_MODELVIEW);//Applies subsequent matrix operations to the
modelview matrix stack.
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);//Initialize glut library
18
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);//sets the initial
display mode
glutInitWindowSize(500,500);//Defining the window size
glutCreateWindow("color cuce");//Creates a top-level window
glutReshapeFunc(myReshape);//sets the reshape callback for the current window
glutDisplayFunc(display);//Sets the display callback for the current window.
glutKeyboardFunc(keys);//Sets keyboard callback for the current window.
glutMouseFunc(mouse);//Sets mouse callback for the current window.
glEnable(GL_DEPTH_TEST);//enables depth testing
/*color array is enabled for writing and
and used during rendering when glDrawElements is called. */
glEnableClientState(GL_COLOR_ARRAY);
/*the vertex array is enabled for writing
and used during rendering when glDrawElements is called. */
glEnableClientState(GL_VERTEX_ARRAY);
/*the normal array is enabled for writing and
used during rendering when glDrawElements is called. */
glEnableClientState(GL_NORMAL_ARRAY);
/*glVertexPointer specifies the location and data of
an array of vertex coordinates to use when rendering.*/
glVertexPointer(3,GL_FLOAT,0,vertices);
glColorPointer(3,GL_FLOAT,0,colors);//define an array of colors
glNormalPointer(GL_FLOAT,0,normals);//define an array of normals
glColor3f(1.0,1.0,1.0);//sets the current color
glutMainLoop();//Enters the GLUT event processing loop
}

19
Output:

20
5. Clip a lines using Cohen-Sutherland algorithm
#include <stdio.h>
#include <GL/freeglut.h>
#define outcode int
#define true 1
#define false 0
double xmin=50,ymin=50, xmax=100,ymax=100; // Window boundaries
double xvmin=200,yvmin=200,xvmax=300,yvmax=300; // Viewport boundaries
const int RIGHT = 8;//bit codes for the right
const int LEFT = 2;//bit codes for the left
const int TOP = 4;//bit codes for the top
const int BOTTOM = 1;//bit codes for the bottom
//used to compute bit codes of a point
outcode ComputeOutCode (double x, double y);
/*Cohen-Sutherland clipping algorithm clips a line from
P0 = (x0, y0) to P1 = (x1, y1) against a rectangle with
diagonal from (xmin, ymin) to (xmax, ymax).*/
void CohenSutherlandLineClipAndDraw (double x0, double y0,double x1, double y1)
{
outcode outcode0, outcode1, outcodeOut; //Outcodes for P0, P1, and whatever point lies
outside //the clip rectangle
BOOL accept = false, done = false;
outcode0 = ComputeOutCode (x0, y0); //computation of outcode0
outcode1 = ComputeOutCode (x1, y1); //computation of outcode1
do{
if (!(outcode0 | outcode1)) //logical or is 0 Trivially accept & exit
{
accept = true;
done = true;
}
21
else if (outcode0 & outcode1) //logical and is not 0. Trivially reject and exit
done = true;
else
{
//failed both tests, so calculate the line segment to clip
//from an outside point to an intersection with clip edge
double x, y;
//At least one endpoint is outside the clip rectangle; pick it.
outcodeOut = outcode0? outcode0: outcode1;
//Now find the intersection point;
//use formulas y = y0 + slope * (x - x0), x = x0 + (1/slope)* (y - y0)
if (outcodeOut & TOP) //point is above the clip rectangle
{
x = x0 + (x1 - x0) * (ymax - y0)/(y1 - y0);
y = ymax;
}
else if (outcodeOut & BOTTOM) //point is below the clip rectangle
{
x = x0 + (x1 - x0) * (ymin - y0)/(y1 - y0);
y = ymin;
}
else if (outcodeOut & RIGHT) //point is to the right of clip rectangle
{
y = y0 + (y1 - y0) * (xmax - x0)/(x1 - x0);
x = xmax;
}
else //point is to the left of clip rectangle
{
y = y0 + (y1 - y0) * (xmin - x0)/(x1 - x0);

22
x = xmin;
}
//Now we move outside point to intersection point to clip
//and get ready for next pass.
if (outcodeOut == outcode0)
{
x0 = x;
y0 = y;
outcode0 = ComputeOutCode (x0, y0);
}
else
{
x1 = x;
y1 = y;
outcode1 = ComputeOutCode (x1, y1);
}
}
}while (!done);
if (accept)
{
// Window to viewport mappings
// Scale parameters
double sx=(xvmax-xvmin)/(xmax-xmin);
double sy=(yvmax-yvmin)/(ymax-ymin);
double vx0=xvmin+(x0-xmin)*sx;
double vy0=yvmin+(y0-ymin)*sy;
double vx1=xvmin+(x1-xmin)*sx;
double vy1=yvmin+(y1-ymin)*sy;
//draw a red colored viewport

23
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINE_LOOP); //Draws connected group of line segments from first vertex to
last
glVertex2f(xvmin, yvmin);
glVertex2f(xvmax, yvmin);
glVertex2f(xvmax, yvmax);
glVertex2f(xvmin, yvmax);
glEnd();
// draw blue colored clipped line
glColor3f(0.0,0.0,1.0); //Sets a new three valued RGB color
glBegin(GL_LINES); //To draw a line between 2 vertices
glVertex2d (vx0, vy0);
glVertex2d (vx1, vy1);
glEnd();
}
}
//Compute the bit code for a point (x, y) using the clip rectangle
//bounded diagonally by (xmin, ymin), and (xmax, ymax)
outcode ComputeOutCode (double x, double y)
{
outcode code = 0;
if (y > ymax) //above the clip window
code |= TOP;
else if (y < ymin) //below the clip window
code |= BOTTOM;
if (x > xmax) //to the right of clip window
code |= RIGHT;
else if (x < xmin) //to the left of clip window
code |= LEFT;

24
return code;
}
void display() //To display the output
{
double x0=120,y0=10,x1=40,y1=130;
glClear(GL_COLOR_BUFFER_BIT); //Clears the OpenGL color and depth buffers
//draw the line with red color
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINES);
glVertex2d (x0, y0);
glVertex2d (x1, y1);
glVertex2d (60,20);
glVertex2d (80,120);
glEnd();
//draw a blue colored window
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINE_LOOP); ); //Draws connected group of line segments from first vertex to
last
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glVertex2f(xmin, ymax);
glEnd();
CohenSutherlandLineClipAndDraw(x0,y0,x1,y1);
CohenSutherlandLineClipAndDraw(60,20,80,120);
glFlush(); //To empty all the buffers values
}
void myinit() //To set OpenGL state variables dealing with viewing and attributes
{

25
glClearColor(1.0,1.0,1.0,1.0); //Specifies RGBA values to clear color buffers
glColor3f(1.0,0.0,0.0);
glPointSize(1.0); //Specifies rasterized(converting image in vector graphics format to raster
image)
//diameter of points
glMatrixMode(GL_PROJECTION); //Used for projection transformation from 3D to 2D onto
screen
glLoadIdentity(); //Replaces current matrix with identity matrix
gluOrtho2D(0.0,499.0,0.0,499.0); //To set clipping area of 2D orthographic view
}
int main(int argc, char** argv)
{
glutInit(&argc,argv); //To initialize GLUT library
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); //Specifies type of display mode when
creating a
//window
glutInitWindowSize(500,500); //Defines size of window on the screen
glutInitWindowPosition(0,0); //Defines position of window on the screen
glutCreateWindow("Cohen Suderland Line Clipping Algorithm"); //Creates a top level
window
glutDisplayFunc(display); //Sets display callback for the current window
myinit(); //Used to set the OpenGL state variables dealing with viewing and attributes
glutMainLoop(); //Tells program to enter the GLUT event processing loop
}

26
Output:

27
6. To draw a simple shaded scene consisting of a tea pot on a table. Define
suitably the position and properties of the light source along with the
properties of the surfaces of the solid object used in the scene.
#ifdef __APPLE__

#include <GLUT/glut.h>

#else

#include <GL/glut.h>

#endif

#include <stdlib.h>

#include <GL/glut.h>

#include <stdio.h>

void wall(double thickness)

glPushMatrix(); //save the current state

glTranslated(0.5,0.5*thickness,0.5); //move your item appropriately

glScaled(1.0,thickness,1.0); //multiply current matrix by general scaling matrix

glutSolidCube(1.0); //render your teapot

glPopMatrix(); //get back your state with the recent changes that you have done

void tableleg(double thick,double len) // table leg which is actually a CUBE

glPushMatrix();

glTranslated(0,len/2,0);

glScaled(thick,len,thick);

glutSolidCube(1.0);

28
glPopMatrix();

void table(double topw,double topt,double legt,double legl) // table top which is actually a
CUBE

glPushMatrix();

glTranslated(0,legl,0);

glScaled(topw,topt,topw);

glutSolidCube(1.0); /*glutSolidCube(size) render a solid cube.The cube is centered at the


modeling coordinates’ origin with sides of length size.*/

glPopMatrix(); /*glPopMatrix pops the current matrix stack, replacing the current matrix with
the one below it on the stack.*/

double dist=0.95*topw/2.0-legt/2.0;

glPushMatrix(); /*glPushMatrix pushes the current matrix stack. It pushes the current matrix
stack down by one, duplicating the current matrix.*/

glTranslated(dist,0,dist); /*glTranslated-moving an object to different position on screen.*/

tableleg(legt,legl); //create 1st leg

glTranslated(0,0,-2*dist);

tableleg(legt,legl); //create 2nd leg

glTranslated(-2*dist,0,2*dist);

tableleg(legt,legl); //create 3rd leg

glTranslated(0,0,-2*dist);

tableleg(legt,legl); // create 4th leg

glPopMatrix();

29
void displaysolid(void) // set the lighting arrangements

GLfloat mat_ambient[]={0.7f,0.7f,0.7f,1.0f}; //ambient color

GLfloat mat_diffuse[]={0.5f,0.5f,0.5f,1.0f};

GLfloat mat_specular[]={1.0f,1.0f,1.0f,1.0f};

GLfloat mat_shininess[]={50.0f}; //shineness value

/*glMaterial — specify material parameters for the lighting model. fv means floating point
vector. */

glMaterialfv(GL_FRONT,GL_AMBIENT,mat_ambient);

glMaterialfv(GL_FRONT,GL_DIFFUSE,mat_diffuse);

glMaterialfv(GL_FRONT,GL_SPECULAR,mat_specular);

glMaterialfv(GL_FRONT,GL_SHININESS,mat_shininess);

GLfloat lightint[]={0.7f,0.7f,0.7f,1.0f};

GLfloat lightpos[]={2.0f,6.0f,3.0f,0.0f};

/*glLight sets the values of individual light source parameters. It takes 3 parameters – light,
pname, params. */

glLightfv(GL_LIGHT0,GL_POSITION,lightpos);

glLightfv(GL_LIGHT0,GL_DIFFUSE,lightint);

glMatrixMode(GL_PROJECTION); //glMatrixMode specifies the current matrix.

glLoadIdentity();

double winht=1.0;

glOrtho(-winht*64/48.0,winht*64/48.0,-winht,winht,0.1,100.0); /*multiply current matrix by


an Orthographic matrix that produces a parallel projection.*/

glMatrixMode(GL_MODELVIEW);

glLoadIdentity(); //replaces current matrix with identity matrix.

30
gluLookAt(2.3,1.3,2.0,0.0,0.25,0.0,0.0,1.0,0.0); // camera position & viewing

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

glPushMatrix();

glRotated(90.0,0.0,0.0,1.0);

wall(0.02); //create 1st wall

glPopMatrix();

wall(0.02); //create 2nd wall

glPushMatrix();

glRotated(-90.0,1.0,0.0,0.0);

wall(0.02); //create 3rd wall

glPopMatrix();

glPushMatrix();

glTranslated(0.4,0,0.4);

table(0.6,0.02,0.02,0.3);

glPopMatrix();

glPushMatrix();

glTranslated(0.6,0.38,0.5);

glRotated(30,0,1,0); //multiply current matrix by a rotation matrix.

glutSolidTeapot(0.08);

glPopMatrix();

glFlush(); // show the output to the user

int main(int argc,char**argv)

31
glutInit(&argc,argv); //Initialize glut library

glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH); //sets initial display


mode

glutInitWindowSize(500,500); //define size of window on screen

glutInitWindowPosition(0,0); //define position of window on screen

glutCreateWindow("teapot"); //create a top level window

glutDisplayFunc(displaysolid); //sets display callback for current window

glEnable(GL_LIGHTING); // enable the lighting properties

glEnable(GL_LIGHT0); // enable the light source

glShadeModel(GL_SMOOTH); // for smooth shading (select flat or smooth shading)

glEnable(GL_DEPTH_TEST); // do depth comparisons and update the depth buffer.

glEnable(GL_NORMALIZE); . /*If enabled and no vertex shader is active, normal vectors


are normalized to unit length after transformation and before lighting.*/

glClearColor(0.1,0.1,0.1,0.0); // specifies clear values to clear color buffers.

glViewport(0,0,640,480); /*specifies affine transformation of x & y from normalized device


coordinates to window coordinates.*/

glutMainLoop(); //tells program to enter GLUT event processing loop(it never exits).

Output:

32
7. Design, develop and implement recursively subdivide a tetrahedron to form 3D
sierpinski gasket. The number of recursive steps is to be specified by the user.
#include <GL/glut.h>

#include <stdlib.h>

#include<stdio.h>

// since all floating point values are points of a triangle in this program, we pre-define it using
typedef

typedef float point[3];

// define the co-ordinates for initial tetrahedron

point v[] = {

{0.0,0.0,1.0},

{0.0,0.943,-0.33},

{-0.816,-0.471,-0.33},

{0.816,-0.471,0.33}

};

// number of recursive steps

int n;

// function to get triangle from three points

void triangle(point a,point b,point c) {

// begin function

glBegin(GL_POLYGON);

// uses 'a' as a normal for the triangle.

// normal for the triangle defines the vector that is perpendicular to the plane on which
the triangle exists

glNormal3fv(a);

// three vertices

33
glVertex3fv(a);

glVertex3fv(b);

glVertex3fv(c);

// end function

glEnd();

// divide triangle into more triangles by considering the mid point of each side of triangle

// each midpoint will reconstruct into a triangle and the new triangles into a tetrahedron

void divide_tri(point a,point b,point c,int m) {

// define three points for recursion or division

point v1,v2,v3;

int j;

// base condition for recursion

// divide triangles till 'm' is greater than 0

if (m>0) {

// get mid points of the edges of current triangle and store them in 'v1','v2' and
'v3'

// since each point data type is an array of size three, we run for loop for three
iterations

for(j=0;j<3;j++) {

v1[j]=(a[j]+b[j])/2;

v2[j]=(a[j]+c[j])/2;

v3[j]=(b[j]+c[j])/2;

34
// recursively divide the triangle while decreasing 'm' and using the newly
devised points

divide_tri(a,v1,v2,m-1);

divide_tri(c,v2,v3,m-1);

divide_tri(b,v3,v1,m-1);

// if base condition is not satisfied, return the triangle as is

// in the end gasket, this triangle represents the hollow triangle in the middle of the
gasket

else

triangle(a,b,c);

// Construct a tetrahedron step by step with four triangles

void tetrahedron(int m) {

// the triangles facing towards left and outside will be colored red

glColor3f(1.0,0.0,0.0);

divide_tri(v[0],v[1],v[2],m);

/* the triangles facing the inside of the tetrahedron (triangle on the back side) will be
colored white*/

glColor3f(1.0,1.0,1.0);

divide_tri(v[3],v[2],v[1],m);

// the triangles facing towards right and outside will be colored blue

glColor3f(0.0,0.0,1.0);

divide_tri(v[0],v[3],v[1],m);

35
// the triangles facing towards bottom and outside will be colored green

glColor3f(0.0,1.0,0.0);

divide_tri(v[0],v[2],v[3],m);

// display gasket with 'n' recursive subdivisions of tetrahedron

void display(void) {

// resets the color bit and depth bit

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

// resets the matrix of bits into identity matrix

glLoadIdentity();

// display tetrahedron with 'n' recursive divisions

tetrahedron(n);

// flush the display if/after window is changed

glFlush();

// reshape function for when window size changes

void myReshape(int w,int h) {

// sets viewport

// the first two parameters represent lower left corner of viewport which here is (0,0)

// the next two parameters represent the size of viewport

// if size is not specified, the window size is considered as size of viewport

glViewport(0,0,w,h);

// make projection matrix as current matrix

36
glMatrixMode(GL_PROJECTION);

// resets the projection matrix bits into identity matrix

glLoadIdentity();

// adjust viewport as per the 'w' and 'h' parameters

if(w<=h)

glOrtho(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w,-
10.0,10.0);

else

glOrtho(-2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,-2.0,2.0,-
10.0,10.0);

// make model view matrix as current matrix

glMatrixMode(GL_MODELVIEW);

// will make the current window to be redisplayed when glutMainLoop tries to persist
display

glutPostRedisplay();

// main function

// asks for the number of recursions from user and displays the gasket

int main(int argc,char **argv) {

// ask for number of recursions and stores it in 'n'

printf("Enter the number of recursive steps you want: ");

scanf("%d", &n);

37
// Initialize glut

glutInit(&argc,argv);

// Initialize display mode of glut

glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH);

// Initialize window parameters

glutInitWindowSize(500,500);

glutCreateWindow("Sierpinski gasket");

//reshape function for when the window size is altered

glutReshapeFunc(myReshape);

// display component from display function

glutDisplayFunc(display);

// allows for depth comparison and changing the depth buffer

// if not enabled, it will not be possible to render 3D images on 2D plane

glEnable(GL_DEPTH_TEST);

// sets default color

glClearColor(0.0,0.0,0.0,1.0);

// persist the output

glutMainLoop();

38
Output:

39
40
41
8. Develop a menu driven program to animate a flag using Bezier Curve algorithm

#include<GL/glut.h>

#include<stdio.h>

#include<math.h>

#define PI 3.1416

/*specify the clipping

Window width and height */

GLsizei winWidth = 600, winHeight = 600;

/* specify the window position( the min and max value of the world coordinate)*/

GLfloat xwcMin = 0.0, xwcMax = 130.0;

GLfloat ywcMin = 0.0, ywcMax = 130.0;

int animate=1;

/* define the structure for the x,y,z coordinates*/

typedef struct wcPt3D

GLfloat x, y, z;

};

/*blending function , calculates the cooeficients*/

void bino(GLint n, GLint *C)

GLint k, j;

for(k=0;k<=n;k++)

C[k]=1;

42
for(j=n;j>=k+1; j--)

C[k]*=j;

for(j=n-k;j>=2;j--)

C[k]/=j;

}} /* calculate polynomial w.r.t

x,y,z*/

void computeBezPt(GLfloat u, wcPt3D *bezPt, GLint nCtrlPts, wcPt3D *ctrlPts,

GLint

*C)

GLint k, n=nCtrlPts-1;

GLfloat bezBlendFcn;

bezPt ->x =bezPt ->y = bezPt->z=0.0;

for(k=0; k< nCtrlPts; k++)

{ /*calculate x,y

value for twenty intervals*/

bezBlendFcn = C[k] * pow(u, k) * pow( 1-u, n-k);

bezPt ->x += ctrlPts[k].x * bezBlendFcn;

bezPt ->y += ctrlPts[k].y * bezBlendFcn;

bezPt ->z += ctrlPts[k].z * bezBlendFcn;

}} //Bezier function

void bezier(wcPt3D *ctrlPts, GLint nCtrlPts, GLint nBezCurvePts)

wcPt3D bezCurvePt;

43
/*parameter value*/

GLfloat u;

/*create instance for the control point*/

GLint *C, k;

C= new GLint[nCtrlPts];

/* call the binomial function,calculates the coeficients*/

bino(nCtrlPts-1, C);

/*draw connected group of line segments from first to last*/

glBegin(GL_LINE_STRIP);

for(k=0; k<=nBezCurvePts; k++)

u=GLfloat(k)/GLfloat(nBezCurvePts);

computeBezPt(u, &bezCurvePt, nCtrlPts, ctrlPts, C);

glVertex2f(bezCurvePt.x, bezCurvePt.y);

glEnd();

delete[]C;

void displayFcn()

{ if(animate)

{ /* specify the control points ,

count of control points */

GLint nCtrlPts = 4, nBezCurvePts =20;

/* initialize the angle with which the flag should fly*/

44
static float theta = 0;

/* assign the values for the control points*/

wcPt3D ctrlPts[4] = {

{20, 100, 0},

{30, 110, 0},

{50, 90, 0},

{60, 100, 0}};

/*specify the angle for movement of flag w.r.t three coordinates*/

ctrlPts[1].x +=10*sin(theta * PI/180.0);

ctrlPts[1].y +=5*sin(theta * PI/180.0);

ctrlPts[2].x -= 10*sin((theta+30) * PI/180.0);

ctrlPts[2].y -= 10*sin((theta+30) * PI/180.0);

ctrlPts[3].x-= 4*sin((theta) * PI/180.0);

ctrlPts[3].y += sin((theta-30) * PI/180.0);

theta+=0.1;

/*reset the buffer*/

glClear(GL_COLOR_BUFFER_BIT);

/* specify the backgroung color ,set color to black*/

glColor3f(1.0, 1.0, 1.0);

/*spcecify the size of the control points*/

glPointSize(5);

glPushMatrix();

/*specify the rasterized width of the line */

glLineWidth(5);

45
glColor3f(255/255, 153/255.0, 51/255.0); //Indian flag: Orange color code

/*generate 8 curves*/

for(int i=0;i<8;i++)

glTranslatef(0, -0.8, 0);

bezier(ctrlPts, nCtrlPts, nBezCurvePts);

glColor3f(1, 1, 1); //Indian flag: white color code

/*generate 8 curves*/

for(int i=0;i<8;i++)

{ /*produce the translation for the 8

curves*/

glTranslatef(0, -0.8, 0);

/*call the Bezier function,parameters-degree,4 control points,20 intermediate control points*/

bezier(ctrlPts, nCtrlPts, nBezCurvePts);

} //glColor3f(19/255.0, 136/255.0, 8/255.0); //Indian flag: green color code

glColor3f(1, 1, 1);

for(int i=0;i<8;i++)

{ /*produce the translation for the 8

curves*/

glTranslatef(0, -0.8, 0);

/*call the Bezier function,parameters-degree,4 control points,20 intermediate control points*/

bezier(ctrlPts, nCtrlPts, nBezCurvePts);

} /* replace the current matrix with the one below */

46
glPopMatrix();

/*set the current color for the pole */

glColor3f(0.7, 0.5,0.3);

/* specify the width of the pole*/

glLineWidth(5);

/*generate the line for the pole */

glBegin(GL_LINES);

glVertex2f(20,100);

glVertex2f(20,40);

glEnd();

/*clear the buffer*/

glFlush();

/*Resdisplay the current window*/

glutPostRedisplay();

/*swaps the buffer to the current window*/

glutSwapBuffers();

}} // Menu exit

void handlemenu(int value)

switch (value) {

case 4:

exit(0);

break;

47
} //Colors menu

void cmenu(int value){

switch(value){

case 1:

animate=1;

glutPostRedisplay();

break;

case 2:

animate=0;

glutPostRedisplay();

break;

/*Reshape the view port*/

void winReshapeFun(GLint newWidth, GLint newHeight)

{ /*set the viewort*/

glViewport(0, 0, newWidth, newHeight);

/* set the current matrix projection matix*/

glMatrixMode(GL_PROJECTION);

/*replace the current matrix with the identity matix*/

glLoadIdentity();

/*define the 2d orthographic projection matrix*/

gluOrtho2D(xwcMin, xwcMax, ywcMin, ywcMax);

/*clear the buffer*/

48
glClear(GL_COLOR_BUFFER_BIT);

} int main(int argc, char **argv)

{ /*initialize glut library*/

glutInit(&argc, argv);

/* use of double buffer

sets the initial display mode.*/

glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);

/*specify the output window position and size*/

glutInitWindowPosition(50, 50);

glutInitWindowSize(winWidth, winHeight);

//create display-window with a title

glutCreateWindow("Bezier Curve");

int a_menu=glutCreateMenu(cmenu);

glutAddMenuEntry("start", 1);

glutAddMenuEntry("stop", 2);

glutCreateMenu(handlemenu);

glutAddSubMenu("animate", a_menu);

glutAddMenuEntry("Quit",4);

glutAttachMenu(GLUT_RIGHT_BUTTON);

//call graphics to be displayed on the window

glutDisplayFunc(displayFcn);

glutReshapeFunc(winReshapeFun);

//calls whenever frame buffer window is resized glutReshapeFunc(winReshapeFun);

//display everything and wait

49
glutMainLoop();

Output:

50
9. Develop a menu driven program to fill the polygon using scan line algorithm.

#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
//declare polygon vertices
float x1,x2,x3,x4,y1,y2,y3,y4;
//Detection of edges of the polygon that intersect with scan line and sort the intersections by
increasing x-coordinate
void edgedetect(float x1,float y1,float x2,float y2,int *le,int *re)
{
float mx,x,temp;
int i;
//swap vertex values using temp if difference of y1 and y2 is 0
if((y2-y1)<0)
{
temp=y1;y1=y2;y2=temp;
temp=x1;x1=x2;x2=temp;
}
//identifying slope of the line
if((y2-y1)!=0)
mx=(x2-x1)/(y2-y1);
else
//slope is the difference of x2 and x1
mx=x2-x1;
//assign x1 value to x vertex
x=x1;
//detection of edge
for(i=y1;i<=y2;i++)
{
if(x<(float)le[i])
le[i]=(int)x;
if(x>(float)re[i])
re[i]=(int)x;

51
x+=mx;
}
}
//to draw pixel
void draw_pixel(int x,int y)
{
//set pixel color to yellow
glColor3f(1.0,1.0,0.0);
//define points
glBegin(GL_POINTS);
//draw vertex x,y where x and y are 2-D integers
glVertex2i(x,y);
//end
glEnd();
}
//fill in all pixels between pairs of intersections
void scanfill(float x1,float y1,float x2,float y2,float x3,float y3,float x4,float y4)
{
//maximum number of scan lines in the window
int le[500],re[500];
int i,y;
for(i=0;i<500;i++)
{
le[i]=500;
re[i]=0;
}
edgedetect(x1,y1,x2,y2,le,re);
edgedetect(x2,y2,x3,y3,le,re);
edgedetect(x3,y3,x4,y4,le,re);
edgedetect(x4,y4,x1,y1,le,re);
//fill the polygon
for(y=0;y<500;y++)
{
if(le[y]<=re[y])
52
for(i=(int)le[y];i<(int)re[y];i++)
draw_pixel(i,y);
}
}
void display()
{
x1=200.0;y1=200.0;x2=100.0;y2=300.0;x3=200.0;y3=400.0;x4=300.0;y4=300.0;
// clears the color and depth buffers
glClear(GL_COLOR_BUFFER_BIT);
//set polygon edge color to blue
glColor3f(0.0, 0.0, 1.0);
//define a polygon object
glBegin(GL_LINE_LOOP);
//define vertices for polygon
glVertex2f(x1,y1);
glVertex2f(x2,y2);
glVertex2f(x3,y3);
glVertex2f(x4,y4);
glEnd();
scanfill(x1,y1,x2,y2,x3,y3,x4,y4);
//empties buffers
glFlush();
}
void myinit()
{
//set background color to white
glClearColor(1.0,1.0,1.0,1.0);
//set point color to red
glColor3f(1.0,0.0,0.0);
//set point size to 1.0
glPointSize(1.0);
//set projection parameters
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
53
gluOrtho2D(0.0,499.0,0.0,499.0);
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
//initialize display mode
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
//set display-window width & height
glutInitWindowSize(500,500);
//set display-window upper-left position
glutInitWindowPosition(0,0);
//creates output window
glutCreateWindow("Filling a Polygon using Scan-line Algorithm");
//call graphics to be displayed on the window
glutDisplayFunc(display);
myinit();
//display everything and wait
glutMainLoop();
}

Output:

54

You might also like