Comp 336 CG Manual Opengl

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 62

LABORATORY MANUAL

Computer Graphics [COMP-336]

Bachelor of Computer Science


Level – 12
ACADEMIC YEAR- 2022-2023

Department of Computer
Science Jazan University, Jazan,
KSA
S.No Program Page No.
1(A) To draw window with clear command 14

1(B) To draw window without clear command 14

2 To create a window and draw a triangle 15

3 To draw a line in the display window 16

4 To draw different line patterns 18

5 To draw lines using gl_Color3f, GL_LINES, GL_LINE_STRIP, 20


GL_LINE_LOOP, GL_Vertex2f, GL_Vertex2i

6 To draw different patterns using GL_TRIANGLE, GL-TRIANGLE_STRIP, 23


GL_TRIANGLE_FAN, GL_QUAD, GL_QUAD_STRIP, GL_POLYGON,
GL_POLYGON_MODE

7 To draw cirlce using Bresenham’s MidpointAlgorithm 26

8 2D Transformations without using gl functions 30

9 2D Transformations using gl functions 34

10 To display Three Dimensional Object (Teapot) 37

11 To display Three Dimensional Objects and use of mouse events 38

12 To display Three Dimensional Spinning Plane 44

13 To display 3D sphere with to show the illumination models 47

14 To display 3D sphere with varying light and color intensities 49

15 To demonstrates simple object drawing with perspective 52

16 To draw multiple spheres with different illumination models 55

2
INTRODUCTION TO OPENGL
What Is OpenGL?

• OpenGL (Open Graphics Library) is a software interface to the graphics hardware.

• OpenGL is specifically designed for efficient processing of three


dimensional applications.

• Graphics function in any package are defined as the set of specifications that are
independent of any programming language. A language binding is then defined for
a particular high level programming language.

• The OpenGL bindings are done with C, C++, Fortran or Ada.

Features of OpenGL:

• high-quality color images composed of geometric and image primitives

• operating system independent

• OpenGL consists of basic library functions for specifying graphic


primitives, geometric and viewing transformations and many other
operations.

• Hides the details of the display adapter, operating system, etc.

• Comprises several libraries with varying levels of abstraction: GL, GLU, and GLUT

OpenGL Hierarchy:

• Several levels of abstraction are provided

• GL (Graphics Library)

– Lowest level: vertex, matrix manipulation


– glVertex3f(point.x, point.y, point.z)

• GLU(GL Utilities)

– Helper functions for shapes, transformations


– gluPerspective( fovy, aspect, near, far )

• GLUT(GL Utility Toolkit)

– Highest level: Window and interface management


– glutSwapBuffers()
3
OpenGL Architecture: (Block Diagram)

DISPLAY LIST:

All data whether it describes geometry or pixels, can be saved in a display list for current or
later use.

EVALUATOR:

All geometric primitives are described by vertices. Parametric curves and surfaces are
initially described by control points and polynomial functions called basis functions. Evaluators
provide a method to derive the vertices used to represent the surface/curves from the control points.

PER VERTEX OPERATION:

In this stage, the vertex are converted to primitives.

PRIMITIVE ASSEMBLY:

Clipping is the major operation done in this stage. It is the elimination of the portions of
geometry that falls outside the half space, defined by plane. The result of this stage is complete
geometric primitives, which are transformed, clipped vertices with related color, depth.

PIXEL OPERATION:

Pixels from the system memory are scaled, biased and processed and the results are clamped
and then written into the texture memory or sent to the rasterization step.

TEXTURE ASSEMBLY:

Texture image can be applied on to geometric objects to make them look more realistic.

4
RASTERIZATION:

Rasterization is the conversion of both geometric and pixel data into fragments. Each
fragment square corresponds to a pixel in the frame buffer.

FRAGMENT OPERATIONS:

Before values are actually stored into the frame buffer, a series of operations are
performed that may alter or even throw out fragments.

OpenGL Geometric Primitives

5
OPENGL BASIC COMMANDS :

1. glutInit

All the functions in GLUT have the prefix glut, and those which perform some kind of initialization
have the prefix glutInit. The first thing you must do is to call the function glutInit.

void glutInit(int *argc, char **argv);

Parameters:
argc - A pointer to the unmodified argc variable from the main function.
argv – A pointer to the unmodified argv variable from the main function

2. glutInitWindowPosition

After initializing GLUT itself, define the window. First establish the window's position on the
screen, i.e. its top left corner. In order to do this use the function glutInitWindowPosition.

void glutInitWindowPosition(int x, int y);

Parameters:
x - the number of pixels from the left of the screen. x should be a positive value, preferably one
that will fit in your screen.

y - the number of pixels from the top of the screen. The comments mentioned for the x parameter
also apply in here.
3. glutInitWindowSize
Next set the window size. In order to do this use the function glutInitWindowSize.

void glutInitWindowSize(int width, int height);

Parameters:
width,height - The width and height of the window [avoid negative values for width and height.]

4. glutInitDisplayMode
Then define the display mode using the function glutInitDisplayMode.

void glutInitDisplayMode(unsigned int mode)

Parameters:
mode - specifies the display mode, it is a Boolean combination (OR bit wise) of the possible
predefined values in the GLUT library.

6
The predefined constants to specify the color model are:
GLUT_RGBA or GLUT_RGB - selects a RGBA window. This is the default color mode.
GLUT_INDEX - selects a color index mode.

The display mode also allows you to select either a single or double buffer window. The
predefined constants for this are:
GLUT_SINGLE - single buffer window,
GLUT_DOUBLE - double buffer window, for smooth animation.

5. glutCreateWindow
The window can be created with glutCreateWindow.

