Introduction to OpenGL Programming RedBook 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
Computer Graphics CSCE 441
1 MAE152 Computer Graphics for Scientists and Engineers Lighting in OpenGL.
Computer Graphics (Fall 2008) COMS 4160, Lecture 9: OpenGL 1
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.
Hidden Surfaces and Shading CS BSP Tree T1T1 T2T2 E if (f 1 (E) < 0) then draw T 1 draw T 2 else draw T 2 draw T 1 f 1 (p) = 0 is the.
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
Computer Graphics (Fall 2003) COMS 4160, Lecture 6: OpenGL 2 Ravi Ramamoorthi Many slides courtesy Greg Humphreys.
CS 248 OpenGL Help Session CS248 Presented by Sean Walker
Computer Graphics (Fall 2005) COMS 4160, Lecture 10: OpenGL 1
Computer Graphics (Spring 2008) COMS 4160, Lecture 14: OpenGL 3
Lighting & Material. Example 1/5 #include ” glut.h ” void display(); void reshape(int, int); void lighting(); int main(int argc, char** argv) { glutInit(&argc,
Development of Interactive 3D Virtual World Applications
Introduction to OpenGL M. Ramanathan STTP CAD 2011Introduction to OpenGL.
Introduction to OpenGL Keng Shih-Ling 2003 Spring.
Write a Simple Program with OpenGL & GLUT. Books and Web Books OpenGL Programming Guide (Red-book) OpenGL Reference Manual (Blue-book) OpenGL Super Bible.
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.
Computer Graphics Bing-Yu Chen National Taiwan University.
CAP4730: Computational Structures in Computer Graphics Introduction to OpenGL.
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.
Lecture 3 OpenGL.
Write a Simple Program with OpenGL & GLUT. Books OpenGL Programming Guide (Red-book) OpenGL Reference Manual (Blue-book) OpenGL Super Bible
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.
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.
Introduction to GL Geb Thomas. Example Code int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode ( GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
Introduction to OpenGL Programming Jian-Liang Lin 2002.
1 Angel: Interactive Computer Graphics 4E © Addison-Wesley 2005 Shading I Ed Angel Professor of Computer Science, Electrical and Computer Engineering,
Computer Graphics Bing-Yu Chen National Taiwan University.
OpenGL Color and Lighting 2003 Spring Keng Shih-Ling.
OpenGL Lighting Jian-Liang Lin 2002 Hidden-Surface Removal -1 Original Code: while (1) { get_viewing_point_from_mouse_position(); glClear(GL_COLOR_BUFFER_BIT);
Draw a Simple Object. Pixel pipeline Vertex pipeline Course Map Transformation & Lighting Primitive assembly Viewport culling & clipping Texture blending.
Viewing and Transformation. Pixel pipeline Vertex pipeline Course Map Transformation & Lighting Primitive assembly Viewport culling & clipping Texture.
Chun-Yuan Lin Introduction to OpenGL 2015/12/19 1 CG.
NoufNaief.net TA: Nouf Al-harbi.
Introduction to OpenGL & HW1 Announcement 劉軒銘, 網媒所 碩二 ICG 2012 Fall.
Doç. Dr. Cemil Öz SAÜ Bilgisayar Mühendisliği Dr. Cemil Öz.
Chap 3 Viewing and Transformation
OpenGL Basic Drawing 2003 Spring Keng Shih-Ling
Chap 2 Write a Simple OpenGL Program. Preparing 1/2 environment : Microsoft Visual C 、 Microsoft Visual C++.Net Also need : GLUT
1 Programming with OpenGL Part 2: Complete Programs.
OpenGL API 2D Graphic Primitives Angel Angel: Interactive Computer Graphics5E © Addison-Wesley
CS559: Computer Graphics Lecture 12: OpenGL - Transformation Li Zhang Spring 2008.
CS559: Computer Graphics Lecture 12: OpenGL: ModelView Li Zhang Spring 2010.
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.
Computer Graphics I, Fall Programming with OpenGL Part 2: Complete Programs.
CS559: Computer Graphics Lecture 16: Shading and OpenGL Li Zhang Spring 2008.
INTRODUCTION TO OPENGL
Computer Graphics (Fall 2003) COMS 4160, Lecture 5: OpenGL 1 Ravi Ramamoorthi Many slides courtesy Greg Humphreys.
CSC Graphics Programming
Computer Graphics Lecture 33
Programming with OpenGL Part 2: Complete Programs
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.
Open GL: Colors and Lighting
גרפיקה ממוחשבת: מבוא ל-OpenGL
Lighting and Shading Lab 8:.
CSC461: Lecture 24 Lighting and Shading in OpenGL
o عَلَّمَهُ الْبَيَانَ
Introduction to OpenGL
Programming with OpenGL Part 2: Complete Programs
Programming with OpenGL Part 2: Complete Programs
Lighting and Shading Lab 8:.
Programming with OpenGL Part 2: Complete Programs
Presentation transcript:

Introduction to OpenGL Programming RedBook OpenGL

Rendering Pipeline (Foley and van Dam)

What is OpenGL? -1 OpenGL is a cross-platform standard for 3D rendering. and software interface to graphics hardware. The OpenGL Architecture Review Board(ARB), and independent consortium formed in 1992, governs the OpenGL specification. OpenGL routines use the prefix gl.

What is OpenGL? -2 Designed as a hardware-independent interface and implemented on many different hardware platforms. No commands for performing windowing tasks or obtaining user input are included in OpenGL. You must work through whatever windowing system controls the particular hardware you're using.

What is OpenGL? -3 OpenGL doesn't provide high-level commands for describing models of three- dimensional objects. With OpenGL, you must build up your desired model from a small set of geometric primitives. –points, lines, triangles, and polygons …etc.

The Advantages of OpenGL Industry standard Fast Portable Easy to use Well-documented

OpenGL rendering pipeline

Color Models RGBA color –Red, Green, Blue, and Alpha channels –Up to 16M colors Color-indexed –Small numbers of colors accessed by indices from a color lookup table(palette) –8 bits = 256 colors

Basic Features Transformation Materials Lighting & Smooth Shading Texture mapping Depth buffer test (Z-Buffer) Alpha blending Double buffering for animation Pixel operations

OpenGL Buffering -1 OpenGL supports a variety of buffers for advanced rendering –Depended on driver implementation Color buffers –Front-left, front-right, back-left, back-right, and any number of auxiliary buffers Depth buffer –Also known as Z-Buffer for HSR

OpenGL Buffering -2 Alpha buffer –Blending Stencil buffer –To restrict drawing to certain portions of the screen. (basic application) Accumulation buffer –Full scene manipulation

OpenGL library -1 SGI’s OpenGL SDK –OpenGL.DLL & GLU.DLL –Open source implementation for hardware vendor reference. –Best software rendering library. –Can be downloaded from SGI’s website.

OpenGL library -2 Microsoft’s implementation –From Win95 OSR2, Microsoft Windows ship with OpenGL32.DLL. –For old Win95 users, you still can download OPENGL95.EXE via Microsoft website. –Header files and import library files are already included in Win32 Platform SDK.

OpenGL Utility Library The OpenGL Utility Library(GLU) provides many of the modeling features, such as quadric surfaces and NURBS curves and surfaces. GLU is a standard part of every OpenGL implementation GLU routines use the prefix glu. – gluLookAt( … ); –…

OpenGL Utility Toolkit -1 The OpenGL Utility Toolkit (GLUT) is a window system-independent toolkit, written by Mark Kilgard, to hide the complexities of differing window system APIs. GLUT routines use the prefix glut. – glutPostRedisplay(); –…

OpenGL Utility Toolkit -2 You can download this toolkit in the following website – We focus on this toolkit.

Compilers – Microsoft Visual C++ Start a new workspace of Win32 Console application. Add OpenGL32.lib glu32.lib glut32.lib in Projects/Setting/Link/Library modules column for linking

OpenGL on VC New as Win32 console application settings –opengl32.lib –glu32.lib –glut32.lib Install –glut32.dll in Windows/System –glut32.lib in lib/ –glut.h in include/GL

Where is the reference? OpenGL official site – You refer to OpenGL API documentation in MSDN Library. OpenGL Programming Guide (Red book) – c__BookViewhttp://heron.cc.ukans.edu/ebt-bin/nph- c__BookView OpenGL Reference Manual (Blue book) – -Man-Pages/opengl_index_spec.htmlhttp:// -Man-Pages/opengl_index_spec.html

OpenGL Basic Drawing #include main() { InitializeAWindowPlease(); glClearColor (0.0, 0.0, 0.0, 0.0); glClear (GL_COLOR_BUFFER_BIT); 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(); UpdateTheWindowAndCheckForEvents(); }

OpenGL Command Syntax -1 OpenGL constants prefix by GL_. OpenGL routines prefixed by gl and suffiexed by the number of arguments and type. –glVertex2i, glNormal3f, glTexCoord2fv…etc

OpenGL Command Syntax -2

OpenGL as a State Machine -1 OpenGL is a state machine. You put it into various states (or modes) that then remain in effect until you change them. As you've already seen, the current color is a state variable Many state variables refer to modes that are enabled or disabled with the command glEnable() or glDisable().

OpenGL as a State Machine -2 Each state variable or mode has a default value, and at any point you can query the system for each variable's current value. Typically, you use one of the six following commands to do this: glGetBooleanv(), glGetDoublev(), glGetFloatv(), glGetIntegerv(), glGetPointerv(), or glIsEnabled().

GLUT: Overview A very useful framework for rapid OpenGL program development. –Portable through lots of platforms. –Provide basic window, input, and event management. –Callback event handler. –Idle routine and timer. –A simple, cascading popup menu facility. –Offers lots of basic object. (wireframe/solid) –…

GLUT: Initialize and creating a window -1 glutInit( int* argc, char** argv ); –Initialize GLUT and process any command line arguments. –This should be called before any GLUT routines. glutInitDisplayMode( unsigned int mode ); –Specify whether to apply RGBA mode or color-indexed mode. GLUT_RGBA, GLUT_INDEX… –Single or double buffering. GLUT_SINGLE, GLUT_DOUBLE… –Other buffers. GLUT_DEPTH, GLUT_STENCIL, GLUT_ACCUM…

GLUT: Initialize and creating a window -2 glutInitWindowPosition( int x, int y ); –Specify the screen location of your window glutInitWindowSize( int w, int h ); –Specify the size of your window in pixels. glutCreateWindow( char* pTitle ); –Create a window with OpenGL context for rendering. –The window will appear until glutMainLoop() is called.

GLUT: Callback function -1 Callback functions are not called by you. They are called by GLUT. You can register some functions to GLUT, and they can be called when meeting the situation. Some types of callback –Window event handler –IO event handler –Global handler

GLUT: Callback function -2 glutDisplayFunc( void (*pfn)(void) ); –Display callback; GLUT called it when the content of the window needed to be updated. –You call manually call glutPostRedisplay() to arbitrarily ask GLUT to call that callback function. glutReshapeFunc( void (*pfn)( int w, int h ) ); –GLUT called it when the size of window is changed. –Recalculate view frustum & viewport…

GLUT: Callback function -3 glutKeyboardFunc( void(*pfn)(unsigned char key, int x, int y )); and glutMouseFunc( void(*pfn)( int button, int state, int x, int y )); –User Input event handler. glutMotionFunc( void(*pfn)( int x, int y )); –GLUT call this registered callback function when the mouse is moved while a mouse button is also pressed. glutIdleFunc( void(*pfn)(void)); –GLUT call this registered callback function when idling. –You can simply call: glutIdleFunc( glutPostRedisplay );

Start GLUT framework glutMainLoop(); –Like Win32’s message loop. –Start all GLUT operations.

GLUT: Complete sample -1 #include 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 (); }

GLUT: Complete sample -2 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); } /* * 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. */

