DERS_05_OPENGL_2006

76
OPENGL OPENGL Y. Doç. Dr. Aybars UĞUR Y. Doç. Dr. Aybars UĞUR Ocak 2006 Ocak 2006

Transcript of DERS_05_OPENGL_2006

Page 1: DERS_05_OPENGL_2006

OPENGLOPENGL

Y. Doç. Dr. Aybars UĞURY. Doç. Dr. Aybars UĞUROcak 2006Ocak 2006

Page 2: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 22

OpenGLOpenGL Nedir?Nedir?

�� OpenGLOpenGL ((OpenOpen GraphicsGraphics LibraryLibrary), ), grafik donanımını kullanmak için hazırlanmış grafik donanımını kullanmak için hazırlanmış

bir yazılım bir yazılım arayüzüdürarayüzüdür..

�� Bu kütüphane yardımıyla, 2B (Boyutlu) ve 3B Grafiksel Bu kütüphane yardımıyla, 2B (Boyutlu) ve 3B Grafiksel nesneler ve işlemler, kolaylıkla tanımlanabilmektedir. nesneler ve işlemler, kolaylıkla tanımlanabilmektedir. Programlama dillerindeki önemli bir eksikliği Programlama dillerindeki önemli bir eksikliği gidermektedir.gidermektedir.

�� İki ve üç boyutlu etkileşimli grafikler içeren yazılımlar İki ve üç boyutlu etkileşimli grafikler içeren yazılımlar geliştirmek için kullanılan 250 farklı komutu (200’ü geliştirmek için kullanılan 250 farklı komutu (200’ü OpenGL’inOpenGL’in kendi içinde, 50’si de kendi içinde, 50’si de OpenGLOpenGL UtilityUtilityLibraryLibrary yani yani glutglut içinde olmak üzere) içermektedir. içinde olmak üzere) içermektedir.

�� Grafik donanımlarının gücünden yararlanmaktadır.Grafik donanımlarının gücünden yararlanmaktadır.

Page 3: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 33

OpenGLOpenGL : Bazı Özellikler: Bazı Özellikler

�� İşİşletim Sistemi bağımsızdır (Windows 95/98/NT/2000..., letim Sistemi bağımsızdır (Windows 95/98/NT/2000..., Linux, Unix, Linux, Unix, MacOSMacOS, , BeOSBeOS). Windows’ta standart ). Windows’ta standart olarak gelir.olarak gelir.

�� Programlama Dili bağımsızdır. Kütüphane, C, Programlama Dili bağımsızdır. Kütüphane, C, C++C++, C#, , C#, Java, Java, VisualVisual BasicBasic, , DelphiDelphi, , FortranFortran, , PerlPerl gibi dillerden gibi dillerden kullanılabilmektedir.kullanılabilmektedir.

�� Pencere yöneticilerinden bağımsızdır. Sisteme özgü ekler Pencere yöneticilerinden bağımsızdır. Sisteme özgü ekler yapılmazsa, programlar, Win32, Xyapılmazsa, programlar, Win32, X--WindowWindow gibi tüm gibi tüm pencere yöneticileri ile sorunsuz çalışır.pencere yöneticileri ile sorunsuz çalışır.

�� Pencere, fare ve klavye işlemlerinden bağımsız hale Pencere, fare ve klavye işlemlerinden bağımsız hale getirmek için kullanılan getirmek için kullanılan glutglut, birçok işletim sistemine , birçok işletim sistemine aktarılmıştır.aktarılmıştır.

Page 4: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 44

OpenGLOpenGL TemelleriTemelleri

� 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.

Page 5: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 55

OpenGLOpenGL RedBookRedBook -- IIII

� Chapter 1, "Introduction toOpenGL,"

� Chapter 2, "State Management andDrawing Geometric Objects,"

� Chapter 3, "Viewing,"� Chapter 4, "Color,"� Chapter 5, "Lighting,"

Page 6: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 66

OpenGLOpenGL RedBookRedBook -- IIII

� 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,"

Page 7: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 77

OpenGLOpenGL RedBookRedBook -- IIIIII

� Chapter 11, "Tessellators andQuadrics,"

� Chapter 12, "Evaluators andNURBS,"

� Chapter 13, "Selection andFeedback,"

� Chapter 14, "Now That You Know,"

Page 8: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 88

OpenGLOpenGL ve ve VisualVisual C++ 6.0C++ 6.0

�� Bu ders notları, basit olarak Bu ders notları, basit olarak VisualVisual C’deC’de OpenGLOpenGLkullanımını anlatmak üzere hazırlanmıştır. kullanımını anlatmak üzere hazırlanmıştır. OpenGL’inOpenGL’indiğer programlama dillerinden kullanımı benzer diğer programlama dillerinden kullanımı benzer şekildedir.şekildedir.

�� Örnek programlar hazırlandıktan sonra, Örnek programlar hazırlandıktan sonra, VisualVisual C++ 6.0 C++ 6.0 kullanılarak çalıştırılmış ve test edilmiştir. Örnekleri kullanılarak çalıştırılmış ve test edilmiştir. Örnekleri çalıştırabilmek için VC++ 6.0 yüklendikten sonra çalıştırabilmek için VC++ 6.0 yüklendikten sonra GLUT’unGLUT’un eklenmesi gerekmektedir.eklenmesi gerekmektedir.