int glutCreateWindow(char *title);

Parameters: title - sets the window title

6. glutDisplayFunc
After defining the window, specify what the display window should contain. For this, create a
picture using OpenGL functions and pass the picture definition to the GLUT routine
glutDisplayFunc, which assigns the picture to the display window.

Example: glutDisplayFunc(lineSegment);

In the above code, lineSegment is a procedure that contains OpenGL code for describing the line
segment.

7) glutMainLoop ()
GLUT provides a function that gets the application in a never ending loop, always waiting for
the next event to process.
The GLUT function is glutMainLoop, and the syntax is as follows:

void glutMainLoop(void)

This must be the last statement in the program.

7
OpenGL Graphics Pipeline

Projection and Viewport

Orthogonal Projection
• Orthographic projection is used for 2D drawing
• Perspective projection is often used for 3D drawing
• 2D Viewing: Orthographic View Specifies the coordinates of 2D region to be projected into the
viewport.

- gluOrtho2D(left, right, bottom, top)

• Viewport : The sub-window into which the current graphics are being drawn.

- glViewport(x, y, width, height)

• OpenGL assumes that you are mapping your graphics to the entire screen window by default.
• (x, y) is the lower-left corner of the viewport.

World Coordinates World Window Screen Window

• World Coordinates
– The real world coordinates.

• World Window/World Coordinate Frame


– The window/frame which models the world coordinates
8
• Screen Window
– The screen which displays objects mapped from the World Coordinates Frame

Understanding Screen Window and World Window (Orthogonal Projection

Example of glViewport

• Assume the output for the following viewport is (A).

– w = width of the screen


– h = height of the screen
– glViewport(0, 0, w, h);
• Then the output for the following viewport is (B)

– glViewport(0, 0, w/2, h/2);

9
OPENGL BASIC COMMANDS :

8. glClearColor
The colors of pixels are stored in the graphics hardware known as bit planes. There are two methods
of storage. Either the red, green, blue, and alpha (RGBA) values of a pixel can be directly stored in
the bit planes, or a single index value that references a color lookup table is stored.

void glClearColor(GLclampf red, GLclampf green, GLclampf blue,GLclampf alpha);

Sets the current clearing color for use in clearing color buffers in RGBA mode. The default
clearing color is (0,0,0,0) which is black

9. glClear
It is important to clear the color buffer before drawing any objects.

void glClear(GLbitfield mask);

Clears the specified buffers to their current clearing values.

10. glLoadIdentity
It replace the current matrix with the identity matrix.

void glLoadIdentity(void)

11. gluLookAt
It defines a viewing transformation
void gluLookAt( GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ,
GLdoublecenterX,GLdouble centerY, GLdouble centerZ,
GLdouble upX,GLdouble upY,GLdouble upZ )

10
Parameters
eyeX, eyeY, eyeZ Specifies the position of the eye point.
centerX, centerY, centerZ Specifies the position of the reference
point. upX, upY, upZ Specifies the direction of the up vector.

12. glFlush

void glFlush(void);

Forces previously issued OpenGL commands to begin execution, thus guaranteeing that they
complete in finite time.

13. glVertex()

void glVertex{234}{sifd}[v](TYPEcoords);

* Specifies a vertex for use in describing a geometric object.


* You can supply up to four coordinates (x, y, z, w) for a particular vertex or as few as two (x,
y) by selecting the appropriate version of the command.
* If you use a version that doesn't explicitly specify z or w, z is understood to be 0 and w
is understood to be 1.
* Calls to glVertex*() are only effective between a glBegin() and glEnd() pair

14. glBegin()

* Specifies a vertex for use in describing a geometric object.

void glBegin(GLenum mode);

Marks the beginning of a vertex-data list that describes a geometric primitive. The type of primitive
is indicated by mode. , which can be any of the values shown in Table.

VALUE MEANING
GL_POINTS individual points
GL_LINES pairs of vertices interpreted as individual line segments
GL_LINE_STRIP series of connected line segments
GL_LINE_LOOP same as above, with a segment added between last and first
vertices GL_TRIANGLES triples of vertices interpreted as triangles
GL_TRIANGLE_STRIP linked strip of triangles
GL_TRIANGLE_FAN linked fan of triangles
GL_QUADS quadruples of vertices interpreted as four-sided polygons

11
GL_QUAD_STRIP linked strip of quadrilaterals
GL_POLYGON boundary of a simple, convex
polygon

15. glEnd ()

void glEnd(void);

Marks the end of a vertex-data list

16. glColor3f
* To set a color, use the command glColor3f().
* It takes three parameters, all of which are floating-point numbers between 0.0 and 1.0.
* The parameters are, in order, the red, green, and blue components of the color.

void glColor3f(float red, float green, float blue);

* Here are eight commands and the colors they would


set. glColor3f(0.0, 0.0, 0.0); black
glColor3f(1.0, 0.0, 0.0); red
glColor3f(0.0, 1.0, 0.0); green
glColor3f(1.0, 1.0, 0.0); yellow
glColor3f(0.0, 0.0, 1.0); blue
glColor3f(1.0, 0.0, 1.0); magenta
glColor3f(0.0, 1.0, 1.0); cyan
glColor3f(1.0, 1.0, 1.0); white

17. glPointSize
* To control the size of a rendered point, use glPointSize() and supply the desired size in pixels as
the argument.

void glPointSize(GLfloat size);

* Sets the width in pixels for rendered points; size must be greater than 0.0 and by default is 1.0.
* if the width is 1.0, the square is 1 pixel by 1 pixel; if the width is 2.0, the square is 2 pixels by
2 pixels, and so on.

18. glMatrixMode

* glMatrixMode() is used first, with the argument GL_PROJECTION.


* This indicates that the current matrix specifies the projection transformation.

void glMatrixMode(GLenum mode);

* Specifies whether the model view, projection, or texture matrix will be modified, using
12
the argument GL_MODELVIEW, GL_PROJECTION, or GL_TEXTURE for mode.

13
* Subsequent transformation commands affect the specified matrix.
* Note that only one matrix can be modified at a time.
* By default, the model view matrix is the one that's modifiable, and all three matrices contain
the identity matrix.
19. glutReshapeFunc

void glutReshapeFunc(void (*func)(int width, int height));

* Specifies the function that's called whenever the window is resized or moved.
* The argument func is a pointer to a function that expects two arguments, the new width
and height of the window.
* Typically, func calls glViewport(), so that the display is clipped to the new size.
* If glutReshapeFunc() isn't called or is deregistered by passing NULL, a default reshape
function is called, which calls glViewport(0, 0, width, height).

20. gluortho2d
* The orthographic projection should be specified with integer coordinates
gluOrtho2D(0, width, 0, height);

* where width and height are the dimensions of the viewport.

21. glViewport
* 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.

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 viewport rectangle.
* By default, the initial viewport values are (0, 0, winWidth, winHeight), where winWidth
and winHeight are the size of the window.

14
// PROGRAM – 1 (A) - TO DRAW WINDOW WITH CLEAR COMMAND
// Program Name : window_with_clear.cpp

#include <GL/glut.h>
void display (void)
{
glClearColor (0.0, 0.0, 0.0, 1.0); //clearing color buffers in RGBA mode
glClear (GL_COLOR_BUFFER_BIT); //clears specified buffers to current clearing values
glLoadIdentity(); //replace current matrix with identity matrix
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); //define viewing transformation
glFlush(); //all commands will be completed at finite time
}
int main (int argc, char **argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE); //define display mode
glutInitWindowSize (500,500); //specify width and height of window
glutInitWindowPosition (100, 100); //number of pixels from left of screen and top of screen
glutCreateWindow ("Simple Window"); //sets window title
glutDisplayFunc (display); // calling procedure display
glutMainLoop(); //never ending
loop return 0;
}