GLUT: Complete sample -3 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; /* ISO C requires main to return int. */ }

GLUT: Complete sample result

GLUT: Simple 3D objects drawing support -1 GLUT includes several 3D objects drawing: –Cone, cube, sphere, dodecahedron, icosahedron, octahedron, teapot, tetrahedron, torus. –Both wireframe and solid. glutWireCube, glutSolidSphere … etc. –These objects are drawn centered at the origin of the world coordinate system.

GLUT: Simple 3D objects drawing support -2 You can try this simple display callback function and see the result. void display(void) { glClear( GL_COLOR_BUFFER_BIT ); glutWireCube( 1.0 ); glFlush(); }

A Drawing Survival Kit -1 Clearing the window –glClear( GLbitfield mask ); GL_COLOR_BUFFER_BIT -> glClearColor( … ); GL_DEPTH_BUFFER_BIT -> glClearDepth( … ); Specifying a color –glColor3f( GLfloat r, GLfloat g, GLfloat b ); –glIndexi( int i ); glutSetColor( int i, GLfloat r, GLfloat g, GLfloat b ); for setting indexed color.

A Drawing Survival Kit -2 Specifying Vertices –glVertex{2,3,4}{sifd}[v]( … ); Ex: glVertex3f( 1.0f, 0.5f, 2.0f ); –Vertex array Not introduced here.