�� Glut’unGlut’un güncel sürümü, aşağıda belirtilen adresten güncel sürümü, aşağıda belirtilen adresten indirilebilmektedir : indirilebilmektedir : http://www.http://www.xmissionxmission.com/~.com/~natenate//openglopengl.html.html

Page 9: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 99

Glut’unGlut’un KurulumuKurulumu

VisualVisual C++ 6.0 yüklendikten sonra, C++ 6.0 yüklendikten sonra, GLUT’unGLUT’un kurulması :kurulması :

GLUT GLUT VersionVersion 3.7.6 (117 KB) içindeki3.7.6 (117 KB) içindeki“GLUT32.DLL“, “GLUT32.DLL“, \\WindowsWindows\\SystemSystem klasörüne (NT tabanlı ise klasörüne (NT tabanlı ise

WINNTWINNT\\SystemSystem))“GLUT.H“, “GLUT.H“, \\Program Program FilesFiles\\Microsoft Microsoft VisualVisual

StudioStudio\\VC98VC98\\IncludeInclude\\GL klasörüneGL klasörüne“GLUT.LIB“, “GLUT.LIB“, \\Program Program FilesFiles\\Microsoft Microsoft VisualVisual StudioStudio\\VC98VC98\\LibLib

klasörüne kopyalanır.klasörüne kopyalanır.Proje ayarlarıProje ayarları

ProjectProject--SettingsSettings--LinkLink--ObjectObject//LibraryLibrary Modules’deModules’de başa : başa : opengl32.opengl32.liblib glut32.glut32.liblib eklenir.eklenir.

Page 10: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 1010

UsingUsing OpenGLOpenGL & GLUT in & GLUT in VisualVisual StudioStudio .NET 2003.NET 2003

�� GLUT.HGLUT.H

C:C:\\Program Program FilesFiles\\Microsoft Microsoft VisualVisual StudioStudio.NET 2003.NET 2003\\Vc7Vc7\\PlatformSDKPlatformSDK\\IncludeInclude\\glgl

�� GLUT.LIBGLUT.LIB

C:C:\\Program Program FilesFiles\\Microsoft Microsoft VisualVisual StudioStudio.NET 2003.NET 2003\\Vc7Vc7\\PlatformSDKPlatformSDK\\LibLib

Page 11: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 1111

GlutGlut : Başlangıç: 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(); // Start GLUT

return 0;}

Page 12: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 1212

İİlk lk OpenGLOpenGL Programı : Programı : Pencere AçmakPencere Açmak

##includeinclude <GL/<GL/glutglut.h>.h>

voidvoid initinit((voidvoid)){{glClearColorglClearColor(1.0,1.0,1.0,0.0);(1.0,1.0,1.0,0.0);glShadeModelglShadeModel(GL_FLAT);(GL_FLAT);

}}voidvoid displaydisplay((voidvoid)){ { glClearglClear(GL_COLOR_BUFFER_BIT); (GL_COLOR_BUFFER_BIT); glutSwapBuffersglutSwapBuffers();();

}}

intint mainmain((intint argcargc, , charchar ****argvargv)){{glutInitglutInit(&(&argcargc,,argvargv););glutInitDisplayModeglutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);(GLUT_DOUBLE|GLUT_RGB);glutInitWindowSizeglutInitWindowSize(400,100);(400,100);glutInitWindowPositionglutInitWindowPosition(100,100);(100,100);glutCreateWindowglutCreateWindow("Merhaba");("Merhaba");initinit();();glutDisplayFuncglutDisplayFunc((displaydisplay););glutMainLoopglutMainLoop();();returnreturn 0;0;

}}

Page 13: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 1313

OpenGL Double BufferingOpenGL Double Buffering

� Double buffering:–– Draw on Draw on back back buffer while buffer while front front buffer is being displayed.buffer is being displayed.

–– When finished drawing, swap the When finished drawing, swap the two, and begin work on the new two, and begin work on the new back buffer.back buffer.

––glutSwapBuffersglutSwapBuffers();();

� Primary purpose: eliminate flicker

Page 14: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 1414

VC++ Programının VC++ Programının İşletimiİşletimi

�� FileFile--NewNew--Workspaces’denWorkspaces’den yeni bir yeni bir WorkspaceWorkspace açılır.açılır.

�� FileFile--NewNew--FilesFiles--C++ C++ SourceSource File ile File ile C++ Kaynak Kodu sayfası açılır.C++ Kaynak Kodu sayfası açılır.

�� Program yazılır veya belgeden Program yazılır veya belgeden kopyalanır.kopyalanır.

�� Derlenip çalıştırılır.Derlenip çalıştırılır.

Page 15: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 1515

OpenGLOpenGL Komut YapısıKomut Yapısı

OpenGL

komutu

öneki

OpenGL

komutu

Komutu

oluşturan

kelimeler

büyük

harfle

başlar

Komutun

üç

parametre

alan tipi

parametre

veri tipi

(float)glColor3f

Page 16: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 1616

OpenGLOpenGL Sabit YapısıSabit Yapısı

GL_COLOR_BUFFER_BITGL_COLOR_BUFFER_BIT

�� Sabitler GL_ ile başlarSabitler GL_ ile başlar�� Tümü büyük harftirTümü büyük harftir�� Kelimeleri Kelimeleri ayırmadaayırmada alt çizgi kullanılıralt çizgi kullanılır

Page 17: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 1717

Nesne Köşelerini BelirtmeNesne Köşelerini Belirtme

� Nesneler köşeleri ile belirtilir :–– glVertex3f (2.0, 4.1, 6.0); glVertex3f (2.0, 4.1, 6.0);