// PROGRAM – 1 (B) - TO DRAW WINDOW WITHOUT CLEAR COMMAND


//Program Name : window_without_clear.cpp

#include <GL/glut.h>
void display (void)
{ glClearColor (0.0, 0.0, 0.0, 1.0);
//glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
//define viewing transformation
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
//all commands will be completed at finite time
glFlush(); }

int main (int argc, char **argv)


{
15
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE);
glutInitWindowSize (500,500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Simple Window");
glutDisplayFunc (display);
glutMainLoop();
return 0;
}

// PROGRAM – 2 - TO CREATE A WINDOW AND DRAW A TRIANGLE


//Program Name : triangle.cpp

#include <GL/glut.h>
void renderScene(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_TRIANGLES);
glColor3f(0.0f, 0.0f, 1.0f); // set the drawing color to blue
glVertex3f(-0.5,-0.5,0.0);
glVertex3f(0.5,0.0,0.0);
glVertex3f(0.0,0.5,0.0);
glEnd();
glFlush();
}

int main(int argc, char** argv)


{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_SINGLE |
GLUT_RGBA); glutInitWindowPosition(100,100);
glutInitWindowSize(320,320);
glutCreateWindow("WINDOW TRIANGLE");
glutDisplayFunc(renderScene);

16
glutMainLoop();
return 0;
}

OUTPUT:

// PROGRAM – 3 - TO DRAW A LINE IN THE DISPLAY WINDOW


//Program Name : line.cpp

#include <GL/glut.h>
void init(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set the display window color to white
glMatrixMode(GL_PROJECTION); // set the projection parameters
gluOrtho2D(0.0, 200.0, 0.0, 150.0);
}
void lineSegment(void)
{
glClear(GL_COLOR_BUFFER_BIT); // clear the display window
glColor3f(1.0,0.0,0.0); //set line segment color to red
glBegin(GL_LINES);
glVertex2i(180,15); // specify the line segment geometry
glVertex2i(10,145);
17
glEnd();
glFlush(); // process all OpenGL functions as quickly as possible
}

int main(int argc, char** argv)


{
glutInit(&argc, argv); // initialize glut
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); //set display mode
glutInitWindowPosition(50,100); //set top left display window position
glutInitWindowSize(400,300); //set display window height and width
glutCreateWindow("An Example OpenGL Program"); //create display window
init(); // execute initialization procedure
glutDisplayFunc(lineSegment); //send graphics to display window
glutMainLoop(); // display everything and wait
}

OUTPUT:

18
// PROGRAM – 4 - TO DRAW DIFFERENT LINE PATTERNS
//Program Name : different_line_pattern.cpp

