Upload
kylar
View
208
Download
20
Tags:
Embed Size (px)
DESCRIPTION
3D Game Programming OpenGL. Ming-Te Chi Department of Computer Science, National Chengchi University. Outline. Coordinate system Basic OpenGL Program GLUT event loop IO. Cartesian Plane. +y. (4, 3). (0, 0). +x. (-3, -2). +z. Coordinate Clipping. +y. (150, 100). (75, 50). - PowerPoint PPT Presentation
Citation preview
3D Game Programming
OpenGL3D Game Programming
OpenGLMing-Te Chi
Department of Computer Science, National Chengchi University
OutlineOutline
Coordinate system
Basic OpenGL Program
GLUT – event loop– IO
Cartesian PlaneCartesian Plane
(0, 0)
(4, 3)
(-3, -2)
+x
+y
+z
Coordinate Clipping Coordinate Clipping
(0, 0) +x
+y
(150, 100)
(-75, -50)
(75, 50)
ViewportViewport
Mapping drawing coordinates to windows coordinates
Window spaceclipping space
(0, 0) +x
+y
ProjectionProjection
Getting 3D to 2D– Orthographic projections
– Perspective projections
Representing VisualsRepresenting Visuals
3D objects– Mesh: geometry– Materials– Texture maps
Lighting
Shader
OpenGL and GLUT OverviewOpenGL and GLUT Overview
What is OpenGL ? What can it do for me?OpenGL in windowing systemsWhy GLUTA GLUT program template
8
What Is OpenGL?What Is OpenGL?
Graphics rendering API– high-quality color images composed of
geometric and image primitives
– window system independent
– operating system independent
9
SGI and GLSGI and GL
Silicon Graphics (SGI) revolutionized the graphics workstation by implementing the pipeline in hardware (1982)To access the system, application
programmers used a library called GLWith GL, it was relatively simple to
program three dimensional interactive applications 10
OpenGLOpenGL
The success of GL lead to OpenGL (1992), a platform-independent API that was – Easy to use– Close enough to the hardware to get
excellent performance– Focus on rendering– Omitted windowing and input to avoid
window system dependencies
11
OpenGL EvolutionOpenGL Evolution
Originally controlled by an Architectural Review Board (ARB) Members included SGI, Microsoft, Nvidia,
HP, 3DLabs, IBM,……. Relatively stable (present version 4.2)
▪ Evolution reflects new hardware capabilities▪ 3D texture mapping and texture objects▪ Vertex programs
Allows for platform specific features through extensions
ARB replaced by Khronos
12
Revolution of GPURevolution of GPU
Graphics Process Unit (GPU)
OpenGL generationOpenGL generation
Timeline of OpenGLTimeline of OpenGL Aug
OpenGL 4.2
OpenGL LibrariesOpenGL Libraries
OpenGL core library
OpenGL32 on Windows
GL on most unix/linux systems (libGL.a)
OpenGL Utility Library (GLU)
Provides functionality in OpenGL core but avoids having to
rewrite code
Links with window system
GLX for X window systems
WGL for Windows
AGL for Macintosh
OpenGL ArchitectureOpenGL Architecture
17
DisplayList
PolynomialEvaluator
Per VertexOperations &PrimitiveAssembly
RasterizationPer FragmentOperations
FrameBuffer
TextureMemory
CPU
PixelOperations
OpenGL as a RendererOpenGL as a Renderer
Geometric primitives– points, lines and polygons
Image Primitives– images and bitmaps– separate pipeline for images and
geometry• linked through texture mapping
Rendering depends on state– colors, materials, light sources, etc.
18
Related APIsRelated APIs
AGL, GLX, WGL– glue between OpenGL and windowing systems
GLU (OpenGL Utility Library)– part of OpenGL– NURBS, tessellators, quadric shapes, etc.
GLUT (OpenGL Utility Toolkit)– portable windowing API– not officially part of OpenGL
19
OpenGL and Related APIsOpenGL and Related APIs
20
GLUT
GLU
GL
GLX, AGLor WGL
X, Win32, Mac O/S
software and/or hardware
application program
OpenGL Motifwidget or similar
OpenGL-related ecosystemOpenGL-related ecosystem
PreliminariesPreliminariesHeaders Files
#ifdef WIN32#include <windows.h> // Must have for Windows platform builds#include "glee.h" // OpenGL Extension "autoloader"#include <gl\gl.h> // Microsoft OpenGL headers (version 1.1 by themselves)#include <gl\glu.h> // OpenGL Utilities#include <gl\glut.h> // Glut (or freeglut). Depend on the install dictionary#endif
Libraries (win32)– opengl32.lib– glu32.lib– glut32.lib
22
Enumerated Types– OpenGL defines numerous types for
compatibility– GLfloat, GLint, GLenum, etc.
Notes on compilationNotes on compilation
See website and ftp for examplesUnix/linux
– Include files usually in …/include/GL– Compile with –lglut –lglu –lgl loader flags– May have to add –L flag for X libraries– Mesa implementation included with
most linux distributions– Check web for latest versions of Mesa
and glut
24
Compilation on WindowsCompilation on Windows
Visual C++– Get glut.h, glut32.lib and glut32.dll from
web– Create a console application– Add opengl32.lib, glu32.lib, glut32.lib to
project settings (under link tab)
Cygwin (Linux under Windows)– Can use gcc and similar makefile to linux– Use –lopengl32 –lglu32 –lglut32 flags
25
Compilation on Mac OSXCompilation on Mac OSX
OpenGL and GLUT come with the OS and Xcode installations. To verify, check for:
/Library/Frameworks/{OpenGL,GLUT}.framework
– Use -framework GLUT -framework OpenGL flags
26
GLUT (OpenGL Utility Toolkit) GLUT (OpenGL Utility Toolkit)
GLUT was originally written by Mark Kilgard to support the sample programs in the second edition OpenGL 'RedBook‘Latest version– glut-3.7.6-bin.zip (117 KB) since 2001!
Strict licenseSweet alternative– freeglut – http://freeglut.sourceforge.net/docs/api.php
GLUT BasicsGLUT Basics
Application Structure– Configure and open window– Initialize OpenGL state– Register input callback functions
• render• resize• input: keyboard, mouse, etc.
– Enter event processing loop
28
29
GLUT Sample ProgramEvent
GLUT Sample ProgramEventInt 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();
return 0;}
Idle
Event Loop
OpenGL and WindowsInitialization
Callback function Registration
Get Event
Process Event
OpenGL InitializationOpenGL Initialization
Set up whatever state you’re going to use
void init( void )
{
glClearColor( 0.0, 0.0, 0.0, 1.0 );
glClearDepth( 1.0 );
glEnable( GL_LIGHT0 );
glEnable( GL_LIGHTING );
glEnable( GL_DEPTH_TEST );
}
30
GLUT Callback FunctionsGLUT Callback Functions
Routine to call when something happens– window resize or redraw– user input– animation
“Register” callbacks with GLUTglutDisplayFunc( display );glutIdleFunc( idle );glutKeyboardFunc( keyboard );
31
OpenGL Command FormatsOpenGL Command Formats
32
glVertexglVertex33ffvv( ( vv ) )
Number ofNumber ofcomponentscomponents
2 - (x,y) 2 - (x,y) 3 - (x,y,z)3 - (x,y,z)4 - (x,y,z,w)4 - (x,y,z,w)
Data TypeData Typeb - byteb - byteub - unsigned byteub - unsigned bytes - shorts - shortus - unsigned shortus - unsigned shorti - inti - intui - unsigned intui - unsigned intf - floatf - floatd - doubled - double
VectorVector
omit “v” foromit “v” forscalar formscalar form
glVertex2f( x, y )glVertex2f( x, y )
Rendering CallbackRendering Callback
Do all of your drawing here• glutDisplayFunc(glutDisplayFunc( display display ););
void display( void ){ glClear( GL_COLOR_BUFFER_BIT ); glBegin( GL_TRIANGLE_STRIP ); glVertex3fv( v[0] ); glVertex3fv( v[1] ); glVertex3fv( v[2] ); glVertex3fv( v[3] ); glEnd(); glutSwapBuffers();}
Idle CallbacksIdle Callbacks
Use for animation and continuous update
glutIdleFunc( glutIdleFunc( idleidle ); );
void idle( void ){ t += dt; glutPostRedisplay();}
34
Animation in GLUT alternativeAnimation in GLUT alternative– glutIdleFunc
• Sets the global idle callback.
• Only one idle function
• Can be easily stopped by
– Call glutPostRedisplay to refresh the screen
void glutIdleFunc ( void (*func)());
glutIdleFunc ( NULL );
User Input CallbacksUser Input CallbacksProcess user input
glutKeyboardFunc( glutKeyboardFunc( keyboardkeyboard ); );void keyboard( unsigned char key, int x, int y ){ switch( key ) { case ‘q’ : case ‘Q’ : exit( EXIT_SUCCESS ); break;
case ‘r’ : case ‘R’ : rotate = GL_TRUE;
glutPostRedisplay(); break; }}
The mouse callbackThe mouse callback
glutMouseFunc(mymouse) void mymouse(GLint button, GLint state, GLint x, GLint y)void mymouse(GLint button, GLint state, GLint x, GLint y)
Returns – which button (GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, GLUT_RIGHT_BUTTON) caused event
– state of that button (GLUT_UP, GLUT_DOWN)
– Position in window
37
PositioningPositioningThe position in the screen window is usually measured in pixels with the origin at the top-left corner• Consequence of refresh done from top to
bottomOpenGL uses a world coordinate system with origin at the bottom left• Must invert y coordinate returned by
callback by height of window• y = h – y;
38
(0,0) h
w
Orthographic ProjectionOrthographic Projection//myReshapevoid myReshape(int w, int h){ /* Save the new width and height */ screenWidth = w; screenHeight = h;
/* Reset the viewport... */ glViewport(0, 0, screenWidth, screenHeight);
glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, (GLfloat)screenWidth, 0.0, (GLfloat)screenHeight, -1.0, 1.0); glMatrixMode(GL_MODELVIEW);
}
Rect DrawingRect Drawingvoid RenderScene(void)
{// Clear the window with current clearing colorglClear(GL_COLOR_BUFFER_BIT);
// Set current drawing color to red// R G BglColor3f(1.0f, 0.0f, 0.0f);
// Draw a filled rectangle with current colorglRectf(x, y, x + rsize, y - rsize);
// Flush drawing commands and swap glutSwapBuffers();
}
Time functionTime functionglutTimerFunc(unsigned int millis, void (GLUTCALLBACK *func)(int
value), int value);
Registers a timer callback to be triggered in a specified number of milliseconds.
BounceBouncevoid TimerFunction(int value) { // Reverse direction when you reach left or right edge if(x > windowWidth-rsize || x < -windowWidth) xstep = -xstep;
// Reverse direction when you reach top or bottom edge if(y > windowHeight || y < -windowHeight + rsize) ystep = -ystep;
// Actually move the square x += xstep; y += ystep;
// Check bounds. This is in case the window is made
// smaller while the rectangle is bouncing and the // rectangle suddenly finds itself outside the new // clipping volume if(x > (windowWidth-rsize + xstep)) x = windowWidth-rsize-1;
else if(x < -(windowWidth + xstep))x = -windowWidth -1;
if(y > (windowHeight + ystep)) y = windowHeight-1;
else if(y < -(windowHeight - rsize + ystep))y = -windowHeight + rsize - 1;
// Redraw the scene with new coordinates glutPostRedisplay(); glutTimerFunc(33,TimerFunction, 1); }