–– glVertex2i (4, 5);glVertex2i (4, 5);

� Etkin Renk köşeleri etkiler :–– glColor3f (0.0, 0.5, 1.0);glColor3f (0.0, 0.5, 1.0);

Page 18: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 1818

Üçgen OluşturmaÜç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.

glBeginglBegin (GL_TRIANGLES);(GL_TRIANGLES);

glVertex2i (0, 0);glVertex2i (0, 0);

glVertex2i (2, 0);glVertex2i (2, 0);

glVertex2i (1, 1);glVertex2i (1, 1);

glEndglEnd();();

Page 19: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 1919

ŞŞekil Oluşturmaekil Oluşturma

Page 20: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 2020

PrimitivePrimitive (İlkel) Türleri (İlkel) Türleri glBeginglBegin içiniçin� Points GL_POINTS

� Lines 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

Page 21: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 2121

Temel Geometrik TiplerTemel Geometrik Tipler

�� GL_POINTS GL_POINTS individualindividual pointspoints�� GL_LINES GL_LINES pairspairs of of verticesvertices interpretedinterpreted as as individualindividual lineline segmentssegments�� GL_LINE_STRIP GL_LINE_STRIP seriesseries of of connectedconnected lineline segmentssegments�� GL_LINE_LOOP GL_LINE_LOOP samesame as as aboveabove, , withwith a a segmentsegment addedadded betweenbetween lastlast

andand firstfirst verticesvertices�� GL_TRIANGLES GL_TRIANGLES triplestriples of of verticesvertices interpretedinterpreted as as trianglestriangles�� GL_TRIANGLE_STRIP GL_TRIANGLE_STRIP linkedlinked stripstrip of of trianglestriangles�� GL_TRIANGLE_FAN GL_TRIANGLE_FAN linkedlinked fan of fan of trianglestriangles�� GL_QUADS GL_QUADS quadruplesquadruples of of verticesvertices interpretedinterpreted as as fourfour--sidedsided polygonspolygons�� GL_QUAD_STRIP GL_QUAD_STRIP linkedlinked stripstrip of of quadrilateralsquadrilaterals�� GL_POLYGON GL_POLYGON boundaryboundary of a of a simplesimple, , convexconvex polygonpolygon

Page 22: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 2222

İİki Boyut ve ki Boyut ve Koordinat SistemiKoordinat Sistemi

OpenGLOpenGL, iki boyutlu grafikler için birçok , iki boyutlu grafikler için birçok alternatif içermektedir. Basit bir dikdörtgen alternatif içermektedir. Basit bir dikdörtgen çizmek için aşağıdaki kod bloğu kullanılır : çizmek için aşağıdaki kod bloğu kullanılır :

glBeginglBegin( GL_QUADS );( GL_QUADS );glColor3f( 1.0, 0.0, 0.0 );glColor3f( 1.0, 0.0, 0.0 );glVertex2f( 0.0, 0.0 );glVertex2f( 0.0, 0.0 );glVertex2f( 0.9, 0.0 );glVertex2f( 0.9, 0.0 );glVertex2f( 1.0, 1.0 );glVertex2f( 1.0, 1.0 );glVertex2f( 0.0, 0.5 );glVertex2f( 0.0, 0.5 );

glEndglEnd();();

(1,1)

(-1,-1)

Page 23: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 2323

RenklerRenkler

glColor3f(0.0, 0.0, 0.0);glColor3f(0.0, 0.0, 0.0); blackblackglColor3f(1.0, 0.0, 0.0);glColor3f(1.0, 0.0, 0.0); redredglColor3f(0.0, 1.0, 0.0);glColor3f(0.0, 1.0, 0.0); greengreenglColor3f(1.0, 1.0, 0.0);glColor3f(1.0, 1.0, 0.0); yellowyellowglColor3f(0.0, 0.0, 1.0);glColor3f(0.0, 0.0, 1.0); blueblueglColor3f(1.0, 0.0, 1.0);glColor3f(1.0, 0.0, 1.0); magentamagentaglColor3f(0.0, 1.0, 1.0);glColor3f(0.0, 1.0, 1.0); cyancyanglColor3f(1.0, 1.0, 1.0);glColor3f(1.0, 1.0, 1.0); whitewhiteglColor3f(0.9, 0.9, 0.9);glColor3f(0.9, 0.9, 0.9); lightlight graygrayglColor3f(0.3, 0.3, 0.3);glColor3f(0.3, 0.3, 0.3); darkdark graygrayTüm renkler, üç ana rengin (r, g, b) bileşiminden oluşur.Tüm renkler, üç ana rengin (r, g, b) bileşiminden oluşur.

KırmızıYeşil Mavi

Page 24: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 2424

Örnek 2 :Örnek 2 :Mavi Dikdörtgen ÇizmekMavi Dikdörtgen Çizmek

##includeinclude <<glgl//glutglut.h>.h>

voidvoid initinit((voidvoid))

{{

glClearColorglClearColor(1.0,1.0,1.0,0.0);(1.0,1.0,1.0,0.0);

glShadeModelglShadeModel(GL_FLAT);(GL_FLAT);

}}

voidvoid DrawDraw_A__A_RectangleRectangle((voidvoid))