A Drawing Survival Kit -3 OpenGL Geometric Drawing Primitives –glBegin( GLenum mode ); mode is GL_POLYGON, GL_LINES … etc –glEnd(); –All primitives should be placed between these two OpenGL routines Ex glBegin(GL_POLYGON); glVertex2f(0.0, 0.0); glVertex2f(0.0, 3.0); glVertex2f(4.0, 3.0); glVertex2f(6.0, 1.5); glVertex2f(4.0, 0.0); glEnd();

A Drawing Survival Kit -4

A Drawing Survival Kit -5 Valid calls between glBegin(…); & glEnd(); –glVertex*(); glNormal*(); glColor*(); glIndex*(); glTexCoord*(); glMaterial*(); … Forcing Completion of Drawing –glFlush(void); Asynchronous –glFinish(void); Synchronous –glutSwapBuffers(void); Swap back buffer and front buffer. (Double buffering for animation)

A Drawing Survival Kit -6 Basic State Management –glEnable( … ); Enable some state. Ex: glEnable( GL_LIGHTING ); –glDisable( … ); Disable some state. Ex. glDisable( GL_TEXTURE_2D ); –glIsEnabled( … ); Query if the specific state is enabled. Ex: glIsEnabled( GL_BLEND ); –glGetBooleanv(…); glGetIntegerv(…); glGetFloatv(…); glGetDoublev( … ); glGetPointerv(…); Query the specific state value. –Ex: glGetIntegerv( GL_VIEWPORT, vp );

