C OpenGL Tutorial - PowerPoint PPT Presentation

1 / 51
About This Presentation
Title:

C OpenGL Tutorial

Description:

You don't have to try out everything just because with C everything is possible ... QuaterNion vs. Quaterion. Veronika Solteszova, Herbert Grasberger. 27 ... – PowerPoint PPT presentation

Number of Views:331
Avg rating:3.0/5.0
Slides: 52
Provided by: insit9
Category:

less

Transcript and Presenter's Notes

Title: C OpenGL Tutorial


1
C/OpenGL Tutorial
2
OUTLINE
  • C Tutorial
  • CG Vocabulary
  • OpenGL Tutorial

3
C Tutorial
4
Rule of thumb
  • You dont have to try out everything just because
    with C everything is possible

5
OUTLINE C Tutorial
  • Syntax differences on the low-level
  • Constants
  • Classes
  • Pointers
  • Memory management
  • In/Output
  • Using vectors and co.
  • What is unique for Java?
  • Useful links

6
Syntax differences on the low-level ( 1 )
  • The unsigned keyword
  • unsigned int ranges in 0, max int
  • Analogy for byte, short, long etc.
  • Not boolean but bool
  • This is valid
  • a b 1
  • Equivalent if statements
  • if( number ! 0 )
  • if( number )

7
Syntax differences on the low-level ( 2 )
  • Beware
  • if( a b )
  • instead
  • Compiles unlike Java
  • Arrays declaration
  • int vertices 10
  • Size fixed in declaration
  • We can trick it anyway ?

8
Syntax differences on the low-level ( 3 )
  • Beware
  • There are no IndexOutOfBoundsExceptions
  • You have to check it yourself
  • Or use stdvector or similar
  • Prevents You from
  • Accessing (read/write) not allocated memory
  • Reading data from any location
  • Undesired application crash

9
Constants and macros
  • Defining a constant
  • define MAX_SIZE 10
  • Usually without semicolon!
  • define MAX_SIZE 10
  • means MAX_SIZE is 10
  • After text replacement

mysize factor MAX_SIZE asize
mysize factor 10 asize
10
Classes ( 1 )
  • A class structure (in a header file ex. pair.h)
  • An example class
  • class Pair
  • public
  • Pair ( ) // The default constructor
  • Pair ( int x, int y ) // The constructor
  • Pair ( ) // The destructor
  • int getX ( )
  • int getY ( )
  • void setX ( int newValue )
  • void setY ( int newValue )
  • private
  • int x
  • int y

11
Classes ( 2 )
  • Function declaration in the .h (header) file
  • Function definition in the .cpp file
  • include pair.h
  • Example function definition

void PairsetX( int _x ) x _x
12
Classes ( 3 )
  • Q How to avoid cyclic includes?
  • A Compiler directives.
  • Ex. define, ifdef, ifndef, else, elseif,
    endif
  • Example code

ifndef _PAIR_H define _PAIR_H_ class Pair
endif
13
Classes inheritance
  • Dynamical binding not by default in C
  • virtual keyword necessary (example)

class Secretary Employee //Secretary extends
Employee public Secretary( int id ) virtual
void work( ) private void write( ) int
identity
  • SecretarySecretary( int id ) Employee( id ),
    identity( id )
  • void Secretarywork( )
  • Employeework( )
  • write( )

14
Pointers ( 1 )
  • Variable containing an address to another
    variable
  • 310 char achar array
  • 410 double pi 3.14
  • 411 long flag 0
  • 412 char pchar achar
  • 510 char pstr string
  • 610 long pli flag

15
Pointers ( 2 )
  • Example
  • Prints
  • i 42 intptr 42

int intptr int i 13, j 29 intptr i
// address operator intptr j //
dereference operator stdcout ltlt i ltlt
i stdcout ltlt intptr ltlt intptr ltlt stdendl
16
Pointers ( 3 )
  • Dereferencing objects example
  • Special operator -gt
  • b-gtdie( ) is equivalent to ( b ).die( )
  • b is the value, the bambus and die( ) its
    member
  • BambusTree b new BambusTree( )
  • BambusTree btree
  • b-gtgrow( 20.0f ) // dereferencing
  • b-gtdie( )
  • btree.grow( 20.0f )
  • btree.die( )