#include <GL/glut.h>
void drawOneLine(GLfloat x1,GLfloat y1,GLfloat x2,GLfloat y2)
{ glBegin(GL_LINES);
glVertex2f ((x1),(y1));
glVertex2f ((x2),(y2));
glEnd();
}
void init(void)
{ glClearColor (0.0, 0.0, 0.0, 0.0); }
void display(void)
{ int i;
glClear (GL_COLOR_BUFFER_BIT);
/* select white color 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);
19
/*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 ();
}
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);
20
glutMainLoop();
return 0;
}
OUTPUT:

// PROGRAM – 5 To draw lines using gl_Color3f, GL_LINES, GL_LINE_STRIP,


GL_LINE_LOOP, GL_Vertex2f, GL_Vertex2i
//Program Name : line_glcolor3f.cpp

#include <windows.h> // use as needed for your system


#include <gl/Gl.h>
#include <gl/glut.h>
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white background color
glColor3f(0.0f, 0.0f, 0.0f); // set the drawing color
glLineWidth(5.0); // a ‘dot’ is 4 by 4 pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 1000.0, 0.0, 600.0);
}
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_LINES); // Black Color
glColor3f(0.0,0.0,0.0);
glVertex2f(50.0,50.0);
21
glVertex2f(200.0,50.0);
glEnd();
glBegin(GL_LINES);
glColor3f(0.0,0.0,1.0); // Blue Color
glVertex2f(50.0,100.0);
glVertex2f(200.0,100.0);
glEnd();
glBegin(GL_LINES); // Green Color
glColor3f(0.0,1.0,0.0);
glVertex2f(50.0,150.0);
glVertex2f(200.0,150.0);
glEnd();
glBegin(GL_LINES); // Cyan Color
glColor3f(0.0,1.0,1.0);
glVertex2f(50.0,200.0);
glVertex2f(200.0,200.0);
glEnd();
glBegin(GL_LINES); // Red Color
glColor3f(1.0,0.0,0.0);
glVertex2f(50.0,250.0);
glVertex2f(200.0,250.0);
glEnd();
glBegin(GL_LINES); // Magenta Color
glColor3f(1.0,0.0,1.0);
glVertex2f(50.0,300.0);
glVertex2f(200.0,300.0);
glEnd();
glBegin(GL_LINES); // Yellow Color
glColor3f(1.0,1.0,0.0);
glVertex2f(50.0,350.0);
glVertex2f(200.0,350.0);
glEnd();

22
glBegin(GL_LINE_STRIP); // Magenta Color
glColor3f(1.0,0.0,1.0);
glVertex2i(250,550);
glVertex2i(400,500);
glVertex2i(250,450);
glVertex2i(400,400);
glEnd();
glBegin(GL_LINE_LOOP); // Red Color
glColor3f(1.0,0.0,0.0);
glVertex2i(450,550);
glVertex2i(600,500);
glVertex2i(450,450);
glVertex2i(600,400);
// glVertex2i(400,350);
glEnd();
glFlush(); // send all output to display
}

int main(int argc, char** argv)


{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(1000,600); // set window size
glutInitWindowPosition(0,0); // set window position on screen
glutCreateWindow("PROGRAM TO DEMONSTRATE COLOR AND GL_LINES");
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
return 0;
}

OUTPUT:

23
// PROGRAM – 6 To draw different patterns using GL_TRIANGLE, GL-TRIANGLE_STRIP,
GL_TRIANGLE_FAN, GL_QUAD, GL_QUAD_STRIP, GL_POLYGON, GL_POLYGON_MODE
//Program Name : different_pattern_line.cpp

#include <windows.h> // use as needed for your system


#include <gl/Gl.h>
#include <gl/glut.h>
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white background color
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 1000.0, 0.0, 600.0);
}
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_TRIANGLES); //Black Color triangle
glColor3f(0.0f,0.0f,0.0f);
glVertex2i(50,500);
glVertex2i(100,550);
glVertex2i(50,600);
24
glEnd();
glBegin(GL_TRIANGLES); //Blue Color triangle
glColor3f(0.0f,0.0f,1.0f);
glVertex2i(200,500);
glVertex2i(200,600);
glVertex2i(150,550);
//glVertex2i(150,500);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glLineWidth(5.0);

glBegin(GL_TRIANGLE_STRIP); //Green and Red Color triangle Strip


glColor3f(0.0f,1.0f,0.0f);
glVertex2i(100,450);
glVertex2i(50,350);
glEnd();

glBegin(GL_TRIANGLE_FAN); //Red,Green,Blue Color triangle Strip


glColor3f(1.0f,0.0f,0.0f);
glVertex2i(100,200);
glVertex2i(50,50);
glVertex2i(100,100);
glColor3f(0.0f,1.0f,0.0f);
glVertex2i(150,150);
glColor3f(0.0f,0.0f,1.0f);
glVertex2i(200,200);
//glColor3f(1.0f,0.0f,0.0f);
glEnd();

glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glBegin(GL_QUADS); // Majenta color quad
glColor3f(1.0f,0.0f,1.0f);
glVertex2i(250,200);

25
glVertex2i(350,200);
glVertex2i(400,325);
glVertex2i(300,325);
glEnd();
glVertex2i(175,400);
glColor3f(1.0f,0.0f,0.0f);
glVertex2i(150,300);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_QUAD_STRIP); // Blue Color Quad Strip
glColor3f(0.0f,0.0f,1.0f);
glVertex2i(500,600);
glVertex2i(500,400);
glVertex2i(600,550);
glVertex2i(600,350);
glVertex2i(700,500);
glVertex2i(700,300);
glEnd();
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
glBegin(GL_POLYGON); // Majenta color quad
glColor3f(0.0f,0.0f,1.0f);
glVertex2i(500,200);
glVertex2i(500,150);
glVertex2i(550,100);
glVertex2i(600,150);
glVertex2i(600,200);
glEnd();
glFlush(); // send all output to display
}
int main(int argc, char** argv) {
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(1000,600); // set window size

26
glutInitWindowPosition(0, 0); // set window position on screen
glutCreateWindow("Display Graphic Primitives"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
return 0;
}

OUTPUT:

// PROGRAM – 7 - To draw cirlce using Bresenham’s MidpointAlgorithm


//Program Name : circle_bresenham.cpp

#include<GL/glut.h>
#include<stdio.h>
#include<stdlib.h>
void setPixel(GLint xCoordinate, GLint yCoordinate)
{
glBegin(GL_POINTS);
glVertex2i(xCoordinate, yCoordinate);
glEnd();
glFlush(); }
void circleMidPoint(GLint xc, GLint yc, GLint radius)
27
{
int x=0,y=radius;
GLint p = 1-radius;
//function prototype
void circlePlotPoints(GLint, GLint, GLint,GLint);
circlePlotPoints(xc, yc,x,y);
while(x < y)
{ x++;
if(p<0) p += 2 * x + 1;
else
{ y--; p += 2 * (x-y) + 1; }
circlePlotPoints(xc, yc, x, y);
} }
void circlePlotPoints(GLint xc, GLint yc, GLint x, GLint y)
{
setPixel(xc + x , yc + y);
setPixel(xc - x , yc + y);
setPixel(xc + x , yc - y);
setPixel(xc - x , yc - y);
setPixel(xc + y , yc + x);
setPixel(xc - y , yc + x);
setPixel(xc + y , yc - x);
setPixel(xc - y , yc - x);
}
void init(void)
{
glClearColor(0.0,0.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0,300.0,0.0,300.0);
}
void drawMyCircle(void)
{
glClear(GL_COLOR_BUFFER_BIT);

28
glColor3f(1.0,0.0,0.0);
glPointSize(3.0);
GLint xCenter=150;
GLint yCenter=150;
GLint radius=50;
circleMidPoint(xCenter, yCenter, radius);
}
int main(int argc, char**argv)
{
glutInit(&argc, argv);
glutInitWindowPosition(10,10);
glutInitWindowSize(500,500);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutCreateWindow("Circle Mid Point Algorithm ");
init();
glutDisplayFunc(drawMyCircle);
glutMainLoop();
return 0;
}

OUTPUT:

Assignment:

29
Write an OpenGL routine to draw concentric circles using bresenham’s midpoint circle algorithm.
The output should appear like the following:

// PROGRAM – 8 - 2D Transformations without using gl functions


//Program Name : 2d_trans_wo_gl.cpp

#include <GL/glut.h>
#include <stdlib.h>
#include <iostream.h>
#include <math.h>
#include <windows.h> // use as needed for your system
#include <gl/gl.h>

class ppoints
{ public:
GLfloat x,y;
30
};
const GLdouble pi = 3.14159;

void init (void)


{
glClearColor (1.0, 1.0, 1.0, 0.0); // Set display-window color to white.
glMatrixMode (GL_PROJECTION); // Set projection parameters.
gluOrtho2D (0.0, 600.0, 0.0, 600.0);
}

void translate(ppoints *verts, GLint nVerts, GLfloat tx, GLfloat ty)


{
GLint k;
for(k=0;k<nVerts; k++)
{
verts[k].x = verts[k].x+tx;
verts[k].y = verts[k].y+ty;
}
}

void scale(ppoints *verts,GLint nVerts,GLfloat sx, GLfloat sy)


{
GLint k;
for(k=0;k<nVerts; k++)
{
verts[k].x = verts[k].x * sx;
verts[k].y = verts[k].y * sy;
}
}
void rotate(ppoints *verts,GLint nVerts,GLdouble theta,ppoints *n)
{
GLint k; for(k=0;k<nVerts;k+
+)

31
{
n[k].x = fabs(verts[k].x * cos(theta) - verts[k].y * sin(theta));
n[k].y = fabs(verts[k].x * sin(theta) + verts[k].y * cos(theta));
}
}
void triangle(ppoints *verts)
{
GLint k;
glBegin(GL_TRIANGLES);
for (k =0;k<3; k++)
glVertex2f(verts[k].x,verts[k].y);
glEnd ( ) ;
glFlush();
}
void myDisplay(void)
{
glClear (GL_COLOR_BUFFER_BIT); // Clear display window.
glColor3f (0.0, 0.0, 1.0); // original triangle in blue color
GLint nVerts=3;
ppoints verts[3] = { {50.0,50.0},{100.0,100.0},{150.0,50.0}};
ppoints n[3]= {{1.0,1.0},{1.0,1.0},{1.0,1.0}};
GLfloat tx = 100.0,ty = 100.0;
GLfloat sx = 2.0,sy = 1.0;
GLdouble theta = pi/2.0;
triangle(verts);
translate(verts,nVerts,tx,ty);
glColor3f (1.0, 0.0, 0.0); // translated triangle in red color
triangle(verts);
scale(verts,nVerts,sx,sy);
glColor3f (0.0, 1.0, 0.0); // Scaled triangle in green color
triangle(verts);
glColor3f (0.0, 1.0, 1.0);
rotate(verts,nVerts,theta,n);

32
glColor3f (1.0, 1.0, 0.0); // Rotated triangle in Yellow color
triangle(n);
}

int main(int argc, char** argv)


{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowPosition (0,0); // Set top-left display-window position.
glutInitWindowSize (600,600); // Set display-window width and height
glutCreateWindow("2D TRANSFORMATIONS-Translation, Scaling, Rotation");
// open the screen window
init();
glutDisplayFunc(myDisplay); // register redraw function
glutMainLoop(); // go into a perpetual loop
return 0;
}

Output:

33
Assignment:
Modify the program to do the following:
1) Implement the translation operation with the polygon and set the translation vector
to (200,200).
2) Implement the scaling operation with uniform scaling.

34
// PROGRAM – 9 - 2D Transformations using gl functions
//Program Name : 2d_trans_gl.cpp
// PROGRAM TO DO TRANSFORMATION USING glScalef(),glTranslatef(),glRotatef()

#include <windows.h>
#include <gl/Gl.h>
#include <gl/glut.h>
void init(void)
{
glClearColor(1,1,1,0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluLookAt(0,0,5, 0,0,0, 0,1,0);
//Original Triangle in red color
glBegin(GL_TRIANGLES);
glColor3f (1.0, 0.0, 0.0);
glVertex2f(0.0,0.0); glVertex2f(1.0,0.0); glVertex2f(0.5,1.0);
glEnd();
glScalef(1,2,1);
//Scaled Triangle in blue color
glBegin(GL_TRIANGLES);
glColor3f (0.0, 0.0, 1.0);
glVertex2f(0.5,0.5); glVertex2f(1.5,0.5); glVertex2f(1.0,1.5);
glEnd();
glRotatef(180,0,0,1);
//Rotated Triangle in magenta color
glBegin(GL_TRIANGLES);
glColor3f (1.0, 0.0, 1.0);
glVertex2f(0.0,0.0); glVertex2f(1.0,0.0); glVertex2f(0.5,1.0);
glEnd();
glTranslatef(2,0,0);
35
//Translated Triangle in yellow color
glBegin(GL_TRIANGLES);
glColor3f (1.0, 1.0, 0.0);
glVertex2f(0.0,0.0); glVertex2f(1.0,0.0); glVertex2f(0.5,1.0);
glEnd();
glFlush();
}
void reshape(int w,int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1, 1, -1, 1, 1.5, 20);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE|GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow("TWO DIMENSIONAL TRANSFORMATION");
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}

36
Output:

Assignment: Create a quadrilateral and apply composite transformations, that is scale and
translate the object before rotating it to 270 degrees. Apply non uniform scaling and consider the
translation vector coordinates as equal.

37
// PROGRAM – 10 -To display Three Dimensional Object (Teapot)
//Program Name : 3d_teapot.cpp
#include <GL/gl.h>
#include <GL/glut.h>
void display ()
{
/* clear window */
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.4,0.9,0.2);
/* draw scene */
glutSolidTeapot(.5);
/* flush drawing routines to the window */
glFlush();
}
int main ( int argc, char * argv[] ) {
/* initialize GLUT, using any commandline parameters passed to the program */
glutInit(&argc,argv);
/* setup the size, position, and display mode for new windows */
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutInitDisplayMode(GLUT_RGB); // create and set up a window
glutCreateWindow("hello, teapot!");
glutDisplayFunc(display);
glutMainLoop(); // tell GLUT to wait for events
}

