Computer Graphics CSC 830 Lecture notes 2 OpenGL.

Slides:



Advertisements
Similar presentations
OpenGL CMSC340 3D Character Design & Animation. What is OpenGL? A low-level graphics library specification designed for use with the C and C++ provides…
Advertisements

Chapter 2: Graphics Programming
OpenGL (Graphics Library) Software Interface to graphics software Allows to create interactive programs that produce color images of moving 3D objects.
CSC 461: Lecture 51 CSC461 Lecture 5: Simple OpenGL Program Objectives: Discuss a simple program Discuss a simple program Introduce the OpenGL program.
1 Angel: Interactive Computer Graphics 4E © Addison-Wesley 2005 Programming with OpenGL Part 2: Complete Programs Ed Angel Professor of Computer Science,
OpenGL and Projections
Objectives Learn to build arbitrary transformation matrices from simple transformations Learn to build arbitrary transformation matrices from simple transformations.
Interactive 3D Graphics and Virtual Reality Introduction to OpenGL concepts Session 2.
1 Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 GLUT Callback Functions.
CSC461 Lecture 9: GLUT Callbacks Objectives Introduce double buffering for smooth animations Programming event input with GLUT.
3D Rendering with JOGL Introduction to Java OpenGL Graphic Library By Ricardo Veguilla
Introduction to OpenGL M. Ramanathan STTP CAD 2011Introduction to OpenGL.
Introduction to OpenGL Jian Huang This set of slides are extracted from the Interactive OpenGL Programming course given by Dave Shreine, Ed Angel and Vicki.
OpenGL A Brief Overview. What is OpenGL?  It is NOT a programming language.  It is a Graphics Rendering API consisting of a set of function with a well.
Reference1. [OpenGL course slides by Rasmus Stenholt]
CS380 LAB I OpenGL Donghyuk Kim Reference1. [OpenGL course slides by Rasmus Stenholt] Reference2. [
Computer Graphics Bing-Yu Chen National Taiwan University.
1 OpenGL Basics A Graphics Standard ©Mel Slater, Anthony Steed
Basic OpenGL Glenn G. Chappell U. of Alaska Fairbanks CS 381 Lecture Notes Wednesday, September 10, 2003.
Using OpenGL. 2 What is OpenGL? A software interface to graphics hardware It is a Graphics Rendering API (Application Programmer’s Interface) that is.
Using OpenGL in Visual C++ Opengl32.dll and glu32.dll should be in the system folder Opengl32.dll and glu32.dll should be in the system folder Opengl32.lib.
OpenGL A Brief Overview. What is OpenGL? It is NOT a programming language. It is a Graphics Rendering API consisting of a set of functions with a well.
CSE 470: Computer Graphics. 10/15/ Defining a Vertex A 2D vertex: glVertex2f(GLfloat x, GLfloat y); 2D vertexfloating pointopenGL parameter type.
Lecture 3 OpenGL.
Introduction to OpenGL 1. 2 OpenGL A Graphics rendering API introduced in 1992 by Silicon Graphics Inc Provide the low-level functions to access graphics.
Ch 2 Graphics Programming page 1 CSC 367 Coordinate Systems (2.1.2) Device coordinates, or screen coordinates (pixels) put limitations on programmers and.
1. OpenGL/GLU/GLUT  OpenGL v4.0 (latest) is the “core” library that is platform independent  GLUT v3.7 is an auxiliary library that handles window creation,
1 Figures are extracted from Angel's book (ISBN x) The Human Visual System vs The Pinhole camera Human Visual System Visible Spectrum Pinhole.
Computer Graphics Bing-Yu Chen National Taiwan University.
Modeling with OpenGL Practice with OpenGL transformations.
Computing & Information Sciences Kansas State University CIS 536/636 Introduction to Computer Graphics Lecture 4 of 41 William H. Hsu Department of Computing.
OpenGL: Introduction Yanci Zhang Game Programming Practice.
Program 2 due 02/01  Be sure to document your program  program level doc  your name  what the program does  each function  describe the arguments.
Viewing and Transformation. Pixel pipeline Vertex pipeline Course Map Transformation & Lighting Primitive assembly Viewport culling & clipping Texture.
Chapters 5 2 March Classical & Computer Viewing Same elements –objects –viewer –projectors –projection plane.
CGGM Lab. Tan-Chi Ho 2001 Viewing and Transformation.
Chun-Yuan Lin Introduction to OpenGL 2015/12/19 1 CG.
NoufNaief.net TA: Nouf Al-harbi.
GLUT functions glutInit allows application to get command line arguments and initializes system gluInitDisplayMode requests properties for the window.
Chap 3 Viewing and Transformation
OpenGL Basic Drawing 2003 Spring Keng Shih-Ling
Lecture 7 Midterm Review. OpenGL Libraries gl: Basic OpenGL library, e.g. primitives. glu: OpenGL Utility library, a set of functions to create texture.
1 Programming with OpenGL Part 2: Complete Programs.
OpenGL API 2D Graphic Primitives Angel Angel: Interactive Computer Graphics5E © Addison-Wesley
Comp 175C - Computer Graphics Dan Hebert Computer Graphics Comp 175 Chapter 4 Instructor: Dan Hebert.
31/1/2006Based on: Angel (4th Edition) & Akeine-Möller & Haines (2nd Edition)1 CSC345: Advanced Graphics & Virtual Environments Lecture 2: Introduction.
Computer Graphics Comp 175 Chapter 2
OpenGL Basic Drawing Jian-Liang Lin A Smidgen of OpenGL Code #include main() { InitializeAWindowPlease(); glClearColor (0.0, 0.0, 0.0, 0.0); glClear.
Introduction to Graphics Programming. Graphics API.
Introduction to Graphics Programming. Graphics: Conceptual Model Real Object Human Eye Display Device Graphics System Synthetic Model Synthetic Camera.
Computer Graphics I, Fall Programming with OpenGL Part 2: Complete Programs.
1 Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 Working with Callbacks.
INTRODUCTION TO OPENGL
Computer Graphics (Fall 2003) COMS 4160, Lecture 5: OpenGL 1 Ravi Ramamoorthi Many slides courtesy Greg Humphreys.
Computer Graphics Lecture 34. OpenGL Programming II Taqdees A. Siddiqi
Program Studi S-1 Teknik Informatika FMIPA Universitas Padjadjaran
The Human Visual System vs The Pinhole camera
Computer Graphics Lecture 33
Reference1. [OpenGL course slides by Rasmus Stenholt]
Programming with OpenGL Part 2: Complete Programs
Materi Anatomi OpenGL Fungsi GLUT Posisi Kamera Proyeksi
OpenGL API 2D Graphic Primitives
Programming with OpenGL Part 2: Complete Programs
OpenGL (Open Graphics Library) Mr. B.A.Swamy Assistant Professor Dept of CSE.
OpenGL A Brief Overview.
Introduction to OpenGL
Programming with OpenGL Part 2: Complete Programs
Programming with OpenGL Part 2: Complete Programs
Programming with OpenGL Part 2: Complete Programs
OpenGL A Brief Overview.
Presentation transcript:

Computer Graphics CSC 830 Lecture notes 2 OpenGL

What is OpenGL? It is NOT a language. It is a Graphics Rendering API (Application Programmer’s Interface) that is a set of function with well defined interface. Whenever we say that a program is OpenGL-based or OpenGL applications, we mean that it is written in some programming language (such as C/C++ or Java) that makes calls to one or more of OpenGL libraries. OpenGL is Not Object-Oriented. OpenGL API does not make use of features such as overloading that are available in object-oriented languages. -> I will show examples with C language bindings.

A History of OpenGL Was SGI’s Iris GL – basis for “Open”GL “Open” standard allowing for wide range hardware platforms OpenGL v1.0 (1992) OpenGL v1.1 (1995) OpenGL v1.5 (latest) Governed by OpenGL Architecture Review Board (ARB) which has members from such as Silicon Graphics, IBM, and NVIDIA. “Mesa” – an Open source (http://www.mesa3d.org) OpenGL is the premier environment for developing portable, interactive 2D and 3D graphics applications. Since its introduction in 1992, OpenGL has become the industry's most widely used and supported 2D and 3D graphics application programming interface (API), bringing thousands of applications to a wide variety of computer platforms. OpenGL fosters innovation and speeds application development by incorporating a broad set of rendering, texture mapping, special effects, and other powerful visualization functions. Developers can leverage the power of OpenGL across all popular desktop and workstation platforms, ensuring wide application deployment.

Useful Websites and Books Official Site http://www.opengl.org Non official sites http://nehe.gamedev.net/ BOOKS OpenGL : A Primer OpenGL Red Book & OpenGL Blue Book

Useful Links Online Reference manual sites GL and GLU GLUT http://www.mevis.de/~uwe/opengl/opengl.html GLUT http://pyopengl.sourceforge.net/documentation/manual/reference-GLUT.html

Three View of OpenGL Programmer’s view State machine Specifying a set of objects to render Describing properties of these objects Defining how these objects should be viewed State machine Keeps states that affects appearances of input ie. States determines how the inputs are processed. Change state (such as color) by using state changing functions OpenGL uses Rendering Pipeline Model Models -> Transformer -> Clipper -> Projector -> Rasterizer -> Image

OpenGL API Functions OpenGL contains over 200 functions Primitive functions : define the elements (eg. A point, line, polygon, etc) Attribute functions : control the appearance of primitives (eg. colors, line types, light source, textures.) Viewing functions : determine the properties of camera. Transformation Windowing functions: not part of core OpenGL Other functions

Window Management OpenGL is meant to be platform independent. i.e. OpenGL is window and operating system independent. OpenGL does not include any functions for window management, user interaction, and file I/O. Host environment is responsible for window management.

Window Management API We need additional libraries to handle window management GLX/AGL/WGL - glue between OpenGL and windowing systems GLUT - OpenGL Window Interface/Utility toolkit AUX - OpenGL Utility Toolkit

OpenGL API Hierarchy • GL: the “core” library of OpenGL that is platform independent GLX: for the X Windows system, common on Unix platforms • AGL: for the Apple Macintosh • WGL: for Microsoft Windows GLUT, AUX: auxiliary libraries that handle window creation, OS system calls (mouse buttons, movement, keyboard, etc), callbacks. OpenGL also includes a utility library, GLU, to simplify common tasks such as: rendering quadric surfaces (i.e. spheres, cones, cylinders, etc. ), working with NURBS and curves, and concave polygon tessellation. The above diagram illustrates the relationships of the various libraries and window system components. Generally, applications which require more user interface support will use a library designed to support those types of features (i.e. buttons, menu and scroll bars, etc.) such as Motif or the Win32 API. Prototype applications, or one which don’t require all the bells and whistles of a full GUI, may choose to use GLUT instead because of its simplified programming model and window system independence.

OpenGL Division of Labor GL - “core” library of OpenGL that is platform independent GLU - an auxiliary library that handles a variety of graphics accessory functions GLUT/AUX - utility toolkits that handle window managements

Libraries and Headers Library Name Library File Header File Note OpenGL opengl32.lib (PC) -lgl (UNIX) gl.h “core” library Auxiliary library glu32.lib (PC) -lglu glu.h handles a variety of accessory functions Utility toolkits glut32.lib (PC) -lglut (UNIX) glaux.lib (PC) -lglaux (UNIX) glut.h glaux.h window managements 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 (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. All are presented in the C language

Learning OpenGL with GLUT GLUT is a Window Manager (handles window creation, user interaction, callbacks, etc) http://www.opengl.org/resources/libraries/glut/spec3/spec3.html Platform Independent Makes it easy to learn and write OpenGL programs without being distracted by your environment All of our discussions will be presented in C/C++ language

Include Header files Include the necessary header files in your code #include <GL/gl.h> // “core”, the only thing is required #include <GL/glu.h> // handles accessory functions #include <GL/glut.h> // handles window managements void main( int argc, char **argv ) { ….. } Only the “core” library (opengl32.lib, gl.h) are required Only the “core” library (opengl32.lib, gl.h) are required

Link Libraries Link GL library Link GLU library Link GLUT library Link the necessary Libraries to your code Link GL library Link opengl32.lib (PC), or -lgl (UNIX) Link GLU library Link glu32.lib (PC), or -lglu (UNIX) Link GLUT library Link glut32.lib (PC), or -lglut (UNIX) Only the “core” library (opengl32.lib, gl.h) are required

Programming Convention : OpenGL Data Types To make it easier to convert OpenGL code from one platform to another, OpenGL defines its own data types that map to normal C data types To make it easier to port OpenGL code from one platform to another, OpenGL defines its own data types. These data types map to normal C data types that you can use instead. To simplify platform independence for OpenGL programs, a complete set of data types are defined. Use them to simplify transferring your programs to other operating systems. GLshort A[10]; short A[10]; GLdouble B; double B;

Programming Convention : OpenGL Data Types Representation As C Type GLbyte 8-bit integer signed char GLshort 16-bit integer short GLint, GLsizei 32-bit integer long GLfloat 32-bit float float GLdouble 64-bit float double GLubyte, GLboolean 8-bit unsigned integer unsigned char GLushort 16-bit unsigned short unsigned short GLunit, GLenum, GLbitfield 32-bit unsigned integer unsigned long

Programming Convention : OpenGL Function Naming OpenGL functions all follow a naming convention that tells you which library the function is from, and how many and what type of arguments that the function takes <Library prefix><Root command><Argument count><Argument type>

Programming Convention : OpenGL Function Naming glColor3f(…) gl library Root command, # of arguments, type of arguments gl means OpenGL glu means GLU glut means GLUT f: the argument is float type i: the argument is integer type v: the argument requires a vector

Programming Convention : OpenGL Function Naming Multiple forms of OpenGL functions to support the variety of data types glVertex3i(ix, iy, iz) glVertex3f(x, y, z) glVertex2i(ix, iy) glVertex2f(x, y) .. We shall use the notation glVertex*() to refer to all the forms of the vertex function

Basic OpenGL Coding Framework Configure GL (and GLUT) - Open window, Display mode, …… Initialize OpenGL state - background color, light, View positions, …… Register callback functions - Render, Interaction (keyboard, mouse), …… Event processing loop - glutMainLoop()

A Sample Program 1 2 3 4 void main (int argc, char **argv) { glutInit (&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (500, 500); glutCreateWindow (“My First Program"); myinit (); glutDisplayFunc ( display ); glutReshapeFunc ( resize ); glutKeyboardFunc ( key ); glutMainLoop (); } 1 2 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 myinit() 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. 3 4

1: Initializing & Creating Window Set up window/display you’re going to use void main (int argc, char **argv) { glutInit (&argc, argv); // GLUT initialization glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // display model glutInitWindowSize (500, 500); // window size glutCreateWindow (“My First Program"); // create window …… } glutInit(…) initializes the GLUT library. Should be called before any other GLUT routine. glutInitDisplayMode(…) specifies display mode (RGB, RGBA, color-index), and display buffer (single or double) glutInitWindowSize(…) specifies window size. glutCreateWindow(…) create window

GLUT Initializing Functions Standard GLUT initialization void glutInit (int *argc, char ** argv) Display model void glutInitDisplayMode (unsigned int mode) Define color model : GLUT_RGB or GLUT_INDEX Define buffering: GLUT_SINGLE | GLUT_DOUBLE Window size and position void glutInitWindowSize (int width, int height) void glutInitWindowPosition(int x, int y) - top-left corner of the screen in pixel Create window int glutCreateWindow (char *title); glutInit(…) initializes the GLUT library. Should be called before any other GLUT routine. glutInitDisplayMode(…) specifies display mode (RGB, RGBA, color-index), and display buffer (single or double) glutInitWindowSize(…) specifies window size. glutCreateWindow(…) create window

2: Initializing OpenGL State Set up whatever state you’re going to use void myinit(void) { glClearColor(1.0, 1.0, 1.0, 1.0); // background color glColor3f(1.0, 0.0, 0.0); // line color glMatrixMode(GL_PROJECTION); // followings set up viewing glLoadIdentity(); gluOrtho2D(0.0, 500.0, 0.0, 500.0); glMatrixMode(GL_MODELVIEW); } Set up whatever state you’re going to use Here’s the internals of the initialization routine, myinit(). Over the course, you’ll learn what each of the above OpenGL calls do.

Event Loops and Callback Functions Interactive programs react to the events such as mouse or keyboard events and window events. Callback Function - Routine to call when something happens (eg. window resize, redraw, user input, etc) GLUT uses a callback mechanism to do its event processing GLUT uses a callback mechanism to do its event processing. Callbacks simplify event processing for the application developer. As compared to more traditional event driven programming, where the author must receive and process each event, and call whatever actions are necessary, callbacks simplify the process by defining what actions are supported, and automatically handling the user events. All the author must do is fill in what should happen when.

GLUT Callback Functions Contents of window need to be refreshed glutDisplayFunc() Window is resized or moved glutReshapeFunc() Key action glutKeyboardFunc() Mouse button action glutMouseFunc() Mouse moves while a button is pressed glutMotionFunc() Mouse moves regardless of mouse button state glutPassiveMouseFunc() Called when nothing else is going on glutIdleFunc() GLUT supports many different callback actions, including: • glutDisplayFunc() - called when pixels in the window need to be refreshed. • glutReshapeFunc() - called when the window changes size • glutKeyboardFunc() - called when a key is struck on the keyboard • glutMouseFunc() - called when the user presses a mouse button on the mouse • glutMotionFunc() - called when the user moves the mouse while a mouse button is pressed • glutPassiveMouseFunc() - called when the mouse is moved regardless of mouse button state • glutIdleFunc() - a callback function called when nothing else is going on. Very useful for animations.

3: Register Callback Functions Set up any callback function you’re going to use void main (int argc, char **argv) { …… glutDisplayFunc ( display ); // display callback glutReshapeFunc ( resize ); // window resize callback glutKeyboardFunc ( key ); // keyboard callback } • glutDisplayFunc() - called when pixels in the window need to be refreshed. • glutReshapeFunc() - called when the window changes size • glutKeyboardFunc() - called when a key is struck on the keyboard

Rendering Callback It’s here that does all of your OpenGL rendering void display( void ) { int k; glClear(GL_COLOR_BUFFER_BIT); for( k=0; k<5000; k++) …… } One of the most important callbacks is the glutDisplayFunc() callback. This callback is called when the window needs to be refreshed. It’s here that you’d do all of your OpenGL rendering.

Window Resize Callback It’s called when the window is resized or moved void resize(int w, int h) { …… display(); } One of the most important callbacks is the glutDisplayFunc() callback. This callback is called when the window needs to be refreshed. It’s here that you’d do all of your OpenGL rendering.

Keyboard Input Callback It’s called when a key is struck on the keyboard void key( char mkey, int x, int y ) { switch( mkey ) case ‘q’ : exit( EXIT_SUCCESS ); break; …… } Above is a simple example of a user input callback. In this case, the routine was registered to receive keyboard input. GLUT supports user input through a number of devices including the keyboard, mouse, dial and button boxes and spaceballs.

4. Event Process Loop This is where your application receives events, and schedules when callback functions are called void main (int argc, char **argv) { …… glutMainLoop(); } Enter the main event processing loop. This is where your application receives events, and schedules when callback functions are called.

2D Geometric Primitives Primitives – fundamental entities such as point and polygons Basic types of geometric primitives Points Line segments Polygons

2D Geometric Primitives GL_POINTS GL_LINES GL_LINE_STRIP GL_LINE_LOOP GL_TRIANGLES GL_POLYGON GL_TRIANGLE_FAN GL_QUADS All geometric primitives are specified by vertices

Geometry Commands glBegin(GLenum type) marks the beginning of a vertex-data list that describes a geometric primitives glEnd (void) marks the end of a vertex-data list glVertex*(…) specifies vertex for describing a geometric object

Specifying Geometric Primitives glBegin( type ); glVertex*(…); …… 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 type determines how vertices are combined

Types GL_POINTS GL_LINES GL_LINE_STRIP GL_LINE_LOOP GL_TRIANGLES GL_POLYGON GL_TRIANGLE_FAN GL_QUADS

Types GL_POINTS GL_LINES : each successive pair for a ling segment GL_LINE_STRIP: vertices defining a sequence of line segments GL_LINE_LOOP: GL_LINE_STRIP + the last vertex connects to the first GL_POLYGON : sequence of vertices of polygon, filled GL_QUADS: each successive group of four vertices for a quadrilaterals GL_TRIANGLES: each successive group of three vertices for a triangle GL_TRIANGLE_FAN: first three vertices for the first triangle and each subsequent vertex with the first vertex and the previous vertex for the next triangle

Attribute : Line void glLineWidth(GLfloat width) Set the width in pixel. Default is 1.0 void glLineStripple(GLint factor, GLushort pattern)

Rectangles glRect*() – defines 2D filled rectangle aligned with the axes. void glRect{sifd} (TYPE x1, TYPE y1, TYPE x2, TYPE y2);

Example void drawSquare () { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON); glVertex2f ( 0.0, 0.0 ); glVertex2f ( 1.0, 0.0 ); glVertex2f ( 1.1, 1.1 ); glVertex2f ( 0.0, 1.0 ); glEnd(); glFlush(); // force the renderer to output the results } The drawSquare(…) routine causes OpenGL to render a single square in a single color. The square is planar, since the z value is automatically set to 0.0 by glVertex2f().

OpenGL Color There are two color models in OpenGL RGB Color (True Color) Indexed Color (Color map) Every OpenGL implementation must support rendering in both RGBA mode, ( sometimes described as TrueColor mode ) and color index ( or colormap ) mode. For RGBA rendering, vertex colors are specified using the glColor*() call. For color index rendering, the vertex’s index is specified with glIndex*(). The type of window color model is requested from the windowing system. Using GLUT, the glutInitDisplayMode() call is used to specify either an RGBA window ( using GLUT_RGBA ), or a color indexed window ( using GLUT_INDEX ).

RGB Color Model R, G, B components are stored for each pixel Every OpenGL implementation must support rendering in both RGBA mode, ( sometimes described as TrueColor mode ) and color index ( or colormap ) mode. For RGBA rendering, vertex colors are specified using the glColor*() call. For color index rendering, the vertex’s index is specified with glIndex*(). The type of window color model is requested from the windowing system. Using GLUT, the glutInitDisplayMode() call is used to specify either an RGBA window ( using GLUT_RGBA ), or a color indexed window ( using GLUT_INDEX ). R, G, B components are stored for each pixel

RGB Color Red Green Blue

How Many Colors? Color number = For example: 4-bit color = 16 colors = 16.77 million colors

How Much Memory? Buffer size = width * height *color depth For example: If width = 640, height = 480, color depth = 24 bits Buffer size = (640 * 480 * 2) bytes If width = 640, height = 480, color depth = 32 bits Buffer size = (640 * 480 * 4) bytes

Alpha Component Alpha value A value indicating the pixels opacity 0 usually represents totally transparent and the 1 represents completely opaque Alpha buffer Hold the alpha value for every pixel Alpha values are commonly represented in 8 bits, in which case transparent to opaque ranges from 0 to 255

RGB Color Commands specifies vertex colors glClearColor(r, g, b, a) glColor*(…) specifies vertex colors glClearColor(r, g, b, a) sets current color for cleaning color buffer

Example void drawLine (GLfloat *color) { glColor3fv ( color ); glBegin(GL_LINE); glVertex2f ( 0.0, 0.0 ); glVertex2f ( 1.0, 0.0 ); glEnd(); } The drawSquare(…) routine causes OpenGL to render a single square in a single color. The square is planar, since the z value is automatically set to 0.0 by glVertex2f().

Example void drawLine (GLfloat *color) { glBegin(GL_LINE); glEnd(); } glColor3f(1.0,0.0,0.0 ); glVertex2f ( 0.0, 0.0 ); glColor3f(0.0,0.0,1.0); glVertex2f ( 1.0, 0.0 ); glEnd(); } The drawSquare(…) routine causes OpenGL to render a single square in a single color. The square is planar, since the z value is automatically set to 0.0 by glVertex2f().

Color Interpolation glShadeModel(GL_SMOOTH); Or glShadeModel(GL_FLAT); - the last vertex color Linear interpolation for a line Bilinear interpolation for a polygons

2D Viewing Where do we draw the 2D object? Assume that we draw objects on an infinite sheet of paper Then we need to specify clipping region and project these 2D objects to the screen void gluOrtho2D(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top);

Coordinate Systems and Transformation Identify which matrix we wish to alter Set the matrix to an identity matrix Alter the matrix to form the desired matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-1.0, 1.0, -1.0, 1.0);

Coordinate Systems and Transformation glMatrixMode(GLenum mode); Identify which matrix we wish to alter – The mode is usually GL_MODELVIEW, GL_PROJECTION glLoadIdentity(); Set the current matrix to an identity matrix

Enabling GL Features Features – lighting, hidden-surface removal, texture mapping, etc… Each feature will slow down the rendering process. We can enable/disable each feature individually void glEnable(GLenum feature) void glDisable(GLenum feature) Eg. glEnable(GL_LINE_STRIPPLE);

Enabling GL Features GL_ALPHA_TEST GL_BLEND GL_CLIP_PLANE i If enabled, do alpha testing. GL_AUTO_NORMAL If enabled, generate normal vectors when either GL_MAP2_VERTEX_3 or GL_MAP2_VERTEX_4 is used to generate vertices. See glMap2. GL_BLEND If enabled, blend the incoming RGBA color values with the values in the color buffers.. GL_CLIP_PLANE i If enabled, clip geometry against user-defined clipping plane i.. GL_COLOR_LOGIC_OP If enabled, apply the currently selected logical operation to the incoming RGBA color and color buffer values. GL_COLOR_MATERIAL If enabled, have one or more material parameters track the current color. GL_COLOR_TABLE If enabled, preform a color table lookup on the incoming RGBA color values. GL_CONVOLUTION_1D If enabled, perform a 1D convolution operation on incoming RGBA color values. GL_CONVOLUTION_2D If enabled, perform a 2D convolution operation on incoming RGBA color values. ……

Queries OpenGL state can be queried by void glGet*(GLenum name, Type *value); Eg. GLfloat color_array[4]; glGetFloatv(GL_CURRENT_COLOR,color_array); Check if a feature has been enabled by GLboolean glIsEnabled(GLenum feature); - returns GL_TRUE or GL_FALSE

Saving the State State changing functions – overwrites the state variables We can store previous state values for later use Matrix stacks void glPushMatrix() void glPopMatrix() Attribute stacks void glPishAttrib(GLbitfield mask) void glPopAttrib()

Saving the State glMatrix(GL_PROJECTION) // set projection matrix // draw scene glPushMatrix(); // change the project matrix //draw scene glPopMatrix();

Callback : Reshape void glutReshapeFunc(void (*f) (int width, int height)); invoked whenever the use changes the size of the window using the mouse. width and height is the new window size. Usually you want to take care of a new aspect ratio (width-to-height ratio).

Callback : Idle void glutIdleFunc(void (*)f (void)) f will be executed whenever there are no other events to be handled. necessary for animation

Callback : Idle glutIdleFunc(myidle); void myidle() { } glutPostRedisplay(); } : Request the display callback to be executed after the current callback returns

Double Buffering Use two buffers :front buffer and back buffer to guarantee to display a fully redrawn butter image glutSwapBuffers(); Replace glFlush() by glutSwapBuffer() in the display callback

Keyboard Interaction glutKeyboardFunc(void *f (unsigned char key, int x, int y)) f is called when any key on the keyboard is pressed. (x, y) is the position of the mouse in the window given in pixel measured from the upper-left corner of the window. glutKeyboardFunc(mykey); void mykey(unsigned char key, int x, int y) { if(key==‘q’) exit(0); }

Keyboard Interaction Special Keys (defined in glut.h) glutSpecialFunc(void *f (int key, int x, int y)) glutSpecialFunc(myskey); void mykey(unsigned char key, int x, int y) { if(key== GLIT_KEY_F1) .. if(key== GLIT_KEY_UP) … }

Keyboard Interaction int glutGetModifiers() – returns the logical AND of GLUT_ACTIVE_SHIFT, GLUT_ACTIVE_CTRL or GLUT_ACTIVE_ALT if that key is pressed at the time a mouse of keyboard event is generated. if(glutGetModifiers() & GLUT_ACTIVE_CTRL) && (key == ‘c’)) exit(0);

Mouse Interaction register mouse callback function void glutMouseFunc(void (*f) (int button, int state, int x, int y); register mouse callback function Button : GLUT_LEFT_BUTTON, GLUT_RIGHT_BUTTON, GLUT_MIDDLE_BUTTON State: GLUT_UP, GLUT_DOWN

Mouse Interaction (x,y) is the current position of the mouse void glutMotionFunc(void (*f) (int x, int y)); -- mouse moved with button down void glutPassiveMotionFunc(void (*f) (int x, int y); -- mouse moved without button down (x,y) is the current position of the mouse void glutEntryFunc(void (*f) (int state)) ; specifies the mouse entry callback state : GLUT_ENTERED, GLUT_LEFT

Null Callback When we no longer need a callback. glutIdleFunc(Null);

Camera Analogy The graphics transformation process is analogous to taking a photograph with a camera Place objects Position camera Adjust camera Produce photograph Note that human vision and a camera lens have cone-shaped viewing volumes. OpenGL (and almost all computer graphics APIs) describe a pyramid-shaped viewing volume. Therefore, the computer will “see” differently from the natural viewpoints, especially along the edges of viewing volumes. This is particularly pronounced for wide-angle “fish-eye” camera lenses.

Transformations and Camera Analogy Modeling transformation Positioning and moving the model. Viewing transformation Positioning and aiming camera in the world. Projection transformation Adjusting the lens of the camera. Viewport transformation Enlarging or reducing the physical photograph. .

OpenGL Transformation Pipeline OpenGL provides matrix stacks for each type of supported matrix (model-view, projection, texture) to store matrices. Matrix stacks are used because it is more efficient to save and restore matrices than to calculate and multiply new matrices. Popping a matrix stack can be said to “jump back” to a previous location or orientation. The depth of matrix stacks are implementation-dependent, but the Modelview matrix stack is guaranteed to be at least 32 matrices deep, and the Projection matrix stack is guaranteed to be at least 2 matrices deep. The material-to-color, flat-shading, and clipping calculations take place after the Modelview matrix calculations, but before the Projection matrix. The polygon culling and rendering mode operations take place after the Viewport operations. There is also a texture matrix stack, which is outside the scope of this class.

Transformations in OpenGL Transformations are specified by matrix operations. Desired transformation can be obtained by a sequence of simple transformations that can be concatenated together. Transformation matrix is usually represented by 4x4 matrix (homogeneous coordinates). Provides matrix stacks for each type of supported matrix to store matrices.

Programming Transformations In OpenGL, the transformation matrices are part of the state, they must be defined prior to any vertices to which they are to apply. In modeling, we often have objects specified in their own coordinate systems and must use transformations to bring the objects into the scene. OpenGL provides matrix stacks for each type of supported matrix (model-view, projection, texture) to store matrices.

Steps in Programming Define matrices: Composite transformations Viewing/modeling, projection, viewport … Composite transformations

Transformation Matrix Operation Current Transformation Matrix (CTM) The matrix that is applied to any vertex that is defined subsequent to its setting. If change the CTM, we change the state of the system. CTM is a 4 x 4 matrix that can be altered by a set of functions.

Current Transformation Matrix The CTM can be set/reset/modify (by post-multiplication) by a matrix Ex: C <= M // set to matrix M C <= CT // post-multiply by T C <= CS // post-multiply by S C <= CR // post-multiply by R

Current Transformation Matrix Each transformation actually creates a new matrix that multiplies the CTM; the result, which becomes the new CTM. CTM contains the cumulative product of multiplying transformation matrices. Ex: If C <= M; C <= CT; C <= CR; C <= CS Then C = M T R S

Ways to Specify Transformations In OpenGL, we usually have two styles of specifying transformations: Specify matrices ( glLoadMatrix, glMultMatrix ) Specify operations ( glRotate, glTranslate )

Specifying Matrix Identify current matrix Modify current matrix Load current matrix Multiple current matrix

Specifying Matrix (1) Identify current matrix glMatrixMode (mode) Specified what transformation matrix is modified. mode: GL_MODELVIEW GL_PROJECTION

Specifying Matrix(2) Modify current matrix glLoadMatrix{fd} ( Type *m ) Set the 16 values of current matrix to those specified by m. Note: m is the 1D array of 16 elements arranged by the columns of the desired matrix

Specifying Matrix(3) Modify current matrix glLoadIdentity ( void ) Set the currently modifiable matrix to the 4x4 identity matrix.

Specifying Matrix(4) Modify current matrix glMultMatrix{fd} ( Type *m ) Multiple the matrix specified by the 16 values pointed by m by the current matrix, and stores the result as current matrix. Note: m is the 1D array of 16 elements arranged by the columns of the desired matrix

Specifying Operations Three OpenGL operation routines for modeling transformations: Translation Scale Rotation

Recall ( ) ( ) Translation: Scale: Three elementary 3D transformations ú û ù ê ë é = 1 z y x d Translation: ( ) , z y x d T ú û ù ê ë é = 1 z y x s Scale: ( ) , z y x s S

Recall ú û ù ê ë é - = 1 cos sin q ) ( Rx Ry Rz Rotation

Specifying Operations (1) Translation glTranslate {fd} (TYPE x, TYPE y, TYPE z) Multiplies the current matrix by a matrix that translates an object by the given x, y, z.

Specifying Operations (2) Scale glScale {fd} (TYPE x, TYPE y, TYPE z) Multiplies the current matrix by a matrix that scales an object by the given x, y, z.

Specifying Operations (3) Rotate glRotate {fd} (TPE angle, TYPE x, TYPE y, TYPE z) Multiplies the current matrix by a matrix that rotates an object in a counterclockwise direction about the ray from origin through the point by the given x, y, z. The angle parameter specifies the angle of rotation in degree.

Order of Transformations The transformation matrices appear in reverse order to that in which the transformations are applied. In OpenGL, the transformation specified most recently is the one applied first.

Order of Transformations In each step: C <= I C <= CT(4.0, 5.0, 6.0) C <= CR(45, 1.0, 2.0, 3.0) C < = CT(-4.0, -5.0, -6.0) Finally C = T(4.0, 5.0, 6.0) CR(45, 1.0, 2.0, 3.0) CT(-4.0, -5.0, -6.0) Write it Read it

Matrix Multiplication is Not Commutative First rotate, then translate => First translate, then rotate =>

Viewing-Modeling Transformation If given an object, and I want to render it from a viewpoint, what information do I have to have? Viewing position Which way I am looking at Which way is “up” …..

Viewing Position x y z R, T x y z Camera Translation Rotation

Where I am and Looking at y y Loot at (atx, aty, atz) View-up vector (upx, upy, upz) x x Model z z Eyepoint (eyex, eyey, eyez)

Define Coordinate System +X +Z +Y In the default position, the camera is at the origin, looking down the negative z-axis In the default position, the camera is at the origin, looking down the negative z-axis If you get this wrong, you may see nothing in your image.

If we use OpenGL Look-At Function gluLookAt (eyex, eyey, eyez, atx, aty, atz, upx, upy, upz ) Define a viewing matrix and multiplies it to the right of the current matrix.

Matrix Stacks OpenGL uses matrix stacks mechanism to manage transformation hierarchy. OpenGL provides matrix stacks for each type of supported matrix to store matrices. Model-view matrix stack Projection matrix stack Texture matrix stack The depth of matrix stacks are implementation-dependent, but the Modelview matrix stack is guaranteed to be at least 32 matrices deep, and the Projection And texture matrix stack is guaranteed to be at least 2 matrices deep.

Matrix Stacks Pushing Popping Top Bottom Current matrix is always the topmost matrix of the stack We manipulate the current matrix is that we actually manipulate the topmost matrix. We can control the current matrix by using push and pop operations. Pushing Popping Top Bottom

Manipulating Matrix Stacks (1) Remember where you are glPushMatrix ( void ) Pushes all matrices in the current stack down one level. The topmost matrix is copied, so its contents are duplicated in both the top and second-from-the top matrix. Note: current stack is determined by glMatrixModel()

Manipulating Matrix Stacks (2) Go back to where you were glPopMatrix ( void ) Pops the top matrix off the stack, destroying the contents of the popped matrix. What was the second-from-the top matrix becomes the top matrix. Note: current stack is determined by glMatrixModel()

Manipulating Matrix Stacks (3) The depth of matrix stacks are implementation-dependent. The Modelview matrix stack is guaranteed to be at least 32 matrices deep. The Projection matrix stack is guaranteed to be at least 2 matrices deep. glGetIntegerv ( Glenum pname, Glint *parms ) Pname: GL_MAX_MODELVIEW_STACT_DEPTH GL_MAX_PROJECTION_STACT_DEPTH

Projection Transformation Projection & Viewing Volume Projection Transformation Viewpoint Transformation

OpenGL and Windows Screen Positive X Y Windows Screen Mapping (50, 50) (0, 0) Positive X Y OpenGL Screen Mapping (50, 50) (0, 0) Remember: the Y coordinates of OpenGL screen is the opposite of Windows screen. But same as in the XWindows system.

Perspective Projection Volume Far-plane: zNear Near-plane: zNear Viewing volume h w aspect ratio = w/h y z x fovy

Perspective Projection Commands glFrustum( left, right, bottom, top, zNear, zFar ) Creates a matrix for a perspective viewing frustum and multiplies the current matrix by it.

Perspective Projection Commands gluPerspective( fovy, aspect, zNear, zFar ) Creates a matrix for an perspective viewing frustum and multiplies the current matrix by it. Note: fovy is the field of view (fov) between the top and bottom planes of the clipping volume. aspect is the aspect ratio

Remember to Initialize glutInitDisplayMode(GLUT_DOUBLE|GLUT_RBG|GLUT_DEPTH); You can also clear the depth buffer (as we did for color buffer) glClear(GL_DEPTH_BUFFER_BIT) Clear z (depth) buffer

Viewing a 3D world View up ViewUp ViewRight Aspect Ratio = View right

Viewport Viewport The region within the window that will be used for drawing the clipping area By default, it is set to the entire rectangle of the window that is opened Measured in the window coordinates, which reflect the position of pixels on the screen related to the lower-left corner of the window Viewpoint the region within the window that will be used for drawing the clipping area. by default, it is set to the entire rectangle of the window that is opened. Measured in the window coordinates, which reflect the position of pixels on the screen related to the lower-left corner of the window.

Viewport Transformation A viewpoint is defined as the same size as the window A viewpoint is defined as half the size of the window h w glViewport() clips the vertex or raster position. For geometric primitives, a new vertex may be created. For raster primitives, the raster position is completely clipped.

Aspect Ratio The Aspect Ratio of a rectangle is the ratio of the rectangle’s width to its height: e.g. Aspect Ratio = width/height Viewport aspect ratio should be same as projection transformation, or resulting image may be distorted.

Viewport Commands glViewport( x, y, width, height ) Defines a pixel rectangle in the window into which the final image is mapped (x, y) specifies the lower-left corner of the viewport (width, height) specifies the size of the viewport rectangle For glOrtho(), the viewing volume is shaped like a rectangular parallelepiped (a box). Vertexes of an object are “projected” towards infinity. Distance does not change the apparent size of an object. Orthographic projection is used for drafting and design (such as blueprints). calls glOrtho with z values near zero