3d game programming opengl

43
3D Game Programming OpenGL Ming-Te Chi Department of Computer Science, National Chengchi University

Upload: kylar

Post on 12-Jan-2016

207 views

Category:

Documents


20 download

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

TRANSCRIPT

Page 1: 3D Game Programming OpenGL

3D Game Programming

OpenGL3D Game Programming

OpenGLMing-Te Chi

Department of Computer Science, National Chengchi University

Page 2: 3D Game Programming OpenGL

OutlineOutline

Coordinate system

Basic OpenGL Program

GLUT – event loop– IO

Page 3: 3D Game Programming OpenGL

Cartesian PlaneCartesian Plane

(0, 0)

(4, 3)

(-3, -2)

+x

+y

+z

Page 4: 3D Game Programming OpenGL

Coordinate Clipping Coordinate Clipping

(0, 0) +x

+y

(150, 100)

(-75, -50)

(75, 50)

Page 5: 3D Game Programming OpenGL

ViewportViewport

Mapping drawing coordinates to windows coordinates

Window spaceclipping space

(0, 0) +x

+y

Page 6: 3D Game Programming OpenGL

ProjectionProjection

Getting 3D to 2D– Orthographic projections

– Perspective projections

Page 7: 3D Game Programming OpenGL

Representing VisualsRepresenting Visuals

3D objects– Mesh: geometry– Materials– Texture maps

Lighting

Shader

Page 8: 3D Game Programming OpenGL

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

Page 9: 3D Game Programming OpenGL

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

Page 10: 3D Game Programming OpenGL

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

Page 11: 3D Game Programming OpenGL

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

Page 12: 3D Game Programming OpenGL

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

Page 13: 3D Game Programming OpenGL

Revolution of GPURevolution of GPU

Graphics Process Unit (GPU)

Page 14: 3D Game Programming OpenGL

OpenGL generationOpenGL generation

Page 15: 3D Game Programming OpenGL

Timeline of OpenGLTimeline of OpenGL Aug

OpenGL 4.2

Page 16: 3D Game Programming OpenGL

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

Page 17: 3D Game Programming OpenGL

OpenGL ArchitectureOpenGL Architecture

17

DisplayList

PolynomialEvaluator

Per VertexOperations &PrimitiveAssembly

RasterizationPer FragmentOperations

FrameBuffer

TextureMemory

CPU

PixelOperations

Page 18: 3D Game Programming OpenGL

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

Page 19: 3D Game Programming OpenGL

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

Page 20: 3D Game Programming OpenGL

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

Page 21: 3D Game Programming OpenGL

OpenGL-related ecosystemOpenGL-related ecosystem

Page 22: 3D Game Programming OpenGL

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

Page 23: 3D Game Programming OpenGL

Enumerated Types– OpenGL defines numerous types for

compatibility– GLfloat, GLint, GLenum, etc.

Page 24: 3D Game Programming OpenGL

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

Page 25: 3D Game Programming OpenGL

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

Page 26: 3D Game Programming OpenGL

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

Page 27: 3D Game Programming OpenGL

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

Page 28: 3D Game Programming OpenGL

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

Page 29: 3D Game Programming OpenGL

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

Page 30: 3D Game Programming OpenGL

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

Page 31: 3D Game Programming OpenGL

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

Page 32: 3D Game Programming OpenGL

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 )

Page 33: 3D Game Programming OpenGL

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();}

Page 34: 3D Game Programming OpenGL

Idle CallbacksIdle Callbacks

Use for animation and continuous update

glutIdleFunc( glutIdleFunc( idleidle ); );

void idle( void ){ t += dt; glutPostRedisplay();}

34

Page 35: 3D Game Programming OpenGL

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 );

Page 36: 3D Game Programming OpenGL

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; }}

Page 37: 3D Game Programming OpenGL

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

Page 38: 3D Game Programming OpenGL

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

Page 39: 3D Game Programming OpenGL

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);

}

Page 40: 3D Game Programming OpenGL

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();

}

Page 41: 3D Game Programming OpenGL

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.

Page 42: 3D Game Programming OpenGL

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;

Page 43: 3D Game Programming OpenGL

// 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); }