Download presentation
Presentation is loading. Please wait.
1
Introduction to OpenGL
Computer Graphic Introduction to OpenGL
2
What is OpenGL? OpenGL is a software interface to graphics hardware. You can use to specify the objects and operations needed to produce interactive three-dimensional applications OpenGL is designed as a hardware-independent interface to be implemented on many different hardware platforms.
3
What is OpenGL? powerful but primitive set of rendering commands
• The most popular raster graphics library, providing a powerful but primitive set of rendering commands • Already supported by every window systems • OpenGL Utility Library (GLU) : higher-level routines, part of OpenGL implementation – Setting up matrices for specific viewing orientations and projections – Performing polygon tessellation and rendering surfaces • OpenGL Utility Toolkit (GLUT): window-system independent high-level library. Need to install this library separately.
4
What is OpenGL? • Install OpenGL Utility Toolkit (GLUT) for MS Windows
– Download GLUT from – Unzip the package – Set “include directory” and “lib directory” in the C Compiler to include the directory containing glut.h, glut.lib – Copy glut32.dll into directory DRIVE:\WINNT\SYSTEM • Add #include <glut.h> to the beginning of the program
5
OpenGL • OpenGL Programming Guide:
– 60/openGL/install/theredbook.zip • Nate Robins’ OpenGL Tutors –
6
OpenGL Libraries In order to write a VC++ application using GLUT you'll need three files: 1- glut.h - You'll have to include This is the file in your source code. The common place to put this file is in C:\Program Files\Microsoft Visual\ Studio\VC98 \ Include \GL folder. 2- glut.lib and glut32.lib This file must be linked to your application so make sure to put it your lib folder. 3- glut32.dll and glut.dll - choose one according to the OpenGL you're using. If using Microsoft's version then you must choose glut32.dll. You should place the dll file in your system folder.
7
Setup In the "Project options" textbox replace "subsystem:console"
With "subsystem:windows" The following files to the Object/library modules: opengl32.lib glut32.lib glu32.lib
8
Compilation on Windows
Visual C++ – Get glut.h, glut32.lib and glut32.dll from web – Create a console application – Add opengl32.lib, glut32.lib, glut32.lib to project settings (under link tab)
9
Programming with OpenGL Part 1: Background
10
OpenGL Functions Primitives Attributes : color ,texture, and font size
Points Line Segments Polygons Attributes : color ,texture, and font size Transformations Viewing Modeling Control Input (GLUT)
11
GLUT Basics Application Structure Configure and open window
Initialize OpenGL state Register input callback functions render resize input: keyboard, mouse, etc. Enter event processing loop Here’s the basic structure that we’ll be using in our applications. This is generally what you’d do in your own OpenGL applications. The steps are: 1) Choose the type of window that you need for your application and initialize it. 2) Initialize any OpenGL state that you don’t need to change every frame of your program. This might include things like the background color, light positions and texture maps. 3) Register the callback functions that you’ll need. Callbacks are routines you write that GLUT calls when a certain sequence of events occurs, like the window needing to be refreshed, or the user moving the mouse. The most important callback function is the one to render your scene, which we’ll discuss in a few slides. 4) Enter the main event processing loop. This is where your application receives events, and schedules when callback functions are called.
12
OpenGL State OpenGL is a state machine
OpenGL functions are of two types Primitive generating Can cause output if primitive is visible How vertices are processes and appearance of primitive are controlled by the state State changing Transformation functions Attribute functions
13
Lack of Object Orientation
OpenGL is not object oriented so that there are multiple functions for a given logical function, e.g. glVertex3f, glVertex2i, glVertex3dv,….. Underlying storage mode is the same Easy to create overloaded functions in C++ but issue is efficiency
14
Preliminaries Headers Files Libraries Enumerated Types
#include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> Libraries Enumerated Types OpenGL defines numerous types for compatibility GLbyte, GLshort, GLushort, GLint, GLuint, GLsizei, GLfloat, GLdouble, GLclampf, GLclampd, GLubyte, GLboolean, GLenum, GLbitfield All of our discussions today will be presented in the C computer language. For C, there are a few required elements which an application must do: Header files describe all of the function calls, their parameters and defined constant values to the compiler. OpenGL has header files for GL (the core library), GLU (the utility library), and GLUT (freeware windowing toolkit). Note: glut.h includes gl.h and glu.h. On Microsoft Windows, including only glut.h is recommended to avoid warnings about redefining Windows macros. Libraries are the operating system dependent implementation of OpenGL on the system you’re using. Each operating system has its own set of libraries. For Unix systems, the OpenGL library is commonly named libGL.so and for Microsoft Windows, it’s named opengl32.lib. Finally, enumerated types are definitions for the basic types (i.e. float, double, int, etc.) which your program uses to store variables. To simplify platform independence for OpenGL programs, a complete set of enumerated types are defined. Use them to simplify transferring your programs to other operating systems.
15
Program Structure Most OpenGL programs have a similar structure that consists of the following functions main(): defines the callback functions opens one or more windows with the required properties enters event loop (last executable statement) init(): sets the state variables viewing Attributes callbacks Display function Input and window functions
16
The Main Program We begin with the basic elements of how to create a window. OpenGL was intentionally designed to be independent of any Specific window system. As a result, a number of the basic window operations are not provided in OpenGL. Therefore, a separate library called GLUT or OpenGL Utility Toolkit was created to provide these functions. Basically, GLUT provides the necessary tools for requesting windows to be created and providing interaction with I/O devices
17
Opening a Window Using GLUT
#include<windows.h> #include <GL/glut.h> void main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutCreateWindow("simple"); init(); glutDisplayFunc(mydisplay); glutMainLoop(); } includes gl.h Specify the display Mode – RGB or color Index, single or double Buffer define window properties define window starting position set OpenGL state display callback enter event loop
18
GLUT functions glutInit allows application to get command line arguments and initializes system gluInitDisplayMode requests properties of the window (the rendering context) Int mode= GLUT_SINGLE|GLUT_RGB RGB color Single buffering Properties logically ORed together glutWindowSize in pixels glutWindowPosition from top-left corner of display glutCreateWindow create window with title “simple” glutDisplayFunc display callback glutMainLoop enter infinite event loop
19
1- Initialization 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 call the function glutInit. void glutInit(int *argc, char **argv); Parameters: argc argv are the standard ones for passing information about the command line ( not used here)
20
Define our window • After initializing GLUT itself, we're going to define our window. First we establish the window's position, i.e. its top left corner.
21
glutInitWindowPosition(10,50) ;
glutInitPosition() This command specifies the location of the upper left corner of the graphics window. The form is glutInitWindowPosition(int x, int y) where the (x, y) coordinates are given relative to the upper left corner of the display. Thus, the arguments (0, 0) places the window in the upper left corner of the display. glutInitWindowPosition(10,50) ;
22
Window Size Next we'll choose the window size. In order to do this
we use the function glutInitWindowSize. This command specifies the desired width and height of the graphics window. The general form is: glutInitWindowSize(int width, int height) glutInitWindowSize(640, 480); The values are given in numbers of pixels.
23
glutInitDisplayMode()
This function performs initializations informing OpenGL how to set up its frame buffer. The argument to glutInitDisplayMode() is a logical-or (using the operator “|”) of a number of possible options, which are given in Table 1. glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
24
glutCreateWindow() This command actually creates the graphics window. The general form of the command is glutCreateWindowchar(*title) where title is a character string. Each window has a title, and the argument is a string which specifies the window’s title. glutCreateWindow(“ This is my First Program”);
25
Colors • Before you start drawing you will want to set the colour of the window (background) and the colour of the drawing (foreground). • The background and foreground can be changed at anytime during the program. • Colours are specified using a mixture of Red, Green and Blue (RGB). • Each amount of colour is specified by a float value between 0 and 1. – 0 = none of this colour – 1 = all of this colour • A colour is specified as (R,G,B) e.g (1, 0.5, 0.2) • Can you guess what R, G and B are set to for black and white?
26
Color Color in RGBA mode is set by specifying the red, green, blue and alpha intensities. alpha = 1 //opaque alpha = 0 // transparent
27
RGB color Each color component stored separately in the frame buffer
Usually 8 bits per component in buffer Note in glColor3f the color values range from 0.0 (none) to 1.0 (all), while in glColor3ub the values range from 0 to 255
28
Indexed Color Memory inexpensive Need more colors for shading
Colors are indices into tables of RGB values Requires less memory indices usually 8 bits not as important now Memory inexpensive Need more colors for shading
29
Color and State The color as set by glColor becomes part of the state and will be used until changed Colors and other attributes are not part of the object but are assigned when the object is rendered We can create conceptual vertex colors by code such as glColor glVertex
30
Setting of color attribute
glClearColor(1.0, 1.0, 1.0, 0.0); //Clear color for background glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0f, 0.0f, 0.0f);// red // for forground Instead of using one color buffer, two can be used Front Buffer: one that is displayed but not written to Back Buffer: one that is written to but not displayed
31
OpenGL Initalization We’ll use the init() routine for our one-time OpenGL state initialization call after window has been created, but before first rendering call void init( void ) { // set the background color // glClearColor( R, G, B, α ); glClearColor( 1.0, 0.0, 0.0, 1.0 ); }
32
Setting the Background Colour
glClearColor(R, G, B, α); glClearColor(1,0,0,0); glClearColor(0,1,0,0); glClearColor(0,0,1,0);
33
init.c black clear color opaque window void init() {
glClearColor (0.0, 0.0, 0.0, 1.0); ////////////////////////////////////////// glMatrixMode (GL_PROJECTION); glLoadIdentity (); // Viewing in 2D gluOrtho2D(0.0 ,// Left 2.0, // Right 0.0, // Bottom 2.0 // Top); } black clear color opaque window
34
Specifying a Vertex’s Color
Use the OpenGL color command glColor3f( r, g, b ); Where you specify the color determines how the primitive is shaded points only get one color
35
Setting the Foreground Colour
glClear(GL_COLOR_BUFFER_BIT); glColor3f(R, G, B); glColor4f(R, G, B, α);
36
Example of setting color
glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0f, 0.0f, 0.0f);//no alpha value form glBegin( GL_TRIANGLEs); glVertex3f( -1.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f); glVertex3f(0.0f, 1.0f, 0.0f); glEnd(); Note that the glColor*() function can be placed inside a glBegin()/glEnd() pair. Therefore you can specify individual colors for each individual vertex
37
OpenGL Command Notation (1/2)
void glSomeFunction {3} {bsifd} {v} (arguments); the first optional term in curly braces indicates that this function takes 3 arguments. the second sets of braces indicates that this function takes 5 possible argument types b = byte, s = short, I = integer, f = float, d = double the last term in curly braces indicate that a vector form of the command also exists.
38
OpenGL Command Notation (2/2)
glVertex3fv( ... ) Number of components Data Type Vector b - byte ub - unsigned byte s - short us - unsigned short i - int ui - unsigned int f - float d - double omit “v” for scalar form glVertex2f( x, y ) 2 - (x,y) 3 - (x,y,z) 4 - (x,y,z,w)
39
OpenGL function format
function name dimensions glVertex3f(x,y,z) x,y,z are floats belongs to GL library glVertex3fv(p) p is a pointer to an array
40
Specifying an OpenGL Vertex
Recall OpenGL specifies geometric primitives by its vertices glVertex3f( x, y, z ); Different primitives require different numbers of vertices
41
OpenGL Command Syntax OpenGL commands use the prefix gl and initial capital letters for each word making up the command name glClearColor( ) Similarly, OpenGL defined constants begin with GL_, use all capital letters, and used underscores to separate words
42
Command Suffixes and Argument Data Types
43
OpenGL drawing To draw a primitive, call glBegin(Primitive)
glEnd() encloses a list of vertices and their attributes Coordinates of a primitive are given counter-clockwise order
44
OpenGL drawing Between glBegin/ glEnd, those opengl commands are allowed: glVertex*() : set vertex coordinates glColor*() : set current color glIndex*() : set current color index glNormal*() : set normal vector coordinates (Light.) glTexCoord*() : set texture coordinates (Texture)
45
Constructive Primitives
The glBegin() / glEnd() Wrappers all OpenGL descriptions of primitives start with glBegin(xxx), where xxx is an OpenGL-defined constant that identifies the OpenGL primitive.
46
Specifying Geometric Primitives
Primitives are specified using glBegin( primType ); glEnd(); primType determines how vertices are combined GLfloat red, greed, blue; Glfloat coords[3]; glBegin( primType ); for ( i = 0; i < nVerts; ++i ) { glColor3f( red, green, blue ); glVertex3fv( coords ); } glEnd(); OpenGL organizes vertices into primitives based upon which type is passed into glBegin(). The possible types are: GL_POINTS GL_LINE_STRIP GL_LINES GL_LINE_LOOP GL_POLYGON GL_TRIANGLE_STRIP GL_TRIANGLES GL_TRIANGLE_FAN GL_QUADS GL_QUAD_STRIP
47
OpenGL Primitives GL_POINTS GL_POLYGON GL_LINE_STRIP GL_LINES
GL_LINE_LOOP GL_TRIANGLES GL_QUAD_STRIP GL_TRIANGLE_STRIP GL_TRIANGLE_FAN
48
Simple Example Drawing Single Point glBegin(GL_POINTS);
glVertex3f(0.0f, 0.0f, 0.0f); glEnd(); Draw triangle The drawRhombus() routine causes OpenGL to render a single quadrilateral in a single color. The rhombus is planar, since the z value is automatically set to 0.0 by glVertex2f(). glBegin(GL_TRIANGLES); glVertex3f(0.0f, 1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 0.0f); glVertex3f(1.0f, -1.0f, 0.0f); glEnd();
49
Drawing Polygon void mydisplay(){ glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glEnd(); glFlush(); }
50
Draw a triangle with different colors :
glBegin(GL_TRIANGLES); glColor3f(1.0f, 0.0f, 0.0f); //pure red glVertex3f(0.0f, 1.0f, 0.0f); glColor3f(0.0f, 1.0f, 0.0f); //pure green glVertex3f(-1.0f, -1.0f, 0.0f); glColor3f(0.0f, 0.0f, 1.0f); //pure blue glVertex3f(1.0f, -1.0f, 0.0f); glEnd();
51
Rendering Callback Callback function where all our drawing is done
Every GLUT program must have a display callback glutDisplayFunc( my_display_func ); /* this part is in main.c */ void my_display_func (void ) { glClear( GL_COLOR_BUFFER_BIT ); glBegin( GL_TRIANGLE ); glVertex3fv( v[0] ); glVertex3fv( v[1] ); glVertex3fv( v[2] ); glEnd(); glFlush(); }
52
glClear(GL_COLOR_BUFFER_BIT); glBegin( GL_QUADS );
void dispaly( void) { glClear(GL_COLOR_BUFFER_BIT); glBegin( GL_QUADS ); glColor3f( 1.0f,0.0f,0.0f ); glVertex2f( 0.0, 0.0 ); glVertex2f( 1.0, 0.0 ); glVertex2f( 1.5, ); glVertex2f( 0.5, ); glEnd(); glFlush( ); glutSwapBuffers(); } Instead of using one color buffer, two can be used Front Buffer: one that is displayed but not written to Back Buffer: one that is written to but not displayed Program then requests a double buffer in main.c glutInitDisplayMode(GL_RGB | GL_DOUBLE) glutSwapBuffers() waits until the current screen refresh period is over so that the previous buffer is completely displayed and then swaps the buffers.
53
GLUT Callback functions
Event-driven: Programs that use windows Input/Output Wait until an event happens and then execute some pre-defined functions according to the user’s input Events – key press, mouse button press and release, window resize, etc. Your OpenGL program will be in infinite loop
54
GLUT Callback Functions
Callback function : Routine to call when an event happens Window resize or redraw User input (mouse, keyboard) Animation (render many frames) “Register” callbacks with GLUT glutDisplayFunc( my_display_func ); glutIdleFunc( my_idle_func ); glutKeyboardFunc( my_key_events_func ); glutMouseFunc ( my_mouse_events_func );
55
Event Queue Keyboard …. Mouse MainLoop() Window Event queue
Mouse_callback() { …. Keypress_callback() { …. window_callback() { ….
56
Sample Program glutSwapBuffers(); #include <glut.h> void draw(){
glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glEnd(); glFlush(); glutSwapBuffers(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(400, 400); glutCreateWindow(“Sample"); glutDisplayFunc(draw); glutMainLoop(); return 0;
57
Sample Program void main( int argc, char** argv ) {
int mode = GLUT_RGB|GLUT_DOUBLE; glutInitDisplayMode( mode ); glutCreateWindow( argv[0] ); init(); glutDisplayFunc( display ); glutReshapeFunc( resize ); glutKeyboardFunc( key ); glutIdleFunc( idle ); glutMainLoop(); } Here’s an example of the main part of a GLUT based OpenGL application. This is the model that we’ll use for most of our programs in the course. The glutInitDisplayMode() and glutCreateWindow() functions compose the window configuration step. We then call the init() routine, which contains our one-time initialization. Here we initialize any OpenGL state and other program variables that we might need to use during our program that remain constant throughout the program’s execution. Next, we register the callback routines that we’re going to use during our program. Finally, we enter the event processing loop, which interprets events and calls our respective callback routines.
58
Idle Callback Use for animation and continuous update
Can use glutTimerFunc or timed callbacks for animations glutIdleFunc( idle ); void idle( void ) { /* change something */ t += dt; glutPostRedisplay(); }
59
Posting redisplays Many events may invoke the display callback function Can lead to multiple executions of the display callback on a single pass through the event loop We can avoid this problem by instead using glutPostRedisplay(); which sets a flag. GLUT checks to see if the flag is set at the end of the event loop If set then the display callback function is executed
60
User Input Callbacks Process user input
glutKeyboardFunc( my_key_events ); void my_key_events (char key, int x, int y ) { switch ( key ) { case ‘q’ : case ‘Q’ : exit ( EXIT_SUCCESS); break; case ‘r’ : case ‘R’ : rotate = GL_TRUE; }
61
Mouse Callback Captures mouse press and release events
glutMouseFunc( my_mouse ); void myMouse(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) … }
62
GLUT Parameters GLUT parameter names associated with mouse events
63
Events in OpenGL Event Example OpenGL Callback Function Keypress
KeyDown KeyUp glutKeyboardFunc Mouse leftButtonDown leftButtonUp glutMouseFunc Motion With mouse press Without glutMotionFunc glutPassiveMotionFunc Window Moving Resizing glutReshapeFunc System Idle Timer glutIdleFunc glutTimerFunc Software What to draw glutDisplayFunc
64
Shapes Tutorial
65
glBegin(GL_POLYGON); glVertex3f(0.25, 0.25, 0.0);
Program1 .c #include <stdlib.h> #include <GL/glut.h> void display(void) { glColor3f(1.0, 1.0, 1.0); glOrtho(0.0, 1.0, 0.0, 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( ); glFlush( ); glutSwapBuffers(); }
66
void init(void){ glClearColor(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); } int main (int argc, char **argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(250,250); glutInitWindowPosition(0,0); glutCreateWindow(“hello”); init( ); glutDisplayFunc(display); glutMainLoop( ); return 0;
67
// Program 2.c #include <stdlib.h> #include <GL/glut.h> static GLfloat spin = 0.0; void init(void){ glClearColor(0.0, 0.0, 0.0, 0.0); glShadeModel(GL_FLAT); } void display(void){ glClear(GL_COLOR_BUFFER_BIT); glPushMatrix( ); glRotatef(spin, 0.0, 0.0, 1.0); glColor3f(1.0, 1.0, 1.0); glRectf(-25.0, -25.0, 25.0, 25.0); glPopMatrix( ); glutSwapBuffers( );
68
void spinDisplay(void){
spin = spin + 2.0; if(spin > 360.0) spin = spin ; glutPostRedisplay( ); } void reshape(int w, int h){ glViewport(0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity( ); glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW);
69
void mouse(int button, int state, int x, int y){
switch(button){ case GLUT_LEFT_BUTTON: if(state == GLUT_DOWN) glutIdleFunc(spinDisplay); break; case GLUT_RIGHT_BUTTON: glutIdleFunc(NULL); default: }
70
int main(int argc, char ** argv){
glutInit(&argc, argv); // request double buffer mode glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(250,250); glutInitWindowPosition(100,100); glutCreateWindow(argv[0]); init( ); glutDisplayFunc(display); // register window resize callback glutReshapeFunc(reshape); // register mouse callback glutMouseFunc(mouse); glutMainLoop( ); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.