Vous êtes sur la page 1sur 66

QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH

DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 01
Objective:
 Installaion of Visual Studio 2010.
Steps:
1. Download the file glut-3.7.6-bin fromhere.Download the file glut-3.7.6-bin fromhere.
http://www.microsoft.com/en-pk/download/details.aspx?id=23691

We start with the familiar install startup menu:

1
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Then we get a banner page, as things start up.

2
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Next, we get a license page, as well as an overview of what is going to be installed. The key
components are:

 VC 9.0 and 10.0 runtime libraries


 .NET Framework 4 Beta 1
 Help 3.0 Beta 1
 Visual Studio Macro Tools
 Visual Studio 2010 Professional Beta 1

3
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Next up is an options page:

Now the actual installation begins and we can see a more complete list of all the components that
will be installed. For completeness, here’s the full list:

 VC 9.0 Runtime
 VC 10.0 Runtime
 Microsoft .NET Framework 4 Beta 1
 Microsoft Help 3.0 Beta 1
 Microsoft Visual Studio Macro Tools
 Microsoft Visual Studio 2010 Professional Beta 1
 Microsoft Web Deployment Tool
 Visual Studio Tools for the Office System 4.0 Runtime

4
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

 Microsoft Office Development Tools for Visual Studio 2010


 Dotfuscator Software Services – Community Edition
 Microsoft SQL Server Compact 3.5 SP1
 SQL Server Compact Tools for Visual Studio 2010 Beta 1
 Microsoft Sync Framework Runtime v1.0
 Microsoft Sync Services for ADO.NET v2.0
 Microsoft Sync Framework Services v1.0
 Microsoft Sync Framework SDK v1.0
 Microsoft SQL Publishing Wizard 1.4
 SQL Server System CLR Types
 Shared Management Objects
 Microsoft SQL Server 2008 Express Edition

Wow. This is going to take a while.

5
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

You’ll have to reboot after the .NET Framework 4 installation.

6
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

You can do your work while the remaining components install..

7
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

You’ll get a warning dialog, indicating that SQL Server 2008 has compatibility issues on
Windows 7 and suggesting that you install SP1.

8
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

I just clicked the Run Program button and proceeded with the install. A little bit later, I got a
second compatibility warning dialog, also mentioning SQL Server 2008. An external DOS
window was also spawned, running a setup.exe command.

9
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Finally, everything finishes up and we’re done!

10
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

After the install completes, we get the main auto run window again and the link for checking for
service releases is now active.

11
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

If you click the Check for Service Releases link, you’ll be redirected to an update web page,
which in turn allows firing up the Windows Update applet.

Finally, we bring up Visual Studio 2010 for the first time.

12
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

As with earlier versions, when you start Visual Studio for the first time, you’re asked to choose a
language, which dictates how the environment is set up. I’m a C# guy.

When things finally start up, we see the new Start Page for the first time.

13
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

The New Project dialog also gets a fresh look.

14
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Finally, we create an empty WPF Application.

That’s it. Click finish button. You are ready to explore the mush waited and fully loaded
visual Studio 2010.

Name: _____
Roll #: _____
Date: _____

Sig: of LAB Engineer

15
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 02
Objective:
 To draw a line using Digital Differential Analyser (DDA) algorithm.
Theory:
1. Line:
A line is produced by means of illuminating a set of intermediary pixels between the two
endpoints. We can say that a straight line segment is defined by the coordinate position for the
end points of the segment i-e Points (x1, y1) and (x2, y2).
All line drawing algorithms make use of the fundamental equations:

 Line Eqn. y = m.x + b

 Slope m = y2 − y1 / x2 − x1 = Δy / Δx

 y-intercept b = y1 − m.x1

 x-interval→Δx = Δy / ma

 y-interval→ Δy = m Δx

1.1. DDA Line Algorithm:

DDA is a line algorithm Based on calculating either Δy or Δx using the above Equations.

It uses simple division operations. It is faster than the direct use of line Equations and also
eliminates the multiplication in line Equation.

16
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

ALGORITHM:

DDA Line ( X1, Y1, XN, YN):


Description: Here X1 and Y1 denote the starting x – coordinate
and y – coordinate of the line and XN and YN denote the ending x –
coordinate and y – coordinate.

1. Set M = (YN – Y1) / (XN – X1) [Calculate slope of line]


2. Repeat For I = X1 to XN
3. If (M <= 1) Then
4. Set DX = 1
5. Set DY = M * DX
6. Else
7. Set DY = 1
8. Set DX = DY / M
[End of If]
9. Set X1 = X1 + DX
10. Set Y1 = Y1 + DY
11. Call PutPixel(X1, Y1)
[End of For]
12. Exit

17
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

PROGRAM:

/**** Program to Draw a Line using DDA Algorithm ****/


#include <stdio.h>
#include <dos.h>
#include "graphics.h"
void lineDDA(int, int, int, int);
void main()
{
int x1, y1, xn, yn;
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
printf("Enter the starting coordinates of line: ");
scanf("%d %d", &x1, &y1);
printf("Enter the ending coordinates of line: ");
scanf("%d %d", &xn, &yn);
lineDDA(x1, y1, xn, yn);
getch();
}
void lineDDA(int x1, int y1, int xn, int yn)
{
int dx, dy, m, i;
m = (yn-y1)/(xn-x1);
for (i=x1; i<=xn; i++)
{
if (m <= 1)
{
dx = 1;
dy = m * dx;
}
else
{
dy = 1;
dx = dy / m;
}
x1 = x1 + dx;
y1 = y1 + dy;
putpixel(x1, y1, RED);
delay(20);
}
}

18
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

OUTPUT:

