Nokia N97 SDK
Example Applications Guide

FloatingDuck.cpp

00001 /*
00002  * ==============================================================================
00003  *  Name        : FloatingDuck.cpp
00004  *  Part of     : OpenGLEx / FloatingDuck
00005  *
00006  *  Copyright (c) 2005-2006 Nokia Corporation.
00007  *  This material, including documentation and any related
00008  *  computer programs, is protected by copyright controlled by
00009  *  Nokia Corporation.
00010  * ==============================================================================
00011  */
00012 
00013 // INCLUDE FILES
00014 
00015 #include <aknnotewrappers.h>
00016 #include <e32math.h>
00017 #include "floatingduck.h"
00018 
00019 // MACROS
00020 #define FRUSTUM_LEFT   -1.f     // left vertical clipping plane
00021 #define FRUSTUM_RIGHT  +1.f     // right vertical clipping plane
00022 #define FRUSTUM_BOTTOM -1.f     // bottom horizontal clipping plane
00023 #define FRUSTUM_TOP    +1.f     // top horizontal clipping plane
00024 #define FRUSTUM_NEAR   +2.f     // near depth clipping plane
00025 #define FRUSTUM_FAR    +1000.f  // far depth clipping plane
00026 
00027 #define WATER_VERTICES      4
00028 #define RIPPLE_SEGMENTS     24
00029 
00030 // CONSTANTS
00031 /** Vertices for the water object. */
00032 static const GLfloat objVertexDataWater[]=
00033     {
00034     -10000.f, 0.f, -10000.f,
00035      10000.f, 0.f, -10000.f,
00036      10000.f, 0.f,  10000.f,
00037     -10000.f, 0.f,  10000.f
00038     };
00039 
00040 /** Indices to the water object vertices. */
00041 static const GLubyte objIndicesWater[]=
00042     {
00043     1, 0, 2, 3
00044     };
00045 
00046 /** Materials for the duck object. */
00047 static const GLfloat objDiffuseDuck[4]     = { 0.6, 0.6, 0.10, 1.0 };
00048 static const GLfloat objAmbientDuck[4]     = { 0.5, 0.4, 0.05, 1.0 };
00049 static const GLfloat objSpecularDuck[4]    = { 0.8, 0.8, 0.20, 1.0 };
00050 static const GLfloat objEmissionDuck[4]    = { 0.2, 0.2, 0.00, 1.0 };
00051 
00052 /** Materials for the underwater duck object. */
00053 static const GLfloat objDiffuseSunkenDuck[4]     = { 0.4, 0.4, 0.60, 1.0 };
00054 static const GLfloat objAmbientSunkenDuck[4]     = { 0.4, 0.3, 0.65, 1.0 };
00055 static const GLfloat objSpecularSunkenDuck[4]    = { 0.6, 0.6, 0.80, 1.0 };
00056 static const GLfloat objEmissionSunkenDuck[4]    = { 0.0, 0.0, 0.20, 1.0 };
00057 
00058 /* Global ambient light. */
00059 static const GLfloat globalAmbient[4]      = { 0.0, 0.0, 0.0, 1.0 };
00060 
00061 /* Lamp parameters. */
00062 static const GLfloat lightDiffuseLamp[4]   = { 1.0, 1.0, 0.85, 1.0 };
00063 static const GLfloat lightAmbientLamp[4]   = { 0.4, 0.4, 0.20, 1.0 };
00064 static const GLfloat lightPositionLamp[4]  = { 0.0, 50.0, 50.0, 0.0 };
00065 
00066 // ============================= LOCAL FUNCTIONS ===============================
00067 
00068 
00069 // ============================= MEMBER FUNCTIONS ===============================
00070 
00071 // -----------------------------------------------------------------------------
00072 // CFloatingDuck::NewL
00073 // Symbian 2-phase constructor. Can leave.
00074 // -----------------------------------------------------------------------------
00075 //
00076 CFloatingDuck* CFloatingDuck::NewL( GLuint aWidth, GLuint aHeight )
00077         {
00078     // Symbian 2-phase constructor. Calls both the default
00079     // C++ constructor and Symbian ConstructL methods
00080     CFloatingDuck* self = new (ELeave) CFloatingDuck( aWidth, aHeight );
00081     CleanupStack::PushL( self );
00082     self->ConstructL();
00083     CleanupStack::Pop();
00084 
00085     return self;
00086         }
00087 
00088 // -----------------------------------------------------------------------------
00089 // CFloatingDuck::~CFloatingDuck()
00090 // Destructor.
00091 // -----------------------------------------------------------------------------
00092 //
00093 CFloatingDuck::~CFloatingDuck()
00094         {
00095         }
00096 
00097 // -----------------------------------------------------------------------------
00098 // CFloatingDuck::AppInit
00099 // Application initialization code.
00100 // -----------------------------------------------------------------------------
00101 //
00102 void CFloatingDuck::AppInitL( void )
00103         {
00104     // Calculate the view frustrum based on the aspect ratio
00105     SetScreenSize( iScreenWidth, iScreenHeight );
00106 
00107     // Set the screen background color.
00108     glClearColor( 0.f, 0.f, 1.f, 1.f );
00109 
00110     // Enable required Open GL ES features
00111     glEnable( GL_DEPTH_TEST );
00112     glEnable( GL_CULL_FACE  );
00113     glEnable( GL_LIGHTING );
00114 
00115     // Make OpenGL ES automatically normalize all normals after tranformations.
00116     // This is important when making irregular transforms like scaling, or if we
00117     // have specified non-unit length normals.
00118     glEnable( GL_NORMALIZE  );
00119 
00120     // Enable vertex, normal and texture arrays
00121     glEnableClientState( GL_VERTEX_ARRAY );
00122     glEnableClientState( GL_NORMAL_ARRAY );
00123 
00124     // Do not use perspective correction
00125     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );
00126 
00127     // Set shading mode to smooth
00128     glShadeModel( GL_SMOOTH );
00129 
00130     // Set up global ambient light
00131     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, globalAmbient );
00132 
00133     // Set up light source
00134     glEnable( GL_LIGHT0 );
00135     glLightfv(  GL_LIGHT0, GL_DIFFUSE,  lightDiffuseLamp  );
00136     glLightfv(  GL_LIGHT0, GL_AMBIENT,  lightAmbientLamp  );
00137     glLightfv(  GL_LIGHT0, GL_SPECULAR, lightDiffuseLamp  );
00138     glLightfv(  GL_LIGHT0, GL_POSITION, lightPositionLamp );
00139 
00140     SetStateL( ERunning );
00141 
00142     iRippleVertices = new GLfloat[(RIPPLE_SEGMENTS * 2) * 3];
00143     iRippleIndices = new GLushort[RIPPLE_SEGMENTS * 2 + 2];
00144 
00145     // Calculate the ripple triangle strip indices now, since they won't change.
00146     // The ripples are drawn as a triangle strip, which goes around a full circle.
00147     for (GLint i = 0; i < RIPPLE_SEGMENTS * 2 + 2; i++)
00148         {
00149         iRippleIndices[i] = i % (RIPPLE_SEGMENTS * 2);
00150         }
00151 
00152     // Create the needed vertex buffers object names
00153     glGenBuffers( 1, &iVertexDataBufferId );
00154     glGenBuffers( 1, &iNormalDataBufferId );
00155     glGenBuffers( 1, &iIndexDataBufferId );
00156 
00157     // Create the vertex buffer object for duck vertices
00158     glBindBuffer( GL_ARRAY_BUFFER, iVertexDataBufferId );
00159     glBufferData( GL_ARRAY_BUFFER,
00160                           ( sizeof(GLfloat) * NUM_DUCK_VERTICES * 3 ),  // Size of the data array
00161                           objVertexdataDuck,      // Vertices
00162                           GL_STATIC_DRAW );           // Hint that the object data is static (non-changing)
00163 
00164     // Create the vertex buffer object for duck normals
00165     glBindBuffer( GL_ARRAY_BUFFER, iNormalDataBufferId );
00166     glBufferData( GL_ARRAY_BUFFER,
00167                           ( sizeof(GLbyte) * NUM_DUCK_VERTICES * 3 ),// Size of the data array
00168                           objNormaldataDuck,    // Normals
00169                           GL_STATIC_DRAW );             // Hint that the object data is static (non-changing)
00170 
00171     // Create the vertex buffer object for duck indices
00172     glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, iIndexDataBufferId );
00173     glBufferData( GL_ELEMENT_ARRAY_BUFFER,
00174                           ( sizeof(GLubyte) * NUM_DUCK_FACES * 3 ), // Size of the index array
00175                           objFacedataDuck,              // No data pointer given (creates empty buffer)
00176                           GL_STATIC_DRAW );             // Hint that the object data is static (non-changing)
00177         }
00178 
00179 // -----------------------------------------------------------------------------
00180 // CFloatingDuck::AppExit
00181 // Application cleanup code.
00182 // -----------------------------------------------------------------------------
00183 //
00184 void CFloatingDuck::AppExit( void )
00185         {
00186         glDeleteBuffers( 1, &iVertexDataBufferId );
00187         glDeleteBuffers( 1, &iNormalDataBufferId );
00188         glDeleteBuffers( 1, &iIndexDataBufferId  );
00189     delete[] iRippleVertices;
00190     delete[] iRippleIndices;
00191     }
00192 
00193 // -----------------------------------------------------------------------------
00194 // CFloatingDuck::AppCycle
00195 // Draws and animates the objects.
00196 // aFrame = Number of the frame to be rendered.
00197 // aTimeSecs = Seconds elapsed since the application started running.
00198 // aDeltaTimeSecs = Seconds elapsed since last call to AppCycle().
00199 // -----------------------------------------------------------------------------
00200 //
00201 void CFloatingDuck::AppCycle( GLuint aFrame, GLfloat aTimeSecs, GLfloat /*aDeltaTimeSecs*/ )
00202         {
00203     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
00204 
00205     // Calculate the slow up-down movement of the camera
00206     GLfloat slowTime = aTimeSecs / 5.f;
00207     GLfloat camY     = sin( slowTime ) * 50.f;
00208 
00209     // Setup the camera using the handy GLU Look At method implemented in the utils.cpp
00210         glLoadIdentity();
00211     gluLookAt(  0.f,    100.f + camY,     150.f, // Position
00212                             0.f,    0.f,       0.f,   // Look At
00213                 0.f,    1.f,       0.f ); // Up Vector
00214 
00215     // Set submerged duck material
00216     glMaterialfv(   GL_FRONT_AND_BACK, GL_AMBIENT,   objAmbientSunkenDuck  );
00217     glMaterialfv(   GL_FRONT_AND_BACK, GL_DIFFUSE,   objDiffuseSunkenDuck  );
00218     glMaterialfv(   GL_FRONT_AND_BACK, GL_SPECULAR,  objSpecularSunkenDuck );
00219     glMaterialfv(   GL_FRONT_AND_BACK, GL_EMISSION,  objEmissionSunkenDuck );
00220     glMaterialx(    GL_FRONT_AND_BACK, GL_SHININESS,     5 << 16     );
00221 
00222     // Draw duck reflection by using y-scale of -1.0
00223     DrawDuck(  aFrame, aTimeSecs, -1.0f );
00224 
00225     // Draw semitransparent water surface
00226     DrawWater( aFrame, aTimeSecs );
00227 
00228     // Draw water ripples
00229     DrawRipples( aFrame, aTimeSecs );
00230 
00231     // Set duck material
00232     glMaterialfv(   GL_FRONT_AND_BACK, GL_AMBIENT,   objAmbientDuck  );
00233     glMaterialfv(   GL_FRONT_AND_BACK, GL_DIFFUSE,   objDiffuseDuck  );
00234     glMaterialfv(   GL_FRONT_AND_BACK, GL_SPECULAR,  objSpecularDuck );
00235     glMaterialfv(   GL_FRONT_AND_BACK, GL_EMISSION,  objEmissionDuck );
00236     glMaterialx(    GL_FRONT_AND_BACK, GL_SHININESS,     5 << 16     );
00237 
00238     // Draw above the water duck by using y-scale of 1.0
00239     DrawDuck(  aFrame, aTimeSecs, 1.0f );
00240         }
00241 
00242 
00243 // -----------------------------------------------------------------------------
00244 // CFloatingDuck::DrawDuck()
00245 // Draws the duck. If yScale is 1.0 the duck is drawn, if the yScale is -1.0
00246 // the reflection of the duck is drawn.
00247 // -----------------------------------------------------------------------------
00248 //
00249 void CFloatingDuck::DrawDuck( GLuint /*aFrame*/, GLfloat aTimeSecs, GLfloat yScale )
00250     {
00251     // Store the model view matrix
00252     glPushMatrix();
00253 
00254     // Reflection and the light position must be mirrored
00255     glScalef( 1.f, yScale, 1.f );
00256     glLightfv(  GL_LIGHT0, GL_POSITION, lightPositionLamp );
00257 
00258         // Define the water clip plane that prevents the duck reflection
00259         // from being drawn above the water
00260     GLfloat coeff[4] =  { 0.f, 1.f, 0.f, 0.f };
00261     glClipPlanef( GL_CLIP_PLANE0, coeff );
00262     glEnable( GL_CLIP_PLANE0 );
00263 
00264 
00265     // Make the duck bob up and down
00266     glTranslatef( 0.f, 7.f + cos( aTimeSecs * 2.f ) * 7.f, 0.f );
00267 
00268     // Rotate the duck around the y-axis
00269     glRotatef( aTimeSecs * 3.f, 0.f, 1.f, 0.f );
00270 
00271     // Make the duck swing back and forth
00272     glRotatef( sin( aTimeSecs * 3.f) * -5.f, 0.f, 0.f, 1.f );
00273     glRotatef( cos( aTimeSecs ) * -5.f, 1.f, 0.f, 0.f );
00274 
00275     // Duck model lies on it's side, it has to be rotated to face up
00276     glRotatef( -90.f, 1.f, 0.f, 0.f );
00277 
00278         // Bind the VBOs
00279     glBindBuffer( GL_ARRAY_BUFFER, iVertexDataBufferId );
00280     glVertexPointer( 3, GL_FLOAT, 0, NULL );
00281     glBindBuffer( GL_ARRAY_BUFFER, iNormalDataBufferId );
00282     glNormalPointer( GL_BYTE,  0, NULL );
00283     glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, iIndexDataBufferId );
00284 
00285     // Draw the duck using currently bound element array buffer
00286     glDrawElements( GL_TRIANGLES, NUM_DUCK_FACES * 3, GL_UNSIGNED_BYTE, NULL );
00287 
00288         // Unbind all VBOs
00289     glBindBuffer( GL_ARRAY_BUFFER, 0 );
00290     glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
00291 
00292         // Disable the clipping plane
00293     glDisable( GL_CLIP_PLANE0 );
00294 
00295         // Restore model view matrix
00296     glPopMatrix();
00297     }
00298 
00299 // -----------------------------------------------------------------------------
00300 // CFloatingDuck::DrawWater()
00301 // Draws the water surface
00302 // -----------------------------------------------------------------------------
00303 //
00304 void CFloatingDuck::DrawWater( GLuint /*aFrame*/, GLfloat /*aTimeSecs*/ )
00305     {
00306     // Disable lighting and normals
00307     glDisable( GL_LIGHTING );
00308     glDisableClientState( GL_NORMAL_ARRAY );
00309 
00310     // Set array pointers for water model.
00311     glVertexPointer( 3, GL_FLOAT, 0, objVertexDataWater );
00312 
00313     glEnable( GL_BLEND );
00314     glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
00315     glNormal3f( 0.f, 1.f, 0.f );
00316     glColor4f(0.204, 0.796, 0.988, 0.600 );
00317     glDrawElements( GL_TRIANGLE_STRIP, WATER_VERTICES, GL_UNSIGNED_BYTE, objIndicesWater );
00318     glDisable( GL_BLEND );
00319 
00320     // Enable lighting and normal arrays
00321     glEnable( GL_LIGHTING );
00322     glEnableClientState( GL_NORMAL_ARRAY );
00323     }
00324 
00325 // -----------------------------------------------------------------------------
00326 // CFloatingDuck::DrawWater()
00327 // Draws the water surface ripples
00328 // -----------------------------------------------------------------------------
00329 //
00330 void CFloatingDuck::DrawRipples( GLuint /*aFrame*/, GLfloat aTimeSecs )
00331     {
00332     // Update the ripple vertex positions
00333     GLint i, n;
00334     GLfloat angle;
00335     const GLfloat maxRadius = 100.0;
00336 
00337     // Disable lighting and normals
00338     glDisable( GL_LIGHTING );
00339     glDisableClientState( GL_NORMAL_ARRAY );
00340 
00341     // Set array pointers for the ripple model.
00342     glVertexPointer( 3, GL_FLOAT, 0, iRippleVertices );
00343 
00344     // Speed up the animation
00345     aTimeSecs *= 3;
00346 
00347     glDisable( GL_DEPTH_TEST );
00348     glEnable( GL_BLEND );
00349     glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
00350     glNormal3f( 0.f, 1.f, 0.f );
00351 
00352     for (n = 0; n < 3; n++)
00353         {
00354         GLfloat radius = (6 * aTimeSecs + 30 * n) - maxRadius * (GLint)((6 * aTimeSecs + 30 * n) / maxRadius);
00355 
00356         for (i = 0, angle = 0; i < RIPPLE_SEGMENTS; i++, angle += 2 * PI / RIPPLE_SEGMENTS)
00357             {
00358             // inner ring
00359             iRippleVertices[(i * 2 + 0) * 3 + 0] = sin(angle) * (radius + 4 * cos(angle * 8 + aTimeSecs));
00360             iRippleVertices[(i * 2 + 0) * 3 + 1] = 0;
00361             iRippleVertices[(i * 2 + 0) * 3 + 2] = cos(angle) * (radius + 4 * cos(angle * 6 + aTimeSecs * 4));
00362             // outer ring
00363             iRippleVertices[(i * 2 + 1) * 3 + 0] = sin(angle) * (radius + 15 + 4 * sin(angle * 5 - aTimeSecs * 3));
00364             iRippleVertices[(i * 2 + 1) * 3 + 1] = 0;
00365             iRippleVertices[(i * 2 + 1) * 3 + 2] = cos(angle) * (radius + 15 + 4 * sin(angle * 7 - aTimeSecs * 2));
00366             }
00367 
00368         glColor4f(1, 1, 1, .6 * (1.0 - radius / maxRadius));
00369         glDrawElements( GL_TRIANGLE_STRIP, RIPPLE_SEGMENTS * 2 + 2, GL_UNSIGNED_SHORT, iRippleIndices );
00370         }
00371 
00372     glDisable( GL_BLEND );
00373     glEnable( GL_DEPTH_TEST );
00374 
00375     // Enable lighting and normal arrays
00376     glEnable( GL_LIGHTING );
00377     glEnableClientState( GL_NORMAL_ARRAY );
00378     }
00379 
00380 
00381 // ----------------------------------------------------------------------
00382 // CFloatingDuck::CFloatingDuck
00383 // C++ default constructor can NOT contain any code, that
00384 // might leave.
00385 // ----------------------------------------------------------------------
00386 //
00387 CFloatingDuck::CFloatingDuck( GLuint aWidth, GLuint aHeight )
00388         : CFiniteStateMachine()
00389         {
00390     iScreenWidth  = aWidth;
00391     iScreenHeight = aHeight;
00392         }
00393 
00394 // ----------------------------------------------------------------------
00395 // CFloatingDuck::ConstructL
00396 // Symbian 2nd phase constructor can leave.
00397 // ----------------------------------------------------------------------
00398 //
00399 void CFloatingDuck::ConstructL( void )
00400         {
00401         }
00402 
00403 // ---------------------------------------------------------
00404 // CFloatingDuck::OnEnterState( TInt aState )
00405 // Called by TFiniteStateMachine when the f.s.m enters a new state
00406 // ---------------------------------------------------------
00407 //
00408 void CFloatingDuck::OnEnterStateL( TInt /*aState*/ )
00409         {
00410         }
00411 
00412 // -------------------------------------------------------------------------------------------------------
00413 // CFloatingDuck::OnStartLoadingTextures()
00414 // Called for a MTextureLoadingListener by the texture manager when texture loading operation starts
00415 // -------------------------------------------------------------------------------------------------------
00416 //
00417 void CFloatingDuck::OnStartLoadingTexturesL()
00418         {
00419     SetStateL( ELoadingTextures );
00420         }
00421 
00422 // ------------------------------------------------------------------------------------------------------------
00423 // CFloatingDuck::OnEndLoadingTextures()
00424 // Called for a MTextureLoadingListener by the texture manager when texture loading operation is completed
00425 // ------------------------------------------------------------------------------------------------------------
00426 void CFloatingDuck::OnEndLoadingTexturesL()
00427         {
00428         if ( GetState() == ELoadingTextures )
00429                 {
00430         SetStateL( ERunning );
00431                 }
00432         }
00433 
00434 // -----------------------------------------------------------------------------
00435 // CFloatingDuck::SetScreenSize
00436 // Reacts to the dynamic screen size change during execution of this program.
00437 // -----------------------------------------------------------------------------
00438 //
00439 void CFloatingDuck::SetScreenSize( GLuint aWidth, GLuint aHeight )
00440     {
00441     iScreenWidth  = aWidth;
00442     iScreenHeight = aHeight;
00443 
00444     // Initialize viewport and projection.
00445     glViewport( 0, 0, iScreenWidth, iScreenHeight );
00446 
00447     // Calculate the view frustrum
00448     glMatrixMode( GL_PROJECTION );
00449     glLoadIdentity();
00450     GLfloat aspectRatio = (GLfloat)(iScreenWidth) / (GLfloat)(iScreenHeight);
00451     glFrustumf( FRUSTUM_LEFT * aspectRatio, FRUSTUM_RIGHT * aspectRatio,
00452                 FRUSTUM_BOTTOM, FRUSTUM_TOP,
00453                 FRUSTUM_NEAR, FRUSTUM_FAR );
00454 
00455         // Restore matrix mode
00456     glMatrixMode( GL_MODELVIEW );
00457     }
00458 
00459 // End of File

© Nokia 2009

Back to top