{{

glBeginglBegin(GL_QUADS);(GL_QUADS);

glColor3f(0.0,1.0,0.0);glColor3f(0.0,1.0,0.0);

glVertex2f(0.25,0.25);glVertex2f(0.25,0.25);

glColor3f(1.0,1.0,0.0);glColor3f(1.0,1.0,0.0);

glVertex2f(0.25,0.75);glVertex2f(0.25,0.75);

glColor3f(1.0,0.0,0.0);glColor3f(1.0,0.0,0.0);

glVertex2f(0.75,0.75);glVertex2f(0.75,0.75);

glColor3f(0.0,0.0,1.0);glColor3f(0.0,0.0,1.0);

glVertex2f(0.75,0.25);glVertex2f(0.75,0.25);

glEndglEnd();();

}}

voidvoid displaydisplay((voidvoid))

{{

glClearglClear(GL_COLOR_BUFFER_BIT);(GL_COLOR_BUFFER_BIT);

DrawDraw_A__A_RectangleRectangle();();

glutSwapBuffersglutSwapBuffers();();

}}

intint mainmain((intint argcargc,,charchar ****argvargv))

{{

glutInitglutInit(&(&argcargc,,argvargv););

glutInitDisplayModeglutInitDisplayMode(GLUT_DOUBLE | (GLUT_DOUBLE | GLUT_RGB);GLUT_RGB);

glutInitWindowSizeglutInitWindowSize(400,100);(400,100);

glutInitWindowPositionglutInitWindowPosition(100,100);(100,100);

glutCreateWindowglutCreateWindow(" (" RectangleRectangle ");");

initinit(); ();

glutDisplayFuncglutDisplayFunc((displaydisplay););

glutMainLoopglutMainLoop();();

returnreturn 0;0;

}}

Page 25: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 2525

Çokgen Üzerinde Çokgen Üzerinde Renk Renk GeçişiGeçişi

glShadeModel(GL_SMOOTH);

voidvoid DrawDraw_A__A_RectangleRectangle((voidvoid)){{glBeginglBegin(GL_QUADS);(GL_QUADS);glColor3f(0.0,1.0,0.0);glColor3f(0.0,1.0,0.0);glVertex2f(0.25,0.25);glVertex2f(0.25,0.25);glColor3f(1.0,1.0,0.0);glColor3f(1.0,1.0,0.0);glVertex2f(0.25,0.75);glVertex2f(0.25,0.75);glColor3f(1.0,0.0,0.0);glColor3f(1.0,0.0,0.0);glVertex2f(0.75,0.75);glVertex2f(0.75,0.75);glColor3f(0.0,0.0,1.0);glColor3f(0.0,0.0,1.0);glVertex2f(0.75,0.25);glVertex2f(0.75,0.25);glEndglEnd();();

}}

GL_FLATGL_FLAT

Page 26: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 2626

OpenGL: ShadingOpenGL: Shading

� OpenGL supports 2 basic shading models: flat and smooth.

glShadeModel(GL_FLATglShadeModel(GL_FLAT););

glShadeModel(GL_SMOOTHglShadeModel(GL_SMOOTH););

Page 27: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 2727

Örnek 3 : Örnek 3 : Döngü ile Çokgen OluşturmaDöngü ile Çokgen Oluşturma

##includeinclude <<glgl//glutglut.h>.h>

##includeinclude <<mathmath.h>.h>

voidvoid initinit((voidvoid))

{{

glClearColorglClearColor(1.0,1.0,1.0,0.0);(1.0,1.0,1.0,0.0);

glShadeModelglShadeModel(GL_FLAT);(GL_FLAT);

}}

voidvoid DrawDraw__PolygonPolygon((voidvoid))

{{

doubledouble M_PI = 3.1415, M_PI = 3.1415, angleangle;;

glColor3f(0.0,1.0,0.0);glColor3f(0.0,1.0,0.0);

glBeginglBegin (GL_LINE_LOOP);(GL_LINE_LOOP);

forfor ((intint j=0; j<10; j++) {j=0; j<10; j++) {

angleangle = 2*M_PI*j/10;= 2*M_PI*j/10;

glVertex2f (glVertex2f (coscos((angleangle), ), sin(sin(angleangle));));

}}

glEndglEnd();();

}}

voidvoid displaydisplay((voidvoid))

{{

glClearglClear(GL_COLOR_BUFFER_BIT);(GL_COLOR_BUFFER_BIT);

DrawDraw__PolygonPolygon();();

glutSwapBuffersglutSwapBuffers();();

}}

intint mainmain((intint argcargc,,charchar ****argvargv))

{{

glutInitglutInit(&(&argcargc,,argvargv););

glutInitDisplayModeglutInitDisplayMode(GLUT_DOUBLE | (GLUT_DOUBLE | GLUT_RGB);GLUT_RGB);

glutInitWindowSizeglutInitWindowSize(400,100);(400,100);

glutInitWindowPositionglutInitWindowPosition(100,100);(100,100);

glutCreateWindowglutCreateWindow(" (" PolygonPolygon ");");

initinit();();

glutDisplayFuncglutDisplayFunc((displaydisplay););

glutMainLoopglutMainLoop();();

returnreturn 0;0;

}}

Page 28: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 2828

GLUT Event CallbacksGLUT Event Callbacks

� Register functions that are called when certain events occur.

� Examples:glutDisplayFuncglutDisplayFunc( Display ); ( Display );

glutKeyboardFuncglutKeyboardFunc( Keyboard ); ( Keyboard );

glutReshapeFuncglutReshapeFunc( Reshape ); ( Reshape );

glutMouseFuncglutMouseFunc( Mouse ); ( Mouse );