17
Pointers ( 4 )
  • Call by value
  • Parameter passing of a function
  • Call by reference
  • Passing an address as a parameter
  • Changes the functions arguments outside the
    function
  • Example

//function add add(int a, int b, int sum)sum
ab int summand1 2, summand2 3 int
result add( summand1, summand2, result )
18
Memory management ( 1 )
  • After creating a new object, we have ALLOCATED
    memory which WE must FREE
  • All pointers set with new must be set free
  • For each new we must provide a delete
  • Example (static destructor for simple objects)

BambusTree b new BambusTree( ) delete b
//calls a destructor of the class BambusTree b
null
19
Memory management ( 2 )
  • Arrays are also pointers, freeing memory
    necessary too
  • Example (dynamic destructor for arrays)
  • Use memory leak checkers

int riceField riceField new int 12
delete riceField riceField null
20
In/Output ( 1 )
  • Reading from a file
  • We include ltiostreamgt, ltfstreamgt, ltstringgt
  • Setup declare/define the necessary
  • Reading itself

stdstring filename name // name is a
parameter stdifstream in_str( filename.c_str(),
stdifstreamin ) stdstring currentLine
stdgetline( ( in_str ), currentLine ) // the
whole line is as a string in currentLine
21
In/Output ( 2 )
  • Reading from a file ( 2 )
  • String handling examples
  • Erasing
  • currentLine.erase( 0, 3 )
  • Getting ints and floats
  • int index float u float v
  • sscanf_s( currentLine.c_str( ), "d f f,
    index, u, v )
  • // currentLine expected to be ex. 1 0.567 0.789
  • Accessing a single character