Name: _____
Roll #: _____
Date: _____
Sig: of LAB Engineer

19
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 03
Objective:
 To draw a line using Bresenham’s Algorithm.
Theory:
Bresenham’s Line Algorithm:
It is an efficient raster line generation algorithm. It can be adapted to display circles

and other curves. It uses simple addition and subtraction operations and is faster than the DDA
line algorithm. DDA line algorithm draw lines with no accuracy as compared to Bresenham’s line
algorithm so it is more sufficient and much simpler than the DDA as it doesn’t use division or
multiplication operations.

In Bresenham’s Algorithm, after plotting a pixel position (xk, yk) we have two choices for
next pixel:
 (xk +1, yk)

 (xk +1, yk+1)

For this assistance we calculate a decision parameter to calculate which pixel is next closer to
line.
 So initial decision parameter p0 can be evaluated as:

 p0 = 2Δy − Δx

 If pk < 0,the next point to plot is (xk +1, yk) and

 pk+1 = pk + 2Δy

 Otherwise, the next point to plot is (xk +1, yk +1) and

 pk+1 = pk + 2Δy −2Δx

20
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

ALGORITHM:

Bresenham’s Line ( X1, Y1, XN, YN):


Description: Here X1 and Y1 denote the starting x – coordinate
and y – coordinate of the line and XN and YN denote the ending x –
coordinate and y – coordinate.
1. Set DX = XN – X1 and DY = YN – Y1
2. Set Di = 2DY - DX
3. Set DS = 2DY and DT = 2(DY – DX)
4. Call PutPixel(X1, Y1)
5. Repeat While (X1 < XN)
6. Set X1 = X1 + 1
7. If (Di < 0) Then
8. Set Di = Di + DS
9. Else
10. Set Y1 = Y1 + 1
11. Set Di = Di + DT
[End of If]
12. Call PutPixel(X1, Y1)
[End of While]
13. Exit

21
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

PROGRAM:

/*** Program to Draw a Line using Bresenham's Algorithm ***/


#include <stdio.h>
#include <dos.h>
#include “graphics.h”
void lineBres(int, int, int, int);
void main()
{
int x1, y1, xn, yn;
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
printf("Enter starting coordinates of line: ");
scanf("%d %d", &x1, &y1);
printf("Enter ending coordinates of line: ");
scanf("%d %d", &xn, &yn);
lineBres(x1, y1, xn, yn);
getch();
}
void lineBres(int x1, int y1, int xn, int yn)
{
int dx = xn - x1, dy = yn - y1;
int di = 2 * dy - dx;
int ds = 2 * dy, dt = 2 * (dy - dx);
putpixel(x1, y1, RED);
while (x1 < xn)
{
x1++;
if (di < 0)
di = di + ds;
else
{
y1++;
di = di + dt;
}
putpixel(x1, y1, WHITE);
delay(100);}}

22
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

OUTPUT:

REVIEW QUESTIONS:
1. What is difference between DDA and Bresenham’s Line algorithm?
_____ _____ _____
_____ _____ _____
_____ _____ _____
_____ _____ _________________

2. Why Bresenham’s algorithm is efficient than DDA?


_____ _____ _____
_____ _____ _____
___________________________________________________

Name: _____
Roll #: _____
Date: _____ Sig: of LAB Engineer

23
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 04
Objective:
 To draw a circle using Mid point Algorithm.
Theory:
Circle:
A circle is defined as the set of points that are all at a given distance r from a center point

(xc, yc). For any circle point (x, y), this distance is expressed by the Equation;

(x − xc)2 + (y − yc)2 = r 2

Midpoint Circle Algorithm:

The midpoint method calculates pixel positions along the circumference of a circle using integer
additions and subtractions, assuming that the circle parameters are specified in screen coordinate.
We can summarize the steps in the midpoint circle algorithm as follows.

24
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

ALGORITHM:
Mid-Point Circle (Xc, Yc, R):
Description: Here Xc and Yc denote the x – coordinate and y – coordinate of the center of the
circle. R is the radius.

1. Set X = 0 and Y = R
2. Set P = 1 – R
3. Repeat While (X < Y)
4. Call Draw Circle(Xc, Yc, X, Y)
5. Set X = X + 1
6. If (P < 0) Then
7. P = P + 2X + 6
8. Else
9. Set Y = Y – 1
10. P = P + 2(X – Y) + 1
[End of If]
11. Call Draw Circle(Xc, Yc, X, Y)
[End of While]
12. Exit

Draw Circle (Xc, Yc, X, Y):


1. Call PutPixel(Xc + X, Yc, + Y)
2. Call PutPixel(Xc - X, Yc, + Y)
3. Call PutPixel(Xc + X, Yc, - Y)
4. Call PutPixel(Xc - X, Yc, - Y)
5. Call PutPixel(Xc + Y, Yc, + X)
6. Call PutPixel(Xc - Y, Yc, + X)
7. Call PutPixel(Xc + Y, Yc, - X)
8. Call PutPixel(Xc - Y, Yc, - X)
9. Exit

25
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

PROGRAM:

