An Interactive Introduction to OpenGL Programming Dr. Mohammad Iqbal Based-on slide : Dave Shreiner, Ed Angel, Vicki Shreiner
Agenda z General
OpenGL Introduction z Rendering Primitives z Rendering Modes z Lighting z Texture Mapping z Additional Rendering Attributes z Imaging 2
Goals for Today z Tujuan
: mendemonstrasikan OpenGL dalam menghasilkan program grafik interaktif dalam Membuat model 3D obyek atau imagery z Lighting - pencahayaan z texture mapping z
z Mengenalkan
topik lanjut untuk pendalaman berikutnya 3
OpenGL and GLUT Overview
OpenGL and GLUT Overview z Apakah
OpenGL & apa manfaatnya? z OpenGL dalam sistem window z Mengapa GLUT z Template program GLUT
5
Apakah OpenGL? z Graphics
rendering API (Application Programming Interface) citra warna high-quality yang terdiri dari geometric dan citra primitif z Independen window system z Independen operating system z
6
Arsitektur OpenGL
Polynomial Evaluator
CPU
Display List
Per Vertex Operations & Primitive Assembly
Rasterization
Per Fragment Operations
Frame Buffer
Texture Memory Pixel Operations 7
OpenGL sebagai Renderer z Geometric z
primitif
titik, garis dan poligon
z Image
Primitif
Citra dan bitmap z Memisahkan pipeline untuk citra dan geometry z
z
linked ketika penerapan texture mapping
z Rendering z
tergantung pada status
warna, material, light sources, dll. 8
API yang Terkait OpenGL z
AGL, GLX, WGL z
z
GLU (OpenGL Utility Library) z z
z
Perekat antara OpenGL dan sistem window Bagian OpenGL NURBS, tessellators, quadric shapes, dll.
GLUT (OpenGL Utility Toolkit) z z
portable windowing API Bukan bagian OpenGL secara ofisial
9
API yang Terkait OpenGL application program OpenGL Motif widget or similar
GLX, AGL or WGL
X, Win32, Mac O/S
GLUT GLU GL
software and/or hardware
10
Preliminaries z Headers
Files
#include
z #include z #include z
z Libraries z Enumerated z
Types
OpenGL defines numerous types for compatibility z
GLfloat, GLint, GLenum, etc. 11
Dasar-dasar GLUT z Struktur
Aplikasi
Configure dan open window z Initialisasi status OpenGL z Register fungsi input callback z
render z resize z input: keyboard, mouse, dll. z
z
Enter event processing loop
12
Contoh Program void 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(); } 13
Inisialisasi OpenGL z
Set up status yg ingin digunakan 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 ); }
14
Fungsi input Callback GLUT z Rutin
yang dipanggil ketika sesuatu terjadi window resize atau redraw z user input z animasi z
z Me-“register”
callbacks pada GLUT
glutDisplayFunc( display ); glutIdleFunc( idle ); glutKeyboardFunc( keyboard ); 15
Rendering Callback z
Lakukan penggambaran grafik pada bagian ini : glutDisplayFunc( 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(); } 16
Idle Callbacks z
Gunakan untuk animasi dan update yang continyu glutIdleFunc( idle );
void idle( void ) { t += dt; glutPostRedisplay(); }
17
User Input Callbacks z
Untuk pemrosesan input dari user glutKeyboardFunc( keyboard );
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; } }
18
Elementary Rendering
Agenda Elementary Rendering z Geometric
Primitives z Managing OpenGL State z OpenGL Buffers
20
OpenGL Geometric Primitif z Semua
jenis geometric primitif dispesifikasikan oleh pipeline vertices GL_LINES
GL_POINTS GL_LINE_STRIP
GL_LINE_LOOP
GL_POLYGON
GL_TRIANGLES GL_TRIANGLE_STRIP
GL_QUADS GL_QUAD_STRIP GL_TRIANGLE_FAN 21
Contoh Sederhana void drawRhombus( GLfloat color[] ) { glBegin( GL_QUADS ); glColor3fv( color ); glVertex2f( 0.0, 0.0 ); glVertex2f( 1.0, 0.0 ); glVertex2f( 1.5, 1.118 ); glVertex2f( 0.5, 1.118 ); glEnd();
} 22
Format Perintah OpenGL glVertex3fv( v )
Number of components 2 3 4
-
(x,y) (x,y,z) (x,y,z,w)
Data Type b ub s us i ui f d
-
byte unsigned byte short unsigned short int unsigned int float double
Vector omit “v” for scalar form glVertex2f( x, y )
23
Specifying Geometric Primitives z Primitif
dispesifikasikan menggunakan :
glBegin( primType ); glEnd(); z
primType menentukan bagaimana vertice dikombinasikan GLfloat red, green, blue; Glfloat coords[3]; glBegin( primType ); for ( i = 0; i < nVerts; ++i ) { glColor3f( red, green, blue ); glVertex3fv( coords ); } glEnd(); 24
Model Warna OpenGL
Per Per Vertex Vertex
Poly. Poly. CPU CPU
DL DL
Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
z RGBA
atau Color Index color index mode Red Green
1
2
4
8
16
Blue
0 1 2 3 24 25 26
Display
123
219
74
RGBA mode
25
Shapes Tutorial
26
Mengendalikan tampilan Appearance (Rendering) Dari Wireframe menjadi Texture Mapped
27
Mesin Status OpenGL z Setiap
atribut rendering di encapsulapsi dalam OpenGL State rendering styles z shading z lighting z texture mapping z
28
Manipulasi Status OpenGL z
Tampilan dikendalikan oleh status terakhir for each ( primitive to render ) { update OpenGL state render primitive
} z
Manipulasi atribut vertex adalah cara umum untuk memanipulasi status glColor*() / glIndex*() glNormal*() glTexCoord*() 29
Mengendalikan Status terakhir z Setting
Status
glPointSize( size ); glLineStipple( repeat, pattern ); glShadeModel( GL_SMOOTH );
z Enabling
Features
glEnable( GL_LIGHTING ); glDisable( GL_TEXTURE_2D );
30
Transformasi
Transformasi dalam OpenGL z Modeling z Viewing
orientasi kamera z projection z
z Animasi z Map
to screen
32
Analogi Kamera z 3D
adalah seperti mengambil citra pada fotografi (Banyak foto!) viewing volume
camera
tripod
model
33
Analogi Kamera dan Transformasi z
Projection transformations z
z
Viewing transformations z
z
Mengatur posisi tripod dan orientasi viewing suatu volume dalam dunia nyata (world)
Modeling transformations z
z
Mengatur lensa kamera
memindahkan model
Viewport transformations z
Memperbesar atau mengurangi fotografi secara fisik 34
Sistem Koordinat dan Transformasi z
Langkah dalam menyiapkan citra z z z z
z z
spesifikasikan geometri (world coordinates) spesifikasikan kamera (camera coordinates) proyeksi (window coordinates) Petakan ke viewport (screen coordinates)
Setiap langkah menggunakan transformasi Setiap transformasi adalah ekuivalen pada perubahan di sistem koordinat (frames)
35
Transformasi Affine z Transformasi
yang mempertahankan bentuk geometri z
garis, poligon, quadric
z Affine
= mempertahankan garis (line preserving) Rotasi, translasi, skala z Proyeksi z Konkatnasi (komposisi) z
36
Koordinat Homogen z
Setiap vertex adalah vector kolom
⎡x ⎤ ⎢ ⎥ G ⎢y⎥ v= ⎢z ⎥ ⎢ ⎥ ⎣w⎦ z z z
w umumnya bernilai 1.0 Semua operasi adalah perkalian matriks Arah (directed line segments) direpresentasikan w = 0.0
37
3D Transformations z
Vertex ditransformasikan oleh 4 x 4 matrik z z z z
Semua operasi affine adalah perkalian matriks Semua matrik disimpan secara column-major dalam OpenGL matriks selalu dalam kondisi post-multiplied K M v Produk matrik dan vector adalah ⎡m0 ⎢m M=⎢ 1 ⎢m2 ⎢ ⎣ m3
m4
m8
m5
m9
m6
m10
m7
m11
m12 ⎤ m13 ⎥ ⎥ m14 ⎥ ⎥ m15 ⎦ 38
Menspesifikasikan Transformasi z Programmer
memiliki 2 styles untuk men-spesifikasikan transformasi spesifikasikan matriks (glLoadMatrix, glMultMatrix) z spesifikasikan operasi (glRotate, glOrtho) glOrtho z
z Programmer
tidak perlu mengingat jenis matriksnya secara tepat z
cek lampiran buku Red Book (Programming Guide) 39
Programming Transformations z Sebelum
proses rendering, view, locate, dan orientasi : Posisi mata/kamera z 3D geometri z
z Mengatur z
matriks
Termasuk matriks stack
z Kombinasikan
(composite) transformasi
40
Pipeline Transformasi
Per Per Vertex Vertex
Poly. Poly. CPU CPU
DL DL
Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
eye
object v e r t e x
normalized device
clip
Modelview Matrix
Projection Matrix
Perspective Division
Modelview
Projection
z
Modelview z z z
window
Viewport Transform
Bbrp kalkulasi tambahan : z z z z z
material Î color shade model (flat) polygon rendering mode polygon culling clipping 41
Operasi Matriks z
Spesifikasikan Matriks Stack terkini glMatrixMode( GL_MODELVIEW atau GL_PROJECTION )
z
Matriks atau operasi Stack lain glLoadIdentity() glPopMatrix()
z
glPushMatrix()
Viewport z z
Biasanya sama dengan ukuran window size aspek rasio viewport harus sama dengan transformasi proyeksi atau citra hasilnya akan terdistorsi glViewport( x, y, width, height ) 42
Transformasi Proyeksi Bentuk untuk menampilkan (viewing) frustum : z Perspective projection gluPerspective( fovy, aspect, zNear, zFar ) glFrustum( left, right, bottom, top, zNear, zFar )
z
Orthographic parallel projection glOrtho( left, right, bottom, top, zNear, zFar ) gluOrtho2D( left, right, bottom, top z
)
Gunakan glOrtho dengan nilai z mendekati nol
43
Mengaplikasikan Transformasi Proyeksi z
Pengunaan Umum (orthographic projection) glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho( left, right, bottom, top, zNear, zFar );
44
Viewing Transformations z
Posisi Kamera/mata dalam scene z
z
Posisikan tripod (eye) ; persiapkan (aim) Kamera
Untuk Scene “fly through” z
z z
Ubah transformasi viewing dan re-draw scene gluLookAt( eyex, eyey, eyez, aimx, aimy, aimz, upx, upy, upz ) up vector menghasilkan orientasi unik Berhati-hati dalam de-generate posisi
tripod
45
Projection Tutorial
46
Modeling Transformations z z
Memindahkan obyek glTranslate{fd}( x, y, z ) Rotasi obyek di sekitar sumbu utama (x y z ) glRotate{fd}( angle, x, y, z ) z
z
angle dalam derajat
Dilasi (stretch atau shrink) atau mirror object glScale{fd}( x, y, z )
47
Transformation Tutorial
48
Connection: Viewing dan Modeling z Memindahkan
kamera equivalent dengan memindahkan setiap obyek di dunia nyata di depan kamera diam z Viewing transformation equivalent dengan transformasi modeling gluLookAt() memiliki perintah tersendiri yaitu polar view atau pilot view
49
Proyeksi dengan kaidah tangan kiri z Projection transformations (gluPerspective, glOrtho) berdasarkan
kaidah tangan kiri z
bayangkan zNear dan zFar sebagai jarak tertentu dari view point
z Setiap
hal selain itu adalah kaidah tangan kanan, termasuk vertex yang di y y render z+ left handed
right handed
x
x z+
50
Penggunaan Umum Transformasi z3 z
contoh rutin resize() Re-status proyeksi & viewing transformations
z Umumnya
dipanggil ketika window
resize z Di-register sebagai callback untuk glutReshapeFunc()
51
resize(): Perspective & LookAt void resize( int w, int h ) { glViewport( 0, 0, (GLsizei) w, (GLsizei) h ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 65.0, (GLdouble) w / h, 1.0, 100.0 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt( 0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 ); } 52
resize(): Perspective & Translate Efek yang sama dengan LookAt : void resize( int w, int h ) { glViewport( 0, 0, (GLsizei) w, (GLsizei) h ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 65.0, (GLdouble) w/h, 1.0, 100.0 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glTranslatef( 0.0, 0.0, -5.0 ); }
53
resize(): Ortho (bagian 1) void resize( int width, int height ) { GLdouble aspect = (GLdouble) width / height; GLdouble left = -2.5, right = 2.5; GLdouble bottom = -2.5, top = 2.5; glViewport( 0, 0, (GLsizei) w, (GLsizei) h ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); … continued … 54
resize(): Ortho (bagian 2) if ( aspect < 1.0 ) { left /= aspect; right /= aspect; } else { bottom *= aspect; top *= aspect; } glOrtho( left, right, bottom, top, near, far ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); } 55
Membangun Modeling Transformations z
Masalah 1: hirarki obyek z z
z
Suatu posisi tergantung pada posisi sebelumnya Lengan robot atau tangan ; sub-assemblies
Solusi 1: memindahkan sistem koordinat lokal z
z z
modeling transformation untuk memindahkan sistem koordinat post-multiply column-major matrices OpenGL post-multiplies matrices
56
Membangun Modeling Transformations z
Masalah 2 : obyek berpindah secara relatif pada absolute world origin z
Obyek berotasi di area yang salah pada origin z
z
Membuat obyek spin di sekitar center atau suatu area
Solusi 2: fixed coordinate system z z z z
modeling transformations akan memindahkan obyek disekitar fixed coordinate system pre-multiply column-major matrices OpenGL post-multiplies matrices harus me-reverse order operasi untuk mendapatkan efek yang diinginkan 57
Area Clipping Tambahan z z z
Paling tidak ada 6 atau lebih area clipping Baik untuk perhitungan cross-sections Modelview matrix memindahkan area clipping clipped Ax + By + Cz + D < 0
glEnable( GL_CLIP_PLANEi )
glClipPlane( GL_CLIP_PLANEi, GLdouble* coeff )
58
Reversing Koordinat Proyeksi z Screen
space kembali ke world space
glGetIntegerv( GL_VIEWPORT, GLint viewport[4] ) glGetDoublev( GL_MODELVIEW_MATRIX, GLdouble mvmatrix[16] ) glGetDoublev( GL_PROJECTION_MATRIX, GLdouble projmatrix[16] ) gluUnProject( GLdouble winx, winy, winz, mvmatrix[16], projmatrix[16], GLint viewport[4], GLdouble *objx, *objy, *objz )
z
gluProject untuk memindahkan
world space ke screen space 59
Pencahayaan (Lighting)
Prinsip Pencahayaan z Pencahayaan
mensimulasikan bagaimana obyek memantulkan cahaya Komposisi material obyek z Warna cahaya dan posisi z Parameter global pencahayaan z
Cahaya ambien z Pencahayaan dua sisi z
z
Terdapat pada color index dan mode RGBA
61
Bagaimana OpenGL Mensimulasikan Cahaya z Model z
Pencahayaan Phong
Perhitungan pada vertices
z Kontributor
Pencahayaan
Properti permukaan material z Properti cahaya z Properti Model pencahayaan z
62
Surface Normals
Poly. Poly. CPU CPU
DL DL
Per Per Vertex Vertex Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
z
Normal mendefinisikan bagaimana pemukaan memantulkan cahaya z z
z
glNormal3f( x, y, z )
Current normal digunakan untuk menghitung warna vertex Gunakan unit normals untuk pencahayaan yang tepat z
Skalakan efek pada panjang normal glEnable( GL_NORMALIZE ) or glEnable( GL_RESCALE_NORMAL ) 63
Material Properties z
Definisikan properti permukaan obyek primitif glMaterialfv( face, property, value );
z
GL_DIFFUSE
Base color
GL_SPECULAR
Highlight Color
GL_AMBIENT
Low-light Color
GL_EMISSION
Glow Color
GL_SHININESS
Surface Smoothness
Pisahkan material antara bagian front dan back
64
Properti Cahaya glLightfv( light, property, value ); z
light menspesifikasikan jenis cahaya z
z
multiple lights, mulai dari GL_LIGHT0 glGetIntegerv( GL_MAX_LIGHTS, &n );
properties Warna z posisi dan type z Attenuation (metode perambatan) z
65
Sumber cahaya z Light
color properties GL_AMBIENT GL_DIFFUSE GL_SPECULAR
66
Tipe Cahaya z OpenGL
mendukung 2 tipe Cahaya :
Local (Point) light sources z Infinite (Directional) light sources z
z Tipe
cahaya dikendalikan oleh koordinat
w
w = 0 Infinite Light directed along ( x w ≠ 0 Local Light positioned at (x w
z)
y y w
z
w
)
67
Menyalakan (Turning on) Cahaya z Flip
setiap “switch” cahaya
glEnable( GL_LIGHTn ); z Turn
on the power
glEnable( GL_LIGHTING );
68
Light Material Tutorial
69
Mengendalikan Posisi Cahaya z Modelview
matrix berpengaruh pada posisi cahaya: z
Perbedaan efek berdasarkan kapan posisi cahaya dispesifikasikan eye coordinates z world coordinates z model coordinates z
z
Matrik Push dan pop untuk pengendali unik posisi cahaya 70
Light Position Tutorial
71
Fitur Pencahayaan Lanjut z Spotlight z
Melokalisasi efek cahaya GL_SPOT_DIRECTION z GL_SPOT_CUTOFF z GL_SPOT_EXPONENT z
72
Fitur Pencahayaan Lanjut z Perambatan z
cahaya (Light attenuation)
decrease light intensity with distance GL_CONSTANT_ATTENUATION z GL_LINEAR_ATTENUATION z GL_QUADRATIC_ATTENUATION z
1 fi = k c + kl d + k q d 2 73
Properti Model Cahaya glLightModelfv( property, value ); z
Enabling two sided lighting GL_LIGHT_MODEL_TWO_SIDE
z
Global ambient color GL_LIGHT_MODEL_AMBIENT
z
Local viewer mode GL_LIGHT_MODEL_LOCAL_VIEWER
z
Separate specular color GL_LIGHT_MODEL_COLOR_CONTROL
74
Tips untuk pencahayaan yg baik z Pemanggilan
Pencahayaan dikomputasi hanya pada vertices z
Pemanggilan pada model tessellation memang menghasilkan kualitas pencahayaan yang lebih baik tapi proses geometrinya lebih kompleks
z Gunakan
cahaya tunggal infinite untuk perhitungan pencahayaan cepat z
Karena komputasi minimal untuk setiap vertex-nya 75
Animasi dan Depth Buffering
Animation dan Depth Buffering z Mendikusikan
double buffering dan
animasi z Mendiskusikan hidden surface removal menggunakan depth buffer
77
Double Buffering
Per Per Vertex Vertex
Poly. Poly. CPU CPU
DL DL
Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
1
1
2
Front Buffer
4
2 8
16
4
8
16
Back Buffer
Display 78
Animasi menggunakan Double Buffering c
Defenisikan double buffered pada color buffer glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE );
d
Clear color buffer glClear( GL_COLOR_BUFFER_BIT );
Render scene f Definisikan swap untuk front dan back buffers e
glutSwapBuffers();
z
Ulangi langkah 2 - 4 untuk animasi
79
Depth Buffering dan Hidden Surface Removal
1
1
2
Color Buffer
4
2 8
16
4
8
16
Depth Buffer
Display 80
Depth Buffering menggunakan OpenGL c
Defenisikan depth buffer glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH );
d
Enable depth buffering glEnable( GL_DEPTH_TEST );
e
Clear color dan depth buffers glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
Render scene g Swap color buffers f
81
An Updated Program Template void main( int argc, char** argv ) { glutInit( &argc, argv ); glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH ); glutCreateWindow( “Tetrahedron” ); init(); glutIdleFunc( idle ); glutDisplayFunc( display ); glutMainLoop(); }
82
An Updated Program Template (Lanjutan) void init( void ) { glClearColor( 0.0, 0.0, 1.0, 1.0 ); } void idle( void ) { glutPostRedisplay(); }
83
An Updated Program Template (Lanjutan) void drawScene( void ) { GLfloat vertices[] = { … }; GLfloat colors[] = { … }; glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glBegin( GL_TRIANGLE_STRIP ); /* calls to glColor*() and glVertex*() */ glEnd(); glutSwapBuffers(); } 84
Texture Mapping
Texture Mapping
Poly. Poly. CPU CPU
DL DL
Per Per Vertex Vertex Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
z mengaplikasikan
citra 1D, 2D, atau 3D ke geometrik primitif z Hal yang digunakan untuk proses Texturing simulasi material z Mengurangi kompleksitas geometrik z image warping z refleksi z
86
Texture Mapping
y
z
x
geometry
screen
t image s
87
Texture Mapping dan OpenGL Pipeline z Citra
dan geometri mengalir dalam pipeline yang terpisah pada proses di rasterizer z
“kompleks” textures tidak berpengaruh pada kompleksitas geometrik vertices
geometry pipeline rasterizer
image
pixel pipeline 88
Contoh Tekstur z Tekstur
ini adalah citra 256 x 256 yang di gabung (mapped) dengan poligon persegi panjang yang di tampilkan pada perspektif
89
Cara mengaplikasikan Tekstur I z Three
steps
c specify
texture
z read or generate image z assign to texture z enable texturing d assign
texture coordinates to vertices e specify texture parameters z
wrapping, filtering
90
Tekstur Obyek z
z
Like display lists for texture images z
one image per texture object
z
may be shared by several graphics contexts
Generate texture names glGenTextures( n, *texIds );
91
Cara mengaplikasikan Tekstur II specify textures in texture objects z set texture filter z set texture function z set texture wrap mode z set optional perspective correction hint z bind texture object z enable texturing z supply texture coordinates for vertex z
z
coordinates can also be generated 92
Tekstur Obyek (lanjutan) z
Create texture objects with texture data and state glBindTexture( target, id );
z
Bind textures before using glBindTexture( target, id );
93
Memilih citra untuk Tekstur
Poly. Poly. CPU CPU
DL DL
Per Per Vertex Vertex Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
z
Define a texture image from an array of texels in CPU memory
z
glTexImage2D( target, level, components, w, h, border, format, type, *texels ); z
z
dimensions of image must be powers of 2
Texel colors are processed by pixel pipeline z
pixel scales, biases and lookups can be done
94
Konversikan citra Tekstur z
If dimensions of image are not power of 2
z
gluScaleImage( format, w_in, h_in, type_in, *data_in, w_out, h_out, type_out, *data_out );
*_in is for source image z *_out is for destination image z Image interpolated and filtered during scaling z
95
Memilih Tekstur: Methode Lainnya z
Use frame buffer as source of texture image z
uses current buffer as source image
glCopyTexImage1D(...) glCopyTexImage2D(...) z Modify part of a defined texture glTexSubImage1D(...) glTexSubImage2D(...) glTexSubImage3D(...) z Do both with glCopyTexSubImage2D(...), etc.
96
Memetakan (Mapping) Tekstur
Poly. Poly. CPU CPU
DL DL
Per Per Vertex Vertex Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
z z
Based on parametric texture coordinates glTexCoord*() specified at each vertex t
0, 1
Texture Space 1, 1
(s, t) = (0.2, 0.8) A
a
b 0, 0
Object Space
c
(0.4, 0.2) B 1, 0
s
C (0.8, 0.4) 97
Membuat Koordinat Tekstur z
Automatically generate texture coords glTexGen{ifd}[v]()
z
specify a plane z
z
generate texture coordinates based upon distance from plane Ax + By + Cz + D = 0
generation modes z z z
GL_OBJECT_LINEAR GL_EYE_LINEAR GL_SPHERE_MAP
98
Tutorial: Texture
99
Metode Aplikasi Tekstur z
Filter Modes z z
z
Wrap Modes z
z
minification or magnification special mipmap minification filters clamping or repeating
Texture Functions z
how to mix primitive’s color with texture’s color z
blend, modulate or replace texels
100
Filter Modes Example: glTexParameteri( target, type, mode );
Texture Polygon Magnification
Texture
Polygon Minification
101
Tekstur Mipmapped z z z
Mipmap allows for prefiltered texture maps of decreasing resolutions Lessens interpolation errors for smaller textured objects Declare mipmap level during texture definition glTexImage*D( GL_TEXTURE_*D, level, … )
z
GLU mipmap builder routines gluBuild*DMipmaps( … )
z
OpenGL 1.2 introduces advanced LOD controls
102
Mode Wrapping z
Example: glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT )
t
s texture
GL_REPEAT wrapping
GL_CLAMP wrapping 103
Fungsi berkaitan dengan Tekstur z Controls how texture is applied z glTexEnv{fi}[v]( GL_TEXTURE_ENV, prop, param ) z GL_TEXTURE_ENV_MODE
modes
z
GL_MODULATE z GL_BLEND z GL_REPLACE z Set
blend color with
GL_TEXTURE_ENV_COLOR 104
Tips untuk Koreksi Perspektif z
Texture coordinate and color interpolation z z
z
either linearly in screen space or using depth/perspective values (slower)
Noticeable for polygons “on edge” z
glHint( GL_PERSPECTIVE_CORRECTION_HINT, hint )
where hint is one of z z z
GL_DONT_CARE GL_NICEST GL_FASTEST
105
Adakah tempat untuk Tekstur? z
Query largest dimension of texture image
typically largest square texture z doesn’t consider internal format size z glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size ) z
z
Texture proxy z z z
will memory accommodate requested texture size? no image specified; placeholder if texture won’t fit, texture state variables set to 0 z z
doesn’t know about other textures only considers whether this one texture will fit all of memory
106
Texture Residency z
Working set of textures z z z z
z
high-performance, usually hardware accelerated textures must be in texture objects a texture in the working set is resident for residency of current texture, check GL_TEXTURE_RESIDENT state
If too many textures, not all are resident z z
can set priority to have some kicked out first establish 0.0 to 1.0 priorities for texture objects
107
Imaging and Raster Primitives
Imaging and Raster Primitives z Describe
OpenGL’s raster primitives: bitmaps and image rectangles z Demonstrate how to get OpenGL to read and render pixel rectangles
109
Pixel-based primitives z Bitmaps z
2D array of bit masks for pixels z
update pixel color based on current color
z Images z
2D array of pixel color information z
complete color information for each pixel
z OpenGL
doesn’t understand image
formats 110
Pixel Pipeline
Poly. Poly. CPU CPU
DL DL
Per Per Vertex Vertex Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
z Programmable
pixel storage and transfer operations
glBitmap(), glDrawPixels() CPU
Pixel Storage Modes
Pixel-Transfer Operations (and Pixel Map)
Rasterization (including Pixel Zoom)
Texture Memory
Per Fragment Operations
glCopyTex*Image();
glReadPixels(), glCopyPixels()
Frame Buffer
Positioning Image Primitives z glRasterPos3f(
x, y, z )
raster position transformed like geometry z discarded if raster position is outside of viewport z
z
may need to fine tune viewport for desired results
Raster Position
112
Rendering Bitmaps
glBitmap( width, height, xorig, yorig, xmove, ymove, bitmap ) ⎣x − xorigbitmap ⎦ ⎣ y − yorig ⎦) z (render in current color
at yorig z advance (xmove ymove) raster position by after rendering
height
z
width xorig xmove
113
Rendering Fonts using Bitmaps z OpenGL
uses bitmaps for font rendering
each character is stored in a display list containing a bitmap z window system specific routines to access system fonts z
glXUseXFont() z wglUseFontBitmaps() z
114
Rendering Images z
glDrawPixels( width, height, format, type, pixels )
render pixels with lower left of image at current raster position z numerous formats and data types for specifying storage in memory z
z
best performance by using format and type that matches hardware
115
Reading Pixels z
glReadPixels( x, y, width, height, format, type, pixels )
read pixels from specified (x,y) position in framebuffer z pixels automatically converted from framebuffer format into requested format and type z
z Framebuffer pixel copy z glCopyPixels( x, y, width, height, type ) 116
Pixel Zoom z glPixelZoom(
x, y )
expand, shrink or reflect pixels around current raster position z fractional zoom supported z
Raster Position
glPixelZoom(1.0, -1.0);
117
Storage and Transfer Modes z Storage
modes control accessing
memory byte alignment in host memory z extracting a subimage z
z Transfer
modes allow modify pixel
values scale and bias pixel component values z replace colors using pixel maps z
118
Advanced OpenGL Topics
Advanced OpenGL Topics z Display
Lists and Vertex Arrays z Alpha Blending and Antialiasing z Using the Accumulation Buffer z Fog z Feedback & Selection z Fragment Tests and Operations z Using the Stencil Buffer 120
Immediate Mode versus Display Listed Rendering z
Immediate Mode Graphics z
z
z
Primitives are sent to pipeline and display right away No memory of graphical entities
Display Listed Graphics z z z z
Primitives placed in display lists Display lists kept on graphics server Can be redisplayed with different state Can be shared among OpenGL graphics contexts
121
Immediate Mode versus Display Lists Immediate Mode
Polynomial Evaluator
CPU
Display List
Per Vertex Operations & Primitive Assembly
Rasterization
Per Fragment Operations
Frame Buffer
Display Listed Texture Memory Pixel Operations 122
Display Lists
Poly. Poly. CPU CPU
DL DL
Per Per Vertex Vertex Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
z Creating
a display list
GLuint id; void init( void ) { id = glGenLists( 1 ); glNewList( id, GL_COMPILE ); /* other OpenGL routines */ glEndList(); }
z Call
a created list
void display( void ) { glCallList( id ); } 123
Display Lists z z z z
Not all OpenGL routines can be stored in display lists State changes persist, even after a display list is finished Display lists can call other display lists Display lists are not editable, but you can fake it z z
make a list (A) which calls other lists (B, C, and D) delete and replace B, C, and D, as needed 124
Display Lists and Hierarchy z Consider
model of a car
Create display list for chassis z Create display list for wheel z
z z z z z z z z
glNewList( CAR, GL_COMPILE ); glCallList( CHASSIS ); glTranslatef( … ); glCallList( WHEEL ); glTranslatef( … ); glCallList( WHEEL ); … glEndList();
125
Advanced Primitives z Vertex
Arrays z Bernstein Polynomial Evaluators z
basis for GLU NURBS z
NURBS (Non-Uniform Rational B-Splines)
z GLU
Quadric Objects
sphere z cylinder (or cone) z disk (circle) z
126
Vertex Arrays
Poly. Poly. CPU CPU
DL DL
Per Per Vertex Vertex Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
z
Pass arrays of vertices, colors, etc. to OpenGL in a large chunk z z z z z
z
glVertexPointer( 3, GL_FLOAT, 0, coords ) glColorPointer( 4, GL_FLOAT, 0, colors ) glEnableClientState( GL_VERTEX_ARRAY ) glEnableClientState( GL_COLOR_ARRAY ) glDrawArrays( GL_TRIANGLE_STRIP, 0, numVerts );
Color Vertex data data
All active arrays are used in rendering
127
Why use Display Lists or Vertex Arrays? z May
provide better performance than immediate mode rendering z Display lists can be shared between multiple OpenGL context z
reduce memory usage for multi-context applications
z Vertex
arrays may format data for better memory access
128
Alpha: the 4th Color Component z Measure z
of Opacity
simulate translucent objects z
glass, water, etc.
composite images z antialiasing z ignored if blending is not enabled z
glEnable( GL_BLEND )
129
Blending
Poly. Poly. CPU CPU
DL DL
Per Per Vertex Vertex Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
z Combine
pixels with what’s in already in the framebuffer z glBlendFunc( src, dst )
K K K Cr = src C f + dst C p Blending Blending Equation Equation Fragment (src)
Blended Pixel
Framebuffer Pixel (dst) 130
Multi-pass Rendering z Blending
allows results from multiple drawing passes to be combined together z
enables more complex rendering algorithms
Example of bump-mapping done with a multi-pass OpenGL algorithm
131
Antialiasing z Removing
the Jaggies z glEnable( mode )
GL_POINT_SMOOTH z GL_LINE_SMOOTH z GL_POLYGON_SMOOTH z
alpha value computed by computing sub-pixel coverage z available in both RGBA and colormap modes z
132
Accumulation Buffer z Problems
of compositing into color
buffers z
limited color resolution clamping z loss of accuracy z
z
Accumulation buffer acts as a “floating point” color buffer accumulate into accumulation buffer z transfer results to frame buffer z
133
Accessing Accumulation Buffer z glAccum( z
op, value )
operations within the accumulation buffer: GL_ADD, GL_MULT z from read buffer: GL_ACCUM, GL_LOAD z transfer back to write buffer: GL_RETURN z
z
glAccum(GL_ACCUM, 0.5) multiplies each value in write buffer by 0.5 and adds to accumulation buffer 134
Accumulation Buffer Applications z Compositing z Full
Scene Antialiasing z Depth of Field z Filtering z Motion Blur
135
Full Scene Antialiasing : Jittering the view z Each
time we move the viewer, the image shifts Different aliasing artifacts in each image z Averaging images using accumulation buffer averages out these artifacts z
136
Depth of Focus : Keeping a Plane in Focus z Jitter
the viewer to keep one plane unchanged
Back Plane Focal Plane
Front Plane
eye pos1
eye pos2 137
Fog z
glFog{if}( property, value )
z Depth z
Cueing
Specify a range for a linear fog ramp z
GL_FOG_LINEAR
z Environmental z
effects
Simulate more realistic fog GL_FOG_EXP z GL_FOG_EXP2 z
138
Fog Tutorial
139
Feedback Mode z Transformed
vertex data is returned to the application, not rendered z
useful to determine which primitives will make it to the screen
z Need to specify a feedback buffer z glFeedbackBuffer( size, type, buffer ) z Select feedback mode for rendering z glRenderMode( GL_FEEDBACK )
140
Selection Mode z Method
to determine which primitives are inside the viewing volume z Need to set up a buffer to have results returned to you glSelectBuffer( size, buffer ) z Select z
selection mode for rendering glRenderMode( GL_SELECT )
141
Selection Mode (cont.) z To z
identify a primitive, give it a name
“names” are just integer values, not strings
z Names z
are stack based
allows for hierarchies of primitives
z Selection
Name Routines
glLoadName( name ) glPushName( name ) glInitNames()
142
Picking z Picking
is a special case of selection z Programming steps z
restrict “drawing” to small region near pointer use gluPickMatrix() on projection matrix
enter selection mode; re-render scene z primitives drawn near cursor cause hits z exit selection; analyze hit records z
143
Picking Template glutMouseFunc( pickMe ); void pickMe( int button, int state, int x, int y ) { GLuint nameBuffer[256]; GLint hits; GLint myViewport[4]; if (button != GLUT_LEFT_BUTTON || state != GLUT_DOWN) return; glGetIntegerv( GL_VIEWPORT, myViewport ); glSelectBuffer( 256, nameBuffer ); (void) glRenderMode( GL_SELECT ); glInitNames();
144
Picking Template (cont.) glMatrixMode( GL_PROJECTION ); glPushMatrix(); glLoadIdentity(); gluPickMatrix( (GLdouble) x, (GLdouble) (myViewport[3]-y), 5.0, 5.0, myViewport ); /* gluPerspective or glOrtho or other projection */ glPushName( 1 ); /* draw something */ glLoadName( 2 ); /* draw something else … continue … */
145
Picking Template (cont.) glMatrixMode( GL_PROJECTION ); glPopMatrix(); hits = glRenderMode( GL_RENDER ); /* process nameBuffer */ }
146
Picking Ideas z
For OpenGL Picking Mechanism z z z
z
only render what is pickable (e.g., don’t clear screen!) use an “invisible” filled rectangle, instead of text if several primitives drawn in picking region, hard to use z values to distinguish which primitive is “on top”
Alternatives to Standard Mechanism z
color or stencil tricks (for example, use glReadPixels() to obtain pixel value from back buffer)
147
Depth Depth Test Test
Scissor Scissor Test Test
Blending Blending
Alpha Alpha Test Test
Dithering Dithering
Stencil Stencil Test Test
Logical Logical Operations Operations
Framebuffer
Fragment
Getting to the Framebuffer
148
Scissor Box z Additional
Clipping Test glScissor( x, y, w, h )
z
any fragments outside of box are clipped z useful for updating a small section of a viewport z
z
affects glClear() operations
149
Alpha Test
Poly. Poly. CPU CPU
DL DL
Per Per Vertex Vertex Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
z Reject
pixels based on their alpha value z glAlphaFunc( func, value ) z glEnable( GL_ALPHA_TEST )
z
use alpha as a mask in textures
150
Stencil Buffer
Poly. Poly. CPU CPU
DL DL
Per Per Vertex Vertex Texture Texture
Raster Raster
Frag Frag
FB FB
Pixel Pixel
z Used
to control drawing based on values in the stencil buffer Fragments that fail the stencil test are not drawn z Example: create a mask in stencil buffer and draw only objects not in mask area z
151
Controlling Stencil Buffer z
glStencilFunc( func, ref, mask )
z z z
z
compare value in buffer with ref using func only applied for bits in mask which are 1 func is one of standard comparison functions
glStencilOp( fail, zfail, zpass ) z
Allows changes in stencil buffer based on passing or failing stencil and depth tests: GL_KEEP, GL_INCR
152
Creating a Mask z z z z z z
glInitDisplayMode( …|GLUT_STENCIL|… ); glEnable( GL_STENCIL_TEST ); glClearStencil( 0x0 ); glStencilFunc( GL_ALWAYS, 0x1, 0x1 ); glStencilOp( GL_REPLACE, GL_REPLACE, GL_REPLACE ); draw mask
153
Using Stencil Mask z Draw z
glStencilFunc( GL_EQUAL, 0x1, 0x1 )
z Draw z
objects where stencil = 1
objects where stencil != 1
glStencilFunc( GL_NOTEQUAL, 0x1, 0x1 ); z glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
z 154
Dithering z
z Dither z
glEnable( GL_DITHER )
colors for better looking results
Used to simulate more available colors
155
Logical Operations on Pixels z Combine
pixels using bitwise logical operations z glLogicOp( mode ) z
Common modes GL_XOR z GL_AND z
156
Advanced Imaging z Imaging z
Subset
Only available if GL_ARB_imaging defined Color matrix z Convolutions z Color tables z Histogram z MinMax z Advanced Blending z
157
Ringkasan dan Penutup
On-Line Resources z
http://www.opengl.org z
start here; up to date specification and lots of sample code
z
news:comp.graphics.api.opengl
z
http://www.sgi.com/software/opengl http://www.mesa3d.org/
z
z
z
Brian Paul’s Mesa 3D
http://www.cs.utah.edu/~narobins/opengl.html z z
very special thanks to Nate Robins for the OpenGL Tutors source code for tutors available here!
159
Buku Programming Guide, 3rd Edition z OpenGL Reference Manual, 3rd Edition z OpenGL Programming for the X Window System z OpenGL
z
includes many GLUT examples
z Interactive
Computer Graphics: A topdown approach with OpenGL, 2nd Edition
160