A Drawing Survival Kit -7 Polygon Detail –glPolygonMode( GLenum face, GLenum mode ); face: GL_FRONT, GL_BACK, GL_FRONT_AND_BACK mode: GL_POINT, GL_LINE, GL_FILL –glFrontFace( GLenum mode ); mode: GL_CCW(default), GL_CW –glCullFace( GLenum mode ); mode: GL_FRONT, GL_BACK, GL_FRONT_AND_BACK glEnable( GL_CULL_FACE );

A Drawing Survival Kit -8 Specifying a Shading Model –glShadeModel( GLenum mode ); mode: GL_SMOOTH(default), GL_FLAT

Some information about Polygon (page Redbook ) –glPolygonMode( GLenum face, GLenum mode ); face: GL_FRONT, GL_BACK, GL_FRONT_AND_BACK mode: GL_POINT, GL_LINE, GL_FILL (default) –glFrontFace( GLenum mode ); mode: GL_CCW( defaul t), GL_CW –glCullFace( GLenum mode ); indicates which polygons should be discarded (culled) before they ’ re converted to screen coordinates mode: GL_FRONT, GL_BACK, GL_FRONT_AND_BACK glEnable( GL_CULL_FACE ); –glShadeModel( GLenum mode ); mode: GL_SMOOTH(default), GL_FLAT

Hidden Surface Removal main() { ………………………….. glutInitDisplayMode (GLUT_DEPTH |.... ); glEnable(GL_DEPTH_TEST);... } display ( ) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ………………………. ……………………….. draw_object_A(); draw_object_B(); }

VIEWING The camera analogy rendering pipeline –stages of vertex transform

Two Transformation Matrices ModelView: geometry transformation and viewpoint placement (dual) Projection: orthographic and perspective

Specifying Projection in OpenGL glFrustum gluPerspective –symmetry viewing volume guaranteed glOrtho gluOrtho2D

Viewport Transformation aspect ratio control

Rendering Pipeline Details Modeling and viewing transformation Orthographic (parallel) and perspective projection 4x4 Matrix OpenGL implementations

Modeling Transformation modeling transformation: –glTranslate –glRotate –glScale –glMultMatrix each generates a corresponding 4x4 matrix (Appendix A) order of interpretation: INML v

Hence,... glRotate (30, 0, 0, 1); glTranslate (10, 0, 0); drawPlant( ); glTranslate (10, 0, 0); glRotate (30, 0, 0, 1); drawPlant( );