#include <stdio.h>
#include <dos.h>
#include “graphics.h”
void circleMidpoint(int, int, int);
void drawCircle(int, int, int, int);
void main()
{
int xc, yc, r;
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
printf("Enter center coordinates of circle: ");
scanf("%d %d", &xc, &yc);
printf("Enter radius of circle: ");
scanf("%d", &r);
circleMidpoint(xc, yc, r);
getch();
}
void circleMidpoint(int xc, int yc, int r)
{
int x = 0, y = r;
int di = 1 - r;
while (x < y)
{
drawCircle(xc, yc, x, y);
x++;
if (di < 0)
di = di + 2 * x + 1;
else
{
y--;
di = di + 2 * (x - y) + 1;
}
drawCircle(xc, yc, x, y);
delay(100);
}
}
void drawCircle(int xc, int yc, int x, int y)
{
putpixel(xc+x, yc+y, WHITE);
putpixel(xc-x, yc+y, WHITE);
putpixel(xc+x, yc-y, WHITE);
putpixel(xc-x, yc-y, WHITE);
putpixel(xc+y, yc+x, WHITE);
putpixel(xc-y, yc+x, WHITE);
putpixel(xc+y, yc-x, WHITE);
putpixel(xc-y, yc-x, WHITE);
}

26
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

OUTPUT:

Name: _____
Roll #: _____
Date: _____
Sig: of LAB Engineer

27
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 05
Objective:
 To draw an Ellipse using Mid point Algorithm.
Theory:
Ellipse:
An Ellipse is the locus of points the sum of whose distance to the two given points is
constant. An Ellipse is a planar curve which in some Cartesian system of coordinates and
the equation for the ellipse shown in Fig. can be written in terms of the ellipse center
coordinates and parameters rx and ry as:

28
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Midpoint Ellipse Algorithm:

The midpoint ellipse method is applied throughout the first quadrant in two parts.

Figure 3-25 shows the division of the first quadrant according to the slope of an ellipse with rx <
ry.

 Regions 1 and 2 (Fig. 3-25) can be processed in various ways.

 We can start at position (0, ry) and step clockwise along the elliptical path in the
first quadrant, shifting from unit steps in x to unit steps in y when the slope
becomes less than −1.0.

 Alternatively, we could start at (rx, 0) and select points in a counterclockwise


order, shifting from unit steps in y to unit steps in x when the slope becomes
greater than −1.0.

29
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

ALGORITHM:

30
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

PROGRAM:

#include <stdio.h>
#include <conio.h>
#include <dos.h>
#include "graphics.h"
void ellipse(int, int, int, int);
void drawellipse(int, int, int, int);
void main ()
{
int gd=DETECT, gm;
initgraph(&gd, &gm, "");
int xc,yc,rx,ry;
printf("enter xc=");
scanf("%d", &xc);
printf("enter the value of yc=");
scanf("%d", &yc);
printf("enter the value of rx=");
scanf("%d", &rx);
printf("enter the value of ry=");
scanf("%d", &ry);
ellipse(xc, yc, rx, ry);
getch();
}
void ellipse(int xc,int yc,int rx,int ry)
{
int x=0, y=ry; //region1
int p=(ry*ry)-(rx*rx*ry)+((rx*rx)/4);
while((2*ry*ry*x)<(2*rx*rx*y))
{
drawellipse(xc, yc, x, y);
x++;
if(p<0)
p=p+(2*ry*ry*x)+(ry*ry);
else
{
y--;
p=p+(2*ry*ry*x)-(2*ry*ry*y)+(ry*ry);
}
drawellipse(xc, yc, x, y);
delay(50);
}

31
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

//region 2
p=(ry*ry*(x+(1/2))*(x+(1/2)))+(rx*rx*(y-1)*(y-1))-(rx*rx*ry*ry);
while(y>0)
{
drawellipse(xc, yc, x, y);
y--;
if(p<0)
{
x++;
p=p+(2*ry*ry*x)-(2*rx*rx*y)+(rx*rx);
}
else
{
p=p-(2*rx*rx*y)+(rx*rx);
}
drawellipse(xc,yc,x,y);
delay(50);
}
}
void drawellipse(int xc, int yc, int x, int y)
{
putpixel(xc+x, yc+y, WHITE);
putpixel(xc-x, yc+y, WHITE);
putpixel(xc+x, yc-y, WHITE);
putpixel(xc-x, yc-y, WHITE);
}

OUTPUT:

32
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 06

Objective:
 Introduction to OpenGL and Setting up OpenGL.

I. Setting up
Steps:
1. Download the file glut-3.7.6-bin from here.
http://dl.dropbox.com/u/3563445/lec/OPENGL/glut-3.7.6-bin.rar
2. Extract the downloaded file glut-3.7.6-bin to the folder X:\path\glut-3.7.6-
bin
3. Open the folder glut-3.7.6-bin where files are located. In the folder you will see 3
subfolders, namely dll, include, and library.

4. Now, Open the VC directory, which by default is located here:


“C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC” (for Visual Studio 2008)
“C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC” (for Visual Studio 2010)
“C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC” (for Visual Studio 2012)
5. Now copy all files from
glut-3.7.6-bin\include →VC\include
glut-3.7.6-bin\library →VC\lib
glut-3.7.6-bin\dll
→C:\Windows\System32 (or C:\Windows\System for XP)
Done!

33
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Note: For Windows 7, 8 Professional 64 bits, we need the additional step as follows.
Now copy all files from glut-3.7.6-bin\dll →C:\Windows\SysWOW64.

II. Checking
1. Create an empty C++ Console Application Project.
File New, Project, and selectWin32 Console Application
Name: enter a project name (e.g., ex1) Location: select a location to store the project.
(e.g., C:\Users\username\Documents\Visual Studio 2010\Projects\icg5)

For Microsoft Visual Studio 2010 Express Edition, you will see the following screen.

34
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

For Microsoft Visual Studio 2010 Professional, you will see the following screen.

Click OK, click Next…

35
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Click Finish.
2. Copy and paste the following code to the opening screen (i.e., ex1.cpp) and run it (F5).

