18csl67 Cgv Lab Manual
18csl67 Cgv Lab Manual
3. Prof. Reshma
(ACCREDITED BY NBA)
Soldevanahalli, Bengaluru-560107
2022-2023
Table of contents
2 Create and rotate a triangle about the origin and a fixed point. 10
4 Draw a color cube and allow the user to move the camera suitably to 15
experiment with perspective viewing.
8 Develop a menu driven program to animate a flag using Bezier Curve algorithm. 27
9 Develop a menu driven program to fill the polygon using scan line algorithm. 33
PSO Statements
Students shall
PSO-1: Apply the knowledge of hardware, system software, algorithms, networking and data
bases.
Design, analyze and develop efficient, Secure algorithms using appropriate data structures,
PSO-2: databases for processing of data.
Be Capable of developing stand alone, embedded and web-based solutions having easy to
PSO-3: operate interface using Software Engineering practices and contemporary computer
programming languages.
Programme Outcomes
Engineering Graduates will be able to:
II
f. The engineer and society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
g. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
h. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
i. Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
j. Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
k. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.
l. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of
technological change.
Course Outcomes:
CO1: Implement computer graphics primitives and algorithms using OpenGL API’s.
CO2: Write programs on 2D/3D objects using modelling, transformation and illumination concepts.
III
OpenGL is a state machine. It is called a state machine because it can be put into various
states until you change them. As you've already seen, the current color is a state variable. You
can set the current color to white, red, or any other color, and thereafter every object is drawn
with that color until you set the current color to something else.
The current color is only one of many state variables that OpenGL maintains. Others control
such things as the current viewing and projection transformations; line and polygon stipple
patterns, polygon drawing modes, pixel-packing conventions, positions and characteristics of
lights, and material properties of the objects being drawn. Many state variables refer to modes
that are enabled or disabled with the command glEnable() or glDisable(). Each state variable
or mode has a default value, and at any point you can query the system for each variable's
current value.
OpenGL-Related Libraries
OpenGL provides a powerful but primitive set of rendering commands, and all higher-
level drawing must be done in terms of these commands. Also, OpenGL programs have to use
the underlying mechanisms of the windowing system. A number of libraries exist to allow you
to simplify your programming tasks, including the following:
The OpenGL Utility Library (GLU) contains several routines that use lower-level
OpenGL commands to perform such tasks as setting up matrices for specific viewing
Include Files
For all OpenGL applications, you want to include the gl.h header file in every file.
Almost all OpenGL applications use GLU, the aforementioned OpenGL Utility Library, which
requires inclusion of the glu.h header file. So almost every OpenGL source file begins with
#include <GL/gl.h>
#include <GL/glu.h>
If you are using GLUT for managing your window manager tasks, you should include
#include <GL/glut.h>
Note that glut.h includes gl.h, glu.h automatically, so including all three files is redundant.
OpenGL Hierarchy
OpenGL: Camera
Two things to specify:
OpenGL Conventions
Many functions have multiple forms:
Event Loop
• Some commands end in a number and one, two or three letters at the end (indicating
number and type of arguments)
• A Number indicates number of arguments
– loop
• redraw
glMatrixMode
• glMatrixMode
• C Specification
• Parameters
– mode Specifies which matrix stack is the target for subsequent matrix
operations. Three values are accepted: GL_MODELVIEW,
GL_PROJECTION, and GL_TEXTURE. The default value is
GL_MODELVIEW.
• Description
– glMatrixMode sets the current matrix mode. mode can assume one of three
values: GL_MODELVIEW Applies subsequent matrix operations to the
modelview matrix stack. GL_PROJECTION Applies subsequent matrix
operations to the projection matrix stack.
OpenGL 3D Viewing Functions
Viewing-transformation function
– glMatrixMode (GL_MODELVIEW);
– gluLookAt(x0,y0,z0,xref,yref,zref,vx,vy,vz);
– glMatrixMode(GL_PROJECTION);
– Note that
PROGRAMS
ALGORITHM:
Step 1 - Input the two end-points of line, storing the left end-point in (x0,y0). Step 2 -
Plot the point (x0,y0).
Step 3 - Calculate the constants dx, dy, 2dy, and (2dy – 2dx) and get the first value for
the decision parameter as -
p0=2dy-dx
Step 4 - At each xk along the line, starting at k = 0, perform the following test -
If pk< 0, the next point to plot is (xk+1,yk) and pk+1=pk+2dy
Otherwise, (xk,yk+1)
pk+1=pk+2dy-2dx
Step 5 - Repeat step 4 (dx – 1) times.
For m > 1, find out whether you need to increment x while incrementing y each time.
PROGRAM:
#include<GL/glut.h>
#include<stdio.h>
#include<stdlib.h>
int x1, y11, x2, y2;
void myInit()
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0, 900, 0, 900);
}
void draw_pixel(int x, int y)
{
glEnable(GL_POINT_SMOOTH);
glPointSize(2.0f);
glBegin(GL_POINTS);
glVertex2i(x, y);
glColor3f(0.0,0.0,1.0);
glEnd();
}
draw_pixel(x, y);
e = 2 * dy-dx;
inc1 = 2*(dy-dx);
inc2 = 2*dy;
for (i=0; i<dx; i++){
if (e >= 0){
y += incy;
e += inc1;
}
else
e += inc2;
x += incx;
draw_pixel(x, y);
}}
else {
draw_pixel(x, y);
e = 2*dx-dy;
inc1 = 2*(dx-dy);
inc2 = 2*dx;
for (i=0; i<dy; i++) {
if (e >= 0) {
x += incx;
e += inc1;
}
else
e += inc2;
y += incy;
draw_pixel(x, y);
}
}
}
void myDisplay()
{
draw_line(x1, x2, y11, y2);
glFlush();
}
int main(int argc, char **argv)
{
glutInitWindowSize(500, 500);
glutInitWindowPosition(0, 0);
glutCreateWindow("Bresenham's Line Drawing");
myInit();
glutDisplayFunc(myDisplay);
glutMainLoop();
return 0;
}
OUTPUT
2) Create and rotate a triangle about the origin and a fixed point
#include<stdio.h>
#include<math.h>
#include<GL/glut.h>
#define PI 3.1425
GLfloat tria[3][3]={{100.0,300.0,200.0},{100.0,100.0,300.0},{1.0,1.0,1.0}};
GLfloat rot_mat[3][3]={{0},{0},{0}};
GLfloat
result[3][3]={{0},{0},{0}};
GLfloat h=100.0;
GLfloat k=100.0;
GLfloat theta;
void multiply()
{
int i,j,l;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
result[i][j]=0;
for(l=0;l<3;l++)
result[i][j]=result[i][j]+rot_mat[i][l]*tria[l][j];
}
}
void rotate(GLfloat m,GLfloat n)
{
rot_mat[0][0]=cos(theta);
rot_mat[0][1]=-sin(theta);
rot_mat[0][2]=m;
rot_mat[1][0]=sin(theta);
rot_mat[1][1]=cos(theta);
rot_mat[1][2]=n;
rot_mat[2][0]=0;
rot_mat[2][1]=0;
rot_mat[2][2]=1;
multiply();
}
void drawtria()
{
glColor3f(0.0,0.0,1.0);
glBegin(GL_TRIANGLES);
glVertex2f(tria[0][0],tria[1][0]);
glVertex2f(tria[0][1],tria[1][1]);
glVertex2f(tria[0][2],tria[1][2]);
glEnd();
}
void drawrotatedtria()
{
glColor3f(1.0,0.0,1.0);
glBegin(GL_TRIANGLES);
glVertex2f(result[0][0],result[1][0]);
glVertex2f(result[0][1],result[1][1]);
glVertex2f(result[0][2],result[1][2]);
glEnd();
}
void display()
{
glClear(GL_COLOR_BUFFER_BI
T); GLfloat m,n;
drawtria();
m=-h*(cos(theta)-1)+k*(sin(theta));
n=-k*(cos(theta)-1)-h*(sin(theta));
rotate(m,n);
glColor3f(0.0,1.0,0.0);
drawrotatedtria();
rotate(0,0);
glColor3f(0.0,1.0,1.0);
drawrotatedtria();
glFlush();
}
void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,1.0,0.0);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION
); glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
}
OUTPUT
#include<GL/glut.h>
GLfloat vertices[][3]={{-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[][3]={{0.0,0.0,0.0},{0.0,0.0,1.0},{0.0,1.0,0.0},
{0.0,1.0,1.0},{1.0,0.0,0.0},{1.0,0.0,1.0},
{1.0,1.0,0.0},{1.0,1.0,1.0}};
void polygon(int a,int b,int c,int d)
{
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glColor3fv(colors[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube(void)
{
polygon(0,3,2,1);
polygon(2,3,7,6);
polygon(0,4,7,3);
polygon(1,2,6,5);
polygon(4,5,6,7);
polygon(0,1,5,4);
}
void display(void)
/* Display callback, clear frame buffer and Z buffer, rotate cube and draw, swap buffers
*/
{ glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
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);
colorcube();
glFlush();
glutSwapBuffers();
}
void spinCube()
/* Idle callback, spin cube 1 degrees about selected axis */
{
theta[axis]+=1.0;
if(theta[axis]>360.0)theta[axis]-=360.0;
/*Display */
glutPostRedisplay();
}
void mouse(int btn,int state,int x,int y)
/* mouse callback, selects an axis about which to rotate */
{
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB
|GLUT_DEPTH); glutInitWindowSize(500,500);
glutCreateWindow("Rotating a Color Cube");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutIdleFunc(spinCube);
glutMouseFunc(mouse);
glEnable(GL_DEPTH_TEST); /* Enable hidden – surface—removal */
glutMainLoop();}
OUTPUT
4) Program to draw a color cube and allow the user to move the camera suitably to
experiment with perspective viewing using OpenGL functions
#include <stdlib.h>
#include <GL/glut.h>
void colorcube()
{
polygon(0,3,2,1);
polygon(2,3,7,6);
polygon(0,4,7,3);
polygon(1,2,6,5);
polygon(4,5,6,7);
polygon(0,1,5,4);
}
AIT Dept of CSE 19
void display(void)
{
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);
/* rotate cube */
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);
colorcube();
glFlush();
glutSwapBuffers();
}
{
glViewport(0, 0, w, h);
/* Use a perspective view */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
OUTPUT
Algorithm:
To perform the trivial acceptance and rejection tests, we extend the edges of the window to
divide the plane of the window into the nine regions. Each end point of the line segment is then
assigned the code of the region in which it lies.
If both codes are 0000,(bitwise OR of the codes yields 0000 ) line lies completely
inside the window: pass the endpoints to the draw routine.
If both codes have a 1 in the same bit position (bitwise AND of the codes is not
0000), the line lies outside the window. It can be trivially rejected.
3. If a line cannot be trivially accepted or rejected, at least one of the two endpoints must
lie outside the window and the line segment crosses a window edge. This line must be
clipped at the window edge before being passed to the drawing routine.
4. Examine one of the endpoints, say . Read 's 4-bit code in order:
Left-to-Right, Bottom-to-Top.
5. When a set bit (1) is found, compute the intersectionI of the corresponding window
edge with the line from to . Replace with I and repeat the algorithm.
PROGRAM
#include <stdio.h>
#include <GL/glut.h>
#define bool int
#define true 1
#define false 0
//compute outcodes
outcode0 = ComputeOutCode (x0, y0);
outcode1 = ComputeOutCode (x1, y1);
do{
if (!(outcode0 | outcode1)) //logical or is 0 Trivially accept & exit
{
accept = true;
done = true;
}
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;
}
else
{ x1 = x; y1 = y;
outcode1 = ComputeOutCode (x1, y1);
}
}
}while (!done);
if (accept)
{ // Window to viewport mappings double
sx=(xvmax-xvmin)/(xmax-xmin);
// Scale parameters
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
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex2f(xvmin, yvmin);
glVertex2f(xvmax, yvmin);
glVertex2f(xvmax, yvmax);
glVertex2f(xvmin, yvmax);
glEnd();
glColor3f(0.0,0.0,1.0);
// draw blue colored clipped line
glBegin(GL_LINES);
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;
return code;
}
void display()
{
double x0=60,y0=20,x1=80,y1=120;
glClear(GL_COLOR_BUFFER_BIT);
//draw the line with red color
glColor3f(1.0,0.0,0.0);
//bres(120,20,340,250);
glBegin(GL_LINES);
glVertex2d (x0, y0);
glVertex2d (x1, y1);
glEnd();
void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(1.0,0.0,0.0);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION
); glLoadIdentity();
gluOrtho2D(0.0,499.0,0.0,499.0);
}
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.
#include<GL/glut.h>
void obj(double tx,double ty,double tz,double sx,double sy,double sz)
{
glRotated(50,0,1,0);
glRotated(10,-1,0,0);
glRotated(11.7,0,0,-1);
glTranslated(tx,ty,tz);
glScaled(sx,sy,sz);
glutSolidCube(1);
glLoadIdentity();
}
void display()
{
glViewport(0,0,700,700);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_
BIT);
obj(0,0,0.5,1,1,0.04); // three walls
obj(0,-0.5,0,1,0.04,1);
obj(-0.5,0,0,0.04,1,1);
obj(0,-0.3,0,0.02,0.2,0.02); // four table legs
obj(0,-0.3,-0.4,0.02,0.2,0.02);
obj(0.4,-0.3,0,0.02,0.2,0.02);
obj(0.4,-0.3,-0.4,0.02,0.2,0.02);
obj(0.2,-0.18,-0.2,0.6,0.02,0.6); // table top
glRotated(50,0,1,0);
glRotated(10,-1,0,0);
glRotated(11.7,0,0,-1);
glTranslated(0.3,-0.1,-0.3);
glutSolidTeapot(0.09);
glFlush();
glLoadIdentity();
}
void main(int argc, char** argv)
{
glutInit(&argc,argv); float
ambient[]={1,1,1,1};
float light_pos[]={27,80,2,3};
glutInitWindowSize(700,700);
glutCreateWindow("scene");
glutDisplayFunc(display);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glMaterialfv(GL_FRONT,GL_AMBIENT,ambient);
glLightfv(GL_LIGHT0,GL_POSITION,light_pos);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
}
OUTPUT
#include<GL/glut.h>
#include<stdio.h>
if(m > 0) {
} else {
glBegin(GL_POLYGON);
glNormal3fv(a);
glVertex3fv(a);
glVertex3fv(b);
glVertex3fv(c);
glEnd();
}
}
}
void display(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
tetrahedron(n);
glFlush();
glutInit(&argc, argv);
glutInitWindowPosition(500, 100);
glutInitWindowSize(500, 500);
glutDisplayFunc(display);
glEnable(GL_DEPTH_TEST);
glClearColor(1, 1, 1, 1);
glutMainLoop();
}
OUTPUT
8) Develop a menu driven program to animate a flag using Bezier Curve algorithm.
#include<glut.h>
#include<stdio.h>
#include<math.h>
#define PI 3.1416
GLsizei winWidth = 600, winHeight = 600;
GLfloat xwcMin = 0.0, xwcMax = 130.0;
GLfloat ywcMin = 0.0, ywcMax = 130.0;
static int window;
static int menu_id=2;
static int submenu_id=1;
static int value = 0;
typedef struct wcPt3D
{
GLfloat x, y, z;
};
void bino(GLint n, GLint *C)
{
GLint k, j;
for (k = 0; k <= n; k++)
{
C[k] = 1;
for (j = n; j >= k + 1; j--)
C[k] *= j;
for (j = n - k; j >= 2; j--)
C[k] /= j;
}
}
void computebzPt(GLfloat u, wcPt3D *bzPt, Glint nCtrlPts, wcPt3D *ctrlPts, GLint *C)
{
GLint k, n = nCtrlPts - 1;
GLfloat bzBdFcn;
{ 30, 110, 0 },
{ 50, 90, 0 },
{ 60, 100, 0 }
};
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;
glClear(GL_COLOR_BUFFER_BI
T); glColor3f(1.0, 1.0, 1.0);
glPointSize(5);
glPushMatrix();
glLineWidth(5);
glColor3f(255 / 255, 153 / 255.0, 51 / 255.0); //Indian flag: Orange color code
void display(void)
{
glClear(GL_COLOR_BUFFER_BI
T); if (value == 1)
{
return; //glutPostRedisplay();
}
else if (value == 2)
{
glPushMatrix();
glColor3d(1.0, 0.0, 0.0);
glutDisplayFunc(displayFunc);
glutWireSphere(0.5, 50, 50);
glPopMatrix();
}
glFlush();
}
void menu(int num)
{
if (num == 0)
{
glutDestroyWindow(window);
exit(0);
}
else
{
value = num;
}
glutPostRedisplay();
}
void createMenu(void)
{
submenu_id = glutCreateMenu(menu);
glutAddMenuEntry("draw a flag", 2);
menu_id = glutCreateMenu(menu);
glutAddMenuEntry("Clear", 1);
glutAddSubMenu("Draw", submenu_id);
glutAddMenuEntry("Quit", 0);
glutAttachMenu(GLUT_RIGHT_BUTTON
);
}
void myinit()
{
glViewport(0, 0, 500, 500);
glClearColor(1.0, 1.0, 1.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION
); glLoadIdentity();
gluOrtho2D(0.0, 499.0, 0.0, 499.0);
}
OUTPUT
9) Develop a menu driven program to fill the polygon using scan line algorithm
ALGORITHM:
Step 1 − Find out the Yminand Ymax from the given polygon.
Step 2 − ScanLine intersects with each edge of the polygon from Ymin to Ymax. Name
each intersection point of the polygon. As per the figure shown above, they are named as
p0, p1, p2, p3.
Step 3 − Sort the intersectionpoint in the increasing order of X coordinatei.e.(p0, p1),
(p1,p2), and (p2, p3).
Step 4 − Fill all those pair of coordinates that are inside polygons and ignore the
alternatepairs.
#include <GL/glut.h>
#include<stdio.h>
static int window;
static int menu_id;
static int submenu_id;
static int value = 1;
float x1 = 200.0, y1_ = 200.0, x2 = 100.0, y2 = 300.0, x3 = 200.0, y3 = 400.0, x4 = 300.0, y4 =
300.0;
void draw_pixel(int x, int y)
{if(value==2){
glColor3f(0.0, 0.0, 1.0);}
else{glColor3f(1.0,1.0,1.0);}
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
glFlush();
}
void edgedetect(float x1, float y1_, float x2, float y2, int *le, int *re)
{
float mx, x, temp;
int i;
if ((y2 - y1_)<0) // y1_>y2 ie. y1_=400 ,y2=300
{
temp = y1_; y1_ = y2; y2 = temp;
temp = x1; x1 = x2; x2 = temp;
}
void scanfill(float x1, float y1_, float x2, float y2, float x3, float y3, float x4, float y4)
{
int le[500], re[500], i, y;
for (i = 0; i<500; i++)
{
le[i] = 500;
re[i] = 0;
}
OUTPUT