Viewing Transformation same as modeling transformation glTranslate (0, 0, -5)

Viewing Transform (cont) common practice –compose the scene (positioning/orienting objects) –then, place viewpoint Hence, issue view transformation commands BEFORE any modeling transformation two ways to do so: –use glTranslate & glRotate less confusing if think in terms of moving objects) –gluLookAt default camera –position at origin, pointed to negative-z

Perspective Projection

Relevant Commands glMatrixMode glLoadIdentity glLoadMatrix glMultMatrix Matrix declared as m[16]

Ex: cube.c #include void init(void) { glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_FLAT); } void display(void) { glClear (GL_COLOR_BUFFER_BIT); glColor3f (1.0, 1.0, 1.0); glLoadIdentity (); /* clear the matrix */ /* viewing transformation */ gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glScalef (1.0, 2.0, 1.0); /* modeling transformation */ glutWireCube (1.0); glFlush (); } void reshape (int w, int h) { glViewport (0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); glFrustum (-1.0, 1.0, -1.0, 1.0, 1.5, 20.0); glMatrixMode (GL_MODELVIEW); } void keyboard(unsigned char key, int x, int y) { switch (key) { case 27: exit(0); break; } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (500, 500); glutInitWindowPosition (100, 100); glutCreateWindow (argv[0]); init (); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutMainLoop(); return 0; }

Lighting (Chapter 4 Redbook) –Step 1: Define Normal Vectors for Each Vertex of Every Object –Step 2: Create, Position, and Enable One or More Light Sources –Step 3: Select a Lighting Model –Step 4: Define Material Properties for the Objects in the Scene –Similar to VRML

Step 1: Specify Normal Vector –By yourself, define normal vectors by call glNormal{3,4}{i,s,f,d}[v]( … ) Ex: glNormal3fv(n1); n1 is array name Ex: glNormal3f(x1,y1,z1). –Normal vectors must be normalized. Automatically normalize normal vectors for you by calling glEnable( GL_NORMALIZE ); but expensive –glutxxx like glutSolidCube(), normal is part of model.

Step 2: Create a Light Source (page 181 RedBook) –void glLight{if}(GLenum light, GLenum pname, TYPE param); void glLight{if}v(GLenum light, GLenum pname, TYPE *param); GL_LIGHT0, GL_LIGHT1,..., or GL_LIGHT7 are availble. The characteristic of the light being set is defined by pname. param indicates the values to which the pname characteristic is set. Ex: glLightfv(GL_LIGHT0,GL_AMBIENT,light_ambient)

– The default values listed for GL_DIFFUSE and GL_SPECULAR apply only to GL_LIGHT0. –For other lights, the default value is (0.0, 0.0, 0.0, 1.0 ) for both GL_DIFFUSE and GL_SPECULAR.

Example: GLfloat light_ambient[] = { 0.0, 0.0, 0.0, 1.0 }; GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 }; glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glLightfv(GL_LIGHT0, GL_POSITION, light_position); See page 53 in notes chapter 4

Example #include void init(void) { GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat mat_shininess[] = { 50.0 }; GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 }; glClearColor (0.0, 0.0, 0.0, 0.0); glShadeModel (GL_SMOOTH); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); }

Positions and Enable Lighting Position ( x, y, z, w ) –w is ZERO, Directional light –W (i.e., 1) is NONZERO, Positional light Define multiple lights in your scene and enable or disable them –glEnable( GL_LIGHT0 ); –glDisable( GL_LIGHT7 ); Enable OpenGL Lighting –glEnable( GL_LIGHTING ); See page 44 in notes

Control Light’s Movements OpenGL treats the position and direction of a light source just as it treats the position of a geometric primitive (i.e., a 3D point) –MODELVIEW Transformation will be applied. Three types of control (see page 187 Redbook) –A light position that remains fixed –A light that moves around a stationary object –A light that moves along with the viewpoint