Solid Teapot
38
Assignment:
Modify the program to display a wire frame teapot that appears small in size.

// PROGRAM – 11 - To display Three Dimensional Objects and use of mouse events


//Program Name : 3d_mouse_events.cpp

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <GL/glut.h>
#define ROT_INC 0.1
void drawSphere(void);
static GLfloat g_rotate = 0;
static GLfloat g_rotInc = ROT_INC;
static void (*drawPrimP)(void) = drawSphere;
void drawSphere(void)
{
glutWireSphere(6.0,20,20);
}
void drawCube(void)
{
glutWireCube(6.0);
}
void drawCone(void)
{
glutWireCone(6.0, 8.0, 10, 20);
}
void drawTorus(void)
{
glutWireTorus(1.0, 6.0, 10, 20);
}
void drawTeapot(void)
{

39
glutWireTeapot(6.0);
}
void setPrim(int value)
{
switch(value)
{
case 1:
drawPrimP = drawSphere;
break;
case 2:
drawPrimP = drawCube;
break;
case 3:
drawPrimP = drawCone;
break;
case 4:
drawPrimP = drawTorus;
break;
case 5:
drawPrimP = drawTeapot;
break;
}
}

void display(void)
{
glClear( GL_COLOR_BUFFER_BIT );
glMatrixMode(GL_MODELVIEW); /* set matrix mode to modelview */
glPushMatrix(); /* save matrix */
glRotatef(g_rotate,1.0,1.0,1.0); /* global rotation */
(*drawPrimP)(); /* draw the geometry */
glPopMatrix(); /* restore matrix */
glutSwapBuffers(); /* swap buffers to display the frame */
}

