CG-lecture04 - Introduction to Computer Graphics Lecture 4...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Introduction to Computer Graphics Lecture 4 OpenGL Programming Guide Introduction to OpenGL OpenGL and Related APIs WGL: glue between OpenGL and Microsoft Windows GLU: OpenGL utility library – rendering quadric surfaces, curves GLUT: OpenGL utility toolkit – creating windows, animation Intro to OpenGL-Preliminaries Header Files •#include <GL/glut.h> Include this header file in your codes for correct compiling. The glut header file includes “glu.h”, and the glu header file includes “gl.h”. Intro to OpenGL-Preliminaries Libraries opengl32.lib glu32.lib glut32.lib Append these library files in your library modules for correct linking. Intro to OpenGL-Preliminaries DLL glut32.dll glut32.dll Copy this file into your system32 directory for Copy correct program performance. correct Intro to OpenGL-Application Structure • Configure and open window • Initialize OpenGL state • Register input callback functions: •render •resize •input: keyboard, mouse, etc. • Enter event processing loop Intro to OpenGL-Event Processing Loop OpenGL operates as an infinite loop • Put things in the scene (points, colored lines, textured polys) • Describe the camera (location, orientation, field of view) • Render – draw the scene • Listen for input (keyboard, mouse, etc.) events OpenGL Basics Window Configuration Callback Functions One-time Initialization: Initialize any OpenGL state and program variables GLUT Callback Functions Event Processing: callbacks define what actions are Event supported and automatically handling the user events. supported glutDisplayFunc() – called for refreshing pixels in the glutDisplayFunc() window window glutReshapeFunc() – called for changing the window size glutKeyboardFunc() – called for keyboard input GLUT Callback Functions glutMouseFunc() – called for mouse input glutMotionFunc() – called for moving the mouse glutMotionFunc() while a button is pressed while glutPassiveMouseFunc() – called for moving the glutPassiveMouseFunc() mouse regardless of mouse button state mouse glutIdleFunc() – called for nothing (useful for glutIdleFunc() animation) animation) Rendering Callback Clear the window Render a triangle strip for smooth animation The callback, glutDisplayFunc(display) is called when the window needs to be refreshed. Idle Callback – for animation global variable for controlling the moving activate glutDisplayFunc() as soon as possible glutIdleFunc(idle) is called for updating the motion variables and then the scene is updated and refreshed User Input Callback – for interactive use glutKeyboardFunc(keyboard) is called for receiving keyboard input Other input devices include the mouse and track ball Intro to OpenGL OpenGL has a “state” • There are a lot of ways your OpenGL program can be There configured configured • The current configuration is stored in OpenGL’s state • Be aware that OpenGL commands affect the program’s state Be rather than redirect its logical execution rather Light Source Placement Setup lighting, if any Simplest option: change the current color between Simplest current polygons or vertices polygons • glColor() sets the current color Or OpenGL provides a simple lighting model: • Set parameters for light(s) – Intensity, position, direction & falloff (if applicable) Intensity, • Set material parameters to describe how light reflects from the Set material surface surface Won’t go into details now; Model (Object) Placement Geometry in OpenGL consists of a list of vertices in Geometry between calls to glBegin() and glEnd() glBegin() glEnd() • A simple example: telling GL to render a triangle glBegin(GL_POLYGON); glVertex3f(x1, y1, z1); glVertex3f(x2, y2, z2); glVertex3f(x3, y3, z3); glEnd(); • Usage: glBegin(geomtype) where geomtype is: Usage: glBegin( – Points, lines, polygons, triangles, quadrilaterals, etc... Model (Object) Placement - Primitive Types GL_POINTS GL_LINE • {S | _STRIP | _LOOP} GL_TRIANGLE • {S | _STRIP | _FAN} GL_QUAD • {S | _STRIP} GL_POLYGON Model (Object) Placement - Drawing Triangles You can draw multiple triangles between You glBegin(GL_TRIANGLES) and glEnd(): glBegin(GL_TRIANGLES) glEnd() float v1[3], v2[3], v3[3], v4[3]; ... glBegin(GL_TRIANGLES); glVertex3fv(v1); glVertex3fv(v2); glVertex3fv(v3); glVertex3fv(v1); glVertex3fv(v3); glVertex3fv(v4); glEnd(); Each set of 3 vertices forms a triangle • What do the triangles drawn above look like? • How much redundant computation is happening? Model (Object) Placement - Triangle Strips An OpenGL triangle strip primitive reduces this redundancy by sharing vertices: An triangle glBegin(GL_TRIANGLE_STRIP); glVertex3fv(v0); glVertex3fv(v1); glVertex3fv(v2); glVertex3fv(v3); v2 v0 v4 glVertex3fv(v4); v5 glVertex3fv(v5); glEnd(); • triangle 0 is v0, v1, v2 • triangle 1 is v2, v1, v3 (why not v1, v2, v3?) • triangle 2 is v2, v3, v4 • triangle 3 is v4, v3, v5 (again, not v3, v4, v5) v1 v3 Intro to OpenGL-Four Coordinate Systems (1) Local Coordinate System (2) World Coordinate System (3) Viewing (Camera) Coordinate System (4) Viewport Coordinate System (Screen or Viewport Window Client Region) Window Intro to OpenGL- Coordinate System Transformation (1) Local to World (Modeling Transformation) We consider it as a vector transformation, and we need programming for its configuration. we (2)World to Viewing (Viewing Transformation) We consider it as a coordinate system transformation, and we need programming for its configuration. its Intro to OpenGL- Coordinate System Transformation (3) Viewing to Viewport (Projection (3) Transformation) Transformation) 1) The perspective projection is a dimension The perspective degrading transformation. (3D to 2D) degrading 2) Because the Aspect Ratios of the camera Because retinal plane and the viewport are different, retinal viewport there is a scaling transformation. scaling Programming is needed for its configuration. Intro to OpenGL- Coordinate System Transformation (4) Rasterization in Viewport 1)This transformation is not a typical Coordinate 1)This system transformation. It is a sampling procedure. system 2)This procedure is performed automatically when 2)This projection is performed. No programming is needed. needed. Synthetic Camera Model and Transformation Modeling transformations – moving the model Viewing transformations – tripod position and orientation of the viewing volume in the world Projection transformations – adjust the retinal plane of the camera Viewport transformations – enlarge or reduce the physical photograph Intro to OpenGL-Matrix OpenGL uses matrices • Matrix describes current configuration of the 3D Matrix space (Modeling Transformation, Viewing space Modeling Transformation) Transformation • Matrix describes camera type (Projection Projection Transformation) Transformation Intro to OpenGL-Two Matrix Type MODELVIEW_MATRIX • Use this matrix type to decide the model (object) and camera Use placement. (Why consider these two placement as the placement. Why same matrix type?) same • The matrix is actually 4x4 because of the homogeneous The coordinates. coordinates. • OpenGL maintains a stack of these matrices. You can control OpenGL this stack with the glPushMatrix and glPopMatrix commands this Intro to OpenGL-Two Matrix Type OpenGL preserves a similar matrix to describe OpenGL the camera type and this is called the PROJECTION_MATRIX. PROJECTION_MATRIX. This matrix is also 4x4 matrix because of the This homogeneous coordinate is used. Operate MODELVIEW_MATRIX • When you decide or modify a MODELVIEW_MATRIX, When the following function must be used. the • glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW); Operate MODELVIEW_MATRIX • (1) Modeling Transformation • glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW); • glLoadIdentity(); // used before any transformation used • glTranslatef(GLfloat x, y, z); glTranslatef(GLfloat • glRotatef(GLfloat degrees, x, y, z); glRotatef(GLfloat • glScalef (GLfloat x, y, z); glScalef Modeling Transformations glTranslate (x, y, z) • Post-multiplies the current matrix by a matrix that moves the object by Post-multiplies the given x-, y-, and z-values the glRotate (theta, x, y, z) • Post-multiplies the current matrix by a matrix that rotates the object in Post-multiplies a counterclockwise direction about the ray from the origin through the point (x, y, z) point glScale (x, y, z) • Post-multiplies the current matrix by a matrix that stretches, shrinks, Post-multiplies or reflects an object along the axes or Modeling Transformations It is important that you understand the order in which It OpenGL concatenates matrices OpenGL glMatrixMode (MODELVIEW); glLoadIdentity(); glMultMatrix(N); glMultMatrix(M); glMultMatrix(L); glBegin(POINTS); glVertex3f(v); glEnd(); Modelview matrix successively contains: I(dentity), N, NM, NML The transformed vertex is: NMLv = N(M(Lv)) Operate MODELVIEW_MATRIX • (2) Viewing Transformation (Setting up camera) • glMatrixMode(GL_MODELVIEW); glMatrixMode(GL_MODELVIEW); • glLoadIdentity(); // used before camera placement used • gluLookAt( eyex, eyey, eyez, aimx, aimy, aimz, upx, • • upy, upz); // Camera Placement; Define the // Viewing Coordinate System • eye[XYZ]: camera position in world coordinates • look[XYZ]: a point centered in camera’s view • up[XYZ]: a vector defining the camera’s vertical vector Operate MODELVIEW_MATRIX • (3)Management of the matrix (3)Management • glPushMatrix(), • glPopMatrix(); glPopMatrix(); • Why a matrix stack is used in opengl? • Because a complex model may be composed of many subobjects, and some sub-objects may control the movement of objects, the others. (Example: Robot Arm) the Manipulating Matrix Stacks Observation: Certain model transformations are shared Observation: among many models among We want to avoid continuously reloading the same We sequence of transformations sequence glPushMatrix ( ) • push all matrices in current stack down one level and copy topmost push matrix of stack matrix glPopMatrix ( ) • pop the top matrix off the stack Matrix Manipulation - Example Drawing a car with wheels and lugnuts draw_wheel( ); for (j=0; j<5; j++) { glPushMatrix (); glRotatef(72.0*j, 0.0, 0.0, 1.0); glTranslatef (3.0, 0.0, 0.0); draw_bolt ( ); glPopMatrix ( ); } Matrix Manipulation - Example draw_wheel( ); for (j=0; j<5; j++) { glPushMatrix (); glRotatef(72.0*j, 0.0, 0.0, 1.0); glTranslatef (3.0, 0.0, 0.0); draw_bolt ( ); glPopMatrix ( );} R RT RTv Vector Transformation (Local to World) – Bottom Up Start Trans Rot Perspective Projection Set projection parameters (e.g., field of view) Typically, we use a perspective projection perspective • Distant objects appear smaller than near objects Distant • Defined by a view frustum Defined view Other projections: orthographic, isometric Other orthographic isometric Perspective Projection In OpenGL: In • Projections implemented by projection matrix Projections projection • gluPerspective() creates a perspective projection matrix: projection glSetMatrix(GL_PROJECTION); glLoadIdentity(); //load an identity load matrix matrix gluPerspective(vfov, aspect, near, gluPerspective(vfov, far); far); Perspective Projection Parameters to Parameters gluPerspective(): gluPerspective() • vfov: vertical field of view • aspect: window width/height • near, far: distance to near & far distance far clipping planes far +Y Projection: Front/Back Rendering Each polygon has two sides, front and back OpenGL can render the two differently The ordering of vertices in the list determines The which is the front side: which • When looking at the front side, the vertices go When front counterclockwise counterclockwise – This is basically the right-hand rule – Note that this still holds after perspective projection Rasterization: Double Buffering Avoids displaying partially rendered frame buffer OpenGL generates one raster image while another OpenGL raster image is displayed on monitor raster glxSwapBuffers (Display *dpy, Window w) glutSwapBuffers (void) 3D Geometric Primitives Pipeline (for direct illumination) Rendering 3D Modeling Transformation Lighting Transform into 3D world coordinate system Illuminate according to lighting and reflectance Viewing Transformation Transform into 3D camera coordinate system Projection Transformation Transform into 2D screen coordinate system Clipping Scan Conversion Image Clip primitives outside camera’s view Draw pixels (includes texturing, hidden surface, ...) OpenGL Example – Complete Camera Setting up void SetUpViewing() { // The viewport transformation glViewport( 0, 0, window_width, window_height ); // Set up camera->screen transformation glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 60, 1, 1, 1000 ); // fov, aspect, near, far // Set up the model->camera transformation glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt( 3, 3, 2, // eye point 0, 0, 0, // look at point 0, 0, 1 ); // up vector glRotatef( theta, 0, 0, 1 ); // rotate the model glScalef( zoom, zoom, zoom ); // scale the model glBegin(); …… glEnd(); } Learn OpenGL by example robot.c from the OpenGL Programming Guide Learn OpenGL by example Two bodies • Upper arm • Lower arm Major tasks • Position • Orientation Learn OpenGL by example Body Placement: Both bodies originally at origin (World Both Coordinate) Coordinate) Learn OpenGL by example Headers #include <GL/gl.h> #include #include <GL/glu.h> #include <GL/glut.h> Learn OpenGL by example int main(int argc, char** argv) { int glutInit(&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); glutInitDisplayMode glutInitWindowSize (500, 500); glutInitWindowPosition (100, 100); glutInitWindowPosition glutCreateWindow (argv[0]); init (); glutDisplayFunc(display); glutReshapeFunc(reshape); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutKeyboardFunc(keyboard); glutMainLoop(); return 0; } return Learn OpenGL by example void init(void) { void glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_FLAT); } Learn OpenGL by example void display(void){ void glClear (GL_COLOR_BUFFER_BIT); glPushMatrix(); glTranslatef (-1.0, 0.0, 0.0); glRotatef ((GLfloat) shoulder, 0.0, 0.0, 1.0); glTranslatef (1.0, 0.0, 0.0); glPushMatrix(); glScalef (2.0, 0.4, 1.0); glutWireCube (1.0); glPopMatrix(); Continued… Continued… Upper Arm Placement Y Translate Rotate Translate X Scaling Learn OpenGL by example glTranslatef (1.0, 0.0, 0.0); glTranslatef glRotatef ((GLfloat) elbow, 0.0, 0.0, 1.0); glTranslatef (1.0, 0.0, 0.0); glPushMatrix(); glScalef (2.0, 0.4, 1.0); glutWireCube (1.0); glPopMatrix(); glPopMatrix(); glutSwapBuffers(); glutSwapBuffers(); } Lower Arm Placement Translate Y Rotate Rotate Upper Arm Translate Translate Translate X Scaling OpenGL: Conventions Functions in OpenGL start with gl gl Functions • Most functions just gl (e.g., glColor()) Most glColor() • Functions starting with glu are utility functions (e.g., Functions glu gluLookAt()) gluLookAt() • Functions starting with glx are for interfacing with the X Functions glx Windows system (e.g., in gfx.c) Windows OpenGL: Conventions Function names indicate argument type and number • Functions ending with f take floats Functions • Functions ending with i take ints Functions • Functions ending with b take bytes Functions • Functions ending with ub take unsigned bytes Functions ub • Functions that end with v take an array. Functions Examples • glColor3f() takes 3 floats • glColor4fv() takes an array of 4 floats glColor4fv() takes OpenGL: Conventions Variables written in CAPITAL letters • Example: GLUT_SINGLE, GLUT_RGB • usually constants • use the bitwise or command (x | y) to combine constants ...
View Full Document

Ask a homework question - tutors are online