glutPassiveMotionFuncglutPassiveMotionFunc( ( PassiveFuncPassiveFunc ); );

glutMotionFuncglutMotionFunc( ( MouseDraggedFuncMouseDraggedFunc ); );

glutIdleFuncglutIdleFunc( Idle );( Idle );

Page 29: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 2929

Etkileşim : KlavyeEtkileşim : Klavyevoidvoid keyboardkeyboard((unsignedunsigned charchar keykey, , intint x, x, intint y)y){{switchswitch((keykey)){{casecase 'x' :'x' :axisaxis = X;= X;spinspin();();glutPostRedisplayglutPostRedisplay();();break;break;

casecase 'y' :'y' :axisaxis = Y;= Y;spinspin();();glutPostRedisplayglutPostRedisplay();();break;break;

defaultdefault ::break;break;

}}}}

Main’eMain’e Eklenmesi gereken :Eklenmesi gereken :

glutKeyboardFuncglutKeyboardFunc((keyboardkeyboard););

Page 30: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 3030

Etkileşim : FareEtkileşim : Farevoidvoid mousemouse((intint buttonbutton, , intint statestate, , intint x, x, intint y)y){{switchswitch ((buttonbutton) {) {casecase GLUT_LEFT_BUTTON:GLUT_LEFT_BUTTON:ifif ((statestate == GLUT_DOWN)== GLUT_DOWN)glutIdleFuncglutIdleFunc((spinDisplayspinDisplay););

break;break;casecase GLUT_MIDDLE_BUTTON:GLUT_MIDDLE_BUTTON:ifif ((statestate == GLUT_DOWN)== GLUT_DOWN)glutIdleFuncglutIdleFunc(NULL);(NULL);

break;break;defaultdefault::break; break;

}}}}

Main’eMain’e Eklenmesi gereken:Eklenmesi gereken:

glutMouseFuncglutMouseFunc((mousemouse););

Page 31: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 3131

OPENGL : 3D CONCEPTSOPENGL : 3D CONCEPTS

The camera initiallypoints down thenegative z-axis. (You're seeing theback of the camera.)

Page 32: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 3232

Summary of Summary of 3D 3D TransformationTransformation

P(x, y, z)

Viewing Transformation

Viewing Transformation

Projection Transformation

Projection Transformation

Window-to-ViewportTransformation

Window-to-ViewportTransformation

P(x, y)

Modeling Transformation

Modeling Transformation

3D Object Coordinates

3D World Coordinates

3D Viewing Coordinates

2D Projection Coordinates

2D Device Coordinates

Page 33: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 3333

The Camera The Camera AnalogyAnalogyTo 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 (viewporttrans.)

• After these steps are performed, the picture can be snapped or the scene can be drawn.

Page 34: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 3434

Stages of Stages of VertexVertex TransformTransform

• 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.

Page 35: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 3535

Example: Drawing Example: Drawing CubeCube 11#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 ();

}

Page 36: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 3636

Example: Drawing Example: Drawing CubeCube 22void 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;

}

Page 37: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 3737

Example: Drawing Example: Drawing CubeCube 33Viewing 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

Page 38: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 3838

Example: Drawing Example: Drawing CubeCube 44Projection 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

Page 39: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 3939

Example: Drawing Example: Drawing CubeCube 55Viewport 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.

Page 40: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 4040

Let’s Think About TransformationsLet’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.

Page 41: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 4141

Transformations Transformations and Viewingand Viewing

OpenGL has 3 different matrix modes:–– GL_MODELVIEWGL_MODELVIEW

–– GL_PROJECTIONGL_PROJECTION

–– GL_TEXTUREGL_TEXTURE

Choose the matrix with: glMatrixMode(…);

Page 42: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 4242

ModelviewModelview matrixmatrix

� 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.

Page 43: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 4343

ModelingModelingTransformationsTransformations

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

Page 44: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 4444

Üç Boyutlu DönüşümlerÜç Boyutlu Dönüşümler

�� glRotateglRotate producesproduces a a rotationrotation of of angleangle degreesdegreesaroundaround thethe vectorvector (x,y,z). (x,y,z). –– voidvoid glRotatedglRotated( ( GLdoubleGLdouble angleangle, , GLdoubleGLdouble xx, , GLdoubleGLdouble yy, ,

GLdoubleGLdouble zz) ) –– voidvoid glRotatefglRotatef( ( GLfloatGLfloat angleangle, , GLfloatGLfloat xx, , GLfloatGLfloat yy, , GLfloatGLfloat zz ))

�� glScaleglScale producesproduces a a nonuniformnonuniform scalingscaling alongalong thethe xx, , yy, , andand zz axesaxes. .

voidvoid glScaledglScaled( ( GLdoubleGLdouble xx, , GLdoubleGLdouble yy, , GLdoubleGLdouble zz ))voidvoid glScalefglScalef( ( GLfloatGLfloat xx, , GLfloatGLfloat yy, , GLfloatGLfloat zz ) )

�� glTranslateglTranslate producesproduces a a translationtranslation byby (x,y,z). (x,y,z). voidvoid glTranslatedglTranslated( ( GLdoubleGLdouble xx, , GLdoubleGLdouble yy, , GLdoubleGLdouble zz ))voidvoid glTranslatefglTranslatef( ( GLfloatGLfloat xx, , GLfloatGLfloat yy, , GLfloatGLfloat zz ) )

Page 45: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 4545