40
void myReshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); /* init projection matrix */
/* perspective parameters: field of view, aspect, near clip, far clip */
gluPerspective( 60.0, (GLdouble)w/(GLdouble)h, 0.1, 40.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0, 0.0, 20.0, /* eye at (0,0,20) */
0.0, 0.0, 0.0, /* lookat point */
0.0, 1.0, 0.0); /* up is in +ive y */
}
void myKey(unsigned char k, int x, int y)
{
switch (k) {
case 'q':
case 'Q': exit(0);
break;
default:
printf("Unknown keyboard command \'%c\'.\n", k);
break;
} }
void myMouse(int btn, int state, int x, int y)
{
if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN) g_rotInc += ROT_INC;
if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN) g_rotInc =
ROT_INC; glutPostRedisplay();
}
void myIdleFunc(void)
{
g_rotate += g_rotInc;
glutPostRedisplay();

41
}

int main(int argc, char **argv)


{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowSize(500, 500);
glutCreateWindow("3D Shapes Test");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutIdleFunc(myIdleFunc);
glutKeyboardFunc(myKey);
glutMouseFunc(myMouse);
/* set up right menu */
glutCreateMenu(setPrim);
glutAddMenuEntry("Sphere", 1);
glutAddMenuEntry("Cube", 2);
glutAddMenuEntry("Cone", 3);
glutAddMenuEntry("Torus", 4);
glutAddMenuEntry("Teapot", 5);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glClearColor(1.0, 1.0, 1.0, 1.0); /* set clear colour */
glColor3f(0.0, 0.0, 0.0); /* set current colour to black */
glutMainLoop();
return 0;
}

Output:

42
Case 1: Sphere

