• Tidak ada hasil yang ditemukan

An Interactive Introduction to OpenGL Programming

N/A
N/A
Protected

Academic year: 2018

Membagikan "An Interactive Introduction to OpenGL Programming"

Copied!
160
0
0

Teks penuh

(1)

An Interactive Introduction to

OpenGL Programming

Dr. Mohammad Iqbal

(2)

Agenda

z

General OpenGL Introduction

z

Rendering Primitives

z

Rendering Modes

z

Lighting

z

Texture Mapping

(3)

Goals for Today

z

Tujuan : mendemonstrasikan OpenGL

dalam menghasilkan program grafik

interaktif dalam

z Membuat model 3D obyek atau imagery

z Lighting - pencahayaan

z texture mapping

(4)
(5)

OpenGL and GLUT Overview

z

Apakah OpenGL & apa manfaatnya?

z

OpenGL dalam sistem window

z

Mengapa GLUT

(6)

Apakah OpenGL?

z

Graphics rendering API (Application

Programming Interface)

z citra warna high-quality yang terdiri dari geometric dan citra primitif

z Independen window system

(7)

Arsitektur OpenGL

Display List

Polynomial Evaluator

Per Vertex Operations &

Primitive Assembly

Rasterization Per Fragment

(8)

OpenGL sebagai Renderer

z

Geometric primitif

z titik, garis dan poligon

z

Image Primitif

z Citra dan bitmap

z Memisahkan pipeline untuk citra dan geometry

z linked ketika penerapan texture mapping

z

Rendering tergantung pada status

(9)

API yang Terkait OpenGL

z AGL, GLX, WGL

z Perekat antara OpenGL dan sistem window z GLU (OpenGL Utility Library)

z Bagian OpenGL

z NURBS, tessellators, quadric shapes, dll. z GLUT (OpenGL Utility Toolkit)

z portable windowing API

(10)

API yang Terkait OpenGL

GLUT

GLU

GL

GLX, AGL or WGL

X, Win32, Mac O/S

software and/or hardware application program

(11)

Preliminaries

z

Headers Files

z #include <GL/gl.h> z #include <GL/glu.h> z #include <GL/glut.h>

z

Libraries

z

Enumerated Types

z OpenGL defines numerous types for compatibility

(12)

Dasar-dasar GLUT

z

Struktur Aplikasi

z Configure dan open window

z Initialisasi status OpenGL

z Register fungsi input callback

z render z resize

z input: keyboard, mouse, dll.

(13)

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

(14)

Inisialisasi OpenGL

z Set up status yg ingin digunakan

