SlideShare a Scribd company logo
OpenGL
OpenGL is an application programming interface---‘‘API’’ for short---which is
merely a software library for accessing features in graphics hardware.
It was first developed at Silicon Graphics Computer Systems with Version 1.0
released in July of 1994.
Properties
• Independent of a computer’s operating or windowing system
• OpenGL doesn’t provide any functionality for describing models of three-
dimensional objects, or operations for reading image files
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 1
Basic OpenGL Program Structure
The basic structure of all OpenGL applications is as follows:
• Initialize the state associated with how objects should be rendered.
• Specify those objects to be rendered.
Rendering is the process by which a computer creates an image from models. OpenGL is
just one example of a rendering system.
Models( or objects) are constructed from geometric primitives such as points, lines, and
triangles that are specified by their vertices.
OpenGL uses Shaders (or little programs that are specifically compiled for your graphics
processing unit) which are special functions that the graphics hardware executes.
In OpenGL, there are four shader stages that you can use. The most common are vertex
shaders, which process vertex data, and fragment shaders, which operate on the fragments
generated by the rasterizer. Both vertex and fragment shaders are required in every
OpenGL program.
The final generated image consists of Pixels drawn on the screen; a pixel is the smallest
visible element on your display. The pixels in your system are stored in a framebuffer.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 2
Basic OpenGL Program Structure
In the preamble of the program, we include the appropriate header files and
declare global variables1 and other useful programming constructs.
The init() routine is used to set up data for use later in the program. This
may be vertex information for later use when rendering.
The display() routine is what really does the rendering. Almost all
display() routines will do the same three steps
1. Clear the window by calling glClear().
2. Issue the OpenGL calls required to render your object.
3. Request that the image is presented to the screen.
Finally, main() does the heavy lifting of creating a window, calling init(), and
finally entering into the event loop.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 3
OpenGL Pipeline
OpenGL begins with the
geometric data you provide
(vertices and geometric
primitives) and first processes it
through a sequence of shader
stages: vertex shading,
tessellation shading (which itself
uses two shaders), and finally
geometry shading, before it’s
passed to the rasterizer. The
rasterizer will generate
fragments for any primitive
that’s inside of the clipping
region, and execute a fragment
shader for each of the
generated fragments. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 4
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 5
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 6
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 7
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 8
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 9
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 10
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 11
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 12
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 13
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 14
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 15
Glut routines for Window Management
• glutInit(int *argc, char **argv) initializes GLUT and processes any command
line arguments.
glutInit() should be called before any other GLUT routine.
• glutInitDisplayMode(unsigned int mode) specifies whether to use an RGBA or
color-index color model. You can also specify whether you want a single- or
double-buffered window. (If you're working in color-index mode, you'll want to
load certain colors into the color map; use glutSetColor() to do this.) Finally, you
can use this routine to indicate that you want the window to have an associated
depth, stencil, and/or accumulation buffer. For example, if you want a window
with double buffering, the RGBA color model, and a depth buffer, you might
call glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH).
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 16
Glut routines for Window Management
• glutInitWindowPosition(int x, int y) specifies the screen location for
the upper-left corner of your window.
• glutInitWindowSize(int width, int size) specifies the size, in pixels, of
your window.
• int glutCreateWindow(char *string) creates a window with an
OpenGL context. It returns a unique identifier for the new window.
Be warned: Until glutMainLoop() is called (see next section), the
window is not yet displayed.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 17
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 18
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 19
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 20
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 21
OpenGL Geometric Primitives
Polygon Types
GL_POLYGON -- draws a polygon
from vertex v0 to vn-1
GL_QUADS -- draws a series of
separate four-sided polygons
GL_TRIANGLES -- draws a series of
separate three-sided polygons
GL_QUAD_STRIP -- draws a strip of
connected quadrilaterals
GL_TRIANGLE_STRIP -- draws a strip
of connected triangles
GL_TRIANGLE_FAN -- draws a strip of
triangles connected about a common
origin
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru
22
Sierpinski Gasket - Algorithm
1. Pick an initial point (x, y, z) at random inside the triangle
2. Select one of the three vertices of the triangle at random
3. Find the location halfway between the initial point and the
randomly selected vertex.
4. Display the new point
5. Replace the point(x, y, z) with this new point
6. Return to step 2
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru
23
Line Attributes
• Color, thickness, stippling.
• glColor3f() sets color.
• glLineWidth(4.0) sets thickness. The default thickness is 1.0.
a). thin lines b). thick lines c). stippled lines
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru
24
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 25
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 26
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 27
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 28
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 29
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 30
Sample Program
#include <GL/gl.h>
#include <GL/glut.h>
void display(void)
{
/* clear all pixels */
glClear(GL_COLOR_BUFFER_BIT);
/* draw white polygon (rectangle) with corners at (0.25, 0.25, 0.0) and (0.75, 0.75,
0.0) */
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_POLYGON);
glVertex3f(0.25, 0.25, 0.0);
glVertex3f(0.75, 0.25, 0.0);
glVertex3f(0.75, 0.75, 0.0);
glVertex3f(0.25, 0.75, 0.0);
glEnd();
/* don't wait! start processing buffered OpenGL routines */
glFlush();
}
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 31
Sample Program
void init(void)
{
/* select clearing (background) color */
glClearColor(0.0, 0.0, 0.0, 0.0);
/* initialize viewing values */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 32
Sample Program
/* Declare initial window size, position, and display mode (single buffer
and
RGBA). Open window with "hello" in its title bar. Call initialization
routines. Register callback function to display graphics. Enter
main loop and process events. */
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(250, 250);
glutInitWindowPosition(100, 100);
glutCreateWindow("hello");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
Output:
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 33
glMatrixMode(mode)
• Specifies which matrix is the current matrix
There are actually only three things you can pass to glMatrixMode:
• glMatrixMode(GL_MODELVIEW); is the common case. This makes all subsequent matrix operations
affect the "gl_ModelViewMatrix", which is primarily used for model setup (for example, shrinking the
car model to fit next to the building model).
• glMatrixMode(GL_PROJECTION); switches to the projection matrix, "gl_ProjectionMatrix". The
projection matrix's job is usually to perform the perspective divide.
• glMatrixMode(GL_TEXTURE); switches to the texture matrix. This can be used to adjust the texture
coordinates you pass in.
To find out which matrix stack is currently the target of all matrix operations, call glGet with argument GL_MATRIX_MODE. The
initial value is GL_MODELVIEW.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 34
The projection matrix is used to create your viewing volume. Imagine a
scene in the real world. You don’t really see everything around you,
only what your eyes allow you to see. So when we say that we set up
the projection matrix we mean that we set up what we want to see
from the scene that we create. I mean you can draw objects anywhere
in your world. If they are not inside the view volume you won’t see
anything. When you create the view volume imagine that you create 6
clipping planes that define your field of view.
glMatrixMode(mode)
The modelview matrix is used to make various transformations to the
models (objects) in your world. Like this you only have to define your
object once and then translate it or rotate it or scale it.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 35
OpenGL Matrix Manipulation
OpenGL has a whole set of useful utility routines that act on the current matrix (as set by glMatrixMode):
•glLoadIdentity();Cleans out the current matrix, replacing it with the identity
•glTranslatef(dx,dy,dz);Shifts the origin of the current coordinate system.
•glScalef(sx,sy,sz);Scales the current coordinate system. Scaling by a big value makes stuff bigger. You can also mirror stuff
by scaling by a negative value.
•glRotatef(ang,x,y,z);Rotate by ang degrees right-handed around the vector x,y,z. For example, glRotatef(45.0,0,0,1); rotates
the stuff onscreen by 45 degrees counterclockwise.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 36
OpenGL Transformations
Translation: Translation refers to moving an object to a different position on the screen.
The OpenGL function is glTranslatef( tx, ty, tz ), where tx, ty and tz are translation distances along the three axes
Rotation: Rotation refers to rotating a point.
The OpenGL function is glRotatef (A, x, y, z), where A is the angle of rotation
The above formula will rotate the point around the origin through an angle A.
Scaling: Scaling refers to zooming in and out an object on different scales across axes.
The OpenGL function is glScalef(float x, float y, float z)
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 37
OpenGL Transformation
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 38
Viewing: Camera Analogy
Positioning the Camera
Positioning the Model
Choose a camera lens and
adjust zoom
Mapping to screen
Viewing Transformation
Modeling Transformation
Projection Transformation
Viewport Transformation
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 39
Viewport Transformation
• Indicates the shape of the available screen area into which the
scene is mapped
• Since viewport specifies the region the image occupies on the
computer screen, you can think of the viewport transformation
as defining the size and location of the final processed
photograph - for example, whether the photograph should be
enlarged or shrunk.
• If the window changes size, the viewport needs to change
accordingly
void glViewport( int x,
int y,
int width,
int height);
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 40
Viewport transformation
glViewport( 0, 0, width, height);
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 41
Projection
Perspective v/s Orthographic
Objects which are far away are smaller than those nearby;
Does not preserve the shape of the objects.
Perspective view points give more information about depth;
Easier to view because you use perspective views in real life.
Useful in architecture, game design, art etc.
All objects appear the same size regardless the distance;
Orthographic views make it much easier to compare sizes
of the objects. It is possible to accurately measure the
distances
All views are at the same scale
Very useful for cartography, engineering drawings,
machine parts.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 42
Projection transformation
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//perspective projection
glFrustum(left, right, bottom, top, near, far);
Or
//orthographic projection
glOrtho (left, right, bottom, top, near, far);
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 43
Perspective Transformation
//perspective projection
void glFrustum(double left,
double right,
double bottom,
double top,
double near,
double far);
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 44
Perspective Transformation
Four sides of the frustum, its top, and its base correspond to the six
clipping planes of the viewing volume.
Objects or parts of objects outside these planes are clipped from the
final image
Does not have to be symmetrical
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 45
Perspective Transformation
//perspective projection
void gluPerspective( double fovy,
double aspect,
double near,
double far);
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 46
Orthographic Transformation
//orthographic projection
void glOrtho( double left,
double right,
double bottom,
double top,
double near,
double far);
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 47
Modelview Matrix
//perspective projection
void gluLookAt(double eyeX, double eyeY, double eyeZ,
double centerX, double centerY, double centerZ,
double upX, double upY, double upZ);
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 48
Setting up the scene
void init(void) { /* called once to set up basic opengl state */
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION); /* Set up the projection matrix */
glLoadIdentity();
// left,right,bottom,top,near,far
glFrustum(-1.0, 1.0, -1.0, 1.0, 1., 10.0); // perspective view
// glOrtho (-1.0, 1.0, -1.0, 1.0, 1., 10.0); // orthographic view
// gluPerspective(45.0f, 1., 1., 10.); // perspective view
glMatrixMode(GL_MODELVIEW); /* Set up the model view matrix */
glLoadIdentity();
eye center up-direction
gluLookAt(0.,0.,2.,0.,0.,0.,0.,1.,0.); /* Camera position */
} Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 49
Additional GLUT callback routines
GLUT supports many different callback actions, including:
glutDisplayFunc()defines the function that sets up the image on the screen
glutReshapeFunc() function is called when the size of the window is changed
glutKeyBoardFunc() callback routine to respond on keyboard entry
glutMouseFunc() callback to respond on pressing the mouse button
glutMotionFunc() callback to respond mouse move while a mouse button is pressed
glutPassiveMouseFunc() callback to respond to mouse motion regardless state of mouse
button
glutIdleFunc() callback routine for idle state, usually used for animation
More info: http://www.opengl.org/resources/libraries/glut/spec3/node45.html
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 50
Additional GLUT callback routines
int main(int argc, char **argv)
{
. . .
/* Set callback function that responds on keyboard pressing */
glutKeyboardFunc (keypress);
. . .
}
/* keyboard callback routine */
void keypress( unsigned char key, int x, int y)
{
if (key == 'q' || key =='Q' || key ==27)exit(0); // exit
} Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 51
Callback routines & Window Resizing
int main(int argc, char **argv) {
. . .
/* Set display as a callback for the current window */
glutDisplayFunc(display);
/* Set callback function that respond to resizing the window */
glutReshapeFunc(resize);
/* Set callback function that responds on keyboard pressing */
glutKeyboardFunc(keypress);
/* Set callback function that responds on the mouse click */
glutMouseFunc(mousepress);
. . .
}
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 52
Callback routines & Window Resizing
void keypress( unsigned char key, int x, int y) { … }
void mousepress( int button, int state, int x, int y) { … }
void resize(int width, int height) {
double aspect;
glViewport(0,0,width,height); /* Reset the viewport */
aspect = (double)width / (double)height; /* compute aspect ratio*/
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); //reset projection matrix
if (aspect < 1.0) {
glOrtho(-4., 4., -4./aspect, 4./aspect, 1., 10.);
} else {
glOrtho(-4.*aspect, 4.*aspect, -4., 4., 1., 10.);
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0., 0., 5., 0., 0., 0., 0., 1., 0.);
}
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 53
Skeleton Event-driven Program
// include OpenGL libraries
void main()
{
glutDisplayFunc(myDisplay); // register the redraw function
glutReshapeFunc(myReshape); // register the reshape function
glutMouseFunc(myMouse); // register the mouse action function
glutMotionFunc(myMotionFunc); // register the mouse motion function
glutKeyboardFunc(myKeyboard); // register the keyboard action function
…perhaps initialize other things…
glutMainLoop(); // enter the unending main loop
}
…all of the callback functions are defined here
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 54
Callback Functions
• glutDisplayFunc(myDisplay);
• (Re)draws screen when window opened or another window moved off it.
• glutReshapeFunc(myReshape);
• Reports new window width and height for reshaped window. (Moving a
window does not produce a reshape event.)
• glutIdleFunc(myIdle);
• when nothing else is going on, simply redraws display using void myIdle()
{glutPostRedisplay();}
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 55
Callback Functions
• glutMouseFunc(myMouse);
• Handles mouse button presses. Knows mouse location and nature of button
(up or down and which button).
• glutMotionFunc(myMotionFunc);
• Handles case when the mouse is moved with one or more mouse buttons
pressed.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 56
Callback Functions
• glutPassiveMotionFunc(myPassiveMotionFunc)
• Handles case where mouse enters the window with no buttons pressed.
• glutKeyboardFunc(myKeyboardFunc);
• Handles key presses and releases. Knows which key was pressed and
mouse location.
• glutMainLoop()
• Runs forever waiting for an event. When one occurs, it is handled by the
appropriate callback function.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 57
What the Call-back functions do?
• The call-back functions you write are registered, and then the
program enters an endless loop, waiting for events to occur.
• When an event occurs, GL calls the relevant handler function.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 58
Simple User Interaction with Mouse
and Keyboard
• Register functions:
• glutMouseFunc (myMouse);
• glutKeyboardFunc (myKeyboard);
• Write the function(s)
• NOTE that any drawing you do when you use these functions must be
done IN the mouse or keyboard function (or in a function called from
within mouse or keyboard callback functions).
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 59
Example Mouse Function
• void myMouse(int button, int state, int x, int y);
• Button is one of GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, or
GLUT_RIGHT_BUTTON.
• State is GLUT_UP or GLUT_DOWN.
• X and y are mouse position at the time of the event.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 60
Example Mouse Function
• The x value is the number of pixels from the left of the window.
• The y value is the number of pixels down from the top of the window.
• In order to see the effects of some activity of the mouse or keyboard,
the mouse or keyboard handler must call either myDisplay() or
glutPostRedisplay().
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 61
Using Mouse Motion Functions
• glutMotionFunc(myMovedMouse); // moved with button held down
• glutPassiveMotionFunc(myMovedMouse); // moved with buttons up
• myMovedMouse(int x, int y); x and y are the position of the mouse
when the event occurred.
• Code for drawing rubber rectangles using these functions is in Fig.
2.41.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 62
Example Keyboard Function
void myKeyboard(unsigned char theKey, int mouseX, int
mouseY)
{
GLint x = mouseX;
GLint y = screenHeight - mouseY; // flip y value
switch(theKey)
{case ‘p’: drawDot(x, y); break;
// draw dot at mouse position
case ‘E’: exit(-1); //terminate the program
default: break; // do nothing
}
}
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 63
Example Keyboard Function
• Parameters to the function will always be (unsigned char key, int
mouseX, int mouseY).
• The y coordinate needs to be flipped by subtracting it from
screenHeight.
• Body is a switch with cases to handle active keys (key value is ASCII
code).
• Remember to end each case with a break!
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 64
Using Menus
• Both GLUT and GLUI make menus available.
• GLUT menus are simple, and GLUI menus are more powerful.
• We will build a single menu that will allow the user to change the
color of a triangle, which is undulating back and forth as the
application proceeds.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 65
GLUT Menu Callback Function
• Int glutCreateMenu(myMenu); returns menu ID
• void myMenu(int num); //handles choice num
• void glutAddMenuEntry(char* name, int value); // value used in
myMenu switch to handle choice
• void glutAttachMenu(int button); // one of GLUT_RIGHT_BUTTON,
GLUT_MIDDLE_BUTTON, or GLUT_LEFT_BUTTON
• Usually GLUT_RIGHT_BUTTON
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 66
GLUT Menu-Example
• int submenu1, submenu2;
• submenu1 = glutCreateMenu(mymenu);
• glutAddMenuEntry("abc", 1);
• glutAddMenuEntry("ABC", 2);
• submenu2 = glutCreateMenu(selectColor);
• glutAddMenuEntry("Green", 1);
• glutAddMenuEntry("Red", 2);
• glutAddMenuEntry("White", 3);
• glutCreateMenu(selectFont);
• glutAddMenuEntry("9 by 15", 0);
• glutAddMenuEntry("Times Roman 10", 1);
• glutAddMenuEntry("Times Roman 24", 2); glutAddSubMenu("Messages", submenu1);
• glutAddSubMenu("Color", submenu2); glutAttachMenu(Glut.GLUT_RIGHT_BUTTON);
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 67
GLUT SubMenu
• Create a subMenu first, using menu commands, then add it to main
menu.
• A submenu pops up when a main menu item is selected.
• glutAddSubMenu (char* name, int menuID); // menuID is the value
returned by glutCreateMenu when the submenu was created
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 68
Using GLUT Menus:
Overview
• What we can do with menus:
• We can create (and destroy) menu data structures.
• We can add entries (and submenus) to a previously created menu.
• We can attach a previously created menu to a mouse button (and we can also detach it).
• We can change the entries of a menu.
• The first three above are illustrated in creature.cpp. We will look at these in
detail shortly.
• Each menu has a callback associated with it: the handler function. This function is
called when the user selects an entry in that menu.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 69
Using GLUT Menus:
Menu Creation
• Creating a Menu
• Creating a menu means creating a data structure in memory; nothing is displayed yet.
• GLUT manages the data structure.
• When we create a menu, we also register the handler callback function.
• The initialization function (“init”) is a good place to create your menus.
• To create a menu, call glutCreateMenu.
• This function takes one parameter:
• A pointer to the handler callback function for this menu.
• A menu handler function takes one int parameter and returns void; more on this later.
• Example: glutCreateMenu(handle_menu);
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 70
• We can add entries to the end of the current menu.
• What is the current menu? For now, if you have created one menu, then it is the current menu
(similarly, if you have one window, then it is the current window).
• To add an entry, call glutAddMenuEntry.
• This function takes two parameters:
• A char* (C-style string) that gives the text of the entry.
• If you are using the C++ string class, you can pass a C-style string using the .c_str() member
function.
• An int that is passed to the handler function when the user selects this entry.
• Example: glutAddMenuEntry("Toggle eye color", 1);
Adding Entries to a Menu
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 71
Using GLUT Menus:
Attaching
• Attaching a Menu to a Mouse Button
• We can attach the current menu to a mouse button in the current window.
• To attach a menu, call glutAttachMenu.
• This function takes one parameter:
• An int indicating which mouse button to attach to.
• Example: glutAttachMenu(GLUT_RIGHT_BUTTON);
• Once we attach a menu, the user can use it.
• Whenever they want, the user pops up the menu with the appropriate mouse action.
• We do not draw the menu; GLUT does this for us.
• When a menu entry is selected, the handler function is called, with the proper number as a
parameter.
• Since a menu is attached in the current window, do not attach a menu until you have created
a window.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 72
Using GLUT Menus:
Example
• The following is called in function init.
void make_main_menu()
{
glutCreateMenu(handle_main_menu);
glutAddMenuEntry("Toggle eye color", 1);
glutAddMenuEntry("Toggle mouth motion", 2);
glutAddMenuEntry("Quit", 3);
glutAddMenuEntry("------------------------", 999);
…
glutAddMenuEntry("for CS 381, fall 2003", 999);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
• Value passed to handler callback can be the same for multiple entries.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 73
Using GLUT Menus:
Example
• Here is part of the handler callback function (declared before make_main_menu!).
// handle_main_menu
// Menu handling callback function for our menu
void handle_main_menu(int value)
{
switch (value)
{
case 1: // Toggle eye color
blueeyes = !blueeyes;
glutPostRedisplay();
break;
…
case 3: // Quit
exit(0);
break;
case 999: // Other menu items do nothing
break;
• Menu handlers, like keyboard functions, typically consist of one switch statement.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 74
• Now, we quickly look at a few more advanced topics. We will discuss
some of these in more detail later on.
• GLUT Menus:
• The “current menu”.
• Submenus.
• Changing menu entries.
• Thoughts on menus in general:
• What are submenus for?
• On changing menus.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 75
More on Menus:
GLUT — The Current Menu
• Some GLUT menuing commands (e.g., glutAddMenuEntry, glutAttachMenu) deal with
the current menu.
• If you have just one menu, then it is the current menu.
• glutCreateMenu sets the current menu to the menu created.
• In a menu handler, the current menu is the one handled.
• Function glutCreateMenu returns an int identifying the menu created. If you have multiple
menus, save this value.
int menu_x = glutCreateMenu(handle_menu_x);
• You can set the current menu yourself using glutSetMenu.
• There is also a “current window”. It is dealt with similarly.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 76
• A submenu is a menu that is an item in another menu.
• To make a submenu (in the “main” menu):
• Create the submenu (as an ordinary menu, but do not attach it).
• Create the main menu.
• Use glutAddSubMenu to make submenu an item in the main menu.
int superduper_menu =
glutCreateMenu(handle_superduper_menu);
…
int rightmouse_menu =
glutCreateMenu(handle_rightmouse_menu);
glutAddSubMenu("Super-Duper Stuff", superduper_menu);
• The submenu does not need to be attached.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 77
More on Menus:
GLUT — Changing Menu Entries
• To change the text or return value of a menu entry:
• Set the the current menu, by passing the proper ID to glutSetMenu.
• If you are in the menu handler, this is unnecessary.
glutSetMenu(superduper_menu);
• Use glutChangeToMenuEntry to set the new text & return value. This function takes 3 parameters:
• The entry number (int): count from the top of the menu, starting at 1.
• The new text (char*).
• The new return value (int).
glutChangeToMenuEntry(1, the_entry.c_str(), 1);
• You can also change submenus, using glutChangeToSubMenu; see the GLUT documentation.
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 78
OpenGL Display Lists - Example
// create one display list
int index = glGenLists(1);
// compile the display list
glNewList(index, GL_COMPILE);
glBegin(GL_TRIANGLES);
glVertex3fv(v0);
glVertex3fv(v1);
glVertex3fv(v2);
glEnd();
glEndList();
...
// draw the display list
glCallList(index);
...
// delete it if it is not used any more
glDeleteLists(index, 1);
Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 79

More Related Content

What's hot

Sr 01-40 good
Sr 01-40 goodSr 01-40 good
Overview of Computer Graphics
Overview of Computer GraphicsOverview of Computer Graphics
Overview of Computer Graphics
United International University
 
What is OpenGL ?
What is OpenGL ?What is OpenGL ?
What is OpenGL ?
Mohammad Hosein Nemati
 
Flat panel displays
Flat panel displaysFlat panel displays
Flat panel displaysMohd Arif
 
Video display devices
Video display devicesVideo display devices
Video display devicesMohd Arif
 
Introduction to 2D/3D Graphics
Introduction to 2D/3D GraphicsIntroduction to 2D/3D Graphics
Introduction to 2D/3D Graphics
Prabindh Sundareson
 
Hidden surface removal
Hidden surface removalHidden surface removal
Hidden surface removal
Punyajoy Saha
 
Visible surface identification
Visible surface identificationVisible surface identification
Visible surface identification
Pooja Dixit
 
Maps in android
Maps in androidMaps in android
Maps in android
Sumita Das
 
Cohen sutherland line clipping algorithm
Cohen sutherland line clipping algorithmCohen sutherland line clipping algorithm
Cohen sutherland line clipping algorithm
Tawfiq Ahmed
 
Computer Graphics - Introduction and CRT Devices
Computer Graphics - Introduction and CRT DevicesComputer Graphics - Introduction and CRT Devices
Computer Graphics - Introduction and CRT Devices
Hisham Al Kurdi, EAVA, DMC-D-4K, HCCA-P, HCAA-D
 
DIGITAL IMAGE PROCESSING - Visual perception - DAY 2
DIGITAL IMAGE PROCESSING - Visual perception - DAY 2DIGITAL IMAGE PROCESSING - Visual perception - DAY 2
DIGITAL IMAGE PROCESSING - Visual perception - DAY 2
vijayanand Kandaswamy
 
Introduction to computer graphics
Introduction to computer graphicsIntroduction to computer graphics
Introduction to computer graphics
Rajamanickam Gomathijayam
 
COMPUTER GRAPHICS DAY1
COMPUTER GRAPHICS DAY1COMPUTER GRAPHICS DAY1
COMPUTER GRAPHICS DAY1
Barnali Gupta Banik
 
Programming with OpenGL
Programming with OpenGLProgramming with OpenGL
Programming with OpenGL
Syed Zaid Irshad
 
Clipping ( Cohen-Sutherland Algorithm )
Clipping ( Cohen-Sutherland Algorithm )Clipping ( Cohen-Sutherland Algorithm )
Clipping ( Cohen-Sutherland Algorithm )
Harshana Madusanka Jayamaha
 
Random scan displays and raster scan displays
Random scan displays and raster scan displaysRandom scan displays and raster scan displays
Random scan displays and raster scan displays
Somya Bagai
 
Region based segmentation
Region based segmentationRegion based segmentation
Region based segmentation
ramya marichamy
 
4. THREE DIMENSIONAL DISPLAY METHODS
4.	THREE DIMENSIONAL DISPLAY METHODS4.	THREE DIMENSIONAL DISPLAY METHODS
4. THREE DIMENSIONAL DISPLAY METHODS
SanthiNivas
 
Polygon filling
Polygon fillingPolygon filling

What's hot (20)

Sr 01-40 good
Sr 01-40 goodSr 01-40 good
Sr 01-40 good
 
Overview of Computer Graphics
Overview of Computer GraphicsOverview of Computer Graphics
Overview of Computer Graphics
 
What is OpenGL ?
What is OpenGL ?What is OpenGL ?
What is OpenGL ?
 
Flat panel displays
Flat panel displaysFlat panel displays
Flat panel displays
 
Video display devices
Video display devicesVideo display devices
Video display devices
 
Introduction to 2D/3D Graphics
Introduction to 2D/3D GraphicsIntroduction to 2D/3D Graphics
Introduction to 2D/3D Graphics
 
Hidden surface removal
Hidden surface removalHidden surface removal
Hidden surface removal
 
Visible surface identification
Visible surface identificationVisible surface identification
Visible surface identification
 
Maps in android
Maps in androidMaps in android
Maps in android
 
Cohen sutherland line clipping algorithm
Cohen sutherland line clipping algorithmCohen sutherland line clipping algorithm
Cohen sutherland line clipping algorithm
 
Computer Graphics - Introduction and CRT Devices
Computer Graphics - Introduction and CRT DevicesComputer Graphics - Introduction and CRT Devices
Computer Graphics - Introduction and CRT Devices
 
DIGITAL IMAGE PROCESSING - Visual perception - DAY 2
DIGITAL IMAGE PROCESSING - Visual perception - DAY 2DIGITAL IMAGE PROCESSING - Visual perception - DAY 2
DIGITAL IMAGE PROCESSING - Visual perception - DAY 2
 
Introduction to computer graphics
Introduction to computer graphicsIntroduction to computer graphics
Introduction to computer graphics
 
COMPUTER GRAPHICS DAY1
COMPUTER GRAPHICS DAY1COMPUTER GRAPHICS DAY1
COMPUTER GRAPHICS DAY1
 
Programming with OpenGL
Programming with OpenGLProgramming with OpenGL
Programming with OpenGL
 
Clipping ( Cohen-Sutherland Algorithm )
Clipping ( Cohen-Sutherland Algorithm )Clipping ( Cohen-Sutherland Algorithm )
Clipping ( Cohen-Sutherland Algorithm )
 
Random scan displays and raster scan displays
Random scan displays and raster scan displaysRandom scan displays and raster scan displays
Random scan displays and raster scan displays
 
Region based segmentation
Region based segmentationRegion based segmentation
Region based segmentation
 
4. THREE DIMENSIONAL DISPLAY METHODS
4.	THREE DIMENSIONAL DISPLAY METHODS4.	THREE DIMENSIONAL DISPLAY METHODS
4. THREE DIMENSIONAL DISPLAY METHODS
 
Polygon filling
Polygon fillingPolygon filling
Polygon filling
 

Similar to OpenGL

Mini Project final report on " LEAKY BUCKET ALGORITHM "
Mini Project final report on " LEAKY BUCKET ALGORITHM "Mini Project final report on " LEAKY BUCKET ALGORITHM "
Mini Project final report on " LEAKY BUCKET ALGORITHM "
Nikhil Jain
 
Lab Practices and Works Documentation / Report on Computer Graphics
Lab Practices and Works Documentation / Report on Computer GraphicsLab Practices and Works Documentation / Report on Computer Graphics
Lab Practices and Works Documentation / Report on Computer Graphics
Rup Chowdhury
 
openGL basics for sample program (1).ppt
openGL basics for sample program (1).pptopenGL basics for sample program (1).ppt
openGL basics for sample program (1).ppt
HIMANKMISHRA2
 
openGL basics for sample program.ppt
openGL basics for sample program.pptopenGL basics for sample program.ppt
openGL basics for sample program.ppt
HIMANKMISHRA2
 
OpenGL Introduction
OpenGL IntroductionOpenGL Introduction
OpenGL Introduction
Jayant Mukherjee
 
1 introduction computer graphics
1 introduction computer graphics1 introduction computer graphics
1 introduction computer graphics
cairo university
 
18csl67 vtu lab manual
18csl67 vtu lab manual18csl67 vtu lab manual
18csl67 vtu lab manual
NatsuDragoneel5
 
Computer Graphics with OpenGL presentation Slides.pptx
Computer Graphics with OpenGL presentation Slides.pptxComputer Graphics with OpenGL presentation Slides.pptx
Computer Graphics with OpenGL presentation Slides.pptx
AnandM62785
 
Computer Graphics Project Report on Sinking Ship using OpenGL
Computer Graphics Project Report on Sinking Ship using OpenGL Computer Graphics Project Report on Sinking Ship using OpenGL
Computer Graphics Project Report on Sinking Ship using OpenGL
Sharath Raj
 
3 CG_U1_P2_PPT_3 OpenGL.pptx
3 CG_U1_P2_PPT_3 OpenGL.pptx3 CG_U1_P2_PPT_3 OpenGL.pptx
3 CG_U1_P2_PPT_3 OpenGL.pptx
ssuser255bf1
 
Chapter02 graphics-programming
Chapter02 graphics-programmingChapter02 graphics-programming
Chapter02 graphics-programming
Mohammed Romi
 
Arkanoid Game
Arkanoid GameArkanoid Game
Arkanoid Game
graphitech
 
Hill ch2ed3
Hill ch2ed3Hill ch2ed3
Hill ch2ed3
Kunal Verma
 
applets.pptx
applets.pptxapplets.pptx
applets.pptx
yashodamb
 
Lecture 6 introduction to open gl and glut
Lecture 6   introduction to open gl and glutLecture 6   introduction to open gl and glut
Lecture 6 introduction to open gl and glut
simpleok
 
Opengl (1)
Opengl (1)Opengl (1)
Opengl (1)
ch samaram
 
Segment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptxSegment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptx
JeoJoyA
 
The Ring programming language version 1.8 book - Part 60 of 202
The Ring programming language version 1.8 book - Part 60 of 202The Ring programming language version 1.8 book - Part 60 of 202
The Ring programming language version 1.8 book - Part 60 of 202
Mahmoud Samir Fayed
 

Similar to OpenGL (20)

Mini Project final report on " LEAKY BUCKET ALGORITHM "
Mini Project final report on " LEAKY BUCKET ALGORITHM "Mini Project final report on " LEAKY BUCKET ALGORITHM "
Mini Project final report on " LEAKY BUCKET ALGORITHM "
 
Lab Practices and Works Documentation / Report on Computer Graphics
Lab Practices and Works Documentation / Report on Computer GraphicsLab Practices and Works Documentation / Report on Computer Graphics
Lab Practices and Works Documentation / Report on Computer Graphics
 
openGL basics for sample program (1).ppt
openGL basics for sample program (1).pptopenGL basics for sample program (1).ppt
openGL basics for sample program (1).ppt
 
openGL basics for sample program.ppt
openGL basics for sample program.pptopenGL basics for sample program.ppt
openGL basics for sample program.ppt
 
OpenGL Introduction
OpenGL IntroductionOpenGL Introduction
OpenGL Introduction
 
1 introduction computer graphics
1 introduction computer graphics1 introduction computer graphics
1 introduction computer graphics
 
18csl67 vtu lab manual
18csl67 vtu lab manual18csl67 vtu lab manual
18csl67 vtu lab manual
 
Computer Graphics with OpenGL presentation Slides.pptx
Computer Graphics with OpenGL presentation Slides.pptxComputer Graphics with OpenGL presentation Slides.pptx
Computer Graphics with OpenGL presentation Slides.pptx
 
Computer Graphics Project Report on Sinking Ship using OpenGL
Computer Graphics Project Report on Sinking Ship using OpenGL Computer Graphics Project Report on Sinking Ship using OpenGL
Computer Graphics Project Report on Sinking Ship using OpenGL
 
3 CG_U1_P2_PPT_3 OpenGL.pptx
3 CG_U1_P2_PPT_3 OpenGL.pptx3 CG_U1_P2_PPT_3 OpenGL.pptx
3 CG_U1_P2_PPT_3 OpenGL.pptx
 
Bai 1
Bai 1Bai 1
Bai 1
 
Chapter02 graphics-programming
Chapter02 graphics-programmingChapter02 graphics-programming
Chapter02 graphics-programming
 
Arkanoid Game
Arkanoid GameArkanoid Game
Arkanoid Game
 
Hill ch2ed3
Hill ch2ed3Hill ch2ed3
Hill ch2ed3
 
Opengl basics
Opengl basicsOpengl basics
Opengl basics
 
applets.pptx
applets.pptxapplets.pptx
applets.pptx
 
Lecture 6 introduction to open gl and glut
Lecture 6   introduction to open gl and glutLecture 6   introduction to open gl and glut
Lecture 6 introduction to open gl and glut
 
Opengl (1)
Opengl (1)Opengl (1)
Opengl (1)
 
Segment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptxSegment Structure Display List in Computer Graphics.pptx
Segment Structure Display List in Computer Graphics.pptx
 
The Ring programming language version 1.8 book - Part 60 of 202
The Ring programming language version 1.8 book - Part 60 of 202The Ring programming language version 1.8 book - Part 60 of 202
The Ring programming language version 1.8 book - Part 60 of 202
 

More from JeoJoyA

Tree (1).pptx
Tree (1).pptxTree (1).pptx
Tree (1).pptx
JeoJoyA
 
Sutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptxSutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptx
JeoJoyA
 
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptxVisible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
JeoJoyA
 
Recursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptxRecursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptx
JeoJoyA
 
Linear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptxLinear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptx
JeoJoyA
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
JeoJoyA
 
Linear and binary search
Linear and binary searchLinear and binary search
Linear and binary search
JeoJoyA
 
Linked list
Linked listLinked list
Linked list
JeoJoyA
 
Tree
TreeTree
Tree
JeoJoyA
 

More from JeoJoyA (9)

Tree (1).pptx
Tree (1).pptxTree (1).pptx
Tree (1).pptx
 
Sutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptxSutherland Hodgman Polygon Clipping Technique.pptx
Sutherland Hodgman Polygon Clipping Technique.pptx
 
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptxVisible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
Visible Surfacte Detection Methods - Z-Buffer and Scanline methods.pptx
 
Recursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptxRecursion Merge Sort Quick Sort.pptx
Recursion Merge Sort Quick Sort.pptx
 
Linear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptxLinear Search Swapping Bubble Sort Binary Search.pptx
Linear Search Swapping Bubble Sort Binary Search.pptx
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
Linear and binary search
Linear and binary searchLinear and binary search
Linear and binary search
 
Linked list
Linked listLinked list
Linked list
 
Tree
TreeTree
Tree
 

Recently uploaded

Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 

Recently uploaded (20)

Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 

OpenGL

  • 1. OpenGL OpenGL is an application programming interface---‘‘API’’ for short---which is merely a software library for accessing features in graphics hardware. It was first developed at Silicon Graphics Computer Systems with Version 1.0 released in July of 1994. Properties • Independent of a computer’s operating or windowing system • OpenGL doesn’t provide any functionality for describing models of three- dimensional objects, or operations for reading image files Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 1
  • 2. Basic OpenGL Program Structure The basic structure of all OpenGL applications is as follows: • Initialize the state associated with how objects should be rendered. • Specify those objects to be rendered. Rendering is the process by which a computer creates an image from models. OpenGL is just one example of a rendering system. Models( or objects) are constructed from geometric primitives such as points, lines, and triangles that are specified by their vertices. OpenGL uses Shaders (or little programs that are specifically compiled for your graphics processing unit) which are special functions that the graphics hardware executes. In OpenGL, there are four shader stages that you can use. The most common are vertex shaders, which process vertex data, and fragment shaders, which operate on the fragments generated by the rasterizer. Both vertex and fragment shaders are required in every OpenGL program. The final generated image consists of Pixels drawn on the screen; a pixel is the smallest visible element on your display. The pixels in your system are stored in a framebuffer. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 2
  • 3. Basic OpenGL Program Structure In the preamble of the program, we include the appropriate header files and declare global variables1 and other useful programming constructs. The init() routine is used to set up data for use later in the program. This may be vertex information for later use when rendering. The display() routine is what really does the rendering. Almost all display() routines will do the same three steps 1. Clear the window by calling glClear(). 2. Issue the OpenGL calls required to render your object. 3. Request that the image is presented to the screen. Finally, main() does the heavy lifting of creating a window, calling init(), and finally entering into the event loop. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 3
  • 4. OpenGL Pipeline OpenGL begins with the geometric data you provide (vertices and geometric primitives) and first processes it through a sequence of shader stages: vertex shading, tessellation shading (which itself uses two shaders), and finally geometry shading, before it’s passed to the rasterizer. The rasterizer will generate fragments for any primitive that’s inside of the clipping region, and execute a fragment shader for each of the generated fragments. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 4
  • 5. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 5
  • 6. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 6
  • 7. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 7
  • 8. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 8
  • 9. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 9
  • 10. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 10
  • 11. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 11
  • 12. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 12
  • 13. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 13
  • 14. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 14
  • 15. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 15
  • 16. Glut routines for Window Management • glutInit(int *argc, char **argv) initializes GLUT and processes any command line arguments. glutInit() should be called before any other GLUT routine. • glutInitDisplayMode(unsigned int mode) specifies whether to use an RGBA or color-index color model. You can also specify whether you want a single- or double-buffered window. (If you're working in color-index mode, you'll want to load certain colors into the color map; use glutSetColor() to do this.) Finally, you can use this routine to indicate that you want the window to have an associated depth, stencil, and/or accumulation buffer. For example, if you want a window with double buffering, the RGBA color model, and a depth buffer, you might call glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH). Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 16
  • 17. Glut routines for Window Management • glutInitWindowPosition(int x, int y) specifies the screen location for the upper-left corner of your window. • glutInitWindowSize(int width, int size) specifies the size, in pixels, of your window. • int glutCreateWindow(char *string) creates a window with an OpenGL context. It returns a unique identifier for the new window. Be warned: Until glutMainLoop() is called (see next section), the window is not yet displayed. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 17
  • 18. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 18
  • 19. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 19
  • 20. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 20
  • 21. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 21
  • 22. OpenGL Geometric Primitives Polygon Types GL_POLYGON -- draws a polygon from vertex v0 to vn-1 GL_QUADS -- draws a series of separate four-sided polygons GL_TRIANGLES -- draws a series of separate three-sided polygons GL_QUAD_STRIP -- draws a strip of connected quadrilaterals GL_TRIANGLE_STRIP -- draws a strip of connected triangles GL_TRIANGLE_FAN -- draws a strip of triangles connected about a common origin Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 22
  • 23. Sierpinski Gasket - Algorithm 1. Pick an initial point (x, y, z) at random inside the triangle 2. Select one of the three vertices of the triangle at random 3. Find the location halfway between the initial point and the randomly selected vertex. 4. Display the new point 5. Replace the point(x, y, z) with this new point 6. Return to step 2 Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 23
  • 24. Line Attributes • Color, thickness, stippling. • glColor3f() sets color. • glLineWidth(4.0) sets thickness. The default thickness is 1.0. a). thin lines b). thick lines c). stippled lines Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 24
  • 25. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 25
  • 26. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 26
  • 27. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 27
  • 28. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 28
  • 29. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 29
  • 30. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 30
  • 31. Sample Program #include <GL/gl.h> #include <GL/glut.h> void display(void) { /* clear all pixels */ glClear(GL_COLOR_BUFFER_BIT); /* draw white polygon (rectangle) with corners at (0.25, 0.25, 0.0) and (0.75, 0.75, 0.0) */ glColor3f(1.0, 1.0, 1.0); glBegin(GL_POLYGON); glVertex3f(0.25, 0.25, 0.0); glVertex3f(0.75, 0.25, 0.0); glVertex3f(0.75, 0.75, 0.0); glVertex3f(0.25, 0.75, 0.0); glEnd(); /* don't wait! start processing buffered OpenGL routines */ glFlush(); } Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 31
  • 32. Sample Program void init(void) { /* select clearing (background) color */ glClearColor(0.0, 0.0, 0.0, 0.0); /* initialize viewing values */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); } Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 32
  • 33. Sample Program /* Declare initial window size, position, and display mode (single buffer and RGBA). Open window with "hello" in its title bar. Call initialization routines. Register callback function to display graphics. Enter main loop and process events. */ int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(250, 250); glutInitWindowPosition(100, 100); glutCreateWindow("hello"); init(); glutDisplayFunc(display); glutMainLoop(); return 0; } Output: Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 33
  • 34. glMatrixMode(mode) • Specifies which matrix is the current matrix There are actually only three things you can pass to glMatrixMode: • glMatrixMode(GL_MODELVIEW); is the common case. This makes all subsequent matrix operations affect the "gl_ModelViewMatrix", which is primarily used for model setup (for example, shrinking the car model to fit next to the building model). • glMatrixMode(GL_PROJECTION); switches to the projection matrix, "gl_ProjectionMatrix". The projection matrix's job is usually to perform the perspective divide. • glMatrixMode(GL_TEXTURE); switches to the texture matrix. This can be used to adjust the texture coordinates you pass in. To find out which matrix stack is currently the target of all matrix operations, call glGet with argument GL_MATRIX_MODE. The initial value is GL_MODELVIEW. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 34
  • 35. The projection matrix is used to create your viewing volume. Imagine a scene in the real world. You don’t really see everything around you, only what your eyes allow you to see. So when we say that we set up the projection matrix we mean that we set up what we want to see from the scene that we create. I mean you can draw objects anywhere in your world. If they are not inside the view volume you won’t see anything. When you create the view volume imagine that you create 6 clipping planes that define your field of view. glMatrixMode(mode) The modelview matrix is used to make various transformations to the models (objects) in your world. Like this you only have to define your object once and then translate it or rotate it or scale it. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 35
  • 36. OpenGL Matrix Manipulation OpenGL has a whole set of useful utility routines that act on the current matrix (as set by glMatrixMode): •glLoadIdentity();Cleans out the current matrix, replacing it with the identity •glTranslatef(dx,dy,dz);Shifts the origin of the current coordinate system. •glScalef(sx,sy,sz);Scales the current coordinate system. Scaling by a big value makes stuff bigger. You can also mirror stuff by scaling by a negative value. •glRotatef(ang,x,y,z);Rotate by ang degrees right-handed around the vector x,y,z. For example, glRotatef(45.0,0,0,1); rotates the stuff onscreen by 45 degrees counterclockwise. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 36
  • 37. OpenGL Transformations Translation: Translation refers to moving an object to a different position on the screen. The OpenGL function is glTranslatef( tx, ty, tz ), where tx, ty and tz are translation distances along the three axes Rotation: Rotation refers to rotating a point. The OpenGL function is glRotatef (A, x, y, z), where A is the angle of rotation The above formula will rotate the point around the origin through an angle A. Scaling: Scaling refers to zooming in and out an object on different scales across axes. The OpenGL function is glScalef(float x, float y, float z) Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 37
  • 38. OpenGL Transformation Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 38
  • 39. Viewing: Camera Analogy Positioning the Camera Positioning the Model Choose a camera lens and adjust zoom Mapping to screen Viewing Transformation Modeling Transformation Projection Transformation Viewport Transformation Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 39
  • 40. Viewport Transformation • Indicates the shape of the available screen area into which the scene is mapped • Since viewport specifies the region the image occupies on the computer screen, you can think of the viewport transformation as defining the size and location of the final processed photograph - for example, whether the photograph should be enlarged or shrunk. • If the window changes size, the viewport needs to change accordingly void glViewport( int x, int y, int width, int height); Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 40
  • 41. Viewport transformation glViewport( 0, 0, width, height); Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 41
  • 42. Projection Perspective v/s Orthographic Objects which are far away are smaller than those nearby; Does not preserve the shape of the objects. Perspective view points give more information about depth; Easier to view because you use perspective views in real life. Useful in architecture, game design, art etc. All objects appear the same size regardless the distance; Orthographic views make it much easier to compare sizes of the objects. It is possible to accurately measure the distances All views are at the same scale Very useful for cartography, engineering drawings, machine parts. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 42
  • 43. Projection transformation glMatrixMode(GL_PROJECTION); glLoadIdentity(); //perspective projection glFrustum(left, right, bottom, top, near, far); Or //orthographic projection glOrtho (left, right, bottom, top, near, far); Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 43
  • 44. Perspective Transformation //perspective projection void glFrustum(double left, double right, double bottom, double top, double near, double far); Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 44
  • 45. Perspective Transformation Four sides of the frustum, its top, and its base correspond to the six clipping planes of the viewing volume. Objects or parts of objects outside these planes are clipped from the final image Does not have to be symmetrical Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 45
  • 46. Perspective Transformation //perspective projection void gluPerspective( double fovy, double aspect, double near, double far); Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 46
  • 47. Orthographic Transformation //orthographic projection void glOrtho( double left, double right, double bottom, double top, double near, double far); Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 47
  • 48. Modelview Matrix //perspective projection void gluLookAt(double eyeX, double eyeY, double eyeZ, double centerX, double centerY, double centerZ, double upX, double upY, double upZ); Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 48
  • 49. Setting up the scene void init(void) { /* called once to set up basic opengl state */ glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); /* Set up the projection matrix */ glLoadIdentity(); // left,right,bottom,top,near,far glFrustum(-1.0, 1.0, -1.0, 1.0, 1., 10.0); // perspective view // glOrtho (-1.0, 1.0, -1.0, 1.0, 1., 10.0); // orthographic view // gluPerspective(45.0f, 1., 1., 10.); // perspective view glMatrixMode(GL_MODELVIEW); /* Set up the model view matrix */ glLoadIdentity(); eye center up-direction gluLookAt(0.,0.,2.,0.,0.,0.,0.,1.,0.); /* Camera position */ } Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 49
  • 50. Additional GLUT callback routines GLUT supports many different callback actions, including: glutDisplayFunc()defines the function that sets up the image on the screen glutReshapeFunc() function is called when the size of the window is changed glutKeyBoardFunc() callback routine to respond on keyboard entry glutMouseFunc() callback to respond on pressing the mouse button glutMotionFunc() callback to respond mouse move while a mouse button is pressed glutPassiveMouseFunc() callback to respond to mouse motion regardless state of mouse button glutIdleFunc() callback routine for idle state, usually used for animation More info: http://www.opengl.org/resources/libraries/glut/spec3/node45.html Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 50
  • 51. Additional GLUT callback routines int main(int argc, char **argv) { . . . /* Set callback function that responds on keyboard pressing */ glutKeyboardFunc (keypress); . . . } /* keyboard callback routine */ void keypress( unsigned char key, int x, int y) { if (key == 'q' || key =='Q' || key ==27)exit(0); // exit } Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 51
  • 52. Callback routines & Window Resizing int main(int argc, char **argv) { . . . /* Set display as a callback for the current window */ glutDisplayFunc(display); /* Set callback function that respond to resizing the window */ glutReshapeFunc(resize); /* Set callback function that responds on keyboard pressing */ glutKeyboardFunc(keypress); /* Set callback function that responds on the mouse click */ glutMouseFunc(mousepress); . . . } Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 52
  • 53. Callback routines & Window Resizing void keypress( unsigned char key, int x, int y) { … } void mousepress( int button, int state, int x, int y) { … } void resize(int width, int height) { double aspect; glViewport(0,0,width,height); /* Reset the viewport */ aspect = (double)width / (double)height; /* compute aspect ratio*/ glMatrixMode(GL_PROJECTION); glLoadIdentity(); //reset projection matrix if (aspect < 1.0) { glOrtho(-4., 4., -4./aspect, 4./aspect, 1., 10.); } else { glOrtho(-4.*aspect, 4.*aspect, -4., 4., 1., 10.); } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0., 0., 5., 0., 0., 0., 0., 1., 0.); } Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 53
  • 54. Skeleton Event-driven Program // include OpenGL libraries void main() { glutDisplayFunc(myDisplay); // register the redraw function glutReshapeFunc(myReshape); // register the reshape function glutMouseFunc(myMouse); // register the mouse action function glutMotionFunc(myMotionFunc); // register the mouse motion function glutKeyboardFunc(myKeyboard); // register the keyboard action function …perhaps initialize other things… glutMainLoop(); // enter the unending main loop } …all of the callback functions are defined here Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 54
  • 55. Callback Functions • glutDisplayFunc(myDisplay); • (Re)draws screen when window opened or another window moved off it. • glutReshapeFunc(myReshape); • Reports new window width and height for reshaped window. (Moving a window does not produce a reshape event.) • glutIdleFunc(myIdle); • when nothing else is going on, simply redraws display using void myIdle() {glutPostRedisplay();} Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 55
  • 56. Callback Functions • glutMouseFunc(myMouse); • Handles mouse button presses. Knows mouse location and nature of button (up or down and which button). • glutMotionFunc(myMotionFunc); • Handles case when the mouse is moved with one or more mouse buttons pressed. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 56
  • 57. Callback Functions • glutPassiveMotionFunc(myPassiveMotionFunc) • Handles case where mouse enters the window with no buttons pressed. • glutKeyboardFunc(myKeyboardFunc); • Handles key presses and releases. Knows which key was pressed and mouse location. • glutMainLoop() • Runs forever waiting for an event. When one occurs, it is handled by the appropriate callback function. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 57
  • 58. What the Call-back functions do? • The call-back functions you write are registered, and then the program enters an endless loop, waiting for events to occur. • When an event occurs, GL calls the relevant handler function. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 58
  • 59. Simple User Interaction with Mouse and Keyboard • Register functions: • glutMouseFunc (myMouse); • glutKeyboardFunc (myKeyboard); • Write the function(s) • NOTE that any drawing you do when you use these functions must be done IN the mouse or keyboard function (or in a function called from within mouse or keyboard callback functions). Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 59
  • 60. Example Mouse Function • void myMouse(int button, int state, int x, int y); • Button is one of GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, or GLUT_RIGHT_BUTTON. • State is GLUT_UP or GLUT_DOWN. • X and y are mouse position at the time of the event. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 60
  • 61. Example Mouse Function • The x value is the number of pixels from the left of the window. • The y value is the number of pixels down from the top of the window. • In order to see the effects of some activity of the mouse or keyboard, the mouse or keyboard handler must call either myDisplay() or glutPostRedisplay(). Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 61
  • 62. Using Mouse Motion Functions • glutMotionFunc(myMovedMouse); // moved with button held down • glutPassiveMotionFunc(myMovedMouse); // moved with buttons up • myMovedMouse(int x, int y); x and y are the position of the mouse when the event occurred. • Code for drawing rubber rectangles using these functions is in Fig. 2.41. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 62
  • 63. Example Keyboard Function void myKeyboard(unsigned char theKey, int mouseX, int mouseY) { GLint x = mouseX; GLint y = screenHeight - mouseY; // flip y value switch(theKey) {case ‘p’: drawDot(x, y); break; // draw dot at mouse position case ‘E’: exit(-1); //terminate the program default: break; // do nothing } } Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 63
  • 64. Example Keyboard Function • Parameters to the function will always be (unsigned char key, int mouseX, int mouseY). • The y coordinate needs to be flipped by subtracting it from screenHeight. • Body is a switch with cases to handle active keys (key value is ASCII code). • Remember to end each case with a break! Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 64
  • 65. Using Menus • Both GLUT and GLUI make menus available. • GLUT menus are simple, and GLUI menus are more powerful. • We will build a single menu that will allow the user to change the color of a triangle, which is undulating back and forth as the application proceeds. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 65
  • 66. GLUT Menu Callback Function • Int glutCreateMenu(myMenu); returns menu ID • void myMenu(int num); //handles choice num • void glutAddMenuEntry(char* name, int value); // value used in myMenu switch to handle choice • void glutAttachMenu(int button); // one of GLUT_RIGHT_BUTTON, GLUT_MIDDLE_BUTTON, or GLUT_LEFT_BUTTON • Usually GLUT_RIGHT_BUTTON Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 66
  • 67. GLUT Menu-Example • int submenu1, submenu2; • submenu1 = glutCreateMenu(mymenu); • glutAddMenuEntry("abc", 1); • glutAddMenuEntry("ABC", 2); • submenu2 = glutCreateMenu(selectColor); • glutAddMenuEntry("Green", 1); • glutAddMenuEntry("Red", 2); • glutAddMenuEntry("White", 3); • glutCreateMenu(selectFont); • glutAddMenuEntry("9 by 15", 0); • glutAddMenuEntry("Times Roman 10", 1); • glutAddMenuEntry("Times Roman 24", 2); glutAddSubMenu("Messages", submenu1); • glutAddSubMenu("Color", submenu2); glutAttachMenu(Glut.GLUT_RIGHT_BUTTON); Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 67
  • 68. GLUT SubMenu • Create a subMenu first, using menu commands, then add it to main menu. • A submenu pops up when a main menu item is selected. • glutAddSubMenu (char* name, int menuID); // menuID is the value returned by glutCreateMenu when the submenu was created Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 68
  • 69. Using GLUT Menus: Overview • What we can do with menus: • We can create (and destroy) menu data structures. • We can add entries (and submenus) to a previously created menu. • We can attach a previously created menu to a mouse button (and we can also detach it). • We can change the entries of a menu. • The first three above are illustrated in creature.cpp. We will look at these in detail shortly. • Each menu has a callback associated with it: the handler function. This function is called when the user selects an entry in that menu. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 69
  • 70. Using GLUT Menus: Menu Creation • Creating a Menu • Creating a menu means creating a data structure in memory; nothing is displayed yet. • GLUT manages the data structure. • When we create a menu, we also register the handler callback function. • The initialization function (“init”) is a good place to create your menus. • To create a menu, call glutCreateMenu. • This function takes one parameter: • A pointer to the handler callback function for this menu. • A menu handler function takes one int parameter and returns void; more on this later. • Example: glutCreateMenu(handle_menu); Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 70
  • 71. • We can add entries to the end of the current menu. • What is the current menu? For now, if you have created one menu, then it is the current menu (similarly, if you have one window, then it is the current window). • To add an entry, call glutAddMenuEntry. • This function takes two parameters: • A char* (C-style string) that gives the text of the entry. • If you are using the C++ string class, you can pass a C-style string using the .c_str() member function. • An int that is passed to the handler function when the user selects this entry. • Example: glutAddMenuEntry("Toggle eye color", 1); Adding Entries to a Menu Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 71
  • 72. Using GLUT Menus: Attaching • Attaching a Menu to a Mouse Button • We can attach the current menu to a mouse button in the current window. • To attach a menu, call glutAttachMenu. • This function takes one parameter: • An int indicating which mouse button to attach to. • Example: glutAttachMenu(GLUT_RIGHT_BUTTON); • Once we attach a menu, the user can use it. • Whenever they want, the user pops up the menu with the appropriate mouse action. • We do not draw the menu; GLUT does this for us. • When a menu entry is selected, the handler function is called, with the proper number as a parameter. • Since a menu is attached in the current window, do not attach a menu until you have created a window. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 72
  • 73. Using GLUT Menus: Example • The following is called in function init. void make_main_menu() { glutCreateMenu(handle_main_menu); glutAddMenuEntry("Toggle eye color", 1); glutAddMenuEntry("Toggle mouth motion", 2); glutAddMenuEntry("Quit", 3); glutAddMenuEntry("------------------------", 999); … glutAddMenuEntry("for CS 381, fall 2003", 999); glutAttachMenu(GLUT_RIGHT_BUTTON); } • Value passed to handler callback can be the same for multiple entries. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 73
  • 74. Using GLUT Menus: Example • Here is part of the handler callback function (declared before make_main_menu!). // handle_main_menu // Menu handling callback function for our menu void handle_main_menu(int value) { switch (value) { case 1: // Toggle eye color blueeyes = !blueeyes; glutPostRedisplay(); break; … case 3: // Quit exit(0); break; case 999: // Other menu items do nothing break; • Menu handlers, like keyboard functions, typically consist of one switch statement. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 74
  • 75. • Now, we quickly look at a few more advanced topics. We will discuss some of these in more detail later on. • GLUT Menus: • The “current menu”. • Submenus. • Changing menu entries. • Thoughts on menus in general: • What are submenus for? • On changing menus. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 75
  • 76. More on Menus: GLUT — The Current Menu • Some GLUT menuing commands (e.g., glutAddMenuEntry, glutAttachMenu) deal with the current menu. • If you have just one menu, then it is the current menu. • glutCreateMenu sets the current menu to the menu created. • In a menu handler, the current menu is the one handled. • Function glutCreateMenu returns an int identifying the menu created. If you have multiple menus, save this value. int menu_x = glutCreateMenu(handle_menu_x); • You can set the current menu yourself using glutSetMenu. • There is also a “current window”. It is dealt with similarly. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 76
  • 77. • A submenu is a menu that is an item in another menu. • To make a submenu (in the “main” menu): • Create the submenu (as an ordinary menu, but do not attach it). • Create the main menu. • Use glutAddSubMenu to make submenu an item in the main menu. int superduper_menu = glutCreateMenu(handle_superduper_menu); … int rightmouse_menu = glutCreateMenu(handle_rightmouse_menu); glutAddSubMenu("Super-Duper Stuff", superduper_menu); • The submenu does not need to be attached. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 77
  • 78. More on Menus: GLUT — Changing Menu Entries • To change the text or return value of a menu entry: • Set the the current menu, by passing the proper ID to glutSetMenu. • If you are in the menu handler, this is unnecessary. glutSetMenu(superduper_menu); • Use glutChangeToMenuEntry to set the new text & return value. This function takes 3 parameters: • The entry number (int): count from the top of the menu, starting at 1. • The new text (char*). • The new return value (int). glutChangeToMenuEntry(1, the_entry.c_str(), 1); • You can also change submenus, using glutChangeToSubMenu; see the GLUT documentation. Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 78
  • 79. OpenGL Display Lists - Example // create one display list int index = glGenLists(1); // compile the display list glNewList(index, GL_COMPILE); glBegin(GL_TRIANGLES); glVertex3fv(v0); glVertex3fv(v1); glVertex3fv(v2); glEnd(); glEndList(); ... // draw the display list glCallList(index); ... // delete it if it is not used any more glDeleteLists(index, 1); Prof. Jeo Joy A, Dept. of Computer Science(UG), Kristu Jayanti College(Autonomous) Bengaluru 79

Editor's Notes

  1. Viewing: Camera Analogy