Case 2: Cube

Case 3: Cone

43
Case 4: Torus

Case 5: Teapot

Assignment:
Modify the program to decrease the rotation factor and also code the middle button of the mouse to
decrease the rotation speed.

44
// PROGRAM – 12 - To display Three Dimensional Spinning Plane
//Program Name : 3d_spinning_plane.cpp

#include <GL/glut.h>
#include <stdlib.h>
static GLfloat spin = 0.0;

void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glRotatef(spin, 0.0, 0.0, 1.0);
glColor3f(1.0, 1.0, 1.0);
glRectf(-25.0, -25.0, 25.0, 25.0);
glPopMatrix();
glutSwapBuffers();
}

void spinDisplay(void)
{
spin = spin + 2.0;
if (spin > 360.0)
spin = spin - 360.0;
glutPostRedisplay();
}

void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
}

45
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_MIDDLE_BUTTON:
case GLUT_RIGHT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(NULL);
break;
default:
break;
}
}
/* Request double buffer display mode. Register mouse input callback functions */
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize (250, 250);
glutInitWindowPosition (100, 100);

46
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMainLoop();
return 0; /* ANSI C requires main to return int. */
}

Output:

Assignment:
Modify the program to code the middle button of the mouse to decrease the rotation speed and
also apply smooth shading to color the object.

47
// PROGRAM – 13 – To display 3D sphere with to show the illumination models
//Program Name : 3d_sphere_1.cpp

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
void init(void)
{
GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_shininess[] = { 50.0 };
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_SMOOTH);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
}
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

48
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();
}

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);
glutMainLoop();
return 0;
}
Output:

49
// PROGRAM – 14 - To display 3D sphere with varying light and color intensities
//Program Name : 3d_sphere_2.cpp

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.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);

50
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();
}
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;

51
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;
}
Output:

52
// PROGRAM – 15 - To demonstrates simple object drawing with perspective
// Program Name : simple_object_draw.cpp

// Header files to include


#include <stdio.h>
#include <gl/glut.h> // GLUT toolkit
// Define initial camera position and viewing window values
#define INIT_VIEW_X 0.0
#define INIT_VIEW_Y 0.0
#define INIT_VIEW_Z -4.5
#define VIEW_LEFT -2.0
#define VIEW_RIGHT 2.0
#define VIEW_BOTTOM -2.0
#define VIEW_TOP 2.0
#define VIEW_NEAR 1.0
#define VIEW_FAR 200.0
// My initialization values for lighting
GLfloat AmbientLight[] = { 0.3f, 0.3f, 0.3f, 1.0f };
GLfloat DiffuseLight[] = { 0.8f, 0.8f, 0.8f, 1.0f };
GLfloat SpecularLight[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat SpecRef[] = { 0.7f, 0.7f, 0.7f, 1.0f };
GLfloat LightPos[] = {-50.0f,50.0f,100.0f,1.0f};
GLubyte Shine = 128;

//Display the current object using My Image's data


void DisplayObject(void)
{
// Clear the window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3ub(150, 150, 250); // Change the draw color to slate blue
glPushMatrix(); //Save viewing matrix state
glRotatef(45.0,1,1,1); // Rotate 45 degrees on each axis to show a little depth
glutWireSphere(1.0f, 30, 30); //Draw WireFrame Sphere
glPopMatrix(); // Restore matrix state
53
glutSwapBuffers(); // Flush drawing commands
} // End of DisplayObject
void SetupRend()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background to black
glEnable(GL_DEPTH_TEST); // Enable depth testing
glEnable(GL_LIGHTING); // Enable lighting
glLightfv(GL_LIGHT0, GL_AMBIENT, AmbientLight); // Set up and enable light zero
glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, SpecularLight);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL); // Enable color tracking
// Set material to folow glColor values
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

// Set specular reflectivity and shine


glMaterialfv(GL_FRONT, GL_SPECULAR, SpecRef);
glMateriali(GL_FRONT, GL_SHININESS, Shine);
}
void ChangeWindow(GLsizei w, GLsizei h) // Set a perspective window
{
GLfloat Ratio;
if (h==0) // Prevent division by zero
h=1;
glViewport(0,0,w,h); // Set viewport to window dimensions
Ratio = (GLfloat)w/(GLfloat)h; // Set the perspective ratios
glMatrixMode( GL_PROJECTION ); // Reset coordinate system
glLoadIdentity();
gluPerspective(50.0f, Ratio, VIEW_NEAR, VIEW_FAR); // Set the viewing perspective
glMatrixMode( GL_MODELVIEW ); // Set viewing translation
glLoadIdentity();
glTranslatef( INIT_VIEW_X, INIT_VIEW_Y, INIT_VIEW_Z );
glLightfv(GL_LIGHT0, GL_POSITION, LightPos);
}
54
// Main program module
int main(void)
{
// Set the buffers we want for best viewing
glutInitDisplayMode ( GLUT_DOUBLE // double-buffered pixel format for flicker-free movement

| GLUT_RGB // use RGB pixel format (easy to color)


| GLUT_DEPTH); // use depth buffer (better perspective)

// Create the viewing window


glutCreateWindow ("Simple.c - Demonstration of Simple C++ OpenGL Code");
glutReshapeFunc (ChangeWindow); // Set function for resizing window
glutDisplayFunc (DisplayObject); // Set function for redisplaying
SetupRend(); // Initialize and get ready to draw
glutMainLoop(); // Keep on going until user gets tired
return 0;
}

Output:

55
// PROGRAM – 16 - To draw multiple spheres with different illumination models
// Program Name : multiple_spheres.cpp