currentLine.erase( 0, 3 )
int index float u float v sscanf_s(currentLine.
c_str(),"d f f,index,u,v) // currentLine
expected to be ex. 1 0.567 0.789
switch( currentLine 0 ) case '' case
'?'
22
In/Output ( 3 )
  • Reading from a file ( 3 )
  • Closing the input stream
  • in_str.close( )
  • Useful print a float/int variable to a buffer
  • char buffer 64
  • float radius 5
  • float perimeter 31.4159f
  • sprintf_s( buffer, "d f", radius, perimeter )
    // 5 31.4159
  • Writing to a command line

in_str.close( )
char buffer 64 float radius 5 float
perimeter 31.4159f sprintf_s( buffer, "d
f", radius, perimeter ) // 5 31.4159
stdcout ltlt radius ltlt ltlt perimeter ltlt
stdendl stdcerr ltlt ERROR OCCURED ltlt
stdendl stdcin.get() // wait until key
pressed, then close exit( 1 )
23
Using stdvector ( 1 )
  • C brother of Java-vector class
  • Grows dynamically
  • definition
  • stdvectorlt Bambus gt bv
  • An empty vector of elements type Bambus
  • stdvectorlt Bambus gt bv( 100 )
  • A Bambus-vector with 100 elements
  • Default constructor necessary

24
Using stdvector ( 2 )
  • bv a vectorlt Bambus gt, b Bambus
  • clear( ) resize(100) push_back( b) pop_back(
    )
  • Accessing elements
  • Many other useful functions

for( int i 0 i lt bv.size() i ) //bv i

25
Features unique for java
  • Thread handling is easy
  • synchronized keyword
  • instanceof operator
  • Interfaces
  • Java is interpreted!

26
Useful links
  • Online reference
  • http//www.cplusplus.com/
  • MS Development Network
  • www.msdn.com
  • Moving from java to C
  • http//www.horstmann.com/ccj2/ccjapp3.html
  • http//www-ali.cs.umass.edu/mckinley/377/labs/c
    _for_java_programmers.html
  • C Kurs
  • http//www.mathematik.uni-marburg.de/cpp/

27
OpenGL Tutorial
28
CG Vocabulary
  • Fixed function pipeline
  • Programmable pipeline
  • LightNing vs. Lighting
  • Gouraud shading
  • QuaterNion vs. Quaterion

29
OpenGL Tutorial - Outline
  • How to get OpenGL
  • Setup project
  • Concepts (state machine, stacks)
  • Viewing pipeline
  • Textures
  • Lighting
  • Render with immediate mode
  • Create window, context with Glut
  • Input handling with Glut

30
How to get OpenGL
  • API standard maintained by Khronos group
  • Implemented by graphics card vendors
  • Current OpenGL version v2.1
  • Windows includes only v1.1
  • Get somewhere else (Cg Toolkit 1)
  • Resources at 2

31
Setup project
  • Include files
  • Link libraries
  • opengl32.lib
  • glu32.lib

include ltGL/gl.hgt //basic OpenGL include
ltGL/glu.hgt //OpenGL utility functions
32
Concepts 1/2 - State machine
  • OpenGL command syntax
  • Certain amount of states are present
  • states set to certain mode, active until change
  • On/Off states (eg. backface culling)
  • Variable states (eg. current color)
  • Call to get value of states

glCommand1234sifd(Type x1, Type x2,
...) GL_CONSTANT //syntax for OpenGL constants
glGet() //several calls beginning with get
33
Concepts 2/2 - Stacks
  • Stacks for different sets of variables
  • Attribute stack
  • All states can be saved

glPushAttrib() //saves the current attribs on
stack glPopAttrib() //restores last saved attribs
  • Matrix stack
  • GL_PROJECTION
  • GL_MODELVIEW
  • GL_TEXTURE

glMatrixMode(GL_MODE) //sets the matrix
mode glPushMatrix() //saves the matrix on
stack glPopMatrix() //restores the last saved
matrix
34
Viewing pipeline 1/4
  • Modifications of matrices
  • Translation
  • Scale
  • Rotation
  • Calls always multiply the current active matrix

glTranslatefd(TYPE x, TYPE y, TYPE z)
glScalefd(TYPE x, TYPE y, TYPE z)
glRotatefd(TYPE angle, TYPE x, TYPE y, TYPE z)
35
Viewing pipeline 2/4
  • Perspective projection via GL_PROJECTION matrix
    mode
  • Build projection out of camera parameters
  • Important!
  • Clear the matrix before changing

glFrustum(l, r, b, t, n, f) //perspective
projection glOrtho(l, r, b, t, n,
f) //orthographic projection
gluPerspective(fov, aspect, near, far)
glLoadIdentity()
36
Viewing pipeline 3/4
  • Model and view matrix via GL_MODELVIEW
  • Must be rebuilt when camera position changes

gluLookAt(eyex, eyey, eyez, centerx, centery,
centerz, upx, upy, upz)
//camera changes glLoadIdentity() gluLookAt( ...
) //creates view matrix //render Models foreach
object glPushMatrix() //store on Matrix
stack transform and render model //modelview
created glPopMatrix() //recover view matrix
37
Viewing pipeline 4/4
  • Advanced methods
  • Generate one yourself
  • Multiply by current matrix

glMatrixMode(GL_MODE) float myMatrix new
float16 //generate the matrix you
want glLoadMatrixf(myMatrix) //replaces current
matrix //with given
glMatrixMode(GL_MODE) float myMatrix new
float16 //generate the matrix you
want glMultMatrixf(myMatrix) //multiplies
current matrix //with given
38
Textures 1/4
  • Texture activation
  • Have to be enabled
  • Unique handle for each texture
  • Bind active texture
  • Must be done every frame for every texture that
    is needed

glEnable(GL_TEXTURE_2D)
int myHandle glGenTextures(1, myHandle) //gener
ates handle for 1
glBindTexture(GL_TEXTURE_2D, myHandle)
39
Textures 2/4
  • Texture initialisation
  • Load texture data into GPU memory
  • Alternative build all mipmaps

enable and activate current texture int mipLevel
0 int border 0 int internalFormat
GL_RGBA, int width 800 int height 600 int
format GL_RGBA int type GL_UNSIGNED_BYTE cha
r data new charwidth height 4 //fill
data with values glTexImage(GL_TEXTURE_2D,
mipLevel, internalFormat, width, height, border,
format, type, data)
gluBuild2DMipmaps(GL_TEXTURE_2D, internalFormat,
width, height, border, format, type, data)
40
Textures 3/4
  • Texture environments
  • State call
  • Filtering types (pname)
  • Filtering method (param)

glTexParameteri(GL_TEXTURE_2D, pname, param)
GL_TEXTURE_MIN_FILTER //minification
filter GL_TEXTURE_MAG_FILTER //maxification
filter
GL_NEAREST //nearest neighbour GL_LINEAR //li
near GL_NEAREST_MIPMAP_NEAREST //nn with
mipmaps GL_LINEAR_MIPMAP_LINEAR //linear with
mipmaps
41
Textures 4/4
  • Texture environments
  • Repetition type (pname)
  • Repetition method (param)

GL_TEXTURE_WRAP_S //in s direction GL_TEXTURE_WRA
P_T //in t direction
GL_CLAMP_TO_EDGE GL_REPEAT
42
Lighting 1/2
  • Lighting activation
  • Set shading
  • GL_FLAT
  • GL_SMOOTH
  • Enable Lighting
  • Enable Light
  • 8 lights supported

glShadeModel(GL_MODE)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
43
Lighting 2/2
  • Lighting setup
  • State call
  • Light characteristic (pname)
  • Characteristic value (param)
  • Usually float4

glLightfv(GL_LIGHTi, pname, param)
GL_AMBIENT //params needed for diffuse
lighting GL_DIFFUSE //more are available GL_SPECUL
AR GL_POSITION
44
Render with immediate mode
  • Transfer each single vertex into GPU memory
  • Different primitives
  • Render primitive(s)

glTexCoord2f(u, v) //optional texcoord for
vertex glNormal3f(nx, ny, nz)//optional normal
for vertex glVertex3f(x, y, z)
GL_POINTS GL_LINES, GL_LINE_STRIP,
GL_LINE_LOOP GL_TRIANGLES, GL_TRIANGLE_STRIP,
GL_TRIANGLE_FAN GL_QUADS, GL_QUAD_STRIP,
GL_POLYGON
glBegin(GL_PRIMITIVE) calls for
vertices glEnd()
45
Create window, context with Glut 1/4
  • Glut OpenGL Utility Toolkit 3 4
  • Platform independent window and input handling
  • Link Library
  • glut32.lib

include ltGL/glut.hgt //must be first gl related
include do other opengl includes
46
Create window, context with Glut 2/4
  • Init Glut
  • Create window
  • windowed
  • full screen
  • Game mode string
  • pxwidth x pxheight depth _at_ refresh rate

glutInit(argc, argv) glutInitDisplayMode(GLUT_RG
BAGLUT_DOUBLEGLUT_DEPTH)
glutInitWindowPosition(50, 50) glutInitWindowSize
(width, height) glutCreateWindow(Windowtitle)
glutGameModeString(1024x76832_at_60) glutEnterGam
eMode()
47
Create window, context with Glut 3/4
  • Init OpenGL

glViewPort(0, 0, pxwidth, pxheight) glEnable(GL_
DEPTH_TEST) glDepthFunc(GL_LEQUAL) glClearDepth(
1.0f) glEnable(GL_CULL_FACE) glClearColor(0.0f
, 0.0f, 0.0f, 0.0f) //some other things done
here too, //but only in advanced OpenGL //see the
first repetitorium
48
Create window, context with Glut 4/4
  • Callbacks have to be set to user defined
    functions
  • Rendering and idle

void myRenderScene() glClear(GL_COLOR_BUFFER_BIT
GL_DEPTH_BUFFER_BIT) update an render
scene glutSwapBuffers() int main(int argc,
char argv) init glut init opengl other glut
callbacks glutDisplayFunc(myRenderScene) //set
callback glutIdleFunc(myRenderScene) //set
callback glutMainLoop() //starts the mainloop
49
Input handling with Glut 1/2
  • Set callbacks
  • Key down / up

float moveway 0.0f void myKeyboardFunc(int
key, int x, int y) if (key a) moveway
1.0f void myKeyboardUpFunc(int key, int x, int
y) if (key a) moveway
0.0f glutIgnoreKeyRepeat(1) //ignore
keyrepeat glutKeyboardFunc(myKeyboardFunc) glutKe
yboardUpFunc(myKeyboardUpFunc)
50
Input handling with Glut 2/2
  • Set callback
  • Mouse move / click

void myMouseMoveFunc(int x, int y) process
mousecoordinates void myMouseFunc(int button,
int state, int x, int y) process
buttons glutPassiveMotionFunc(myMouseMoveFunc)
glutMouseFunc(myMouseFunc)
51
References
  • 1 nVidia Cg Toolkit http//developer.nvidia.com/
    object/cg_toolkit.html
  • 2 OpenGLhttp//www.opengl.org
  • 3 Gluthttp//www.xmission.com/nate/glut.html
  • 4 Lighthouse3Dhttp//www.lighthouse3d.com/openg
    l/glut/
Write a Comment
User Comments (0)
About PowerShow.com