#include"stdafx.h"
#include<glut.h>
void Draw(void);
int main(int argc, char* argv[])
{
glutCreateWindow("OpenGL glut configuration is done!");
glutDisplayFunc(Draw);
glutMainLoop();
return 0;
}
Void Draw(void)
{
// Origin (0, 0) located at centre of display window
glBegin(GL_LINES);
// draw a horizontal line (i.e., x-axis)
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.75, 0.0, 0.0);
// draw a vertical line (i.e., y-axis)
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.75, 0.0);
glEnd();
glFlush();
}

36
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

OUTPUT:

Review Question/Assignment
Write a program that will display first character of your name.

(Note: Use Simple GLUT_LINES functions to draw first character of your name, give your
answer with output).

Remarks:
Add extra sheet if necessary.

Name: _____
Roll #: _____
Date: _____

Sig: of LAB Engineer

37
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 07
Objective:
 To draw various lines with different width and stippled(dotted, dashed) lines.

Theory:

Line Details:
With OpenGL, you can specify lines with different widths and lines that are
stippled in various ways—dotted, dashed, drawn with alternating dots and dashes, and
so on.

 glBegin(GL_LINES);

 glEnd();

Wide Lines:
Void glLineWidth(GLfloat width); Sets the width, in pixels, for rendered lines;
Width must be greater than 0.0 and by default is 1.0.
The actual rendering of lines is affected if either anti aliasing or multisampling is
enabled. Without antialiasing, widths of 1, 2, and 3 draw lines 1, 2, and 3 pixels wide.
With antialiasing enabled, non integer line widths are possible, and pixels on the
boundaries are typically drawn at less than full intensity.

 glLineWidth(GLfloat Width);

Stippled Lines:
To make stippled (dotted or dashed) lines, you use the command
glLineStipple() to define the stipple pattern, and then you enable line stippling with
glEnable().
Syntax:

 glLineStipple(GLint factor, GLushort pattern);

Example:

 glEnable(GL_LINE_STIPPLE);

 glLineStipple(1, 0x3F07);
With the preceding example and the pattern 0x3F07 (which translates to
0011111100000111 in binary), a line would be drawn with 3 pixels on, then 5 off, 6
on, and 2 off. If factor had been 2, the pattern would have been elongated: 6 pixels
on, 10 off, 12 on, and 4 off.

38
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

PROGRAM:

#include "stdafx.h"
#include <glut.h>
#define drawOneLine(x1,y1,x2,y2)\
glBegin(GL_LINES); glVertex2f((x1),(y1));glVertex2f((x2),(y2));glEnd();
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
}
void display(void)
{
int i;
glClear(GL_COLOR_BUFFER_BIT);
/* select white for all lines */
glColor3f(1.0, 1.0, 1.0);
/* in 1st row, 3 lines, each with a different stipple */
glEnable(GL_LINE_STIPPLE);
glLineStipple(1, 0x0101); /* dotted */
drawOneLine(50.0, 125.0, 150.0, 125.0);
glLineStipple(1, 0x00FF); /* dashed */
drawOneLine(150.0, 125.0, 250.0, 125.0);
glLineStipple(1, 0x1C47); /* dash/dot/dash */
drawOneLine(250.0, 125.0, 350.0, 125.0);
/* in 2nd row, 3 wide lines, each with different stipple */
glLineWidth(5.0);
glLineStipple(1, 0x0101); /* dotted */
drawOneLine(50.0, 100.0, 150.0, 100.0);
glLineStipple(1, 0x00FF); /* dashed */
drawOneLine(150.0, 100.0, 250.0, 100.0);
glLineStipple(1, 0x1C47); /* dash/dot/dash */
drawOneLine(250.0, 100.0, 350.0, 100.0);
glLineWidth(1.0);
/* in 3rd row, 6 lines, with dash/dot/dash stipple */
/* as part of a single connected line strip */
glLineStipple(1, 0x1C47); /* dash/dot/dash */
glBegin(GL_LINE_STRIP);
for (i = 0; i < 7; i++)
glVertex2f(50.0 + ((GLfloat) i * 50.0), 75.0);
glEnd();
/* in 4th row, 6 independent lines with same stipple */
for (i = 0; i < 6; i++) {
drawOneLine(50.0 + ((GLfloat) i * 50.0), 50.0,
50.0 + ((GLfloat)(i+1) * 50.0), 50.0);
}
/* in 5th row, 1 line, with dash/dot/dash stipple */
/* and a stipple repeat factor of 5 */
glLineStipple(5, 0x1C47); /* dash/dot/dash */
drawOneLine(50.0, 25.0, 350.0, 25.0);
glDisable(GL_LINE_STIPPLE);
glFlush();
}

39
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

void reshape(int w, int h)


{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble) w, 0.0, (GLdouble) h);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(400, 150);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}

OUTPUT:

Name: _____
Roll #: _____
Date: _____
Sig: of LAB Engineer

40
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 08
Objective:
 Two Dimensional Transformation
 Translation
 Scaling, &
 Rotation.
Theory:
2D Transformations:
Transformations are a fundamental part of computer graphics. Transformations are used to
position objects, to shape objects, to change viewing positions, and even to change how
something is viewed.
One of the most common and important tasks in computer graphics is to transform the coordinates
(position, orientation, and size) of either objects within the graphical scene or the camera that is
viewing the scene. It is also frequently necessary to transform coordinates from one coordinate
system to another, (e.g. world coordinates to viewpoint coordinates to screen coordinates).

1. Translation:
Syntax:
void glTranslatef (TYPEx, TYPEy, TYPEz);

Translation in OpenGL is done with glTranslatef (dx, dy, dz) where the parameters specify the
amount of displacement in the x, y, and z directions. By setting the third parameter, dz, to 0, we
get a 2D translation. The parameters are of type float, as indicated by the "f" at the end of
"translatef". If you want to use parameters of type double, you can use gl.translated. The names
for the other transform methods work in the same way.