void init( void ) {

glClearColor( 0.0, 0.0, 0.0, 1.0 ); glClearDepth( 1.0 );

(15)

Fungsi input Callback GLUT

z

Rutin yang dipanggil ketika sesuatu

terjadi

z window resize atau redraw

z user input

z animasi

z

Me-“register” callbacks pada GLUT

glutDisplayFunc( display );

glutIdleFunc( idle );

(16)

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

(17)

Idle Callbacks

z Gunakan untuk animasi dan update yang continyu

glutIdleFunc( idle );

void idle( void ) {

t += dt;

(18)

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;

(19)
(20)

Agenda Elementary Rendering

z

Geometric Primitives

(21)

OpenGL Geometric Primitif

GL_POINTS GL_LINESGL_LINES

GL_LINE_LOOP

z

Semua jenis geometric primitif

(22)

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

(23)

Format Perintah OpenGL

glVertex3fv(

glVertex3fv(

v

v

)

)

Number of Number of components

Data Type Data Type b

b -- bytebyte ub

ub -- unsigned byteunsigned byte s

s -- shortshort us

us -- unsigned shortunsigned short i

i -- intint ui

ui -- unsigned intunsigned int f scalar form scalar form

(24)

Specifying Geometric Primitives

z

Primitif dispesifikasikan menggunakan :

glBegin(

glBegin( primType primType ););

glEnd();

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

(25)

Model Warna

OpenGL

color index mode

Display

Red Green Blue 0

Poly. Per Vertex

(26)

2

(27)

Mengendalikan tampilan

Appearance

(Rendering)

Dari

(28)

Mesin Status OpenGL

z

Setiap atribut rendering di encapsulapsi

dalam

OpenGL State

z rendering styles

z shading

z lighting

(29)

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

(30)

Mengendalikan Status terakhir

z

Setting Status

glPointSize(

glPointSize( sizesize ););

glLineStipple(

glLineStipple( repeatrepeat, , pattern pattern ););

glShadeModel(

glShadeModel( GLGL__SMOOTHSMOOTH ););

z

Enabling Features

glEnable(

glEnable( GLGL__LIGHTING LIGHTING ););

glDisable(

(31)
(32)

Transformasi dalam OpenGL

z

Modeling

z

Viewing

z orientasi kamera

z projection

z

Animasi

(33)

Analogi Kamera

z

3D adalah seperti mengambil citra pada

fotografi (Banyak foto!)

camera

tripod model

(34)

Analogi Kamera dan Transformasi

z Projection transformations

z Mengatur lensa kamera z Viewing transformations

z Mengatur posisi tripod dan orientasi viewing suatu

volume dalam dunia nyata (world)

z Modeling transformations

z memindahkan model

z Viewport transformations

z Memperbesar atau mengurangi fotografi secara

(35)

Sistem Koordinat dan Transformasi

z Langkah dalam menyiapkan citra

z spesifikasikan geometri (world coordinates) z spesifikasikan kamera (camera coordinates) z proyeksi (window coordinates)

z Petakan ke viewport (screen coordinates)

z Setiap langkah menggunakan transformasi

(36)

Transformasi Affine

z

Transformasi yang mempertahankan

bentuk geometri

z garis, poligon, quadric

z

Affine = mempertahankan garis (line

preserving)

z Rotasi, translasi, skala

z Proyeksi

(37)

Koordinat Homogen

z Setiap vertex adalah vector kolom

z w umumnya bernilai 1.0

z Semua operasi adalah perkalian matriks

z Arah (directed line segments) direpresentasikan w = 0.0

(38)

3D Transformations

z Vertex ditransformasikan oleh 4 x 4 matrik

z Semua operasi affine adalah perkalian matriks

z Semua matrik disimpan secara column-major

dalam OpenGL

z matriks selalu dalam kondisi post-multiplied

(39)

Menspesifikasikan Transformasi

z

Programmer memiliki 2 styles untuk

men-spesifikasikan transformasi

z spesifikasikan matriks (glLoadMatrix, glLoadMatrix,

glMultMatrix

glMultMatrix)

z spesifikasikan operasi (glRotate, glRotate, glOrtho

glOrtho)

z

Programmer tidak perlu mengingat jenis

matriksnya secara tepat

z cek lampiran buku Red Book (Programming

(40)

Programming Transformations

z

Sebelum proses rendering, view, locate,

dan orientasi :

z Posisi mata/kamera

z 3D geometri

z

Mengatur matriks

z Termasuk matriks stack

(41)

v

object eye clip normalized

device window

z Bbrp kalkulasi tambahan :

z material Î color z shade model (flat)

z polygon rendering mode z polygon culling

z clipping

Pipeline

Transformasi

CPUCPU DLDL Poly.

(42)

Operasi Matriks

z Spesifikasikan Matriks Stack terkini

glMatrixMode( GL_MODELVIEW atau

GL_PROJECTION )

z Matriks atau operasi Stack lain

glLoadIdentity() glPushMatrix()

glLoadIdentity() glPushMatrix()

glPopMatrix()

glPopMatrix()

z Viewport

z Biasanya sama dengan ukuran window size z aspek rasio viewport harus sama dengan

transformasi proyeksi atau citra hasilnya akan terdistorsi

(43)

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 )

(44)

Mengaplikasikan Transformasi Proyeksi

z Pengunaan Umum (orthographic projection)

glMatrixMode( GL_PROJECTION ); glMatrixMode( GL_PROJECTION ); glLoadIdentity();

glLoadIdentity();

glOrtho( left, right, bottom, top, zNear, zFar glOrtho( left, right, bottom, top, zNear, zFar

(45)

Viewing Transformations

z Posisi Kamera/mata dalam scene

z Posisikan tripod (eye) ; persiapkan (aim) Kamera z Untuk Scene “fly through”

z Ubah transformasi viewing dan

re-draw scene

gluLookAt( eyex, eyey, eyez, aimx, aimy, aimz, upx, upy, upz )

z up vector menghasilkan orientasi unik z Berhati-hati dalam de-generate posisi

(46)

4

(47)

Modeling Transformations

z Memindahkan obyek glTranslate{fd}(

glTranslate{fd}( x, y, zx, y, z ))

z Rotasi obyek di sekitar sumbu utama glRotate

glRotate{{fdfd}( }( angle, x, y, zangle, x, y, z ))

z angle dalam derajat

z Dilasi (stretch atau shrink) atau mirror object

glScale{fd}(

glScale{fd}( x, y, zx, y, z ))

(48)

4

(49)

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

(50)

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

render

y

y z+

(51)

Penggunaan Umum Transformasi

z

3 contoh rutin resize()

z Re-status proyeksi & viewing transformations

z

Umumnya dipanggil ketika window

resize

z

Di-register sebagai callback untuk

(52)

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

(53)

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

(54)

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

(55)

if ( aspect < 1.0 ) { left /= aspect;

right /= aspect; } else {

bottom *= aspect; top *= aspect;

}

glOrtho( left, right, bottom, top, near, far );

glMatrixMode( GL_MODELVIEW ); glLoadIdentity();

}

(56)

Membangun Modeling Transformations

z Masalah 1: hirarki obyek

z Suatu posisi tergantung pada posisi sebelumnya z Lengan robot atau tangan ; sub-assemblies

z Solusi 1: memindahkan sistem koordinat lokal

z modeling transformation untuk memindahkan

sistem koordinat

(57)

Membangun Modeling Transformations

z Masalah 2 : obyek berpindah secara relatif pada absolute world origin

z Obyek berotasi di area yang salah pada origin

z Membuat obyek spin di sekitar center atau suatu area

z Solusi 2: fixed coordinate system

z modeling transformations akan memindahkan

obyek disekitar fixed coordinate system

z pre-multiply column-major matrices z OpenGL post-multiplies matrices

z harus me-reverse order operasi untuk

(58)

Area Clipping Tambahan

z Paling tidak ada 6 atau lebih area clipping

z Baik untuk perhitungan cross-sections

z Modelview matrix memindahkan area clipping clipped

glEnable( GL_CLIP_PLANEi )

glClipPlane( GL_CLIP_PLANEi, GLdouble* coeff )

0

< +

+

(59)

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

(60)
(61)

Prinsip Pencahayaan

z

Pencahayaan mensimulasikan

bagaimana obyek memantulkan cahaya

z Komposisi material obyek

z Warna cahaya dan posisi

z Parameter global pencahayaan

z Cahaya ambien

z Pencahayaan dua sisi

(62)

Bagaimana OpenGL

Mensimulasikan Cahaya

z

Model Pencahayaan Phong

z Perhitungan pada vertices

z

Kontributor Pencahayaan

z Properti permukaan material

z Properti cahaya

(63)

Surface

Normals

z Normal mendefinisikan bagaimana pemukaan memantulkan cahaya

z

z glNormal3f( x, y, zglNormal3f( x, y, z ))

z Current normal digunakan untuk menghitung warna

vertex

z Gunakan unit normals untuk pencahayaan yang

tepat

z Skalakan efek pada panjang normal

glEnable( GL_NORMALIZE )

or

glEnable( GL_RESCALE_NORMAL )

CPU CPU

DL DL Poly.

(64)

Material Properties

z Definisikan properti permukaan obyek primitif

glMaterialfv( face, property, value );

z Pisahkan material antara bagian front dan back GL_DIFFUSE Base color

GL_SPECULAR Highlight Color

GL_AMBIENT Low-light Color

GL_EMISSION Glow Color

(65)

Properti Cahaya

glLightfv( light, property, value );

z

light

menspesifikasikan jenis cahaya

z multiple lights, mulai dari GL_LIGHT0

glGetIntegerv( GL_MAX_LIGHTS, &n );

z

properties

z Warna

z posisi dan type

(66)

Sumber cahaya

z

Light color properties

(67)

Tipe Cahaya

z

OpenGL mendukung 2 tipe Cahaya :

z Local (Point) light sources

z Infinite (Directional) light sources

z

Tipe cahaya dikendalikan oleh koordinat

w

Infinite

0 0

(68)

Menyalakan (Turning on) Cahaya

z

Flip setiap “switch” cahaya

glEnable( GL_LIGHTn );

z

Turn on the power

(69)

6

(70)

Mengendalikan Posisi Cahaya

z

Modelview matrix berpengaruh pada

posisi cahaya:

z Perbedaan efek berdasarkan kapan posisi cahaya dispesifikasikan

z eye coordinates z world coordinates z model coordinates

(71)

7

(72)

Fitur Pencahayaan Lanjut

z

Spotlight

z Melokalisasi efek cahaya

z GL_SPOT_DIRECTION z GL_SPOT_CUTOFF

(73)

Fitur Pencahayaan Lanjut

z

Perambatan cahaya (Light attenuation)

z decrease light intensity with distance

z GL_CONSTANT_ATTENUATION z GL_LINEAR_ATTENUATION

z GL_QUADRATIC_ATTENUATION

(74)

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

(75)

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

(76)

dan

(77)

Animation dan Depth Buffering

z

Mendikusikan double buffering dan

animasi

z

Mendiskusikan

hidden surface removal

(78)

Double

(79)

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

e Render scene

f Definisikan swap untuk front dan back buffers

glutSwapBuffers();

(80)

Depth Buffering dan

Hidden Surface Removal

(81)

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

f Render scene

(82)

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

(83)

An Updated Program Template

(Lanjutan)

void init( void ) {

glClearColor( 0.0, 0.0, 1.0, 1.0 );

}

void idle( void ) {

(84)

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

(85)
(86)

Texture

Mapping

CPUCPU DLDL Poly.

Poly. Per Vertex

z

mengaplikasikan citra 1D, 2D, atau 3D

ke geometrik primitif

z

Hal yang digunakan untuk proses

Texturing

z simulasi material

z Mengurangi kompleksitas geometrik

z image warping

(87)

8

7

s

t

x

y

z

image

geometry

(88)

Texture Mapping dan OpenGL

Pipeline

geometry pipeline vertices

pixel pipeline image

rasterizer

z

Citra dan geometri mengalir dalam

pipeline yang terpisah pada proses di

rasterizer

(89)

Contoh Tekstur

z

Tekstur ini adalah citra

(90)

Cara mengaplikasikan Tekstur I

z

Three steps

c specify texture

zread or generate image

zassign to texture

zenable texturing

d assign texture coordinates to vertices

e specify texture parameters

(91)

Tekstur Obyek

z Like display lists for texture images

z one image per texture object

z may be shared by several graphics contexts

z Generate texture names

(92)

Cara mengaplikasikan Tekstur II

z 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

(93)

Tekstur Obyek (lanjutan)

z Create texture objects with texture data and state

glBindTexture( target, id );

z Bind textures before using

(94)

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 dimensions of image must be powers of 2

z Texel colors are processed by pixel pipeline

z pixel scales, biases and lookups can be

done

Memilih citra

untuk Tekstur

CPUCPU DLDL Poly.

(95)

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

z *_in is for source image

z *_out is for destination image

z Image interpolated and filtered during

(96)

Memilih Tekstur: Methode Lainnya

z Use frame buffer as source of texture image

z uses current buffer as source image

glCopyTexImage1D(...)

glCopyTexImage1D(...)

glCopyTexImage2D(...)

glCopyTexImage2D(...)

z Modify part of a defined texture

glTexSubImage1D(...)

glTexSubImage1D(...)

glTexSubImage2D(...)

glTexSubImage2D(...)

glTexSubImage3D(...)

glTexSubImage3D(...)

(97)

z Based on parametric texture coordinates

z glTexCoord*() specified at each vertex

s

Texture Space Object Space

Memetakan

(Mapping) Tekstur

CPUCPU

DL DL Poly.

(98)

Membuat Koordinat Tekstur

z Automatically generate texture coords

glTexGen{ifd}[v]()

z specify a plane

z generate texture coordinates based upon distance

from plane

z generation modes

z GL_OBJECT_LINEAR z GL_EYE_LINEAR

z GL_SPHERE_MAP

(99)

9

(100)

z Filter Modes

z minification or magnification

z special mipmap minification filters

z Wrap Modes

z clamping or repeating z Texture Functions

z how to mix primitive’s color with texture’s color

z blend, modulate or replace texels

(101)

Filter Modes

Texture Polygon

Magnification Minification

Polygon Texture

Example:

glTexParameteri(

(102)

Tekstur Mipmapped

z Mipmap allows for prefiltered texture maps of

decreasing resolutions

z Lessens interpolation errors for smaller textured

objects

z Declare mipmap level during texture definition

glTexImage*D(

glTexImage*D( GL_TEXTURE_*D, level, GL_TEXTURE_*D, level, ))

z GLU mipmap builder routines

gluBuild*DMipmaps(

gluBuild*DMipmaps( …… ))

(103)

Mode Wrapping

z Example:

glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ) glTexParameteri( GL_TEXTURE_2D,

GL_TEXTURE_WRAP_T, GL_REPEAT )

texture s t

GL_CLAMP wrapping GL_REPEAT

(104)

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

(105)

Tips untuk Koreksi Perspektif

z Texture coordinate and color interpolation

z either linearly in screen space

z or using depth/perspective values (slower) z Noticeable for polygons “on edge”

z glHint( GL_PERSPECTIVE_CORRECTION_HINT, hint )

where hint is one of

z GL_DONT_CARE z GL_NICEST

(106)

Adakah tempat untuk Tekstur?

z Query largest dimension of texture image

z typically largest square texture

z doesn’t consider internal format size

z glGetIntegerv( GL_MAX_TEXTURE_SIZE, &size

)

z Texture proxy

z will memory accommodate requested texture size? z no image specified; placeholder

z if texture won’t fit, texture state variables set to 0

z doesn’t know about other textures

(107)

Texture Residency

z Working set of textures

z high-performance, usually hardware accelerated z textures must be in texture objects

z a texture in the working set is resident z for residency of current texture, check

GL_TEXTURE_RESIDENT state

z If too many textures, not all are resident

z can set priority to have some kicked out first

(108)
(109)

Imaging and Raster Primitives

z

Describe OpenGL’s raster primitives:

bitmaps and image rectangles

(110)

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

(111)

Frame Buffer Rasterization

(including Pixel Zoom)

Per Fragment Operations

Texture Memory Pixel-Transfer

Operations (and Pixel Map) CPU

Pixel Storage

Modes

glReadPixels(), glCopyPixels() glBitmap(), glDrawPixels()

glCopyTex*Image();

Pixel Pipeline

z

Programmable pixel storage

and transfer operations

CPU CPU

DL DL Poly.

(112)

Positioning Image Primitives

z

glRasterPos3f(

x, y, z

)

z raster position transformed like geometry

z discarded if raster position is outside of viewport

z may need to fine tune

viewport for desired results

(113)

Rendering Bitmaps

z glBitmap( width, height, xorig, yorig, xmove, ymove, bitmap )

z render bitmap in current color at

(114)

Rendering Fonts using Bitmaps

z

OpenGL uses bitmaps for font rendering

z each character is stored in a display list containing a bitmap

z window system specific routines to access system fonts

z glXUseXFont()

(115)

Rendering Images

z glDrawPixels( width, height, format, type, pixels )

z render pixels with lower left of image at current raster position

z numerous formats and data types for specifying storage in memory

z best performance by using format and type that

(116)

Reading Pixels

z glReadPixels( x, y, width, height, format, type, pixels )

z read pixels from specified (x,y) position in

framebuffer

z pixels automatically converted from

framebuffer format into requested format and type

z

Framebuffer pixel copy

z glCopyPixels( x, y, width, height,

(117)

Raster

Position glPixelZoom(1.0, -1.0);

Pixel Zoom

z

glPixelZoom(

x, y

)

z expand, shrink or reflect pixels around current raster position

(118)

Storage and Transfer Modes

z

Storage modes control accessing

memory

z byte alignment in host memory

z extracting a subimage

z

Transfer modes allow modify pixel

values

z scale and bias pixel component values

(119)
(120)

Advanced OpenGL Topics

z

Display Lists and Vertex Arrays

z

Alpha Blending and Antialiasing

z

Using the Accumulation Buffer

z

Fog

z

Feedback & Selection

(121)

Immediate Mode versus Display Listed

Rendering

z Immediate Mode Graphics

z Primitives are sent to pipeline and display right

away

z No memory of graphical entities z Display Listed Graphics

z Primitives placed in display lists

z Display lists kept on graphics server z Can be redisplayed with different state

(122)

Immediate Mode versus

Display Lists

Immediate Mode

Display Listed

Display List

Polynomial Evaluator

Per Vertex Operations &

Primitive Assembly

Rasterization Per Fragment

(123)

Display Lists

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

(124)

Display Lists

z Not all OpenGL routines can be stored in display lists

z State changes persist, even after a display list is finished

z Display lists can call other display lists

z Display lists are not editable, but you can fake it

(125)

Display Lists and Hierarchy

z

Consider model of a car

z Create display list for chassis

z Create display list for wheel

z glNewList( CAR, GL_COMPILE ); z glCallList( CHASSIS );

z glTranslatef( … ); z glCallList( WHEEL ); z glTranslatef( … ); z glCallList( WHEEL );

z …

(126)

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

z sphere

z cylinder (or cone)

(127)

Vertex

Poly. Per Vertex

z Pass arrays of vertices, colors, etc. to OpenGL in a large chunk

z glVertexPointer( 3, GL_FLOAT, 0, coords ) z glColorPointer( 4, GL_FLOAT, 0, colors ) z glEnableClientState( GL_VERTEX_ARRAY ) z glEnableClientState( GL_COLOR_ARRAY ) z glDrawArrays( GL_TRIANGLE_STRIP, 0,

numVerts );

(128)

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

(129)

Alpha: the 4

th

Color Component

z

Measure of Opacity

z simulate translucent objects

z glass, water, etc.

z composite images

z antialiasing

z ignored if blending is not enabled

(130)

Blending

z

Combine pixels with what’s in already

in the framebuffer

z

glBlendFunc(

src, dst

)

Framebuffer

(131)

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

(132)

Antialiasing

z

Removing the Jaggies

z

glEnable(

mode

)

z GL_POINT_SMOOTH z GL_LINE_SMOOTH

z GL_POLYGON_SMOOTH

z alpha value computed by computing sub-pixel coverage

(133)

Accumulation Buffer

z

Problems of compositing into color

buffers

z limited color resolution

z clamping

z loss of accuracy

z Accumulation buffer acts as a “floating point” color buffer

(134)

Accessing Accumulation Buffer

z

glAccum(

op, value

)

z operations

z 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 glAccum(GL_ACCUM, 0.5) multiplies

(135)

Accumulation Buffer Applications

z

Compositing

z

Full Scene Antialiasing

z

Depth of Field

z

Filtering

(136)

Full Scene Antialiasing :

Jittering

the view

z

Each time we move the viewer, the

image shifts

z Different aliasing artifacts in each image

z Averaging images using accumulation buffer averages out

(137)

Depth of Focus :

Keeping a

Plane in Focus

z

Jitter the viewer to keep one plane

unchanged

Front Plane Back Plane

Focal Plane

(138)

Fog

z glFog{if}( property, value )

z

Depth Cueing

z Specify a range for a linear fog ramp

z GL_FOG_LINEAR

z

Environmental effects

z Simulate more realistic fog

(139)

1

3

(140)

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

(141)

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(

glSelectBuffer( size, buffersize, buffer ))

z

Select selection mode for rendering

(142)

Selection Mode (cont.)

z

To identify a primitive, give it a name

z “names” are just integer values, not strings

z

Names are stack based

z allows for hierarchies of primitives

z

Selection Name Routines

glLoadName( name ) glPushName( name )

(143)

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

z enter selection mode; re-render scene

z primitives drawn near cursor cause hits

(144)

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

(145)

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

(146)

Picking Template (cont.)

glMatrixMode( GL_PROJECTION ); glPopMatrix();

hits = glRenderMode( GL_RENDER );

/* process nameBuffer */

(147)

Picking Ideas

z For OpenGL Picking Mechanism

z only render what is pickable (e.g., don’t clear

screen!)

z use an “invisible” filled rectangle, instead of text

z if several primitives drawn in picking region, hard to

use z values to distinguish which primitive is “on top”

z Alternatives to Standard Mechanism

z color or stencil tricks (for example, use

(148)

Getting to the Framebuffer

Test DitheringDithering

(149)

Scissor Box

z

Additional Clipping Test

z

glScissor(

x, y, w, h

)

z any fragments outside of box are clipped

z useful for updating a small section of a viewport

(150)

Alpha Test

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

CPU CPU

DL DL Poly.

(151)

Stencil Buffer

z

Used to control drawing based on values

in the stencil buffer

z 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

CPU CPU

DL DL Poly.

(152)

Controlling Stencil Buffer

z glStencilFunc( func, ref, mask )

z compare value in buffer with ref using func z only applied for bits in mask which are 1

z func is one of standard comparison functions

z glStencilOp( fail, zfail, zpass )

z Allows changes in stencil buffer based on passing

or failing stencil and depth tests: GL_KEEP,

(153)

Creating a Mask

z glInitDisplayMode( …|GLUT_STENCIL|… ); z glEnable( GL_STENCIL_TEST );

z glClearStencil( 0x0 );

z glStencilFunc( GL_ALWAYS, 0x1, 0x1 ); z glStencilOp( GL_REPLACE, GL_REPLACE,

GL_REPLACE );

(154)

Using Stencil Mask

z

Draw objects where stencil = 1

z glStencilFunc( GL_EQUAL, 0x1, 0x1 )

z

Draw objects where stencil != 1

z glStencilFunc( GL_NOTEQUAL, 0x1,

0x1 );

z glStencilOp( GL_KEEP, GL_KEEP,

GL_KEEP );

(155)

Dithering

z glEnable( GL_DITHER )

z

Dither colors for better looking results

(156)

Logical Operations on Pixels

z

Combine pixels using bitwise logical

operations

z

glLogicOp(

mode

)

z Common modes

(157)

Advanced Imaging

z

Imaging Subset

z Only available if GL_ARB_imaging defined

z Color matrix z Convolutions z Color tables z Histogram z MinMax

(158)
(159)

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

z http://www.mesa3d.org/

z Brian Paul’s Mesa 3D

z http://www.cs.utah.edu/~narobins/opengl.html

(160)

Buku

z

OpenGL Programming Guide, 3

rd

Edition

z

OpenGL Reference Manual, 3

rd

Edition

z

OpenGL Programming for the X Window

System

z includes many GLUT examples

z

Interactive Computer Graphics: A

Referensi

Dokumen terkait

Derajat desentralisasi fiskal Kota Tangerang Selatan dalam kurun waktu tahun 2013-2017 menunjukkan bahwa kemandirian pemerintah Kota Tangerang Selatan cukup baik.,

Untuk setiap tindakan atau pelayanan yang dilakukan tetapi tidak terdapat kotak dalam kolom clinical pathway maka ditulis di kolom variasi disertai dengan tanggal/

Karya Tulis Ilmiah ini telah dipertahankan di depan tim penguji Ujian Sidang Karya Tulis Ilmiah pada Program Studi D3 Analis Kesehatan.. Fakultas Ilmu Kesehatan

Pendapat yang dikemukakan Susilo (2002) menggambarkan bahwa audit sumber daya manusia adalah pemeriksaan dan penilaian secara sistematis, objektif, dan terdokumentasi terhadap

PA pada tahu nakan tingka pelayanan IK sting yang t distribusi ba amatan Pasea PA di Kecama n Pasean te r yang masih   ku dan Produ 5-2035 ur bor sebag camatan tetap or yang

Parameter laporan dapat berupa profil laporan (periode pelaporan, tanggal pelaporan terdahulu yang paling baru, siklus pelaporan, contact person dari laporan tersebut),

Penelitian ini bertujuan melakukan isolasi dan identifikasi parasit telur cacing dari feses hewan koleksi kebun binatang di Taman Margasatwa

Dengan demikian dapat diketahui bahwa analisis SWOT merupakan faktor penting dalam merumuskan strategi, terutama strategi yang diterapkan oleh RSUD Kabupaten Kepulauan