#include <stdlib.h>
#include <GL/glut.h>
/* Initialize z-buffer, projection matrix, light source, and lighting model. Do not specify a material
property here. */
void init(void)
{
GLfloat ambient[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat position[] = { 0.0, 3.0, 2.0, 0.0 };
GLfloat lmodel_ambient[] = { 0.4, 0.4, 0.4, 1.0 };
GLfloat local_view[] = { 0.0 };
glClearColor(0.0, 0.1, 0.1, 0.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, position);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, local_view);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0); }

/* Draw twelve spheres in 3 rows with 4 columns.


* The spheres in the first row have materials with no ambient reflection. * The second row has materials
with significant ambient reflection. * The third row has materials with colored ambient reflection. * * The
first column has materials with blue, diffuse reflection only. * The second column has blue diffuse reflection,
as well as specular * reflection with a low shininess exponent. * The third column has blue diffuse reflection,
as well as specular * reflection with a high shininess exponent (a more concentrated highlight). * The fourth
column has materials which also include an emissive component. * * glTranslatef() is used to move spheres
to their appropriate locations. */

56
void display(void)
{
GLfloat no_mat[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat mat_ambient[] = { 0.7, 0.7, 0.7, 1.0 };
GLfloat mat_ambient_color[] = { 0.8, 0.8, 0.2, 1.0 };
GLfloat mat_diffuse[] = { 0.1, 0.5, 0.8, 1.0 };
GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat no_shininess[] = { 0.0 };
GLfloat low_shininess[] = { 5.0 };
GLfloat high_shininess[] = { 100.0 };
GLfloat mat_emission[] = {0.3, 0.2, 0.2, 0.0};
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

/* draw sphere in first row, first column * diffuse reflection only; no ambient or specular */
glPushMatrix();
glTranslatef (-3.75, 3.0, 0.0);
glMaterialfv(GL_FRONT, GL_AMBIENT, no_mat);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, no_mat);
glMaterialfv(GL_FRONT, GL_SHININESS, no_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, no_mat);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();

/* draw sphere in first row, second column * diffuse and specular reflection; low shininess; no ambient */
glPushMatrix();
glTranslatef (-1.25, 3.0, 0.0);
glMaterialfv(GL_FRONT, GL_AMBIENT, no_mat);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, low_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, no_mat);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();
57
/* draw sphere in first row, third column * diffuse and specular reflection; high shininess; no ambient */
glPushMatrix();
glTranslatef (1.25, 3.0, 0.0);
glMaterialfv(GL_FRONT, GL_AMBIENT, no_mat);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, no_mat);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();

/* draw sphere in first row, fourth column * diffuse reflection; emission; no ambient or specular reflection */
glPushMatrix();
glTranslatef (3.75, 3.0, 0.0);
glMaterialfv(GL_FRONT, GL_AMBIENT, no_mat);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, no_mat);
glMaterialfv(GL_FRONT, GL_SHININESS, no_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, mat_emission);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();

/* draw sphere in second row, first column * ambient and diffuse reflection; no specular */
glPushMatrix();
glTranslatef (-3.75, 0.0, 0.0);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, no_mat);
glMaterialfv(GL_FRONT, GL_SHININESS, no_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, no_mat);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();

58
/* draw sphere in second row, second column * ambient, diffuse and specular reflection; low shininess */
glPushMatrix();
glTranslatef (-1.25, 0.0, 0.0);
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, low_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, no_mat);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();

/* draw sphere in second row, third column * ambient, diffuse and specular reflection; high shininess */
glPushMatrix();
glTranslatef (1.25, 0.0, 0.0);
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, high_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, no_mat);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();

/* draw sphere in second row, fourth column * ambient and diffuse reflection; emission; no specular */
glPushMatrix();
glTranslatef (3.75, 0.0, 0.0);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, no_mat);
glMaterialfv(GL_FRONT, GL_SHININESS, no_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, mat_emission);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();

59
/* draw sphere in third row, first column * colored ambient and diffuse reflection; no specular */
glPushMatrix();
glTranslatef (-3.75, -3.0, 0.0);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient_color);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, no_mat);
glMaterialfv(GL_FRONT, GL_SHININESS, no_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, no_mat);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();

/* draw sphere in third row, second column * colored ambient, diffuse and specular reflection; low shininess */
glPushMatrix();
glTranslatef (-1.25, -3.0, 0.0);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient_color);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, low_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, no_mat);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();

/* draw sphere in third row, third column * colored ambient, diffuse and specular reflection; high shininess */
glPushMatrix();
glTranslatef (1.25, -3.0, 0.0);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient_color);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, no_mat);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();

60
/* draw sphere in third row, fourth column * colored ambient and diffuse reflection; emission; no specular */
glPushMatrix();
glTranslatef (3.75, -3.0, 0.0);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient_color);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, no_mat);
glMaterialfv(GL_FRONT, GL_SHININESS, no_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, mat_emission);
glutSolidSphere(1.0, 16, 16);
glPopMatrix();
glFlush();
}
void reshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= (h * 2))
glOrtho (-6.0, 6.0, -3.0*((GLfloat)h*2)/(GLfloat)w, 3.0*((GLfloat)h*2)/(GLfloat)w, -10.0, 10.0);
else
glOrtho (-6.0*(GLfloat)w/((GLfloat)h*2), 6.0*(GLfloat)w/((GLfloat)h*2), -3.0, 3.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}

void keyboard(unsigned char key, int x, int y)


{
switch (key)
{
case 27:
exit(0);
break;
}
}
61
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize (600, 450);
glutCreateWindow(argv[0]);
init();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutKeyboardFunc (keyboard);
glutMainLoop();
return 0;
}
Output:

62

You might also like