Professional Documents
Culture Documents
Comp 336 CG Manual Opengl
Comp 336 CG Manual Opengl
Comp 336 CG Manual Opengl
Department of Computer
Science Jazan University, Jazan,
KSA
S.No Program Page No.
1(A) To draw window with clear command 14
2
INTRODUCTION TO OPENGL
What Is OpenGL?
• 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.
Features of OpenGL:
• Comprises several libraries with varying levels of abstraction: GL, GLU, and GLUT
OpenGL Hierarchy:
• GL (Graphics Library)
• GLU(GL Utilities)
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.
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.
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.
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.
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.
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.
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.
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)
7
OpenGL Graphics Pipeline
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.
• Viewport : The sub-window into which the current graphics are being drawn.
• 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
– The real world coordinates.
Example of glViewport
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.
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.
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);
14. glBegin()
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);
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.
17. glPointSize
* To control the size of a rendered point, use glPointSize() and supply the desired size in pixels as
the argument.
* 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
* 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
* 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);
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.
* 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;
}
#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(); }
#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();
}
16
glutMainLoop();
return 0;
}
OUTPUT:
#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
}
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:
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
}
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
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:
#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:
#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;
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);
}
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.
#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
}
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();
}
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
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); }
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();
}
62