OpenGL Matrix StacksOpenGL 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.

Page 46: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 4646

OpenGL Matrix StacksOpenGL 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.

Page 47: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 4747

OpenGL Matrix StacksOpenGL 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

Page 48: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 4848

�� OpenGL supports two stacks of matrices OpenGL supports two stacks of matrices –– ModelviewModelview matrix stack (4x4 matrices)matrix stack (4x4 matrices)–– Projection matrix stack (4x4 matrices)Projection matrix stack (4x4 matrices)

�� These stacks are useful for constructing These stacks are useful for constructing hierarchical models. For example a car hierarchical models. For example a car made of its body and the four wheels:made of its body and the four wheels:

Rotate wheelsRotate wheels

+ Rotate body

Matrix StacksMatrix Stacks

Page 49: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 4949

�� glPushMatrixglPushMatrix(void(void) ) -- Pushes Pushes all matrices in the current stack all matrices in the current stack down one level. down one level.

�� glPopMatrixglPopMatrix(void(void) ) -- Pops the Pops the top matrix off the current stack, top matrix off the current stack, losing the topmost matrix!losing the topmost matrix!

�� (The current stack is determined (The current stack is determined by by glMatrixModeglMatrixMode).).

Matrix StacksMatrix Stacks

M5

M4

M3

M2

M1

M5

M4

M3

M2

M1

Pop

Push

M4

M3

M2

M1

M4

M4

M3

M2

M1

Current matrix

level

Current matrix

level

Page 50: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 5050