Keeping the Light Stationary (page 187 Redbook) glMatrixMode (GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho (-1.5, 1.5, -1.5*h/w, 1.5*h/w, -10.0, 10.0); else glOrtho (-1.5*w/h, 1.5*w/h, -1.5, 1.5, -10.0, 10.0); glMatrixMode (GL_MODELVIEW); glLoadIdentity(); … /* later in init() */ GLfloat light_position[] = { 1.0, 1.0, 1.0, 1.0 }; glLightfv(GL_LIGHT0, GL_POSITION, position); /* NO other MODELVIEW transformation is set before it…*/

Independently Moving the Light (see page 188 RedBook) static GLdouble spin; void display(void) { GLfloat light_position[] = { 0.0, 0.0, 1.5, 1.0 }; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glPushMatrix(); glRotated(spin, 1.0, 0.0, 0.0); glLightfv(GL_LIGHT0, GL_POSITION, light_position); glPopMatrix(); glutSolidTorus (0.275, 0.85, 8, 15); glPopMatrix(); glFlush(); }

Moving the Light Source Together with Your Viewpoint (see page 191 Redbook) GLfloat light_position() = { 0.0, 0.0, 0.0, 1.0 }; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLightfv(GL_LIGHT0, GL_POSITION, light_position); …… static GLdouble ex, ey, ez, upx, upy, upz; void display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); gluLookAt (ex, ey, ez, 0.0, 0.0, 0.0, upx, upy, upz); glutSolidTorus (0.275, 0.85, 8, 15); glPopMatrix(); glFlush(); }

Attenuation (page 206 Redbook) d = distance between the light's position and the vertex kc = GL_CONSTANT_ATTENUATION kl = GL_LINEAR_ATTENUATION kq = GL_QUADRATIC_ATTENUATION Ex: glLightf(GL_LIGHT0,option, value) –If light is directional light, the attenuation is 1

Spot Light (page 184 in RedBook) –Define your light as positional light –Define light spot direction GLfloat spot_direction[] = { -1.0, -1.0, 0.0 }; glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spot_direction); –Define light spot exponent glLightf(GL_LIGHT1, GL_SPOT_EXPONENT, 2.0); (default: 0) –Define light spot cutoff glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 45.0); By default, the spotlight feature is disabled because the GL_SPOT_CUTOFF parameter is (i.e. 2*180=360, all directions so it is not a spotlight at all), The value for GL_SPOT_CUTOFF is restricted to being within the range [0.0,90.0] (unless it has the special value 180.0).

Step 3: Lighting Model (see page 193 Redbook) Selecting a lighting model –void glLightModel{if}(GLenum pname, TYPEparam); void glLightModel{if}v(GLenum pname, TYPE *param); Sets properties of the lighting model. The characteristic of the lighting model being set is defined by pname, which specifies a named parameter. param indicates the values to which the pname characteristic is set Ex: Glfloat lmodel_ambient[]={0.2,0.2,0.2,1} –glLightModelfv(GL_LIGHT_MODEL_AMBIENT,lmodel_a mbient); –Even there is no light in your scene, object is lit by it.

Lighting Models

Step 4: Object Materials (see page 196 Redbook) –void glMaterial{if}(GLenum face, GLenum pname, TYPEparam); void glMaterial{if}v(GLenum face, GLenum pname, TYPE *param); Specifies a current material property for use in lighting calculations. face can be GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK. The particular material property being set is identified by pname and the desired values for that property are given by param. GL_AMBIENT_AND_DIFFUSE allows you to set both Glfloat mat_specular[] = {1.0,1.0,1.0,1.0} –glMaterialfv(GL_FRONT,GL_SPECULAR,mat_specular)

Material (like VRML) See example on page 47 in notes

Examples No ambient Reflection Gray ambient Reflection Blue ambient Reflection Diffuse Add Higher Emission Only Specular Shininess

Color Tracking (see page 45 in notes) Another technique for minimizing performance costs associated with changing material properties is to use glColorMaterial(). – void glColorMaterial(GLenum face, GLenum mode); Causes the material property (or properties) specified by mode of the specified material face (or faces) specified by face to track the value of the current color at all times. A change to the current color (using glColor*() ) immediately updates the specified material properties. The face parameter can be GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK (the default). The mode parameter can be GL_AMBIENT, GL_DIFFUSE, GL_AMBIENT_AND_DIFFUSE (the default), GL_SPECULAR, or GL_EMISSION. At any given time, only one mode is active. glColorMaterial() has no effect on color-index lighting.

Color Tracking glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT,GL_DIFFUSE); glColor3f(0.2,0.5,0.8) /** draw some objects here ***/ glColorMaterial(GL_FRONT,GL_SPECULAR); glColor3f(0.9,0.0,0.2); /** draw some objects here **/