OPENGL Y. Doç. Dr. Aybars UĞUR
OpenGL Nedir? OpenGL (Open Graphics Library), grafik donanımını kullanmak için hazırlanmış bir yazılım arayüzüdür. Bu kütüphane yardımıyla, 2B (Boyutlu) ve 3B Grafiksel nesneler ve işlemler, kolaylıkla tanımlanabilmektedir. Programlama dillerindeki önemli bir eksikliği gidermektedir. İki ve üç boyutlu etkileşimli grafikler içeren yazılımlar geliştirmek için kullanılan 250 farklı komutu (200 ü OpenGL in kendi içinde, 50 si de OpenGL Utility Library yani glut içinde olmak üzere) içermektedir. Grafik donanımlarının gücünden yararlanmaktadır. Dr. Aybars UĞUR 2
OpenGL : Bazı Özellikler İşletim Sistemi bağımsızdır (Windows 95/98/NT/2000..., Linux, Unix, MacOS, BeOS). Windows ta standart olarak gelir. Programlama Dili bağımsızdır. Kütüphane, C, C++,, C#, Java, Visual Basic, Delphi, Fortran, Perl gibi dillerden kullanılabilmektedir. Pencere yöneticilerinden bağımsızdır. Sisteme özgü ekler yapılmazsa, programlar, Win32, X-WindowX gibi tüm pencere yöneticileri ile sorunsuz çalışır. Pencere, fare ve klavye işlemlerinden bağımsız hale getirmek için kullanılan glut,, birçok işletim sistemine aktarılmıştır. Dr. Aybars UĞUR 3
OpenGL Temelleri Red Book tan yararlanınız OpenGL bir durum makinesidir : Çokgenler, etkin (current) renk, dönüşüm, çizim modu vs. etkilenir. OpenGL Spesifikasyonundaki herşey, tüm gerçekleştirimlerinde desteklenir. Dr. Aybars UĞUR 4
OpenGL RedBook - II Chapter 1, "Introduction to OpenGL," Chapter 2, "State Management and Drawing Geometric Objects," Chapter 3, "Viewing," Chapter 4, "Color," Chapter 5, "Lighting," Dr. Aybars UĞUR 5
OpenGL RedBook - II Chapter 6, "Blending, Antialiasing, Fog, and Polygon Offset," Chapter 7, "Display Lists," Chapter 8, "Drawing Pixels, Bitmaps, Fonts, and Images," Chapter 9, "Texture Mapping," Chapter 10, "The Framebuffer," Dr. Aybars UĞUR 6
OpenGL RedBook - III Chapter 11, "Tessellators and Quadrics," Chapter 12, "Evaluators and NURBS," Chapter 13, "Selection and Feedback," Chapter 14, "Now That You Know," Dr. Aybars UĞUR 7
OpenGL ve Visual C++ 6.0 Bu ders notları, basit olarak Visual C de OpenGL kullanımını anlatmak üzere hazırlanmıştır. OpenGL in diğer programlama dillerinden kullanımı benzer şekildedir. Örnek programlar hazırlandıktan sonra, Visual C++ 6.0 kullanılarak çalıştırılmış ve test edilmiştir. Örnekleri çalıştırabilmek için VC++ 6.0 yüklendikten sonra GLUT un eklenmesi gerekmektedir. Glut un güncel sürümü, aşağıda belirtilen adresten indirilebilmektedir : http://www.xmission xmission.com/~.com/~nate/opengl.html Dr. Aybars UĞUR 8
Glut un Kurulumu Visual C++ 6.0 yüklendikten sonra, GLUT un kurulması : GLUT Version 3.7.6 (117 KB) içindeki GLUT32.DLL, \Windows\System klasörüne (NT tabanlı ise WINNT\System System) GLUT.H, \Program Files\Microsoft Visual Studio\VC98 VC98\Include\GL klasörüne GLUT.LIB, \Program Files\Microsoft Visual Studio\VC98 VC98\Lib klasörüne kopyalanır. Proje ayarları Project-Settings Settings-Link-Object/Library Modules de başa : opengl32.lib lib glut32.lib lib eklenir. Dr. Aybars UĞUR 9
Using OpenGL & GLUT in Visual Studio.NET 2003 GLUT.H C:\Program Files\Microsoft Visual Studio.NET 2003\Vc7 Vc7\PlatformSDK\Include\gl GLUT.LIB C:\Program Files\Microsoft Visual Studio.NET 2003\Vc7 Vc7\PlatformSDK\Lib Dr. Aybars UĞUR 10
Glut : Başlangıç int main (int argc, char *argv[]) { glutinit(&argc, argv); glutinitdisplaymode (GLUT_DEPTH GLUT_DOUBLE GLUT_RGBA); glutinitwindowsize (windowwidth, windowheight); glutinitwindowposition (0, 0); glutcreatewindow ( 248 Video Game!"); } SetStates(); // Initialize rendering states* RegisterCallbacks(); // Set event callbacks* glutmainloop(); return 0; // Start GLUT Dr. Aybars UĞUR 11
İlk OpenGL Programı : Pencere Açmak #include <GL/glut glut.h> void init(void void) { glclearcolor(1.0,1.0,1.0,0.0); glshademodel(gl_flat); } void display(void void) { glclear(gl_color_buffer_bit); glutswapbuffers(); } int main(int int argc, char **argv argv) { glutinit(& (&argc,argv); glutinitdisplaymode(glut_double GLUT_RGB); glutinitwindowsize(400,100); glutinitwindowposition(100,100); glutcreatewindow("merhaba"); init(); glutdisplayfunc(display display); glutmainloop(); return 0; } Dr. Aybars UĞUR 12
OpenGL Double Buffering Double buffering: Draw on back buffer while front buffer is being displayed. When finished drawing, swap the two, and begin work on the new back buffer. glutswapbuffers(); Primary purpose: eliminate flicker Dr. Aybars UĞUR 13
VC++ Programının İşletimi File-New New-Workspaces den yeni bir Workspace açılır. File-New New-Files-C++ Source File ile C++ Kaynak Kodu sayfası açılır. Program yazılır veya belgeden kopyalanır. Derlenip çalıştırılır. Dr. Aybars UĞUR 14
OpenGL Komut Yapısı glcolor3f parametre veri tipi (float) OpenGL komutu öneki OpenGL komutu Komutu oluşturan kelimeler büyük harfle başlar Komutun üç parametre alan tipi Dr. Aybars UĞUR 15
OpenGL Sabit Yapısı GL_COLOR_BUFFER_BIT Sabitler GL_ ile başlar Tümü büyük harftir Kelimeleri ayırmada alt çizgi kullanılır Dr. Aybars UĞUR 16
Nesne Köşelerini Belirtme Nesneler köşeleri ile belirtilir : glvertex3f (2.0, 4.1, 6.0); glvertex2i (4, 5); Etkin Renk köşeleri etkiler : glcolor3f (0.0, 0.5, 1.0); Dr. Aybars UĞUR 17
Üçgen Oluşturma Şeklin köşeleri, glbegin(mode) ve glend() bloğu içinde ve saat yönü (counter-clockwise) sırasında yazılır. glbegin (GL_TRIANGLES); glvertex2i (0, 0); glvertex2i (2, 0); glvertex2i (1, 1); glend(); Dr. Aybars UĞUR 18
Şekil Oluşturma Dr. Aybars UĞUR 19
Primitive (İlkel) Türleri glbegin için Points Lines GL_POINTS GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP Triangles GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN Quads GL_QUADS, GL_QUAD_STRIP Polygons GL_POLYGON Dr. Aybars UĞUR 20
Temel Geometrik Tipler GL_POINTS individual points GL_LINES pairs of vertices interpreted as individual line segments GL_LINE_STRIP series of connected line segments GL_LINE_LOOP same as above, with a segment added between last and first vertices GL_TRIANGLES triples of vertices interpreted as triangles GL_TRIANGLE_STRIP linked strip of triangles GL_TRIANGLE_FAN linked fan of triangles GL_QUADS quadruples of vertices interpreted as four-sided polygons GL_QUAD_STRIP linked strip of quadrilaterals GL_POLYGON boundary of a simple, convex polygon Dr. Aybars UĞUR 21
İki Boyut ve Koordinat Sistemi OpenGL,, iki boyutlu grafikler için birçok alternatif içermektedir. Basit bir dikdörtgen çizmek için aşağıdaki kod bloğu kullanılır : glbegin( ( GL_QUADS ); glcolor3f( 1.0, 0.0, 0.0 ); glvertex2f( 0.0, 0.0 ); glvertex2f( 0.9, 0.0 ); (-1,-1) glvertex2f( 1.0, 1.0 ); glvertex2f( 0.0, 0.5 ); glend(); (1,1) Dr. Aybars UĞUR 22
Renkler KırmızıYeşil Mavi glcolor3f(0.0, 0.0, 0.0); black glcolor3f(1.0, 0.0, 0.0); red glcolor3f(0.0, 1.0, 0.0); green glcolor3f(1.0, 1.0, 0.0); yellow glcolor3f(0.0, 0.0, 1.0); blue glcolor3f(1.0, 0.0, 1.0); magenta glcolor3f(0.0, 1.0, 1.0); cyan glcolor3f(1.0, 1.0, 1.0); white glcolor3f(0.9, 0.9, 0.9); light gray glcolor3f(0.3, 0.3, 0.3); dark gray Tüm renkler, üç ana rengin (r, g, b) bileşiminden oluşur. Dr. Aybars UĞUR Tüm renkler, üç ana rengin (r, g, b) bileşiminden oluşur. 23
Örnek 2 : Mavi Dikdörtgen Çizmek #include <gl/glut.h> void init(void void) { glclearcolor(1.0,1.0,1.0,0.0); glshademodel(gl_flat); } void Draw_A A_Rectangle(void) { glbegin(gl_quads); glcolor3f(0.0,1.0,0.0); glvertex2f(0.25,0.25); glcolor3f(1.0,1.0,0.0); glvertex2f(0.25,0.75); glcolor3f(1.0,0.0,0.0); glvertex2f(0.75,0.75); glcolor3f(0.0,0.0,1.0); glvertex2f(0.75,0.25); glend(); } void display(void void) { glclear(gl_color_buffer_bit); Draw_A A_Rectangle(); glutswapbuffers(); } int main(int int argc,char char **argv argv) { glutinit(& (&argc,argv); glutinitdisplaymode(glut_double GLUT_RGB); glutinitwindowsize(400,100); glutinitwindowposition(100,100); glutcreatewindow(" Rectangle "); init(); glutdisplayfunc(display display); glutmainloop(); return 0; } Dr. Aybars UĞUR 24
Çokgen Üzerinde Renk Geçişi glshademodel(gl_smooth); void Draw_A A_Rectangle(void) { glbegin(gl_quads); glcolor3f(0.0,1.0,0.0); glvertex2f(0.25,0.25); glcolor3f(1.0,1.0,0.0); glvertex2f(0.25,0.75); glcolor3f(1.0,0.0,0.0); glvertex2f(0.75,0.75); glcolor3f(0.0,0.0,1.0); glvertex2f(0.75,0.25); glend(); } GL_FLAT Dr. Aybars UĞUR 25
OpenGL: Shading OpenGL supports 2 basic shading models: flat and smooth. glshademodel(gl_flat); glshademodel(gl_smooth); Dr. Aybars UĞUR 26
Örnek 3 : Döngü ile Çokgen Oluşturma #include <gl/glut.h> #include <math.h> void init(void void) { glclearcolor(1.0,1.0,1.0,0.0); glshademodel(gl_flat); } void Draw_Polygon Polygon(void) { double M_PI = 3.1415, angle; glcolor3f(0.0,1.0,0.0); glbegin (GL_LINE_LOOP); for (int j=0; j<10; j++) { angle = 2*M_PI*j/10; glvertex2f (cos( cos(angle), sin(angle angle)); } glend(); } void display(void void) { glclear(gl_color_buffer_bit); Draw_Polygon Polygon(); glutswapbuffers(); } int main(int int argc,char char **argv argv) { glutinit(& (&argc,argv); glutinitdisplaymode(glut_double GLUT_RGB); glutinitwindowsize(400,100); glutinitwindowposition(100,100); glutcreatewindow(" Polygon "); init(); glutdisplayfunc(display display); glutmainloop(); return 0; } Dr. Aybars UĞUR 27
GLUT Event Callbacks Register functions that are called when certain events occur. Examples: glutdisplayfunc( ( Display ); glutkeyboardfunc( ( Keyboard ); glutreshapefunc( ( Reshape ); glutmousefunc( ( Mouse ); glutpassivemotionfunc( PassiveFunc ); glutmotionfunc( MouseDraggedFunc ); glutidlefunc( ( Idle ); Dr. Aybars UĞUR 28
Etkileşim : Klavye void keyboard(unsigned char key, int x, int y) { switch(key key) { case 'x' : axis = X; spin(); glutpostredisplay(); break; case 'y' : axis = Y; spin(); glutpostredisplay(); break; default : break; } } Main e Eklenmesi gereken : glutkeyboardfunc(keyboard keyboard); Dr. Aybars UĞUR 29
Etkileşim : Fare void mouse(int button, int state, int x, int y) { switch (button)) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) glutidlefunc(spindisplay spindisplay); break; case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) glutidlefunc(null); break; default: break; } } Main e Eklenmesi gereken: glutmousefunc(mouse mouse); Dr. Aybars UĞUR 30
OPENGL : 3D CONCEPTS The camera initially points down the negative z-axis. (You're seeing the back of the camera.) Dr. Aybars UĞUR 31
Summary of 3D Transformation P(x, y, z) Modeling Transformation Viewing Transformation Projection Transformation Window-to-Viewport Transformation P(x, y) 3D Object Coordinates 3D World Coordinates 3D Viewing Coordinates 2D Projection Coordinates 2D Device Coordinates Dr. Aybars UĞUR 32
The Camera Analogy To take a photograph with a camera, steps might be Set up your tripod and pointing the camera at the scene (viewing trans.) Arrange the scene to be photographed into the desired composition (modoling trans.) Choose a camera lens or adjust the zoom (projection trans.) Determine how large you want the final photograph to be - for example, you might want it enlarged (viewport trans.) After these steps are performed, the picture can be snapped or the scene can be drawn. Dr. Aybars UĞUR 33
Stages of Vertex Transform Modelview matrix: orients the model and the camera relative to each other. Projection matrix: specifies the shape and orietation of the viewing volume. Viewport transformation: controls the conversion of 3D model coordinates to screen coordinates. Dr. Aybars UĞUR 34
Example: Drawing Cube 1 #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> 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 (); } Dr. Aybars UĞUR 35
Example: Drawing Cube 2 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); } 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); glutmainloop(); return 0; } Dr. Aybars UĞUR 36
Example: Drawing Cube 3 Viewing Transformation Analogus to positioning and aiming the camera. Usage: glulookat() Arguments indicate where the camera (eye position) is placed, where it is aimed, and which way is up. In the example, we place the camera at (0, 0, 5), aim the camera lens toward (0, 0, 0) and specify the up-vector as (0, 1, 0) By default the camera is at the origin (0, 0, 0), points down the negative z-axis and has an up-vector of (0, 0, 1) Modeling Transformation Analogous to positioning and orienting the model. Uasge: glscalef() Arguments specify how scaling should occur along the 3 axes. In the example, the cube is drawn twice as large in the y direction Dr. Aybars UĞUR 37
Example: Drawing Cube 4 Projection Transformation Similar to choosing a lens for a camera as determining what the field of view (FOV) or viewing volume is. In addition, it determines how objects are projected onto screen. Usage: glfrustum() Arguments describe values of left, right, bottom, top, near and far for a viewing volume. Before calling glfrustum(), glmatrixmode() with the argument GL_PROJECTION must be called. After calling glfrustum(), the matrix stack must be set back to GL_MODELVIEW Take care the current matrix with glloadidentity() Note: Default matrix stack is GL_MODELVIEW Dr. Aybars UĞUR 38
Example: Drawing Cube 5 Viewport Transformation Indicates the region of available screen area into which the scene is mapped. Usage: glviewport() The arguments describe the origin, the width and height of the region within the window. What does OpenGL do when all transformations have been specified? Transforms each vertex of every object in the scene by the modeling and viewing transformations. Transforms the vertices and clips the objects by the projection transformations Divides the remaining transformed vertices with w and maps them onto the viewport. Dr. Aybars UĞUR 39
Let s Think About Transformations In general, the order of transformation is critical If oyu do transformation A and then transformation B, you almost always get something different than you do them the the opposite order. Dr. Aybars UĞUR 40
Transformations and Viewing OpenGL has 3 different matrix modes: GL_MODELVIEW GL_PROJECTION GL_TEXTURE Choose the matrix with: glmatrixmode( ); Dr. Aybars UĞUR 41
Modelview matrix Transforms objects within the scene. glmatrixmode(gl_modelview); glloadidentity(); gltranslatef(10.5, 0, 0); glrotatef(45, 0, 0, 1); DrawCube(); Remember that the operations are right multiplied, so the transformation just before DrawCube() takes effect first. Dr. Aybars UĞUR 42
Modeling Transformations void gltranslate{fd}(type x, TYPE y, TYPE z); Multiplies the current matrix by a matrix that moves (translates) an object by the given x, y, and z values (or moves the local coordinate system by the same amounts). Dr. Aybars UĞUR 43
Üç Boyutlu Dönüşümler glrotate produces a rotation of angle degrees around the vector (x,y,z). void glrotated( GLdouble angle, GLdouble x, GLdouble y, GLdouble z) void glrotatef( GLfloat angle, GLfloat x, GLfloat y, GLfloat z ) glscale produces a nonuniform scaling along the x, y, and z axes. void glscaled( GLdouble x, GLdouble y, GLdouble z ) void glscalef( GLfloat x, GLfloat y, GLfloat z ) gltranslate produces a translation by (x,y,z). void gltranslated( GLdouble x, GLdouble y, GLdouble z ) void gltranslatef( GLfloat x, GLfloat y, GLfloat z ) Dr. Aybars UĞUR 44
OpenGL Matrix Stacks glloadidentity(void); Clears the currently modifiable matrix for future transformation instructions. Typically we call this instruction before specifying modeling, viewing or projection transformations. Dr. Aybars UĞUR 45
OpenGL Matrix Stacks Manipulating stacks: the OpenGL calls to push, pop, or multiply top of stack glloadmatrix(void); glmultmatrix(void); glpushmatrix(void); the topmost matrix is copied glpopmatrix(void); the topmost matrix is destroyed All vertices of the object are multiplied by the matrix. Dr. Aybars UĞUR 46
OpenGL Matrix Stacks Manipulating stacks: the OpenGL calls to push, pop, or multiply top of stack glloadmatrix(const type *m); glmultmatrix(const type *m); m1 m5 m9 m13 m2 m6 m10 m14 m3 m7 m11 m15 m4 m8 m12 m16 Dr. Aybars UĞUR 47
Matrix Stacks OpenGL supports two stacks of matrices Modelview matrix stack (4x4 matrices) Projection matrix stack (4x4 matrices) These stacks are useful for constructing hierarchical models. For example a car made of its body and the four wheels: Rotate wheels Rotate wheels + Rotate body Dr. Aybars UĞUR 48
Matrix Stacks glpushmatrix(void (void) - Pushes all matrices in the current stack down one level. glpopmatrix(void (void) - Pops the top matrix off the current stack, losing the topmost matrix! (The current stack is determined by glmatrixmode). Current matrix level Current matrix level M4 M3 M2 M1 M5 M5 M4 M3 M2 Push Pop M4 M4 M3 M2 M1 M4 M3 M2 M1 M1 Dr. Aybars UĞUR 49
Matrix Stacks Example code: void drawcar() { } glmatrixmode(gl_modelview) ) ; gltranslatef(x,y,z) ) ; /*/ glrotatef(car_ang,, 0, 1, 0) ; /*/ draw_car_body() ; glpushmatrix() ; gltranslate(-1,0,1) ; glrotatef(wheels_ang,, 0, 1, 0) ; draw_car_wheel() ; glpopmatrix() ; glpushmatrix() ; gltranslate(1,0,1) ; glrotatef(wheels_ang,, 0, 1, 0) ; draw_car_wheel() ; glpopmatrix() ; First we move and rotate the car (body + wheels) - as it is the top level in the hierarchy. Next we push the stack - and therefore store a copy. Then we draw the right and left wheels in their appropriate position and orientation. Note that on each wheel the transformation /*/ will operate. The last pop will retrieve the matrix containing only the /*/ transformations. Dr. Aybars UĞUR 50
3D GLUT predefined shapes Dr. Aybars UĞUR 51
Üç Boyutlu Hazır Nesneler glutsolidsphere, glutwiresphere glutsolidcube, glutwirecube glutsolidcone, glutwirecone glutsolidtorus, glutwiretorus glutsoliddodecahedron, glutwiredodecahedron glutsolidoctahedron, glutwireoctahedron glutsolidtetrahedron, glutwiretetrahedron glutsolidicosahedron, glutwireicosahedron glutsolidteapot, glutwireteapot I Dr. Aybars UĞUR 52
Üç Boyutlu Hazır Nesneler II glutsolidcone - render a solid or wireframe cone respectively. glutwirecone glutsolidcube - render a solid or wireframe cube respectively. glutsoliddodecahedron - render a solid or wireframe dodecahedron (12-sided regular solid) respectively. glutsolidicosahedron - render a solid or wireframe icosahedron (20-sided regular solid) respectively. glutsolidoctahedron - render a solid or wireframe octahedron (8-sided regular solid) respectively. glutsolidsphere - render a solid or wireframe sphere respectively. glutsolidteapot - render a solid or wireframe teapot respectively. glutsolidtetrahedron - render a solid or wireframe tetrahedron (4-sided regular solid) respectively. glutsolidtorus - render a solid or wireframe torus (doughnut) respectively. Dr. Aybars UĞUR 53
Projection Matrix I Sets up a perspective projection. glfrustrum (...); gluperspective (fovy, aspect, near, far); glortho (...); glulookat (...); (often applied to modelview matrix) Dr. Aybars UĞUR 54
Projection Matrix - II Example: glmatrixmode(gl_projection); glloadidentity(); gluperspective(64, (float)windowwidth / (float)windowheight, 4, 4096); glulookat(0.0, 0.0, 2.0, // camera position 0.0, 0.0, 0.0, // target position 0.0, 0.0, 2.0);// up vector Dr. Aybars UĞUR 55
Perspective Viewing Volume Specified by gluperspective() Dr. Aybars UĞUR 56
Viewing Transformations Default camera position glulookat(4.0, 2.0, 1.0, 2.0, 4.0, -3.0, 2.0, 2.0, -1.0); Dr. Aybars UĞUR 57
Viewport Transformation The viewport transformation specifies the rectangular region of the window where the model is drawn. void glviewport(glint x, GLint y, GLsizei width, GLsizei height); Defines a pixel rectangle in the window into which the final image is mapped. The (x, y) parameter specifies the lowerleft corner of the viewport, and width and height are the size of the viewport rectangle. By default, the initial viewport values are (0, 0, winwidth, winheight), where winwidth and winheight are the size of the window. Dr. Aybars UĞUR 58
Viewport Transformation The aspect ratio of a viewport should generally equal to the aspect ratio of the viewing volume. gluperspective(fovy, 1.0, near, far); glviewport(0, 0, 400, 400); gluperspective(fovy, 1.0, near, far); glviewport (0, 0, 400, 200); Dr. Aybars UĞUR 59
Sample Viewport Application // top left: top view glviewport(0, win_height/2, win_width/2, win_height/2); glmatrixmode(gl_projection); glloadidentity(); glortho(-3.0, 3.0, -3.0, 3.0, 1.0, 50.0); glulookat(0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0); glmatrixmode(gl_modelview); glloadidentity(); glcalllist(object); // top right: right view glviewport(win_width/2, win_height/2, win_width/2, win_height/2); glmatrixmode(gl_projection); glloadidentity(); glortho(-3.0, 3.0, -3.0, 3.0, 1.0, 50.0); glulookat(5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glmatrixmode(gl_modelview); glloadidentity(); glcalllist(object); // bottom left: front view glviewport(0, 0, win_width/2, win_height/2); glmatrixmode(gl_projection); glloadidentity(); glortho(-3.0, 3.0, -3.0, 3.0, 1.0, 50.0); glulookat(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glmatrixmode(gl_modelview); glloadidentity(); glcalllist(object); // bottom right: rotating perspective view glviewport(win_width/2, 0, win_width/2, win_height/2); glmatrixmode(gl_projection); glloadidentity(); gluperspective(70.0, 1.0, 1, 50); glulookat(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); glmatrixmode(gl_modelview); glloadidentity(); glrotatef(30.0, 1.0, 0.0, 0.0); glrotatef(angle, 0.0, 1.0, 0.0); glcalllist(object); Dr. Aybars UĞUR 60
OpenGL : Setting Up Rendering States OpenGL is a state machine: polygons are affected by the current color, transformation, drawing mode, etc. Enable and disable features such as lighting, texturing, and alpha blending. glenable (GL_LIGHTING); gldisable (GL_FOG); Forgetting to enable something is a common source of bugs! Dr. Aybars UĞUR 61
OpenGL: Normals and Lighting OpenGL can do lighting computations for you Normal vectors should be of unit length (normalized) in most cases. Normal vector kept as state each vertex is assigned the most recently set normal vector... glnormal3fv (n0); glvertex3fv (v0); glvertex3fv (v1); glvertex3fv (v2);... Dr. Aybars UĞUR 62
OpenGL: Lighting glenable (GL_LIGHTING); OpenGL supports a minimum of 8 lights. glenable (GL_LIGHT0);... glenable (GL_LIGHT7); Lights have a position, type, and color, among other things (more details in text). Types of lights are point light, directional light, and spotlight. Dr. Aybars UĞUR 63
Lighting in OpenGL GLfloat amb0[] = {0.2, 0.4, 0.6, 1.0}; GLfloat diff0[] = {0.8, 0.9, 0.5, 1.0}; GLfloat spec0[] = {1.0, 0.8, 1.0, 1.0}; gllightfv(gl_light0, GL_AMBIENT, amb0); //attach them to LIGHT0 gllightfv(gl_light0, GL_DIFFUSE, diff0); gllightfv(gl_light0, GL_SPECULAR, spec0); Dr. Aybars UĞUR 64
OpenGL: Material Properties Material properties are associated with each polygon (corresponding light properties) glmaterial*( *(GLenum face, GLenum pname,, TYPE param); Some properties (pname) : GL_AMBIENT: Ambient color of material GL_DIFFUSE: Diffuse color of material GL_SPECULAR: Specular component (for highlights) GL_SHININESS: Specular exponent (intensity of highlight) Dr. Aybars UĞUR 65
OpenGL: Texturing Mapping the texture to the polygon specify (s,t( s,t) ) texture coordinates for (x,y,z)) polygon vertices texture coordinates (s,t)are( from 0,1: gltexcoord2f(s,t); t (x3,y3,z3) (x1,y1,z1) 1,1 0,1 1,1 + 0,0 s 0,0 (x0,y0,z0) 1,0 (x2,y2,z2) Dr. Aybars UĞUR 66
OpenGL: Alpha Blending When enabled, OpenGL uses the alpha channel to blend a new fragment s color value with a color in the framebuffer + =? New color (r1,g1,b1,a1) source Color in framebuffer (r0,g0,b0,a0) destination (r,g,b,a ) Useful for overlaying textures or other effects Dr. Aybars UĞUR 67
OpenGL: Fog Simulate atmospheric effects glfog (): Sets fog parameters glenable (GL_FOG); Dr. Aybars UĞUR 68
Rendering Pipeline Dr. Aybars UĞUR 69
OpenGL: Other Features Display Lists (ch( 7): Speed up your game! Quadrics (ch( 11): Pre-made objects Also look at GLUT s objects Evaluators (ch( 12): Bezier curves and surfaces Selection (ch( 13): Clicking on game objects with a mouse Dr. Aybars UĞUR 70
CSGL C Sharp Graphics Library
CSGL OpenGL in.net ortamında kullanımını sağlayan grafik kütüphanesidir. Adresler : http://sourceforge.net/projects/csgl http://csgl.sourceforge.net/.net üzerinde csgl.1.4.1..1.4.1.dll.zip install dosyasından kurularak program geliştirmeye başlanabilir. Dr. Aybars UĞUR 72
Dikdörtgen Çizdiren CSGL Kodu (1) using System; using System.Drawing Drawing; using System.Windows..Windows.Forms; using CsGL.OpenGL OpenGL; public class RectDemo : Form { MyView view = new MyView(); public RectDemo() { Text = "Rect" demo!"; view.dock = DockStyle.Fill Fill; Controls.Add Add( view ); } } public static void Main() { RectDemo di = new RectDemo(); Application.Run Run( ( di ); } Dr. Aybars UĞUR 73
Dikdörtgen Çizdiren CSGL Kodu (2) class MyView : OpenGLControl { public override void gldraw() { GL.glClear glclear( ( GL.GL_COLOR_BUFFER_BIT GL.GL_DEPTH_BUFFER_BIT ); // Clear Screen And Depth Buffer GL.glBegin glbegin( ( GL.GL_QUADS ); GL.glVertex2i( 10, 10 ); GL.glVertex2i( 10, 50 ); GL.glVertex2i( 100, 50 ); GL.glVertex2i( 100, 10 ); GL.glEnd glend(); GL.glFlush glflush(); } protected override void InitGLContext() { GL.glClearColor glclearcolor( ( 1.0f, 1.0f, 1.0f, 0.0f ); GL.glColor3f( 0.0f, 0.0f, 0.0f ); GL.glPointSize glpointsize( ( 4.0f ); } Dr. Aybars UĞUR 74
Dikdörtgen Çizdiren CSGL Kodu (3) protected override void OnSizeChanged(EventArgs e) { base.onsizechanged OnSizeChanged(e); } } GL.glMatrixMode glmatrixmode(gl.gl_projection); GL.glLoadIdentity glloadidentity(); GL.gluOrtho2D( 0.0, Size.Width Width,, 0.0, Size.Height ); Dr. Aybars UĞUR 75
KAYNAKLAR Bilgisayar Grafikleri ders notları, Aybars UĞUR, Ege Üniversitesi OpenGL Red Book Sean Walker ve Ian Buck ders slaytları, Stanford University Dr. Aybars UĞUR 76