Translation is movement along any of the three axis in a 3D scene, for example, moving
something the left is a translation on the X axis if you are looking straight on. In OpenGL, the
length of translation is called units, and a unit has no definitive length.

If point (x, y) is to be translated by amount tx and ty to a new location (x',y')


x'  x  t x y '  y  t y

 x'  x t x 
P'    P  T  
 y '  y t y 

P'  P  T

41
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Fig.(a). Translating an Object


PROGRAM:

//Program to translate an Object


#include "stdafx.h"
#include <glut.h>
void draw(void);
void display(void);
void draw(void)
{
glBegin(GL_LINE_LOOP);
glVertex3f(0.2, 0.0,0.0);
glVertex3f(0.5, 0.0,0.0);
glVertex3f(0.5,0.8,0.0);
glEnd();
glFlush();
}
void display()
{
glColor3f(1.0,0.0,0.0);
draw();
glTranslatef(0.25,0.1,0.0);
draw();
glFlush();
}

int main(int argc, _TCHAR* argv[])


{
glutCreateWindow("Open Gl");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
OUTPUT:

42
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

2. Scaling:
Syntax:
glScalef(TYPE x, TYPE y, TYPE z);

Scaling can be done with glScalef (sx, sy, sz), where the parameters specify the scaling factor in
the x, y, and z directions. To avoid changing the scale in the z direction, the third parameter, sz,
should be 1.
glScale*() is the only one of the three modeling transformations that changes the apparent size of
an object: Scaling with values greater than 1.0 stretches an object, and using values less than 1.0
shrinks it. Scaling with a 1.0 value reflects an object across an axis.

Figure(b) shows the effect of glScalef(2.0, -0.5, 1.0)

Fig.(b). Scaling an Object

43
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

PROGRAM:

//Program to Scale an Object


#include "stdafx.h"
#include <glut.h>
void draw(void);
void display(void);
void draw(void)
{
glBegin(GL_LINE_LOOP);
glVertex3f(0.2, 0.0,0.0);
glVertex3f(0.5, 0.0,0.0);
glVertex3f(0.5,0.8,0.0);
glEnd();
glFlush();
}
void display()
{
glColor3f(1.0,0.0,0.0);
draw();
//Scaling an object
glScalef(0.4,0.6,0.0);
draw();
glFlush();
}

int main(int argc, _TCHAR* argv[])


{
glutCreateWindow("Open Gl");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

44
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

OUTPUT:

3. Rotation:
Syntax:
glRotatef (GLfloat angle, TYPE x, TYPE y, TYPE z);
In two dimensions, rotation is rotation about a point, and by default, the rotation is about the
origin, (0, 0).Rotating an object follows as similar scheme. We want a matrix R that when applied
to all vertices v in an object will rotate it. The following example, shown in Fig(c) rotates 50
degrees counter clockwise around the z-axis.

Fig(c). Rotating an object 50 degrees in the xy-plane.

45
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

PROGRAM:

//Program to Scale an Object


#include "stdafx.h"
#include <glut.h>
void draw(void);
void display(void);
void draw(void)
{
glBegin(GL_LINE_LOOP);
glVertex3f(0.2, 0.0,0.0);
glVertex3f(0.5, 0.0,0.0);
glVertex3f(0.5,0.8,0.0);
glEnd();
glFlush();
}
void display()
{
glColor3f(1.0,0.0,0.0);
draw();
//Rotating an object 60 degrees in xy-plane
glRotatef(60,0.2,0.1,0.1);
draw();
glFlush();
}

int main(int argc, _TCHAR* argv[])


{
glutCreateWindow("Open Gl");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

46
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

OUTPUT:

Review Questions:
Write a program to Translate, Scale and Rotate (120 degree) a Triangle, Quadrilateral
and Polygon.

(Note: Use GL_TRIANGLE, GL_QUADS and GL_POLYGON functions).

Remarks:
Use extra sheet if necessary.

Name: _____
Roll #: _____
Date: _____

Sig: of LAB Engineer

47
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 09
Objective:
 Three Dimensional Transformation
 Translation, Scaling, & Rotation.
 To be familiar with following Functions:
 glPushMatrix(),glPopMatrix(), glutWireSphere(), glViewPort(), gluLookAt().
 Write a Program to Build a Solar System.

3D-Transformation:
1. Translation:
Translation is defined as moving the object from one position to another position along
straight line path. We can move the objects based on translation distances along x and y
axis. tx denotes translation distance along x-axis and ty denotes translation distance
along y axis.
Translation Distance: It is nothing but by how much units we should shift the object
from one location to another along x, y-axis. Consider (x, y) are old coordinates of a point.
Then the new coordinates of that same point (X’, Y’) can be obtained as follows:

X’=x+tx
Y’=y+ty
Z’=z+tz

We denote translation transformation as P’. We can write the above equations in matrix
form as follows:

 x' 1 0 0 tx   x
 y ' 0 1 0 t y   y 
  
 z '  0 0 1 tz   z 
     
 1  0 0 0 1  1 

P'  T  P

48
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

2. Scaling: scaling refers to changing the size of the object either by increasing or decreasing.
We will increase or decrease the size of the object based on scaling factors along x and y -
axis. If (x, y) are old coordinates of object, then new coordinates of object after applying
scaling transformation are obtained as:

X’=x*sx
Y’=y*sy.
Z’=z*sz.

sx ,sy and sz are scaling factors along x-axis, y-axis and z-axis. We can write the above
equations in matrix form as follows:

 x'  s x 0 0 0  x 
 y '  0 sy 0 0  y 
  
 z'  0 0 sz 0  z  P'  S  P
     
1  0 0 0 1  1 

3. Rotation: A rotation repositions all points in an object along a circular path in the plane
centered at the pivot point. We rotate an object by an angle theta. The Transformation
matrices for above 3D transformations are given below:

 x' cos  sin  0 0  x 


x '  x cos  y sin   y '  sin 
  cos 0 0  y 
y '  x sin   y cos 
 z'  0 0 1 0  z 
z'  z      
1  0 0 0 1  1 

Some Basic Functions:


1. glPushMatrix() & glPopMatrix():
Since the transformations are stored as matrices, a matrix stack provides an ideal mechanism for
doing this sort of successive remembering, translating, and throwing away. You can control
which matrix is on top with the commands that perform stack operations: glPushMatrix(), which

49
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

copies the current matrix and adds the copy to the top of the stack, and glPopMatrix(), which
discards the top matrix on the stack, as shown in Figure.

Fig. Pushing & Popping the Matrix.


Syntax:
void glPushMatrix(void);
Pushes all matrices in the current stack down one level. The current stack is determined by
glMatrixMode(). The topmost matrix is copied, so its contents are duplicated in both the top and
second-from-the-top matrix. If too many matrices are pushed, an error is generated.
Syntax:
void glPopMatrix(void);
Pops the top matrix off the stack. What was the second-from-the-top matrix becomes the top
matrix. The current stack is determined by glMatrixMode(). The contents of the topmost matrix
are destroyed. If the stack contains a single matrix, calling glPopMatrix() generates an error.

2. Defining the Viewport


The window manager, not OpenGL, is responsible for opening a window on the screen.
However, by default the viewport is set to the entire pixel rectangle of the window that's opened.
You use the glViewport() command to choose a smaller drawing region; for example, you can
subdivide the window to create a split-screen effect for multiple views in the same window.
Syntax:
void glViewport(GLint x, GLint y, GLsizei width, GLsizei height);
Defines a pixel rectangle in the window into which the final image is mapped. The (x, y)
parameter specifies the lower left corner of the viewport, and width and height are the size of the

50
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

viewport rectangle. By default, the initial viewport values are (0, 0, winWidth, winHeight), where
winWidth and winHeight are the size of the window.

Fig. How the viewport is defined.

3. Controlling the camera


Let’s look again at the OpenGL viewing pipeline, in Figure below.

Fig. The OpenGL camera.

We set the position and orientation of the OpenGL camera, as shown in Figure, using
gluLookAt().

51
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Syntax:
void gluLookAt( GLdouble eyex, GLdouble eyey, GLdouble eyez, GLdouble centerx,
GLdouble centery, GLdouble centerz, Ldouble upx, GLdouble upy, GLdouble upz );
The position of the camera in space – sometimes also called the eyepoint – is given by (eyex,
eyey, eyez). (centerx, centery, centerz) specifies a look point for the camera to “look at”, and a
good choice for this would a point of interest in the scene, and often the center of the scene is
used. Together, the points (eyex, eyey, eyez) and (centerx, centery,centerz) define a view
vector. The last set of gluLookAt()’s arguments specify the up vector of the camera. This
defines the camera’s orientation at the eyepoint.
4. Sphere:
Syntax
Void glutWireSphere( GLdoubleradius, GLintslices, GLintstacks);
glutWireSphere() draws a sphere, of radius radius, centred on (0,0,0) in object coordinates.
Slices is the number of subdivisions around the Zaxis (like lines of longitude); stacks is the
number of subdivisions along the Zaxis (like lines of latitude). Solid version: glutSolidSphere().

Fig. WireSphere Fig. SolidSphere

52
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

PROGRAM:
// planetsystem.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <glut.h>
static int year = 0, day = 0;
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
//glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glColor3f(1.0, 1.0, 0.0);
glutSolidSphere(1.0, 20, 16); /* draw sun */
glRotatef((GLfloat) year, 0.0, 1.0, 0.0);
glTranslatef(2.0, 0.0, 0.0);
glRotatef((GLfloat) day, 0.0, 1.0, 0.0);
glColor3f(0.0, 1.0, 1.0);
glutWireSphere(0.3, 10, 8); /* draw smaller planet */
glPopMatrix();
glutSwapBuffers();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case 'd':
day = (day + 10) % 360;
glutPostRedisplay();
break;
case 'D':
day = (day - 10) % 360;
glutPostRedisplay();
break;
case 'y':
year = (year + 5) % 360;
glutPostRedisplay();
break;

53
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

case 'Y':
year = (year - 5) % 360;
glutPostRedisplay();
break;
default:
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}

OUTPUT:

54
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 10
Objective:
 Animation using OpenGL.

Theory:
Animation:
One of the most exciting things you can do on a graphics computer is draw pictures that
move. Whether you’re an engineer trying to see all sides of a mechanical part you’re
designing, a pilot learning to fly an airplane using a simulation, or merely a computer-game
aficionado, it’s clear that animation is an important part of computer graphics. In a movie
theater, motion is achieved by taking a sequence of pictures and projecting them at 24 per second
on the screen. Each frame is moved into position behind the lens, the shutter is opened,
and the frame is displayed. The shutter is momentarily closed while the film is advanced
to the next frame, then that frame is displayed, and so on. Although you’re watching 24
different frames each second, your brain blends them all into a smooth animation.

Program:

// Animation.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <glut.h>
static GLfloat spin = 0.0;
void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glRotatef(spin, 0.0, 0.0, 1.0);
glColor3f(1.0, 1.0, 0.0);
glRectf(-25.0, -25.0, 25.0, 25.0);
glPopMatrix();
glutSwapBuffers();
}

55
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

void spinDisplay(void)
{
spin = spin + 2.0;
if (spin > 360.0)
spin = spin - 360.0;
glutPostRedisplay();
}
void reshape(int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void mouse(int button, int state, int x, int y)
{
switch (button)
{
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(spinDisplay);
break;
case GLUT_RIGHT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(NULL);
break;
default:
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize (250, 250);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}

56
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Output:

Name: _____
Roll #: _____
Date: _____ Sig: of LAB Engineer

57
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 11
Objective:
 Basic Lighting Effects in OpenGL.

Theory:
OpenGL Lighting:
In this lab, we use OpenGL to demonstrate the local illumination model that we covered in our
previous lab about 3D rendering. Here we explain the ambient, diffuse, and specular components
of the lighting model and the type of effects that each represents.

In OpenGL, we set lighting and material properties in order to illuminate polygonal surfaces. To
calculate the lighting at a vertex, we need the position that we view from, the normal vector, an
active light source, lighting properties, material properties, and to have lighting enabled. To
simply the settings, we use a single square as our polygonal surface for this lesson. The square is
actually a grid of squares to reflect light more accurately; the reasoning become more apparent
when we cover shading.

58
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Although OpenGL allows for multiple light sources, we use a single light source for simplicity
(GL_LIGHT0). The ambient component is set to .2, which correspond to a dimly light
environment. The diffuse component is .8—typically ambient and diffuse components sum to 1,
unless a dimmer environment is required. If the ambient and diffuse components sum to more
than 1, then saturation will occur and give an unrealistic appearance. The specular component is
set to 1. These components have separate red, green, and blue color channels. However, it is
usually best to leave them all equal as this represents white light, which is what most light sources
are. The ambient, diffuse, and specular components are set via calls to glLight(), as is the light’s
position.

In addition to lighting properties, each polygon has


material properties which are set via calls to
glMaterial(). These properties are the amount and type
of ambient, diffuse, and specular light that the surface
reflects. The ambient and diffuse properties model the
color of the surface, while the specular property will
usually reflect white light. Also, the size of specular
highlights, or shininess, is set this way. Fortunately,
these values only need to be set when the surface type
changes. So, we only set them once in this lab.

59
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Before any lighting takes place, the lighting model needs to be enabled via a call to glEnable()
with the parameter GL_LIGHTING. Lights must also be enabled with glEnable(), and we use this
to enable GL_LIGHT0: the first light. We set the lighting model to use a local viewer via a call to
glLightModel().

Program:

#include "stdafx.h"
#include <glut.h>
void Draw() {
glClear(GL_COLOR_BUFFER_BIT);

// Set material properties


GLfloat qaBlack[] = {0.0, 0.0, 0.0, 1.0};
GLfloat qaGreen[] = {0.0, 1.0, 0.0, 1.0};
GLfloat qaWhite[] = {1.0, 1.0, 1.0, 1.0};
glMaterialfv(GL_FRONT, GL_AMBIENT, qaGreen);
glMaterialfv(GL_FRONT, GL_DIFFUSE, qaGreen);
glMaterialfv(GL_FRONT, GL_SPECULAR, qaWhite);
glMaterialf(GL_FRONT, GL_SHININESS, 60.0);

// Draw square with many little squares


glBegin(GL_QUADS);
glNormal3f(0.0, 0.0, 1.0);
const GLfloat kqDelta = .01;
for (int i = -90; i < 90; ++i) {
for (int j = -90; j < 90; ++j) {
glVertex3f(j*kqDelta, i*kqDelta, -.2);
glVertex3f((j+1)*kqDelta, i*kqDelta, -.2);
glVertex3f((j+1)*kqDelta, (i+1)*kqDelta, -.2);
glVertex3f(j*kqDelta, (i+1)*kqDelta, -.2);
}
}
glEnd();

glFlush();
}
void Initialize() {
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

// Lighting set up
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

// Set lighting intensity and color


GLfloat qaAmbientLight[] = {0.2, 0.2, 0.2, 1.0};
GLfloat qaDiffuseLight[] = {0.8, 0.8, 0.8, 1.0};
GLfloat qaSpecularLight[] = {1.0, 1.0, 1.0, 1.0};
glLightfv(GL_LIGHT0, GL_AMBIENT, qaAmbientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, qaDiffuseLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, qaSpecularLight);

60
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

// Set the light position


GLfloat qaLightPosition[] = {.5, .5, 0.0, 1.0};
glLightfv(GL_LIGHT0, GL_POSITION, qaLightPosition);
}

int main(int iArgc, char** cppArgv) {


glutInit(&iArgc, cppArgv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(250, 250);
glutInitWindowPosition(200, 200);
glutCreateWindow("Lab 11: Lighting");
Initialize();
glutDisplayFunc(Draw);
glutMainLoop();
return 0;
}

Output:

Conclusion:
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Name: _____
Roll #: _____
Date: _____
Sig: of LAB Engineer

61
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Practical # 12
Objective:
 Rendering an object with lighting effects.

Theory:
OpenGL Lighting:
When you look at a physical surface, your eye's perception of the color depends on the
distribution of photon energies that arrive and trigger your cone cells. Those photons come from a
light source or combination of sources, some of which are absorbed and some of which are
reflected by the surface. In addition, different surfaces may have very different properties - some
are shiny and preferentially reflect light in certain directions, while others scatter incoming light
equally in all directions. Most surfaces are somewhere in between.

OpenGL approximates light and lighting as if light can be broken into red, green, and blue
components. Thus, the color of light sources is characterized by the amount of red, green, and
blue light they emit, and the material of surfaces is characterized by the percentage of the
incoming red, green, and blue components that is reflected in various directions.

In the OpenGL lighting model, the light in a scene comes from several light sources that can be
individually turned on and off. Some light comes from a particular direction or position, and some
light is generally scattered about the scene.

The OpenGL lighting model considers the lighting to be divided into four independent
components: emissive, ambient, diffuse, and specular. All four components are computed
independently and then added together.

Ambient, Diffuse, and Specular Light:


Ambient illumination is light that's been scattered so much by the environment that its direction is
impossible to determine - it seems to come from all directions. Backlighting in a room has a large
ambient component, since most of the light that reaches your eye has first bounced off many
surfaces. A spotlight outdoors has a tiny ambient component; most of the light travels in the same
direction, and since you're outdoors, very little of the light reaches your eye after bouncing off
other objects. When ambient light strikes a surface, it's scattered equally in all directions.

The diffuse component is the light that comes from one direction, so it's brighter if it comes
squarely down on a surface than if it barely glances off the surface. Once it hits a surface,
however, it's scattered equally in all directions, so it appears equally bright, no matter where the
eye is located. Any light coming from a particular position or direction probably has a diffuse
component.

62
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Finally, specular light comes from a particular direction, and it tends to bounce off the surface in
a preferred direction. A well-collimated laser beam bouncing off a high-quality mirror produces
almost 100 percent specular reflection. Shiny metal or plastic has a high specular component, and
chalk or carpet has almost none. You can think of specularity as shininess.

Although a light source delivers a single distribution of frequencies, the ambient, diffuse, and
specular components might be different. For example, if you have a white light in a room with red
walls, the scattered light tends to be red, although the light directly striking objects is white.
OpenGL allows you to set the red, green, and blue values for each component of light
independently.

Defining Material Properties:


Syntax:
void glMaterial{if}v(GLenum face, GLenum pname, TYPE * param);

Specifies a current material property for use in lighting calculations. face can be GL_FRONT,
GL_BACK, or GL_FRONT_AND_BACK to indicate which face of the object the material
should be applied to. The particular material property being set is identified by pname and the
desired values for that property are given by param, which is either a pointer to a group of values
(if the vector version is used) or the actual value (if the non vector version is used). The non
vector version works only for setting GL_SHININESS. The possible values for pname are shown
in Table. Note that GL_AMBIENT_AND_DIFFUSE allows you to set both the ambient and
diffuse material colors simultaneously to the same RGBA value.

Table: Default Values for pname Parameter of glMaterial*()


Parameter Name Default Value Meaning
GL_AMBIENT (0.2, 0.2, 0.2, 1.0) ambient color of material
GL_DIFFUSE (0.8, 0.8, 0.8, 1.0) diffuse color of material
GL_AMBIENT_AND_DIFFUSE ambient and diffuse color of
material
GL_SPECULAR (0.0, 0.0, 0.0, 1.0) specular color of material
GL_SHININESS 0.0 specular exponent
GL_EMISSION (0.0, 0.0, 0.0, 1.0) emissive color of material
GL_COLOR_INDEXES (0,1,1) ambient, diffuse, and
specular color indices

Note that most of the material properties set with glMaterial*() are (R, G, B, A) colors. regardless
of what alpha values are supplied for other parameters, the alpha value at any particular vertex is
the diffuse-material alpha value.

63
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Program:
// lighting Effect.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <glut.h>
#include <gl.h>
#include <glu.h>

GLfloat diffuseMaterial[4] = { 0.5, 0.5, 0.5, 1.0 };

void init(void)
{
GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseMaterial);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialf(GL_FRONT, GL_SHININESS, 25.0);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

glColorMaterial(GL_FRONT, GL_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
}

void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glutSolidSphere(1.0, 20, 16);
glFlush ();
}

void reshape (int w, int h)


{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho (-1.5, 1.5, -1.5*(GLfloat)h/(GLfloat)w,
1.5*(GLfloat)h/(GLfloat)w, -10.0, 10.0);
else
glOrtho (-1.5*(GLfloat)w/(GLfloat)h,
1.5*(GLfloat)w/(GLfloat)h, -1.5, 1.5, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

64
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

void mouse(int button, int state, int x, int y)


{
switch (button) {
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN) { /* change red */
diffuseMaterial[0] += 0.1;
if (diffuseMaterial[0] > 1.0)
diffuseMaterial[0] = 0.0;
glColor4fv(diffuseMaterial);
glutPostRedisplay();
}
break;
case GLUT_MIDDLE_BUTTON:
if (state == GLUT_DOWN) { /* change green */
diffuseMaterial[1] += 0.1;
if (diffuseMaterial[1] > 1.0)
diffuseMaterial[1] = 0.0;
glColor4fv(diffuseMaterial);
glutPostRedisplay();
}
break;
case GLUT_RIGHT_BUTTON:
if (state == GLUT_DOWN) { /* change blue */
diffuseMaterial[2] += 0.1;
if (diffuseMaterial[2] > 1.0)
diffuseMaterial[2] = 0.0;
glColor4fv(diffuseMaterial);
glutPostRedisplay();
}
break;
default:
break;
}
}

int main(int argc, char** argv)


{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}

65
QUAID-E-AWAM UNIVERSITY OF ENGINEERING, SCIENCE & TECHNOLOGY, NAWABSHAH
DEPARTMENT OF COMPUTER SYSTEMS ENGINEERING

Computer Graphics (CG)

Output:

Name: _____
Roll #: _____
Date: _____
Sig: of LAB Engineer

66

Vous aimerez peut-être aussi