2d and 3d graphics.doc

Upload: suada-bow-weezy

Post on 04-Jun-2018

239 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 2D and 3D Graphics.doc

    1/41

    OPENGL WITH 2D & 3D GRAPHICS

    OpenGL with 2D Graphics

    Instructins!Copy code for each example into a new source file and execute. Read

    explanations of each example to understand the concepts.

    "#" E$a%pe "!GL'"He#cpp

    #include // for MS Windows#include // GLUT, include glu.h and gl.h/* andler for window!re"aint eent. $all %ac& when the window first a""ears and wheneer the window needs to %e re!"ainted. */oid dis"la'() gl$lear$olor(+.+f, +.+f, +.+f, .+f)- // Set %ac&ground color to %lac& and o"aue gl$lear(GL$0L012U334125T)- // $lear the color %uffer (%ac&ground)

    // 6raw a 1ed 7 Suare centered at origin gl2egin(GL8U96S)- // 4ach set of : ertices for; a uad gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f(!+.?f, !+.?f)- // 7, '

    gl=erte7f( +.?f, !+.?f)- gl=erte7f( +.?f, +.?f)- gl=erte7f(!+.?f, +.?f)- gl4nd()-

    gl3lush()- // 1ender now@/* Main functionA GLUT runs as a console a""lication starting at ;ain() */int ;ain(int argc, char** arg) glut5nit(Bargc, arg)- // 5nitialiCe GLUT glut$reateWindow(D0"enGL Setu" TestD)- // $reate a window with the gien title glut5nitWindowSiCe(+, +)- // Set the windowEs initial width B height glut5nitWindowFosition(?+, ?+)- // Fosition the windowEs initial to"!left corner glut6is"la'3unc(dis"la')- // 1egister dis"la' call%ac& handler for window re!"aint

    glutMainLoo"()- // 4nter the eent!"rocessing loo" return +-@

    Explanation of the code#include

    The header "windows.h" is needed for the Windows platform only.

    #include

    We also included the GLUT header, which is guaranteed to include "glu.h" for GL Utility! and "gl.h"

    for Core penGL!.

    The rest ( the pr)ra% is e$paine* in su+se,uent sectins#

    2# Intr*uctin

    penGL pen Graphics Li#rary! is a cross$platform, hardware$accelerated, language$independent,

    industrial standard %&' for producing () including *)! graphics. +odern computers hae dedicated

    G&U Graphics &rocessing Unit! with its own memory to speed up graphics rendering. penGL is the

    software interface to graphics hardware. 'n other words, penGL graphic rendering commands issued #yyour applications could #e directed to the graphic hardware and accelerated.

  • 8/14/2019 2D and 3D Graphics.doc

    2/41

    We use ( sets of li#raries in our penGL programs-

    1. Core penGL GL!- consists of hundreds of commands, which #egin with a prefix "gl" e.g.,

    gl$olor, gl=erte7, glTranslate, gl1otate!. The Core penGL models an o#ect ia a set of

    geometric primities such as point, line and polygon.

    2. penGL Utility Li#rary GLU!- #uilt on$top of the core penGL to proide important utilities

    such as setting camera iew and proection! and more #uilding models such as /radric surfaces

    and polygon tessellation!. GLU commands start with a prefix "glu" e.g., gluLoo&9t,

    gluFers"ectie!.

    3. penGL Utilities Tool0it GLUT!- penGL is designed to #e independent of the windowing

    system or operating system. GLUT is needed to interact with the perating 1ystem such as

    creating a window, handling 0ey and mouse inputs!2 it also proides more #uilding models such

    as sphere and torus!. GLUT commands start with a prefix of "glut" e.g., glut$reatewindow,

    glutMouse3unc!. GLUT is platform independent, which is #uilt on top of platform$specific

    penGL extension such as GL3 for 3 Window 1ystem, WGL for +icrosoft Window, and %GL,

    CGL or Cocoa for +ac 1.

    4.

    5uoting from the opengl.org- "GLUT is designed for constructing small to medium si6ed

    penGL programs. While GLUT is well$suited to learning penGL and deeloping simple

    penGL applications, GLUT is not a full$featured tool0it so large applications re/uiring

    sophisticated user interfaces are #etter off using natie window system tool0its. GLUT is simple,easy, and small."

    3# -erte$. Pri%iti/e an* Cr

    3#" E$a%pe 2! -erte$. Pri%iti/e an* Cr 0GL'2Pri%iti/e#cpp1

    Try #uilding and running this penGL C7C88 program-

    /** GL+Fri;itie.c""A =erte7, Fri;itie and $olor* 6raw Si;"le 6 colored Sha"esA uad, triangle and "ol'gon.

    */#include // for MS Windows#include // GLUT, include glu.h and gl.h/* 5nitialiCe 0"enGL Gra"hics */oid initGL() // Set DclearingD or %ac&ground color gl$lear$olor(+.+f, +.+f, +.+f, .+f)- // 2lac& and o"aue@/* andler for window!re"aint eent. $all %ac& when the window first a""ears and wheneer the window needs to %e re!"ainted. */oid dis"la'() gl$lear(GL$0L012U334125T)- // $lear the color %uffer with current clearing color

    // 6efine sha"es enclosed within a "air of gl2egin and gl4nd gl2egin(GL8U96S)- // 4ach set of : ertices for; a uad gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f(!+.f, +.f)- // 6efine ertices in counter!cloc&wise ($$W) order gl=erte7f(!+.f, +.f)- // so that the nor;al (front!face) is facing 'ou gl=erte7f(!+.f, +.Hf)- gl=erte7f(!+.f, +.Hf)-

    gl$olorf(+.+f, .+f, +.+f)- // Green gl=erte7f(!+.Hf, !+.If)- gl=erte7f(!+.f, !+.If)- gl=erte7f(!+.f, +.+f)- gl=erte7f(!+.Hf, +.+f)-

    gl$olorf(+.f, +.f, +.f)- // 6ar& Gra'

    gl=erte7f(!+.Jf, !+.Hf)-

    http://www.opengl.org/resources/libraries/glut/http://www.opengl.org/resources/libraries/glut/http://www.opengl.org/resources/libraries/glut/
  • 8/14/2019 2D and 3D Graphics.doc

    3/41

    gl$olorf(.+f, .+f, .+f)- // White gl=erte7f(!+.?f, !+.Hf)- gl$olorf(+.f, +.f, +.f)- // 6ar& Gra' gl=erte7f(!+.?f, !+.f)- gl$olorf(.+f, .+f, .+f)- // White gl=erte7f(!+.Jf, !+.f)- gl4nd()-

    gl2egin(GLT159KGL4S)- // 4ach set of ertices for; a triangle gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(+.f, !+.If)- gl=erte7f(+.Hf, !+.If)-

    gl=erte7f(+.:f, !+.f)-

    gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f(+.f, !+.:f)- gl$olorf(+.+f, .+f, +.+f)- // Green gl=erte7f(+.Jf, !+.:f)- gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(+.If, !+.Jf)- gl4nd()-

    gl2egin(GLF0LG0K)- // These ertices for; a closed "ol'gon gl$olorf(.+f, .+f, +.+f)- // ellow gl=erte7f(+.:f, +.f)- gl=erte7f(+.If, +.f)- gl=erte7f(+.Hf, +.:f)-

    gl=erte7f(+.If, +.If)- gl=erte7f(+.:f, +.If)- gl=erte7f(+.f, +.:f)- gl4nd()-

    gl3lush()- // 1ender now@/* Main functionA GLUT runs as a console a""lication starting at ;ain() */int ;ain(int argc, char** arg) glut5nit(Bargc, arg)- // 5nitialiCe GLUT glut$reateWindow(D=erte7, Fri;itie B $olorD)- // $reate window with the gien title glut5nitWindowSiCe(+, +)- // Set the windowEs initial width B height glut5nitWindowFosition(?+, ?+)- // Fosition the windowEs initial to"!left corner glut6is"la'3unc(dis"la')- // 1egister call%ac& handler for window re!"aint eent

    initGL()- // 0ur own 0"enGL initialiCation glutMainLoo"()- // 4nter the eent!"rocessing loo" return +-@

    The expected output and the coordinates are as follows. Ta0e note that 4 shapes hae pure color, and *

    shapes hae color #lending from their ertices.

  • 8/14/2019 2D and 3D Graphics.doc

    4/41

    The program is explained in the program in the following sections.

    3#2 OpenGL as a State achine

    penGL operates as astate machine, and maintain a set ofstate variablessuch as the foreground color,

    #ac0ground color, and many more!. 'n a state machine, once the alue of a state aria#le is set, the alue

    persists until a new alue is gien.

    9or example, we set the "clearing" #ac0ground! color to #lac0 oncein initGL(). We use this setting to

    clear the window in the dis"la'()repeatedlydis"la'()is called #ac0 wheneer there is a window re$

    paint re/uest! $ the clearing color is not changed in the entire program.

    // 5n initGL(), set the DclearingD or %ac&ground color

    gl$lear$olor(+.+f, +.+f, +.+f, .+f)- // %lac& and o"aue// 5n dis"la'(), clear the color %uffer (i.e., set %ac&ground) with the currentDclearingD colorgl$lear(GL$0L012U334125T)-

    %nother example- 'f we use gl$olorfunction to set the current foreground color to "red", then "red" will

    #e used for all the su#se/uent ertices, until we use another gl$olorfunction to change the foreground

    color.

    In a state machine, everything shall remain until you explicitly change it!

    3#3 Na%in) Cn/entin (r OpenGL unctins

    %n penGL functions-

    #egins with lowercase glfor core penGL!, glufor penGL Utility! or glutfor penGL

    Utility Tool0it!.

    followed #y the purpose of the function, in camel caseinitial$capitali6ed!, e.g., gl$olorto

    specify the drawing color, gl=erte7to define the position of a ertex.

    followed #y specifications for the parameters, e.g., gl$olorfta0es three floatparameters.

    gl=ecte7ita0es two intparameters.

    This is needed as C7C88 Language does not support function oerloading. )ifferent ersions ofthe function need to #e written for different parameter lists.!

  • 8/14/2019 2D and 3D Graphics.doc

    5/41

    The conention can #e expressed as follows-

    returnTypeglFunction[234][sifd](type value, ...)- // , or : "ara;etersreturnTypeglFunction[234][sifd]v(type*value)- // an arra' "ara;eter

    The function may ta0e *, (, or 4 parameters, in type of sGLshort!, iGLint!, fGLfloat! or d

    GLdou%le!. The :: for ector! denotes that the parameters are 0ept in an array of *, (, or 4 elements, and

    pass into the function as an array pointer.

    penGL defines its own data types-

    1igned 'ntegers- GL%'te;$#it!, GLshort and !.

    GL%ooleanunsigned char with > for false and non$> for true!.

    GLsiCei(*$#it non$negatie integers!.

    GLenu;(*$#it enumerated integers!.

    The penGL types are defined ia t'"edefin "gl.h" as follows-

    t'"edef unsigned int GLenu;-t'"edef unsigned char GL%oolean-t'"edef unsigned int GL%itfield-t'"edef oid GLoid-t'"edef signed char GL%'te- /* !%'te signed */t'"edef short GLshort- /* !%'te signed */t'"edef int GLint- /* :!%'te signed */t'"edef unsigned char GLu%'te- /* !%'te unsigned */t'"edef unsigned short GLushort- /* !%'te unsigned */

    t'"edef unsigned int GLuint- /* :!%'te unsigned */t'"edef int GLsiCei- /* :!%'te signed */t'"edef float GLfloat- /* single "recision float */t'"edef float GLcla;"f- /* single "recision float in +,N */t'"edef dou%le GLdou%le- /* dou%le "recision float */t'"edef dou%le GLcla;"d- /* dou%le "recision float in +,N */

    penGL:s constants#egins with "GL", "GLU" or "GLUT", in uppercase separated with underscores, e.g.,

    GL$0L012U334125T.

    9or examples,

    gl=erte7f(.f, .f, .f)- // GLfloat "ara;eters

    gl=erte7i(:, ?)- // GLint "ara;atersgl$olor:f(+.+f, +.+f, +.+f, .+f)- // : GLfloat "ara;etersGLdou%le a=erte7N O ., ., .@-gl=erte7f(a=erte7)- // an arra' of GLfloat alues

    3#4 One5ti%e Initiai6atin initGL01

    The initGL()is meant for carrying out one$time penGL initiali6ation tas0s, such as setting the clearing

    color. initGL()is ino0ed once and only once! in ;ain().

    3#7 Ca+ac8 Han*er *ispa901

  • 8/14/2019 2D and 3D Graphics.doc

    6/41

    The function dis"la'()is 0nown as a callback event handler. %n eent handler proides the responseto

    a particular eventsuch as 0ey$press, mouse$clic0, window$paint!. The function dis"la'()is meant to #e

    the handler for windowpainteent. The penGL graphics system calls #ac0 dis"la'()in response to a

    window$paint re/uest to re$paint the window e.g., window first appears, window is restored after

    minimi6ed, and window is resi6ed!. Call#ac0 means that the function is ino0ed #y the system, instead ofcalled #y your program.

    The 6is"la'()runs when the window first appears and once per su#se/uent re$paint re/uest. #sere

    that we included penGL graphics rendering code inside the dis"la'()function, so as to re$draw the

    entire window when the window first appears and upon each re$paint re/uest.

    3#: Settin) up GL;T 5 %ain01

    GLUT proides high$leel utilities to simplify penGL programming, especially in interacting with the

    perating 1ystem such as creating a window, handling 0ey and mouse inputs!. The following GLUT

    functions were used in the a#oe program-

    glut5nit- initiali6es GLUT, must #e called #efore other GL7GLUT functions. 't ta0es the same

    arguments as the ;ain().

    oid glutInit(int *argc, char **argv)

    glut$reateWindow- creates a window with the gien title.

    int glutCreateWindow(char *title)

    glut5nitWindowSiCe- specifies the initial window width and height, in pixels.

    oid glutInitWindowSize(int width, int height)

    glut5nitWindowFosition- positions the top$left corner of the initial window at x,y!. The

    coordinates x,y!, in term of pixels, is measured in window coordinates, i.e., origin >, >! is at the

    top$left corner of the screen2 x$axis pointing right and y$axis pointing down.

    oid glutInitWindowosition(int x, int y)

    glut6is"la'3unc- registers the call#ac0 function or eent handler! for handling window$paint

    eent. The penGL graphic system calls #ac0 this handler when it receies a window re$paintre/uest. 'n the example, we register the function dis"la'()as the handler.

    oid glut!ispla"#unc(oid (*func)(oid))

    glutMainLoo"- enters the infinite eent$processing loop, i.e, put the penGL graphics system to

    wait for eents such as re$paint!, and trigger respectie eent handlers such as dis"la'()!.

    oid glut$ain%oop()

    'n the ;ain()function of the example-

    glut5nit(Bargc, arg)-

    glut$reateWindow(D=erte7, Fri;itie B $olorD)-glut5nitWindowSiCe(+, +)-glut5nitWindowFosition(?+, ?+)-

    We initiali6e the GLUT and create a window with a title, an initial si6e and position.

    glut6is"la'3unc(dis"la')-

    We register dis"la'()function as the call#ac0 handler for window$paint eent. That is, dis"la'()runs

    when the window first appears and wheneer there is a re/uest to re$paint the window.

    initGL()-

  • 8/14/2019 2D and 3D Graphics.doc

    7/41

    We call the initGL()to perform all the one$time initiali6ation operations. 'n this example, we set the

    clearing #ac0ground! color once, and use it repeata#ly in the dis"la'()function.

    glutMainLoo"()-

    We then put the program into the eent$handling loop, awaiting for eents such as window$paint re/uest!

    to trigger off the respectie eent handlers such as dis"la'()!.

    3#< Cr

    We use gl$olorfunction to set theoreground color, and gl$lear$olorfunction to set the background

    or clearing! color.

    oid glColor3f(GLfloat red, GLfloat green, GLfloat blue)oid glColor3fv(GLfloat *colorRGB)oid glColor4f(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)oid glColor4fv(GLfloat *colorRGBA)oid glClearColor(GLcla;"f red, GLcla;"f green, GLcla;"f blue, GLcla;"f alpha) // GLcla;"f in the range of +.+f to .+f

    ?otes-

    Color is typically specified in floatin the range +.+fand .+f.

    Color can #e specified using RG@ Red$Green$@lue! or RG@% Red$Green$@lue$%lpha!

    components. The :%: or alpha! specifies the transparency or opacity! index, with alue of denotes total transparent.

    We shall discuss alpha later.

    'n the a#oe example, we set the #ac0ground color ia gl$lear$olorin initGL(), with RA>, GA>, @A>

    #lac0! and %A< opa/ue and cannot see through!.

    // 5n initGL(), set the DclearingD or %ac&ground colorgl$lear$olor(+.+f, +.+f, +.+f, .+f)- // 2lac& and o"ague

    'n dis"la'(), we set the ertex color ia gl$olorffor su#se/uent ertices. 9or example, RA,

    @A> red!.

    // 5n dis"la'(), set the foreground color of the "i7elgl$olorf(.+f, +.+f, +.+f)- // 1ed

    3#= Ge%etric Pri%iti/es

    'n penGL, an o#ect is made up of geometric primities such as triangle, /uad, line segment and point.% primitie is made up of one or more ertices. penGL supports the following primities-

  • 8/14/2019 2D and 3D Graphics.doc

    8/41

    % geometric primitie is defined #y specifying its ertices ia gl=erte7function, enclosed within a pair

    gl2eginand gl4nd.

    oid gl&egin(GLenu; shape) oid gl'ertex[234][sifd](typex, typey, typez, ...) oid gl'ertex[234][sifd]v (type*coords)oid glEnd()

    gl2eginspecifies the type of geometric o#ect, such as GLF05KTS, GLL5K4S,GL8U96S, GLT159KGL4S,

    and GLF0LG0K. 9or types that end with :S:, you can define multiple o#ects of the same type in each

    gl2egin7gl4ndpair. 9or example, for GLT159KGL4S, each set of three gl=erte7:s defines a triangle.

    The ertices are usually specified in floatprecision. 't is #ecause integer is not suita#le for trigonometric

    operations needed to carry out transformations such as rotation!. &recision of floatis sufficient forcarrying out intermediate operations, and render the o#ects finally into pixels on screen with resolution

    of says ;>>x=>>, integral precision!. dou%leprecision is often not necessary.

    'n the a#oe example-

    gl2egin(GL8U96S)- .... : uads with 7 gl=erte7() ....gl4nd()-

    we define ( color /uads GL8U96S! with

  • 8/14/2019 2D and 3D Graphics.doc

    9/41

    gl=erte7f(!+.f, +.f)-gl=erte7f(!+.f, +.f)-gl=erte7f(!+.f, +.Hf)-gl=erte7f(!+.f, +.Hf)-

    We set the color to red RA, @A>!. %ll su#se/uent ertices will hae the color of red. Ta0e note

    that in penGL, color and many properties! is applied to ertices rather than primitie shapes. The color

    of the primitie shape is interpolatedfrom its ertices.

    We similarly define a second /uad in green.

    9or the third /uad as follows!, the ertices hae different color. The color of the /uad surface is

    interpolated from its ertices, resulting in shades of white to dar0 gray, as shown in the output.

    gl$olorf(+.f, +.f, +.f)- // 6ar& Gra'gl=erte7f(!+.Jf, !+.Hf)-gl$olorf(.+f, .+f, .+f)- // Whitegl=erte7f(!+.?f, !+.Hf)-gl$olorf(+.f, +.f, +.f)- // 6ar& Gra'gl=erte7f(!+.?f, !+.f)-gl$olorf(.+f, .+f, .+f)- // Whitegl=erte7f(!+.Jf, !+.f)-

    3#> 2D Cr*inate S9ste% an* the De(aut -iew 0THIS TOPIC WILL ?E DISC;SSED LATER?;T GO THRO;GH IT AS WE HA-E TAC@LED A ?IT O IT IN O;R PROGRAS1

    The following diagram shows the penGL *) Coordinate 1ystem, which corresponds to the eeryday *)

    Cartesian coordinates with origin located at the #ottom$left corner.

    The default penGL *) clippingareai.e., what is captured #y the camera! is an orthographic iew withx and y in the range of $ and , i.e., a *x* s/uare with centered at the origin. This clipping$area is

    mapped to the viewporton the screen. Biewport is measured in pixels.

  • 8/14/2019 2D and 3D Graphics.doc

    10/41

    1tudy the a#oe example to conince yourself that the *) shapes created are positioned correctly on the

    screen.

    4# Cippin)5Area & -iewprt

    Try dragging the corner of the window to ma0e it #igger or smaller. #sere that all the shapes are

    distorted.

    We can handle the re$si6ing of window ia a call#ac0 handler resha"e(), which can #e programmed to

    adust the penGL clipping$area according to the window:s aspect ratio.

    Clipping %rea- "lipping arearefers to the area that can #e seen i.e., captured #y the camera!, measured

    in penGL coordinates.

    The function glu0rtho6can #e used to set the clipping area of *) orthographic iew. #ects outside

    the clipping area will #e clippedaway and cannot #e seen.

    oid glu(rtho2!(GLdou%le left, GLdou%le right, GLdou%le bottom, GLdou%le top) // The default cli""ing area is (!.+, .+, !.+, .+) in 0"enGL coordinates,

    // i.e., 7 suare centered at the origin.

    To set the clipping area, we need to issue a series of commands as follows- we first select the so$called

    pro#ection matrixfor operation, and reset the proection matrix to identity. We then choose the *)

    orthographic iew with the desired clipping area, ia glu0rtho6().

    // Set to 6 orthogra"hic "roPection with the s"ecified cli""ing areaglMatri7Mode(GLF10Q4$T50K)- // Select the FroPection ;atri7 for o"erationglLoad5dentit'()- // 1eset FroPection ;atri7glu0rtho6(!.+, .+, !.+, .+)- // Set cli""ing areaEs left, right, %otto;, to"

    Biewport- $iewportrefers to the display area on the window screen!, which is measured in pixels in

    screen coordinates excluding the title #ar!.

    The clipping area is mapped to the iewport. We can use gl=iew"ortfunction to configure the iewport.

    oid gl'iewport(GLint xTopLeft, GLint yTopLeft, GLsiCei width, GLsiCei height)

    1uppose the clipping area:s left, right, #ottom, top! is $, , $, ! in penGL coordinates! and

    the iewport:s xTopLeft, xTopRight, width, height! is >, >, =4>, 4;>! in screen coordinates in pixels!,then the #ottom$left corner $, $! maps to >, >! in the iewport, the top$right corner , ! maps

  • 8/14/2019 2D and 3D Graphics.doc

    11/41

    to =(, 4D!. 't is o#ious that if the aspect ratiosfor the clipping area and the iewport are not the same,

    the shapes will #e distorted.

    Ta0e note that in the earlier example, the windows: si6e of (*>x(*> has a s/uare shape, with an aspect

    ratio consistent with the default *x* s/uarish clipping$area.

    4#" E$a%pe 3! Cippin)5area an* -iewprt 0GL'3-iewprt#cpp1

    /*

    * GL+=iew"ort.c""A $li""ing!area and =iew"ort* 5;"le;enting resha"e to ensure sa;e as"ect ratio %etween the* cli""ing!area and the iew"ort.*/#include // for MS Windows#include // GLUT, include glu.h and gl.h/* 5nitialiCe 0"enGL Gra"hics */oid initGL() // Set DclearingD or %ac&ground color gl$lear$olor(+.+f, +.+f, +.+f, .+f)- // 2lac& and o"aue@oid dis"la'() gl$lear(GL$0L012U334125T)-// $lear the color %uffer with current clearing color

    // 6efine sha"es enclosed within a "air of gl2egin and gl4nd gl2egin(GL8U96S)- // 4ach set of : ertices for; a uad gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f(!+.f, +.f)- // 6efine ertices in counter!cloc&wise ($$W) order gl=erte7f(!+.f, +.f)- // so that the nor;al (front!face) is facing 'ou gl=erte7f(!+.f, +.Hf)- gl=erte7f(!+.f, +.Hf)-

    gl$olorf(+.+f, .+f, +.+f)- // Green gl=erte7f(!+.Hf, !+.If)- gl=erte7f(!+.f, !+.If)- gl=erte7f(!+.f, +.+f)- gl=erte7f(!+.Hf, +.+f)-

    gl$olorf(+.f, +.f, +.f)- // 6ar& Gra' gl=erte7f(!+.Jf, !+.Hf)- gl$olorf(.+f, .+f, .+f)- // White gl=erte7f(!+.?f, !+.Hf)- gl$olorf(+.f, +.f, +.f)- // 6ar& Gra' gl=erte7f(!+.?f, !+.f)- gl$olorf(.+f, .+f, .+f)- // White gl=erte7f(!+.Jf, !+.f)- gl4nd()-

    gl2egin(GLT159KGL4S)- // 4ach set of ertices for; a triangle gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(+.f, !+.If)- gl=erte7f(+.Hf, !+.If)- gl=erte7f(+.:f, !+.f)-

    gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f(+.f, !+.:f)- gl$olorf(+.+f, .+f, +.+f)- // Green gl=erte7f(+.Jf, !+.:f)- gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(+.If, !+.Jf)- gl4nd()-

    gl2egin(GLF0LG0K)- // These ertices for; a closed "ol'gon gl$olorf(.+f, .+f, +.+f)- // ellow gl=erte7f(+.:f, +.f)- gl=erte7f(+.If, +.f)- gl=erte7f(+.Hf, +.:f)- gl=erte7f(+.If, +.If)-

    gl=erte7f(+.:f, +.If)-

  • 8/14/2019 2D and 3D Graphics.doc

    12/41

    gl=erte7f(+.f, +.:f)- gl4nd()-

    gl3lush()- // 1ender now@)* +andler for window re,size event- Called .ac/ when the window first appears and whenever the window is re,sized with its new width and height *)void reshape01%sizei width 1%sizei height )) 1%sizei for non,negative integer )) Co5pute aspect ratio of the new window if 0height 66 7 height 6 89 )) :o prevent divide ." 7 1%float aspect 6 01%floatwidth ) 01%floatheight9

    )) Set the viewport to cover the new window

    gl'iewport07 7 width height9

    )) Set the aspect ratio of the clipping area to 5atch the viewport gl$atrix$ode01%;9 )) :o operate on the ro?ection 5atrix gl%oadIdentit"09 )) O height) glu0rtho6(!.+ * as"ect, .+ * as"ect, !.+, .+)-@ else glu0rtho6(!.+, .+, !.+ / as"ect, .+ / as"ect)-@

    We set the aspect ratio of the clipping area to match the iewport. To set the clipping area, we first choose

    the operate on the proection matrix ia glMatri7Mode(GLF10Q4$T50K). penGL has two matrices, a

  • 8/14/2019 2D and 3D Graphics.doc

    13/41

    proection matrix which deals with camera proection such as setting the clipping area! and a model$iew

    matrix for transforming the o#ects from their local spaces to the common world space!. We reset the

    proection matrix ia glLoad5dentit'().

    9inally, we ino0e glu0rtho6()to set the clipping area with an aspect ratio matching the iewport. The

    shorter side has the range from $< to 8

  • 8/14/2019 2D and 3D Graphics.doc

    14/41

    /* 5nitialiCe 0"enGL Gra"hics */oid initGL() // Set DclearingD or %ac&ground color gl$lear$olor(+.+f, +.+f, +.+f, .+f)- // 2lac& and o"aue@/* andler for window!re"aint eent. $all %ac& when the window first a""ears and wheneer the window needs to %e re!"ainted. */oid dis"la'() gl$lear(GL$0L012U334125T)- // $lear the color %uffer gl$atrix$ode01%;$(!E%'IEW9 )) :o operate on $odel,'iew 5atrix

    gl%oadIdentit"09 ))

  • 8/14/2019 2D and 3D Graphics.doc

    15/41

    gl'ertex2f0,7-2f 7-7f9 glEnd09

    gl3lush()- // 1ender now@/* andler for window re!siCe eent. $alled %ac& when the window first a""ears and wheneer the window is re!siCed with its new width and height */oid resha"e(GLsiCei width, GLsiCei height) // GLsiCei for non!negatie integer // $o;"ute as"ect ratio of the new window if (height OO +) height O - // To "reent diide %' + GLfloat as"ect O (GLfloat)width / (GLfloat)height-

    // Set the iew"ort to coer the new window

    gl=iew"ort(+, +, width, height)-

    // Set the as"ect ratio of the cli""ing area to ;atch the iew"ort glMatri7Mode(GLF10Q4$T50K)- // To o"erate on the FroPection ;atri7 glLoad5dentit'()- if (width >O height) // as"ect >O , set the height fro; ! to , with larger width glu0rtho6(!.+ * as"ect, .+ * as"ect, !.+, .+)- @ else // as"ect < , set the width to ! to , with larger height glu0rtho6(!.+, .+, !.+ / as"ect, .+ / as"ect)- @@

    /* Main functionA GLUT runs as a console a""lication starting at ;ain() */int ;ain(int argc, char** arg) glut5nit(Bargc, arg)- // 5nitialiCe GLUT glut5nitWindowSiCe(I:+, :+)- // Set the windowEs initial width B height ! non!suare glut5nitWindowFosition(?+, ?+)- // Fosition the windowEs initial to"!left corner glut$reateWindow(DModel Transfor;D)- // $reate window with the gien title glut6is"la'3unc(dis"la')- // 1egister call%ac& handler for window re!"aint eent glut1esha"e3unc(resha"e)- // 1egister call%ac& handler for window re!siCe eent initGL()- // 0ur own 0"enGL initialiCation glutMainLoo"()- // 4nter the infinite eent!"rocessing loo" return +-@

    glMatri7Mode(GLM064L=54W)- // To o"erate on ;odel!iew ;atri7glLoad5dentit'()- // 1eset

    Translation and rotation are parts of so$called model transorm, which transform from the o#ects fromthe local space or model space! to the common world space. To carry out model transform, we set the

    matrix mode to mode$iew matrix GLM064L=54W! and reset the matrix. Recall that in the preious

    example, we set the matrix mode to proection matrix GLF10Q4$T50K! to set the clipping area.!

    penGL is operating as a state machine. That is, once a state is set, the alue of the state persists until it is

    changed. 'n other words, once the coordinates are translated or rotated, all the su#se/uent operations will

    #e #ased on this coordinates.

    Translation is done ia glTranslatefunction-

    oid gltranslatef(GLfloat x, GLfloat y, GLfloat z) // where (7, ', C) is the translational ector

    Ta0e note that glTranslateffunction must #e placed outside the gl2egin7gl4nd, where as gl$olorcan

    #e placed inside gl2egin7gl4nd.

    Rotation is done ia gl1otateffunction-

    oid gl

  • 8/14/2019 2D and 3D Graphics.doc

    16/41

    Ta0e note that the rotational angle is measured in degrees instead of radians! in penGL.

    'n the a#oe example, we translate within the x$y plane 6A>! and rotate a#out the 6$axis which is normal

    to the x$y plane!.

    :# Ani%atin

    :#" I*e unctin

    To perform animation e.g., rotating the shapes!, you could register an idle()call#ac0 handler withGLUT, ia glut5dle3unccommand. The graphic system will call #ac0 the idle()function when there is

    no other eent to #e processed.

    oid glut5dle3unc(oid (*func)(oid))

    'n the idle()function, you could issue glutFost1edis"la'command to post a window re$paint re/uest,

    which in turn will actiate dis"la'()function.

    oid idle() glutFost1edis"la'()- // Fost a re!"aint reuest to actiate dis"la'()@

    Ta0e note that the a#oe is e/uialent to registering dis"la'()as the idlefunction.

    // ;ainglut5dle3unc(dis"la')-

    :#2 Du+e ?u((erin)

    )ou#le #uffering uses two display #uffers to smoothen animation. The next screen is prepared in a back

    #uffer, while the current screen is held in aront#uffer. nce the preparation is done, you can use

    glutSwa"2uffercommand to swap the front and #ac0 #uffers.

    To use dou#le #uffering, you need to ma0e two changes-

    1. 'n the ;ain(), include this line #efore creating the window-

    glut5nit6is"la'Mode(GLUT60U2L4)- // Set dou%le %uffered ;ode

    2. 'n the dis"la'()function, replace gl3lush()with glutSwa"2uffers(), which swap the front

    and #ac0 #uffers.

    )ou#le #uffering should #e used in animation. 9or static display, single #uffering is sufficient. +anygraphics hardware always dou#le #uffered, so it is hard to see the differences.!

    :#3 E$a%pe 7! Ani%atin usin) I*e unctin 0GL'7I*eunc#cpp1

    The following program rotates all the shapes created in our preious example using idle function with

    dou#le #uffering.

    /** GL+?5dle3unc.c""A Translation and 1otation* Transfor; "ri;ities fro; their ;odel s"aces to world s"ace (Model Transfor;).*/#include // for MS Windows#include // GLUT, include glu.h and gl.h// Glo%al aria%le1%float angle 6 7-7f9 )) Current rotational angle of the shapes

  • 8/14/2019 2D and 3D Graphics.doc

    17/41

    /* 5nitialiCe 0"enGL Gra"hics */oid initGL() // Set DclearingD or %ac&ground color gl$lear$olor(+.+f, +.+f, +.+f, .+f)- // 2lac& and o"aue@)* Called .ac/ when there is no other event to .e handled *)void idle0 glutost

  • 8/14/2019 2D and 3D Graphics.doc

    18/41

    gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f(!+.f, !+.f)- gl$olorf(+.+f, .+f, +.+f)- // Green gl=erte7f( +.f, !+.f)- gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f( +.+f, +.f)- gl4nd()- glop$atrix09 )) O height) // as"ect >O , set the height fro; ! to , with larger width glu0rtho6(!.+ * as"ect, .+ * as"ect, !.+, .+)- @ else // as"ect < , set the width to ! to , with larger height glu0rtho6(!.+, .+, !.+ / as"ect, .+ / as"ect)- @@/* Main functionA GLUT runs as a console a""lication starting at ;ain() */int ;ain(int argc, char** arg) glut5nit(Bargc, arg)- // 5nitialiCe GLUT glutInit!ispla"$ode01%G:;!(G&%E9 )) Ena.le dou.le .uffered 5ode glut5nitWindowSiCe(I:+, :+)- // Set the windowEs initial width B height ! non!suare glut5nitWindowFosition(?+, ?+)- // Fosition the windowEs initial to"!left corner

    glut$reateWindow(D9ni;ation ia 5dle 3unctionD)-// $reate window with the gien title glut6is"la'3unc(dis"la')- // 1egister call%ac& handler for window re!"aint eent glut1esha"e3unc(resha"e)- // 1egister call%ac& handler for window re!siCe eent glutIdle#unc0idle9 ))

  • 8/14/2019 2D and 3D Graphics.doc

    19/41

    GLfloat angle O +.+f- // $urrent rotational angle of the sha"es

    We define a glo#al aria#le called angleto 0eep trac0 of the rotational angle of all the shapes. We will

    later use gl1otatefto rotate all the shapes to this angle.

    angle RO +.f-

    %t the end of each refresh in dis"la'()!, we update the rotational angle of all the shapes.

    glutSwa"2uffers()- // Swa" front! and %ac& fra;e%ufferglut5nit6is"la'Mode(GLUT60U2L4)- // 5n ;ain(), ena%le dou%le %uffered ;ode

    'nstead of gl3lush()which flushes the frame#uffer for display immediately, we ena#le dou#le #uffering

    and use glutSwa"2uffer()to swap the front$ and #ac0$#uffer during the B1ync for smoother display.

    oid idle() glutFost1edis"la'()- // Fost a re!"aint reuest to actiate dis"la'()@glut5dle3unc(idle)- // 5n ;ain() ! 1egister call%ac& handler if no other eent

    We define an idle()function, which posts a re$paint re/uest and ino0e dis"la'(), if there is no eent

    outstanding. We register this idle()function in ;ain()ia glut5dle3unc().

    :#4 Du+e ?u((erin) & Re(resh Rate

    When dou#le #uffering is ena#led, glutSwa"2uffers synchroni6es with the screen refresh interal

    B1ync!. That is, the #uffers will #e swapped at the same time when the monitor is putting up a new

    frame. %s the result, idle()function, at #est, refreshes the animation at the same rate as the refresh rate

    of the monitor =>E6 for LC)7LF) monitor!. 't may operates at half the monitor refresh rate if the

    computations ta0es more than < refresh interal!, one$third, one$fourth, and so on, #ecause it need to wait

    for the B1ync.

    :#7 Ti%er unctin

    With idle(), we hae no control to the refresh interal. We could register a Ti;er()function with

    GLUT ia glutTi;er3unc. The Ti;er()function will #e called #ac0 at the specified fixed interal.

    oid glutTi;er3unc(unsigned int millis, oid (*func)(int value), value) // where millisis the dela' in ;illiseconds, valuewill %e "assed to the ti;erfunction.

    :#: E$a%pe :! Ani%atin /ia Ti%er unctin 0GL':Ti%erunc#cpp1

    The following modifications rotate all the shapes created in the earlier example counter$cloc0wise #y *

    degree per (> milliseconds.

    /** GL+ITi;er3unc.c""A Translation and 1otation* Transfor; "ri;ities fro; their ;odel s"aces to world s"ace (Model Transfor;).*/#include // for MS Windows#include // GLUT, include glu.h and gl.h// glo%al aria%leGLfloat angle O +.+f- // rotational angle of the sha"esint refreshMills O +- // refresh interal in ;illiseconds

  • 8/14/2019 2D and 3D Graphics.doc

    20/41

    /* 5nitialiCe 0"enGL Gra"hics */oid initGL() // Set DclearingD or %ac&ground color gl$lear$olor(+.+f, +.+f, +.+f, .+f)- // 2lac& and o"aue@)* Called .ac/ when ti5er expired *)void :i5er0int value glutost

  • 8/14/2019 2D and 3D Graphics.doc

    21/41

    gl2egin(GLT159KGL4S)- gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f(!+.f, !+.f)- gl$olorf(+.+f, .+f, +.+f)- // Green gl=erte7f( +.f, !+.f)- gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f( +.+f, +.f)- gl4nd()- glFo"Matri7()- // 1estore the ;odel!iew ;atri7

    glFushMatri7()- // Sae ;odel!iew ;atri7 setting glTranslatef(+.?f, +.:f, +.+f)- // Translate

    gl1otatef(angle, +.+f, +.+f, .+f)- // rotate %' angle in degrees gl2egin(GLF0LG0K)- gl$olorf(.+f, .+f, +.+f)- // ellow gl=erte7f(!+.f, !+.f)- gl=erte7f( +.f, !+.f)- gl=erte7f( +.f, +.+f)- gl=erte7f( +.f, +.f)- gl=erte7f(!+.f, +.f)- gl=erte7f(!+.f, +.+f)- gl4nd()- glFo"Matri7()- // 1estore the ;odel!iew ;atri7

    glutSwa"2uffers()- // 6ou%le %uffered ! swa" the front and %ac& %uffers

    // $hange the rotational angle after each dis"la'()

    angle RO .+f-@/* andler for window re!siCe eent. $alled %ac& when the window first a""ears and wheneer the window is re!siCed with its new width and height */oid resha"e(GLsiCei width, GLsiCei height) // GLsiCei for non!negatie integer // $o;"ute as"ect ratio of the new window if (height OO +) height O - // To "reent diide %' + GLfloat as"ect O (GLfloat)width / (GLfloat)height-

    // Set the iew"ort to coer the new window gl=iew"ort(+, +, width, height)-

    // Set the as"ect ratio of the cli""ing area to ;atch the iew"ort glMatri7Mode(GLF10Q4$T50K)- // To o"erate on the FroPection ;atri7

    glLoad5dentit'()- if (width >O height) // as"ect >O , set the height fro; ! to , with larger width glu0rtho6(!.+ * as"ect, .+ * as"ect, !.+, .+)- @ else // as"ect < , set the width to ! to , with larger height glu0rtho6(!.+, .+, !.+ / as"ect, .+ / as"ect)- @@/* Main functionA GLUT runs as a console a""lication starting at ;ain() */int ;ain(int argc, char** arg) glut5nit(Bargc, arg)- // 5nitialiCe GLUT glut5nit6is"la'Mode(GLUT60U2L4)- // 4na%le dou%le %uffered ;ode glut5nitWindowSiCe(I:+, :+)- // Set the windowEs initial width B height ! non!suare

    glut5nitWindowFosition(?+, ?+)- // Fosition the windowEs initial to"!left corner glut$reateWindow(D9ni;ation ia 5dle 3unctionD)-// $reate window with the gien title glut6is"la'3unc(dis"la')- // 1egister call%ac& handler for window re!"aint eent glut1esha"e3unc(resha"e)- // 1egister call%ac& handler for window re!siCe eent glut:i5er#unc07 :i5er 79 // 3irst ti;er call i;;ediatel' initGL()- // 0ur own 0"enGL initialiCation glutMainLoo"()- // 4nter the infinite eent!"rocessing loo" return +-@

    oid Ti;er(int alue) glutFost1edis"la'()- // Fost re!"aint reuest to actiatedis"la'() glutTi;er3unc(refreshMills, Ti;er, +)- // ne7t Ti;er call ;illiseconds later@

  • 8/14/2019 2D and 3D Graphics.doc

    22/41

    We replace the idle()function #y a ti;er()function, which post a re$paint re/uest to ino0e

    dis"la'(), after the timer expired.

    glutTi;er3unc(+, Ti;er, +)- // 3irst ti;er call i;;ediatel'

    'n ;ain(), we register the ti;er()function, and actiate the ti;er()immediately with initial timer A

    >!.

    :#< re GL;T (unctins

    glut5nit6is"la'Mode- re/uests a display with the specified mode, such as color mode

    GLUT1G2, GLUT1G29, GLUT5K64!, single7dou#le #uffering GLUTS5KGL4, GLUT60U2L4!,

    ena#le depth GLUT64FT!, oined with a #it 01::.

    oid glut5nit6is"la'Mode(unsigned int displayode)

    9or example,

    glut5nit6is"la'Mode(GLUT1G29 GLUT60U2L4 GLUT64FT)- // Use 1G29 color, ena%le dou%le %uffering and ena%le de"th %uffer

    :#= E$a%pe

  • 8/14/2019 2D and 3D Graphics.doc

    23/41

    GLfloat %all1adius O +.?f- // 1adius of the %ouncing %allGLfloat %all O +.+f- // 2allEs center (7, ') "ositionGLfloat %all O +.+f-GLfloat %allMa7, %allMin, %allMa7, %allMin- // 2allEs center (7, ') %oundsGLfloat 7S"eed O +.+f- // 2allEs s"eed in 7 and ' directionsGLfloat 'S"eed O +.++Hf-int refreshMillis O +- // 1efresh "eriod in ;illiseconds// FroPection cli""ing areaGLdou%le cli"9reaLeft, cli"9rea1ight, cli"9rea2otto;, cli"9reaTo"-/* 5nitialiCe 0"enGL Gra"hics */

    oid initGL() gl$lear$olor(+.+, +.+, +.+, .+)- // Set %ac&ground (clear) color to %lac&@/* $all%ac& handler for window re!"aint eent */oid dis"la'() gl$lear(GL$0L012U334125T)- // $lear the color %uffer glMatri7Mode(GLM064L=54W)- // To o"erate on the ;odel!iew ;atri7 glLoad5dentit'()- // 1eset ;odel!iew ;atri7

    glTranslatef(%all, %all, +.+f)- // Translate to (7Fos, 'Fos) // Use triangular seg;ents to for; a circle gl2egin(GLT159KGL439K)- gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(+.+f, +.+f)- // $enter of circle

    int nu;Seg;ents O ++- GLfloat angle- for (int i O +- i O height) cli"9reaLeft O !.+ * as"ect- cli"9rea1ight O .+ * as"ect-

  • 8/14/2019 2D and 3D Graphics.doc

    24/41

    cli"9rea2otto; O !.+- cli"9reaTo" O .+- @ else cli"9reaLeft O !.+- cli"9rea1ight O .+- cli"9rea2otto; O !.+ / as"ect- cli"9reaTo" O .+ / as"ect- @ glu0rtho6(cli"9reaLeft, cli"9rea1ight, cli"9rea2otto;, cli"9reaTo")- %allMin O cli"9reaLeft R %all1adius- %allMa7 O cli"9rea1ight ! %all1adius- %allMin O cli"9rea2otto; R %all1adius-

    %allMa7 O cli"9reaTo" ! %all1adius-@/* $alled %ac& when the ti;er e7"ired */oid Ti;er(int alue) glutFost1edis"la'()- // Fost a "aint reuest to actiate dis"la'() glutTi;er3unc(refreshMillis, Ti;er, +)- // su%seuent ti;er call at ;illiseconds@/* Main functionA GLUT runs as a console a""lication starting at ;ain() */int ;ain(int argc, char** arg) glut5nit(Bargc, arg)- // 5nitialiCe GLUT glut5nit6is"la'Mode(GLUT60U2L4)- // 4na%le dou%le %uffered ;ode glut5nitWindowSiCe(windowWidth, windoweight)- // 5nitial window width and height glut5nitWindowFosition(windowFos, windowFos)- // 5nitial window to"!left corner (7, ')

    glut$reateWindow(title)- // $reate window with gien title glut6is"la'3unc(dis"la')- // 1egister call%ac& handler for window re!"aint glut1esha"e3unc(resha"e)- // 1egister call%ac& handler for window re!sha"e glutTi;er3unc(+, Ti;er, +)- // 3irst ti;er call i;;ediatel' initGL()- // 0ur own 0"enGL initialiCation glutMainLoo"()- // 4nter eent!"rocessing loo" return +-@

  • 8/14/2019 2D and 3D Graphics.doc

    25/41

    int windowWidth O I:+- // Windowed ;odeEs widthint windoweight O :+- // Windowed ;odeEs heightint windowFos O ?+- // Windowed ;odeEs to"!left corner 7int windowFos O ?+- // Windowed ;odeEs to"!left corner 'GLfloat %all1adius O +.?f- // 1adius of the %ouncing %allGLfloat %all O +.+f- // 2allEs center (7, ') "ositionGLfloat %all O +.+f-GLfloat %allMa7, %allMin, %allMa7, %allMin- // 2allEs center (7, ') %oundsGLfloat 7S"eed O +.+f- // 2allEs s"eed in 7 and ' directionsGLfloat 'S"eed O +.++Hf-int refreshMillis O +- // 1efresh "eriod in ;illiseconds

    // FroPection cli""ing areaGLdou%le cli"9reaLeft, cli"9rea1ight, cli"9rea2otto;, cli"9reaTo"-

    .ool fullScreen$ode 6 true9 )) #ull,screen or windowed 5odeN/* 5nitialiCe 0"enGL Gra"hics */oid initGL() gl$lear$olor(+.+, +.+, +.+, .+)- // Set %ac&ground (clear) color to %lac&@/* $all%ac& handler for window re!"aint eent */oid dis"la'() gl$lear(GL$0L012U334125T)- // $lear the color %uffer glMatri7Mode(GLM064L=54W)- // To o"erate on the ;odel!iew ;atri7

    glLoad5dentit'()- // 1eset ;odel!iew ;atri7

    glTranslatef(%all, %all, +.+f)- // Translate to (7Fos, 'Fos) // Use triangular seg;ents to for; a circle gl2egin(GLT159KGL439K)- gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(+.+f, +.+f)- // $enter of circle int nu;Seg;ents O ++- GLfloat angle- for (int i O +- i

  • 8/14/2019 2D and 3D Graphics.doc

    26/41

    // Set the as"ect ratio of the cli""ing area to ;atch the iew"ort

    glMatri7Mode(GLF10Q4$T50K)- // To o"erate on the FroPection ;atri7 glLoad5dentit'()- // 1eset the "roPection ;atri7 if (width >O height) cli"9reaLeft O !.+ * as"ect- cli"9rea1ight O .+ * as"ect- cli"9rea2otto; O !.+- cli"9reaTo" O .+- @ else cli"9reaLeft O !.+- cli"9rea1ight O .+-

    cli"9rea2otto; O !.+ / as"ect- cli"9reaTo" O .+ / as"ect- @ glu0rtho6(cli"9reaLeft, cli"9rea1ight, cli"9rea2otto;, cli"9reaTo")- %allMin O cli"9reaLeft R %all1adius- %allMa7 O cli"9rea1ight ! %all1adius- %allMin O cli"9rea2otto; R %all1adius- %allMa7 O cli"9reaTo" ! %all1adius-@/* $alled %ac& when the ti;er e7"ired */oid Ti;er(int alue) glutFost1edis"la'()- // Fost a "aint reuest to actiate dis"la'() glutTi;er3unc(refreshMillis, Ti;er, +)- // su%seuent ti;er call at ;illiseconds@

    )* Call.ac/ handler for special,/e" event *)void specialMe"s0int /e" int x int " switch 0/e" case 1%G:;MEK;#8O )) #8O :oggle .etween full,screen and windowed 5ode fullScreen$ode 6 PfullScreen$ode9 )) :oggle state if 0fullScreen$ode )) #ull,screen 5ode windowosQ 6 glut1et01%G:;WI>!(W;Q9 )) Save para5eters for restoring later windowosK 6 glut1et01%G:;WI>!(W;K9 windowWidth 6 glut1et01%G:;WI>!(W;WI!:+9 window+eight 6 glut1et01%G:;WI>!(W;+EI1+:9 glut#ullScreen09 )) Switch into full screen A else )) Windowed 5ode glut

  • 8/14/2019 2D and 3D Graphics.doc

    27/41

    /** GL+Je'$ontrol.c""A 9 &e'!controlled %ouncing %all*/#include // for MS Windows#include // GLUT, include glu.h and gl.h#include // Keeded for sin, cos#define F5 .:?JI?f// Glo%al aria%leschar titleN O D3ull!Screen B Windowed ModeD- // Windowed ;odeEs titleint windowWidth O I:+- // Windowed ;odeEs widthint windoweight O :+- // Windowed ;odeEs height

    int windowFos O ?+- // Windowed ;odeEs to"!left corner 7int windowFos O ?+- // Windowed ;odeEs to"!left corner 'GLfloat %all1adius O +.?f- // 1adius of the %ouncing %allGLfloat %all O +.+f- // 2allEs center (7, ') "ositionGLfloat %all O +.+f-GLfloat %allMa7, %allMin, %allMa7, %allMin- // 2allEs center (7, ') %oundsGLfloat 7S"eed O +.+f- // 2allEs s"eed in 7 and ' directionsGLfloat 'S"eed O +.++Hf-int refreshMillis O +- // 1efresh "eriod in ;illiseconds// FroPection cli""ing areaGLdou%le cli"9reaLeft, cli"9rea1ight, cli"9rea2otto;, cli"9reaTo"-%ool fullScreenMode O true- // 3ull!screen or windowed ;odeV

    /* 5nitialiCe 0"enGL Gra"hics */oid initGL() gl$lear$olor(+.+, +.+, +.+, .+)- // Set %ac&ground (clear) color to %lac&@/* $all%ac& handler for window re!"aint eent */oid dis"la'() gl$lear(GL$0L012U334125T)- // $lear the color %uffer glMatri7Mode(GLM064L=54W)- // To o"erate on the ;odel!iew ;atri7 glLoad5dentit'()- // 1eset ;odel!iew ;atri7

    glTranslatef(%all, %all, +.+f)- // Translate to (7Fos, 'Fos) // Use triangular seg;ents to for; a circle gl2egin(GLT159KGL439K)-

    gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(+.+f, +.+f)- // $enter of circle int nu;Seg;ents O ++- GLfloat angle- for (int i O +- i

  • 8/14/2019 2D and 3D Graphics.doc

    28/41

    @/* $all %ac& when the windows is re!siCed */oid resha"e(GLsiCei width, GLsiCei height) // $o;"ute as"ect ratio of the new window if (height OO +) height O - // To "reent diide %' + GLfloat as"ect O (GLfloat)width / (GLfloat)height-

    // Set the iew"ort to coer the new window gl=iew"ort(+, +, width, height)-

    // Set the as"ect ratio of the cli""ing area to ;atch the iew"ort

    glMatri7Mode(GLF10Q4$T50K)- // To o"erate on the FroPection ;atri7 glLoad5dentit'()- // 1eset the "roPection ;atri7 if (width >O height) cli"9reaLeft O !.+ * as"ect- cli"9rea1ight O .+ * as"ect- cli"9rea2otto; O !.+- cli"9reaTo" O .+- @ else cli"9reaLeft O !.+- cli"9rea1ight O .+- cli"9rea2otto; O !.+ / as"ect- cli"9reaTo" O .+ / as"ect- @ glu0rtho6(cli"9reaLeft, cli"9rea1ight, cli"9rea2otto;, cli"9reaTo")- %allMin O cli"9reaLeft R %all1adius-

    %allMa7 O cli"9rea1ight ! %all1adius- %allMin O cli"9rea2otto; R %all1adius- %allMa7 O cli"9reaTo" ! %all1adius-@/* $alled %ac& when the ti;er e7"ired */oid Ti;er(int alue) glutFost1edis"la'()- // Fost a "aint reuest to actiate dis"la'() glutTi;er3unc(refreshMillis, Ti;er, +)- // su%seuent ti;er call at ;illiseconds@)* Call.ac/ handler for nor5al,/e" event *)void /e".oard0unsigned char /e" int x int " switch 0/e" case 2JO )) ESC /e" exit079 .rea/9 AA)* Call.ac/ handler for special,/e" event *)void specialMe"s0int /e" int x int " switch 0/e" case 1%G:;MEK;#8O )) #8O :oggle .etween full,screen and windowed 5ode fullScreen$ode 6 PfullScreen$ode9 )) :oggle state if 0fullScreen$ode )) #ull,screen 5ode windowosQ 6 glut1et01%G:;WI>!(W;Q9 )) Save para5eters for restoring later windowosK 6 glut1et01%G:;WI>!(W;K9 windowWidth 6 glut1et01%G:;WI>!(W;WI!:+9 window+eight 6 glut1et01%G:;WI>!(W;+EI1+:9 glut#ullScreen09 )) Switch into full screen A else )) Windowed 5ode glut

  • 8/14/2019 2D and 3D Graphics.doc

    29/41

    .all

  • 8/14/2019 2D and 3D Graphics.doc

    30/41

    int windowFos O ?+- // Windowed ;odeEs to"!left corner 'GLfloat %all1adius O +.?f- // 1adius of the %ouncing %allGLfloat %all O +.+f- // 2allEs center (7, ') "ositionGLfloat %all O +.+f-GLfloat %allMa7, %allMin, %allMa7, %allMin- // 2allEs center (7, ') %oundsGLfloat 7S"eed O +.+f- // 2allEs s"eed in 7 and ' directionsGLfloat 'S"eed O +.++Hf-int refreshMillis O +- // 1efresh "eriod in ;illiseconds// FroPection cli""ing areaGLdou%le cli"9reaLeft, cli"9rea1ight, cli"9rea2otto;, cli"9reaTo"-

    %ool fullScreenMode O true- // 3ull!screen or windowed ;odeV

    .ool paused 6 false9 )) $ove5ent paused or resu5ed1%float xSpeedSaved "SpeedSaved9 )) :o support resu5e/* 5nitialiCe 0"enGL Gra"hics */oid initGL() gl$lear$olor(+.+, +.+, +.+, .+)- // Set %ac&ground (clear) color to %lac&@/* $all%ac& handler for window re!"aint eent */oid dis"la'() gl$lear(GL$0L012U334125T)- // $lear the color %uffer glMatri7Mode(GLM064L=54W)- // To o"erate on the ;odel!iew ;atri7 glLoad5dentit'()- // 1eset ;odel!iew ;atri7

    glTranslatef(%all, %all, +.+f)- // Translate to (7Fos, 'Fos)

    // Use triangular seg;ents to for; a circle gl2egin(GLT159KGL439K)- gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(+.+f, +.+f)- // $enter of circle int nu;Seg;ents O ++- GLfloat angle- for (int i O +- i

  • 8/14/2019 2D and 3D Graphics.doc

    31/41

    // Set the as"ect ratio of the cli""ing area to ;atch the iew"ort glMatri7Mode(GLF10Q4$T50K)- // To o"erate on the FroPection ;atri7 glLoad5dentit'()- // 1eset the "roPection ;atri7 if (width >O height) cli"9reaLeft O !.+ * as"ect- cli"9rea1ight O .+ * as"ect- cli"9rea2otto; O !.+- cli"9reaTo" O .+- @ else cli"9reaLeft O !.+- cli"9rea1ight O .+- cli"9rea2otto; O !.+ / as"ect-

    cli"9reaTo" O .+ / as"ect- @ glu0rtho6(cli"9reaLeft, cli"9rea1ight, cli"9rea2otto;, cli"9reaTo")- %allMin O cli"9reaLeft R %all1adius- %allMa7 O cli"9rea1ight ! %all1adius- %allMin O cli"9rea2otto; R %all1adius- %allMa7 O cli"9reaTo" ! %all1adius-@/* $alled %ac& when the ti;er e7"ired */oid Ti;er(int alue) glutFost1edis"la'()- // Fost a "aint reuest to actiate dis"la'() glutTi;er3unc(refreshMillis, Ti;er, +)- // su%seuent ti;er call at ;illiseconds@

    /* $all%ac& handler for nor;al!&e' eent */oid &e'%oard(unsigned char &e', int 7, int ') switch (&e') case HA // 4S$ &e' e7it(+)- %rea&- @@/* $all%ac& handler for s"ecial!&e' eent */oid s"eciale's(int &e', int 7, int ') switch (&e') case GLUT43A // 3A Toggle %etween full!screen and windowed ;ode fullScreenMode O fullScreenMode- // Toggle state if (fullScreenMode) // 3ull!screen ;ode

    windowFos O glutGet(GLUTW5K60W)- // Sae "ara;eters for restoring later windowFos O glutGet(GLUTW5K60W)- windowWidth O glutGet(GLUTW5K60WW56T)- windoweight O glutGet(GLUTW5K60W45GT)- glut3ullScreen()- // Switch into full screen @ else // Windowed ;ode glut1esha"eWindow(windowWidth, windoweight)- // Switch into windowed ;ode glutFositionWindow(windowFos, windowFos)- // Fosition to"!left corner @ %rea&- case GLUT415GTA // 1ightA increase 7 s"eed 7S"eed *O .+?f- %rea&- case GLUT4L43TA // LeftA decrease 7 s"eed 7S"eed *O +.J?f- %rea&- case GLUT4UFA // U"A increase ' s"eed

    'S"eed *O .+?f- %rea&- case GLUT460WKA // 6ownA decrease ' s"eed 'S"eed *O +.J?f- %rea&- case GLUT4F9G4UFA // Fage!U"A increase %allEs radius %all1adius *O .+?f- %allMin O cli"9reaLeft R %all1adius- %allMa7 O cli"9rea1ight ! %all1adius- %allMin O cli"9rea2otto; R %all1adius- %allMa7 O cli"9reaTo" ! %all1adius- %rea&- case GLUT4F9G460WKA // Fage!6ownA decrease %allEs radius %all1adius *O +.J?f- %allMin O cli"9reaLeft R %all1adius- %allMa7 O cli"9rea1ight ! %all1adius- %allMin O cli"9rea2otto; R %all1adius-

  • 8/14/2019 2D and 3D Graphics.doc

    32/41

    %allMa7 O cli"9reaTo" ! %all1adius- %rea&- @@)* Call.ac/ handler for 5ouse event *)void 5ouse0int .utton int state int x int " if 0.utton 66 1%G:;%E#:;&G::(> TT state 66 1%G:;!(W> )) ause)resu5e paused 6 Ppaused9 )) :oggle state if 0paused xSpeedSaved 6 xSpeed9 )) Save para5eters for restore later "SpeedSaved 6 "Speed9

    xSpeed 6 79 )) Stop 5ove5ent "Speed 6 79 A else xSpeed 6 xSpeedSaved9 ))

  • 8/14/2019 2D and 3D Graphics.doc

    33/41

    glint(GLF41SF4$T5=4$0114$T50K5KT, GLK5$4ST)- // Kice "ers"ectie corrections@/* andler for window!re"aint eent. $alled %ac& when the window first a""ears and wheneer the window needs to %e re!"ainted. */oid dis"la'() gl$lear(GL$0L012U334125T GL64FT2U334125T)- // $lear color and de"th %uffers glMatri7Mode(GLM064L=54W)- // To o"erate on ;odel!iew ;atri7

    // 1ender a color!cu%e consisting of I uads with different colors glLoad5dentit'()- // 1eset the ;odel!iew ;atri7 glTranslatef(.?f, +.+f, !H.+f)- // Moe right and into the screen

    gl2egin(GL8U96S)- // 2egin drawing the color cu%e with I uads

    // To" face (' O .+f) // 6efine ertices in counter!cloc&wise ($$W) order with nor;al "ointing out gl$olorf(+.+f, .+f, +.+f)- // Green gl=erte7f( .+f, .+f, !.+f)- gl=erte7f(!.+f, .+f, !.+f)- gl=erte7f(!.+f, .+f, .+f)- gl=erte7f( .+f, .+f, .+f)-

    // 2otto; face (' O !.+f) gl$olorf(.+f, +.?f, +.+f)- // 0range gl=erte7f( .+f, !.+f, .+f)- gl=erte7f(!.+f, !.+f, .+f)- gl=erte7f(!.+f, !.+f, !.+f)-

    gl=erte7f( .+f, !.+f, !.+f)-

    // 3ront face (C O .+f) gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f( .+f, .+f, .+f)- gl=erte7f(!.+f, .+f, .+f)- gl=erte7f(!.+f, !.+f, .+f)- gl=erte7f( .+f, !.+f, .+f)-

    // 2ac& face (C O !.+f) gl$olorf(.+f, .+f, +.+f)- // ellow gl=erte7f( .+f, !.+f, !.+f)- gl=erte7f(!.+f, !.+f, !.+f)- gl=erte7f(!.+f, .+f, !.+f)- gl=erte7f( .+f, .+f, !.+f)-

    // Left face (7 O !.+f)

    gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(!.+f, .+f, .+f)- gl=erte7f(!.+f, .+f, !.+f)- gl=erte7f(!.+f, !.+f, !.+f)- gl=erte7f(!.+f, !.+f, .+f)-

    // 1ight face (7 O .+f) gl$olorf(.+f, +.+f, .+f)- // Magenta gl=erte7f(.+f, .+f, !.+f)- gl=erte7f(.+f, .+f, .+f)- gl=erte7f(.+f, !.+f, .+f)- gl=erte7f(.+f, !.+f, !.+f)- gl4nd()- // 4nd of drawing color!cu%e

    // 1ender a "'ra;id consists of : triangles

    glLoad5dentit'()- // 1eset the ;odel!iew ;atri7 glTranslatef(!.?f, +.+f, !I.+f)- // Moe left and into the screen

    gl2egin(GLT159KGL4S)- // 2egin drawing the "'ra;id with : triangles // 3ront gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f( +.+f, .+f, +.+f)- gl$olorf(+.+f, .+f, +.+f)- // Green gl=erte7f(!.+f, !.+f, .+f)- gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(.+f, !.+f, .+f)-

    // 1ight

  • 8/14/2019 2D and 3D Graphics.doc

    34/41

    gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f(+.+f, .+f, +.+f)- gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(.+f, !.+f, .+f)- gl$olorf(+.+f, .+f, +.+f)- // Green gl=erte7f(.+f, !.+f, !.+f)-

    // 2ac& gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f(+.+f, .+f, +.+f)- gl$olorf(+.+f, .+f, +.+f)- // Green gl=erte7f(.+f, !.+f, !.+f)-

    gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(!.+f, !.+f, !.+f)-

    // Left gl$olorf(.+f,+.+f,+.+f)- // 1ed gl=erte7f( +.+f, .+f, +.+f)- gl$olorf(+.+f,+.+f,.+f)- // 2lue gl=erte7f(!.+f,!.+f,!.+f)- gl$olorf(+.+f,.+f,+.+f)- // Green gl=erte7f(!.+f,!.+f, .+f)- gl4nd()- // 6one drawing the "'ra;id

    glutSwa"2uffers()- // Swa" the front and %ac& fra;e %uffers (dou%le %uffering)@

    /* andler for window re!siCe eent. $alled %ac& when the window first a""ears and wheneer the window is re!siCed with its new width and height */oid resha"e(GLsiCei width, GLsiCei height) // GLsiCei for non!negatie integer // $o;"ute as"ect ratio of the new window if (height OO +) height O - // To "reent diide %' + GLfloat as"ect O (GLfloat)width / (GLfloat)height-

    // Set the iew"ort to coer the new window gl=iew"ort(+, +, width, height)-

    // Set the as"ect ratio of the cli""ing olu;e to ;atch the iew"ort glMatri7Mode(GLF10Q4$T50K)- // To o"erate on the FroPection ;atri7 glLoad5dentit'()- // 1eset // 4na%le "ers"ectie "roPection with fo', as"ect, CKear and C3ar gluFers"ectie(:?.+f, as"ect, +.f, ++.+f)-

    @/* Main functionA GLUT runs as a console a""lication starting at ;ain() */int ;ain(int argc, char** arg) glut5nit(Bargc, arg)- // 5nitialiCe GLUT glut5nit6is"la'Mode(GLUT60U2L4)- // 4na%le dou%le %uffered ;ode glut5nitWindowSiCe(I:+, :+)- // Set the windowEs initial width B height glut5nitWindowFosition(?+, ?+)- // Fosition the windowEs initial to"!left corner glut$reateWindow(title)- // $reate window with the gien title glut6is"la'3unc(dis"la')- // 1egister call%ac& handler for window re!"aint eent glut1esha"e3unc(resha"e)- // 1egister call%ac& handler for window re!siCe eent initGL()- // 0ur own 0"enGL initialiCation glutMainLoo"()- // 4nter the infinite eent!"rocessing loo" return +-@

  • 8/14/2019 2D and 3D Graphics.doc

    35/41

    GL;T Setup 5 %ain01

    The program contains a initGL(), dis"la'()and resha"e()functions.

    The ;ain()program-

    , H>!2

    glutCreateWindowtitle!2

    Creates a window with a title, initial width and height positioned at initial top$left corner.

    3. glut)isplay9uncdisplay!2

    Registers dis"la'()as the re$paint eent handler. That is, the graphics su#$system calls #ac0

    dis"la'()when the window first appears and wheneer there is a re$paint re/uest.

    4. glutReshape9uncreshape!2

    Registers resha"e()as the re$si6ed eent handler. That is, the graphics su#$system calls #ac0

    resha"e()when the window first appears and wheneer the window is re$si6ed.

    5. glut'nit)isplay+odeGLUTI)U@LF!2

    Fna#les dou#le #uffering. 'n dis"la'(), we use glutSwa"2uffers()to signal to the G&U to

    swap the front$#uffer and #ac0$#uffer during the next B1ync Bertical 1ynchroni6ation!.

    6. initGL!2

    'no0es the initGL()once to perform all one$time initiali6ation tas0s.

    D. glut+ainLoop!2

    9inally, enters the eent$processing loop.

    One5Ti%e Initiai6atin Operatins 5 initGL01

    The initGL()function performs the one$time initiali6ation tas0s. 't is ino0ed from ;ain()once and

    only once!.

    glClearColor>.>f, >.>f, >.>f, f!2 77 1et #ac0ground color to #lac0 and opa/ueglClear)epthf!2 77 1et #ac0ground depth to farthest

    77 'n display!

  • 8/14/2019 2D and 3D Graphics.doc

    36/41

    glClearGLICLRI@U99FRI@'T J GLI)F&TEI@U99FRI@'T!2

    1et the clearing #ac0ground! color to #lac0 RA>, GA>, @A>! and opa/ue %A

    #ac0ground! depth to the farthest KA

    depth #uffer, with the clearing color and depth, #efore rendering the graphics. @esides the color #uffer

    and depth #uffer, penGL also maintains an accumulation buerand astencil buerwhich shall #e

    discussed later.!

    glFna#leGLI)F&TEITF1T!2 77 Fna#le depth testing for 6$culling

    gl)epth9uncGLILF5U%L!2 77 1et the type of depth$test

    We need to ena#le depth$test to remoe the hidden surface, and set the function used for the depth test.

    gl1hade+odelGLI1+TE!2 77 Fna#le smooth shading

    We ena#le smooth shading in color transition. The alternatie is GL3L9T. Try it out and see the

    difference.

    glEintGLI&FR1&FCT'BFICRRFCT'?IE'?T, GLI?'CF1T!2 77 ?ice perspectie corrections'n graphics rendering, there is often a trade$off #etween processing speed and isual /uality. We can use

    glint()to decide on the trade$off. 'n this case, we as0 for the #est perspectie correction, which may

    inole more processing. The default is GL60KT$914.

    De(inin) the Cr5cu+e an* P9ra%i*

    penGL:s o#ect is made up of primities such as triangle, /uad, polygon, point and line!. % primitie is

    defined ia one or more ertices. The color$cu#e is made up of = /uads. Fach /uad is made up of 4

    ertices, defined in counter$cloc0wise CCW! order, such as the normal ector is pointing out, indicating

    the front face. %ll the 4 ertices hae the same color. The color$cu#e is defined in its local space called

    model space! with origin at the center of the cu#e with sides of * units.

    1imilarly, the pyramid is made up of 4 triangles without the #ase!. Fach triangle is made up of ( ertices,

    defined in CCW order. The H ertices of the pyramid are assigned different colors. The color of the

    triangles are interpolated and #lend smoothly! from its ( ertices. %gain, the pyramid is defined in its

    local space with origin at the center of the pyramid.

    *e Trans(r%

    The o#ects are defined in their local spaces model spaces!. We need to transform them to the common

    world space, 0nown as model transorm.

  • 8/14/2019 2D and 3D Graphics.doc

    37/41

    To perform model transform, we need to operate on the so$called modelview matrixpenGL has a few

    transformation matrices!, #y setting the current matrix mode to model$iew matrix-

    gl+atrix+odeGLI+)FLB'FW!2 77 To operate on model$iew matrix

    We perform translations on cu#e and pyramid, respectiely, to position them on the world space-

    77 Color$cu#e

    glLoad'dentity!2 77 Reset model$iew matrix

    glTranslatef.>f, $D.>f!2 77 +oe right and into the screen77 &yramid

    glLoad'dentity!2

    glTranslatef$.>f, $=.>f!2 77 +oe left and into the screen

    -iew Trans(r%

    The default camera position is-

    gluLoo&9t(+.+, +.+, +.+, +.+, +.+, !++.+, +.+, .+, +.+)

    That is, 44O(+,+,+)at the origin, 9TO(+,+,!++)pointing at negatie$6 axis into the screen!, and

    UFO(+,,+)corresponds to y$axis.

    penGL graphics rendering pipeline performs so$called view transormto #ring the world spaceto

    camera:s view space. 'n the case of the default camera position, no transform is needed.

    -iewprt Trans(r%

    oid reshapeGLsi6ei width, GLsi6ei height!

    glBiewport>, >, width, height!2

    The graphics su#$system calls #ac0 resha"e()when the window first appears and wheneer the window

    is resi6ed, gien the new window:s widthand height, in pixels. We set our application iewport to coer

    the entire window, top$left corner at >, >! of widthand height, with default ;inXof > and ;a7Xof

  • 8/14/2019 2D and 3D Graphics.doc

    38/41

    is a special case of perspectie proection where the camera is placed ery far away. We shall discuss the

    orthographic proection in the later example.

    To set the proection, we need to operate on the proection matrix. Recall that we operated on the model$

    iew matrix in model transform.!

    We set the matrix mode to proection matrix and reset the matrix. We use the gluFers"ectie()to

    ena#le perspectie proection, and set the foy iew angle from the #ottom$plane to the top$plane!,

    aspect ratio width7height!, 6?ear and 69ar of the $iew %rustumtruncated pyramid!. 'n this example, we

    set the foy to 4HN. We use the same aspect ratio as the iewport to aoid distortion. We set the 6?ear to>.< and 69ar to > 6A$>!. Ta0e that note the color$cu#e , $D! and the pyramid $, $=! are

    contained within the Biew 9rustum.

    Thepro#ection transormtransforms the view rustumto a *x*x< cu#oid clippingvolumecentered on the

    near plane 6A>!. The su#se/uent viewport transormtransforms the clippingvolumeto the viewportin

    screen space. The iewport is set earlier ia the gl=iew"ort()function.

    2# E$a%pe 2! 3D Shape with Ani%atin 0OGL'2Ani%atin#cpp1

    Let:s modify the preious example to carry out animation rotating the cu#e and pyramid!.

    /** 0GL+9ni;ation.c""A 6 Sha"es with ani;ation*/#include // for MS Windows#include // GLUT, include glu.h and gl.h/* Glo%al aria%les */char titleN O D6 Sha"es with ani;ationD-1%float angle"ra5id 6 7-7f9 ))

  • 8/14/2019 2D and 3D Graphics.doc

    39/41

    gl=erte7f(!.+f, !.+f, .+f)- gl=erte7f(!.+f, !.+f, !.+f)- gl=erte7f( .+f, !.+f, !.+f)-

    // 3ront face (C O .+f) gl$olorf(.+f, +.+f, +.+f)- // 1ed gl=erte7f( .+f, .+f, .+f)- gl=erte7f(!.+f, .+f, .+f)- gl=erte7f(!.+f, !.+f, .+f)- gl=erte7f( .+f, !.+f, .+f)-

    // 2ac& face (C O !.+f)

    gl$olorf(.+f, .+f, +.+f)- // ellow gl=erte7f( .+f, !.+f, !.+f)- gl=erte7f(!.+f, !.+f, !.+f)- gl=erte7f(!.+f, .+f, !.+f)- gl=erte7f( .+f, .+f, !.+f)-

    // Left face (7 O !.+f) gl$olorf(+.+f, +.+f, .+f)- // 2lue gl=erte7f(!.+f, .+f, .+f)- gl=erte7f(!.+f, .+f, !.+f)- gl=erte7f(!.+f, !.+f, !.+f)- gl=erte7f(!.+f, !.+f, .+f)-

    // 1ight face (7 O .+f) gl$olorf(.+f, +.+f, .+f)- // Magenta

    gl=erte7f(.+f, .+f, !.+f)- gl=erte7f(.+f, .+f, .+f)- gl=erte7f(.+f, !.+f, .+f)- gl=erte7f(.+f, !.+f, !.+f)- gl4nd()- // 4nd of drawing color!cu%e

    // 1ender a "'ra;id consists of : triangles glLoad5dentit'()- // 1eset the ;odel!iew ;atri7 glTranslatef(!.?f, +.+f, !I.+f)- // Moe left and into the screen gl

  • 8/14/2019 2D and 3D Graphics.doc

    40/41

    glutSwa"2uffers()- // Swa" the front and %ac& fra;e %uffers (dou%le %uffering)

    )) Gpdate the rotational angle after each refresh [>EW] angle"ra5id L6 7-2f9 angleCu.e ,6 7-8f9@)* Called .ac/ when ti5er expired [>EW] *)void ti5er0int value glutost

  • 8/14/2019 2D and 3D Graphics.doc

    41/41

    angleCu#e $A >.