�� Example code:Example code:void void drawCardrawCar() {() {

glMatrixMode(GL_MODELVIEWglMatrixMode(GL_MODELVIEW) ;) ;

glTranslatef(x,y,zglTranslatef(x,y,z) ; /*/) ; /*/

glRotatef(car_angglRotatef(car_ang, 0, 1, 0) ; /*/, 0, 1, 0) ; /*/draw_car_body() ;draw_car_body() ;

glPushMatrixglPushMatrix() ;() ;

glTranslate(glTranslate(--1,0,1) ;1,0,1) ;glRotatef(wheels_angglRotatef(wheels_ang, 0, 1, 0) ;, 0, 1, 0) ;

draw_car_wheel() ;draw_car_wheel() ;

glPopMatrixglPopMatrix() ;() ;

glPushMatrixglPushMatrix() ;() ;glTranslate(1,0,1) ;glTranslate(1,0,1) ;

glRotatef(wheels_angglRotatef(wheels_ang, 0, 1, 0) ;, 0, 1, 0) ;

draw_car_wheel() ;draw_car_wheel() ;glPopMatrixglPopMatrix() ;() ;

}}

�� First we move and rotate First we move and rotate the car (body + wheels) the car (body + wheels) --as it is the top level in the as it is the top level in the hierarchy.hierarchy.

�� Next we push the stack Next we push the stack --and therefore store a and therefore store a copy. copy.

�� Then we draw the right Then we draw the right and left wheels in their and left wheels in their appropriate position and appropriate position and orientation. Note that on orientation. Note that on each wheel the each wheel the transformation /*/ will transformation /*/ will operate.operate.

�� The last pop will retrieve The last pop will retrieve the matrix containing only the matrix containing only the /*/ transformations.the /*/ transformations.

Matrix StacksMatrix Stacks

Page 51: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 5151

3D GLUT predefined 3D GLUT predefined shapesshapes

Page 52: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 5252

Üç Boyutlu Hazır NesnelerÜç Boyutlu Hazır NesnelerII

�� glutSolidSphereglutSolidSphere, , glutWireSphereglutWireSphere�� glutSolidCubeglutSolidCube, , glutWireCubeglutWireCube�� glutSolidConeglutSolidCone, , glutWireConeglutWireCone�� glutSolidTorusglutSolidTorus, , glutWireTorusglutWireTorus�� glutSolidDodecahedronglutSolidDodecahedron, , glutWireDodecahedronglutWireDodecahedron�� glutSolidOctahedronglutSolidOctahedron, , glutWireOctahedronglutWireOctahedron�� glutSolidTetrahedronglutSolidTetrahedron, , glutWireTetrahedronglutWireTetrahedron�� glutSolidIcosahedronglutSolidIcosahedron, , glutWireIcosahedronglutWireIcosahedron�� glutSolidTeapotglutSolidTeapot, , glutWireTeapotglutWireTeapot

Page 53: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 5353

Üç Boyutlu Hazır NesnelerÜç Boyutlu Hazır NesnelerIIII

glutSolidConeglutSolidCone -- renderrender a a solidsolid oror wireframewireframe conecone respectivelyrespectively. . glutWireConeglutWireCone

glutSolidCubeglutSolidCube -- renderrender a a solidsolid oror wireframewireframe cubecube respectivelyrespectively. . glutSolidDodecahedronglutSolidDodecahedron -- renderrender a a solidsolid oror wireframewireframe

dodecahedrondodecahedron (12(12--sidedsided regularregular solidsolid) ) respectivelyrespectively. . glutSolidIcosahedronglutSolidIcosahedron -- renderrender a a solidsolid oror wireframewireframe

icosahedronicosahedron (20(20--sidedsided regularregular solidsolid) ) respectivelyrespectively. . glutSolidOctahedronglutSolidOctahedron -- renderrender a a solidsolid oror wireframewireframe

octahedronoctahedron (8(8--sidedsided regularregular solidsolid) ) respectivelyrespectively. . glutSolidSphereglutSolidSphere -- renderrender a a solidsolid oror wireframewireframe spheresphere

respectivelyrespectively. . glutSolidTeapotglutSolidTeapot -- renderrender a a solidsolid oror wireframewireframe teapotteapot

respectivelyrespectively. . glutSolidTetrahedronglutSolidTetrahedron -- renderrender a a solidsolid oror wireframewireframe

tetrahedrontetrahedron (4(4--sidedsided regularregular solidsolid) ) respectivelyrespectively. . glutSolidTorusglutSolidTorus -- renderrender a a solidsolid oror wireframewireframe torustorus

((doughnutdoughnut) ) respectivelyrespectively..

Page 54: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 5454

Projection MatrixProjection Matrix –– I I

Sets up a perspective projection. ––glFrustrumglFrustrum (...);(...);

––gluPerspectivegluPerspective ((fovyfovy, ,

aspect, near, far);aspect, near, far);

––glOrthoglOrtho (...);(...);

––gluLookAtgluLookAt (...);(...);

(often applied to (often applied to modelviewmodelview matrix)matrix)

Page 55: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 5555

Projection MatrixProjection Matrix -- IIII

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

Page 56: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 5656

Perspective Viewing VolumeSpecified by gluPerspective()

Page 57: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 5757

Viewing Viewing TransformationsTransformations

Default camera position gluLookAt(4.0, 2.0, 1.0, 2.0, 4.0, -3.0, 2.0, 2.0, -1.0);

Page 58: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 5858

ViewportViewport TransformationTransformation

The viewport transformation specifies the rectangular region of the window where the model is drawn.

void glViewport(GLint x, GLint y, GLsizei width, GLsizeiheight);

Defines a pixel rectangle in the window into which the final image is mapped. The (x, y) parameter specifies the lower-left 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.

Page 59: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 5959

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

Page 60: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 6060

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

Sample ViewportSample Viewport

ApplicationApplication

Page 61: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 6161

OpenGLOpenGL : : Setting Up Setting Up Rendering StatesRendering 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.

–– glEnableglEnable (GL_LIGHTING);(GL_LIGHTING);

–– glDisableglDisable (GL_FOG);(GL_FOG);

� Forgetting to enable something is a common source of bugs!

Page 62: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 6262

OpenGL: OpenGL: NormalsNormals and Lightingand 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);

...

Page 63: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 6363

OpenGL: LightingOpenGL: Lighting

� glEnable (GL_LIGHTING);

� OpenGL supports a minimum of 8 lights.glEnableglEnable (GL_LIGHT0); ... (GL_LIGHT0); ... glEnableglEnable

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

Page 64: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 6464

Lighting in OpenGLLighting in OpenGL

�� GLfloatGLfloat amb0[] = {0.2, 0.4, 0.6, 1.0};amb0[] = {0.2, 0.4, 0.6, 1.0};�� GLfloatGLfloat diff0[] = {0.8, 0.9, 0.5, 1.0};diff0[] = {0.8, 0.9, 0.5, 1.0};�� GLfloatGLfloat spec0[] = {1.0, 0.8, 1.0, 1.0};spec0[] = {1.0, 0.8, 1.0, 1.0};

�� glLightfv(GL_LIGHT0, GL_AMBIENT, amb0); glLightfv(GL_LIGHT0, GL_AMBIENT, amb0); //attach them to LIGHT0//attach them to LIGHT0

�� glLightfv(GL_LIGHT0, GL_DIFFUSE, diff0); glLightfv(GL_LIGHT0, GL_DIFFUSE, diff0); �� glLightfv(GL_LIGHT0, GL_SPECULAR, spec0);glLightfv(GL_LIGHT0, GL_SPECULAR, spec0);

Page 65: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 6565

OpenGL: OpenGL: Material PropertiesMaterial Properties� Material properties are associated with each

polygon (corresponding light properties)–– glMaterialglMaterial*(*(GLenumGLenum face, face, GLenumGLenum

pnamepname, TYPE , TYPE paramparam););

� Some properties (pname) :–– GL_AMBIENT: Ambient color of materialGL_AMBIENT: Ambient color of material–– GL_DIFFUSE: Diffuse color of materialGL_DIFFUSE: Diffuse color of material–– GL_SPECULAR: GL_SPECULAR: SpecularSpecular component (for highlights)component (for highlights)–– GL_SHININESS: GL_SHININESS: SpecularSpecular exponent (intensity of exponent (intensity of

highlight)highlight)

Page 66: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 6666

OpenGL: TexturingOpenGL: Texturing

�� Mapping the texture to the polygonMapping the texture to the polygon–– specify (specify (s,ts,t) texture coordinates for ) texture coordinates for

((x,y,zx,y,z) polygon vertices) polygon vertices–– texture coordinates (texture coordinates (s,t)ares,t)are from 0,1: from 0,1: glTexCoord2f(s,t);glTexCoord2f(s,t);

s

t

0,0

1,1

0,0

1,1

(x0,y0,z0)

(x1,y1,z1)

1,0

0,1

(x2,y2,z2)

(x3,y3,z3)

+

Page 67: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 6767

OpenGL: Alpha BlendingOpenGL: Alpha Blending

�� When enabled, OpenGL uses the alpha When enabled, OpenGL uses the alpha channel to blend a new fragment’s color channel to blend a new fragment’s color value with a color in the value with a color in the framebufferframebuffer

�� Useful for overlaying textures or other effectsUseful for overlaying textures or other effects

New color Color in framebuffer

+ = ?

(r1,g1,b1,a1) (r0,g0,b0,a0)

(r’,g’,b’,a’)

“source” “destination”

Page 68: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 6868

OpenGL: FogOpenGL: Fog

Simulate atmospheric effects

•glFog (): Sets fog parameters

•glEnable (GL_FOG);

Page 69: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 6969

RenderingRendering PipelinePipeline

Page 70: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 7070

OpenGL: Other FeaturesOpenGL: Other Features

�� Display Lists (Display Lists (chch 7): Speed up your 7): Speed up your game!game!

�� Quadrics (Quadrics (chch 11): Pre11): Pre--made objectsmade objects–– Also look at Also look at GLUT’sGLUT’s objectsobjects

�� Evaluators (Evaluators (chch 12): Bezier curves and 12): Bezier curves and surfacessurfaces

�� Selection (Selection (chch 13): Clicking on game 13): Clicking on game objects with a mouse objects with a mouse

Page 71: DERS_05_OPENGL_2006

CSGL CSGL

C C SharpSharp GraphicsGraphics LibraryLibrary

Page 72: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 7272

CSGLCSGL

�� OpenGL’inOpenGL’in .NET ortamında kullanımını .NET ortamında kullanımını sağlayan grafik kütüphanesidir.sağlayan grafik kütüphanesidir.

�� Adresler :Adresler :–– http://sourceforge.net/projects/csglhttp://sourceforge.net/projects/csgl–– http://csgl.sourceforge.net/http://csgl.sourceforge.net/

•• .NET üzerinde .NET üzerinde csglcsgl.1.4.1..1.4.1.dlldll..zipzip installinstalldosyasından kurularak program dosyasından kurularak program geliştirmeye başlanabilir.geliştirmeye başlanabilir.

Page 73: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 7373

Dikdörtgen Çizdiren CSGL Dikdörtgen Çizdiren CSGL Kodu (1)Kodu (1)usingusing SystemSystem;;usingusing SystemSystem..DrawingDrawing;;usingusing SystemSystem.Windows..Windows.FormsForms;;usingusing CsGLCsGL..OpenGLOpenGL;;

publicpublic classclass RectDemoRectDemo : Form: Form{{

MyViewMyView viewview = = newnew MyViewMyView();();

publicpublic RectDemoRectDemo()(){{

TextText = "= "RectRect demodemo !";!";viewview..DockDock = = DockStyleDockStyle..FillFill;;ControlsControls..AddAdd( ( viewview ););

}}

publicpublic staticstatic voidvoid MainMain()()

{{

RectDemoRectDemo di = di = newnewRectDemoRectDemo();();

ApplicationApplication..RunRun( di );( di );}}

}}

Page 74: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 7474

Dikdörtgen Çizdiren CSGL Dikdörtgen Çizdiren CSGL Kodu (2)Kodu (2)classclass MyViewMyView : : OpenGLControlOpenGLControl{{

publicpublic overrideoverride voidvoid glDrawglDraw()(){{

GL.GL.glClearglClear( GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT ); ( GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT ); // // ClearClear ScreenScreen AndAnd DepthDepth BufferBuffer

GL.GL.glBeginglBegin( GL.GL_QUADS );( GL.GL_QUADS );GL.glVertex2i( 10, 10 );GL.glVertex2i( 10, 10 );GL.glVertex2i( 10, 50 );GL.glVertex2i( 10, 50 );GL.glVertex2i( 100, 50 );GL.glVertex2i( 100, 50 );GL.glVertex2i( 100, 10 );GL.glVertex2i( 100, 10 );GL.GL.glEndglEnd();();GL.GL.glFlushglFlush();();

}}protectedprotected overrideoverride voidvoid InitGLContextInitGLContext() () {{

GL.GL.glClearColorglClearColor( 1.0f, 1.0f, 1.0f, 0.0f );( 1.0f, 1.0f, 1.0f, 0.0f );GL.glColor3f( 0.0f, 0.0f, 0.0f );GL.glColor3f( 0.0f, 0.0f, 0.0f );GL.GL.glPointSizeglPointSize( 4.0f );( 4.0f );

}}

Page 75: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 7575

Dikdörtgen Çizdiren CSGL Dikdörtgen Çizdiren CSGL Kodu (3)Kodu (3)protectedprotected overrideoverride voidvoid OnSizeChangedOnSizeChanged((EventArgsEventArgs e)e){{

basebase..OnSizeChangedOnSizeChanged(e);(e);

GL.GL.glMatrixModeglMatrixMode(GL.GL_PROJECTION);(GL.GL_PROJECTION);GL.GL.glLoadIdentityglLoadIdentity();();GL.gluOrtho2D( 0.0, Size.GL.gluOrtho2D( 0.0, Size.WidthWidth, 0.0, Size., 0.0, Size.HeightHeight ););

}}}}

Page 76: DERS_05_OPENGL_2006

Ocak 2006Ocak 2006 Dr. Aybars UĞURDr. Aybars UĞUR 7676

KAYNAKLARKAYNAKLAR

�� Bilgisayar Grafikleri ders notları, Bilgisayar Grafikleri ders notları, Aybars UĞUR, Ege ÜniversitesiAybars UĞUR, Ege Üniversitesi

�� OpenGLOpenGL RedRed BookBook�� SeanSean WalkerWalker ve ve IanIan BuckBuck ders slaytları, ders slaytları,

Stanford University Stanford University