Sign in to follow this  
atifraja83

OpenGL PBO issue using SDL

Recommended Posts

Currently I am using SDL for my openGL application which using Pixel Buffer Object (PBO) to capture screen pixels, an advanced buffer technique. The issue that I am facing currently is that after binding to the pbo, the pixels read time is much more than expected approx. 11ms. But if run the same application using GLUT library instead of PBO or using some plain windows programming in which the screen built using WinMain then it gives much faster read time of approx. 0.01 ms. The only difference between all these three applications is that the windows are built using different techniques. But all other code is exactly similar. I am also pasting my code here for review for all of the three different techniques.

1. First code is using SDL (Read time is 11ms)
===========================================


/*
* SimpleSDL.cpp
* SimpleSDL
*
* Created by david on 19/06/2010.
*/

// in order to get function prototypes from glext.h, define GL_GLEXT_PROTOTYPES before including glext.h
#define GL_GLEXT_PROTOTYPES

#define SCREEN_WIDTH 256//800
#define SCREEN_HEIGHT 256//600
#define SCREEN_BPP 32

#include <iostream>
#include <vector>

#ifdef __APPLE__//Apple Headers
//#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#include "SDL.h"
#include "SDL_opengl.h"
#else//Windows and linux headers

#include "oglext\glext.h"
#include "SDL.h"
#include "SDL_opengl.h"
#include <gl\gl.h>
#include <gl\glu.h>
#include "glut.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include "Timer.h"
#include "glInfo.h" // glInfo struct

#endif

using std::stringstream;
using std::cout;
using std::endl;
using std::ends;


// VBO Extension Definitions, From glext.h
#define GL_ARRAY_BUFFER_ARB 0x8892
#define GL_STATIC_DRAW_ARB 0x88E4
typedef void (APIENTRY * PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
typedef void (APIENTRY * PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
typedef void (APIENTRY * PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
typedef void (APIENTRY * PFNGLBUFFERDATAARBPROC) (GLenum target, int size, const GLvoid *data, GLenum usage);

typedef void (APIENTRY * PFNGLBUFFERSUBDATAARBPROC) (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid const *);
typedef void (APIENTRY * PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum, GLenum, GLint *);
typedef GLvoid* (APIENTRY * PFNGLMAPBUFFERARBPROC) (GLenum, GLenum);
typedef GLboolean* (APIENTRY * PFNGLUNMAPBUFFERARBPROC) (GLenum);



//Surface for OpenGL to be drawn to
SDL_Surface *screen = NULL;

//False unti program quit by ESC or clicking top corner 'X'
bool quit;

//Keyboard and other Input Device events
SDL_Event event;


GLfloat rtri; // Angle For The Triangle ( NEW )
GLfloat rquad; // Angle For The Quad ( NEW )

// function pointers for PBO Extension
// Windows needs to get function pointers from ICD OpenGL drivers,
// because opengl32.dll does not support extensions higher than v1.1.
#ifdef _WIN32
PFNGLGENBUFFERSARBPROC pglGenBuffersARB = 0; // VBO Name Generation Procedure
PFNGLBINDBUFFERARBPROC pglBindBufferARB = 0; // VBO Bind Procedure
PFNGLBUFFERDATAARBPROC pglBufferDataARB = 0; // VBO Data Loading Procedure
PFNGLBUFFERSUBDATAARBPROC pglBufferSubDataARB = 0; // VBO Sub Data Loading Procedure
PFNGLDELETEBUFFERSARBPROC pglDeleteBuffersARB = 0; // VBO Deletion Procedure
PFNGLGETBUFFERPARAMETERIVARBPROC pglGetBufferParameterivARB = 0; // return various parameters of VBO
PFNGLMAPBUFFERARBPROC pglMapBufferARB = 0; // map VBO procedure
PFNGLUNMAPBUFFERARBPROC pglUnmapBufferARB = 0; // unmap VBO procedure
#define glGenBuffersARB pglGenBuffersARB
#define glBindBufferARB pglBindBufferARB
#define glBufferDataARB pglBufferDataARB
#define glBufferSubDataARB pglBufferSubDataARB
#define glDeleteBuffersARB pglDeleteBuffersARB
#define glGetBufferParameterivARB pglGetBufferParameterivARB
#define glMapBufferARB pglMapBufferARB
#define glUnmapBufferARB pglUnmapBufferARB
#endif

// constants
//const int SCREEN_WIDTH = 256;
//const int SCREEN_HEIGHT = 256;
const int CHANNEL_COUNT = 4;
const int DATA_SIZE = SCREEN_WIDTH * SCREEN_HEIGHT * CHANNEL_COUNT;
const GLenum PIXEL_FORMAT = GL_BGRA;
const int PBO_COUNT = 2;

// global variables
void *font = GLUT_BITMAP_8_BY_13;
bool pboSupported;
GLubyte* colorBuffer = 0;
bool pboUsed;
GLuint pboIds[PBO_COUNT]; // IDs of PBOs

float cameraAngleX;
float cameraAngleY;
float cameraDistance;

Timer timer, t1;
float readTime, processTime;



//Methods In Program
bool init();
void init_GL();
bool init_SDL();
void clean_up();
void display();
void draw();
void handle_input();


///////////////////////////////////////////////////////////////////////////////
// change the brightness
///////////////////////////////////////////////////////////////////////////////
void add(unsigned char* src, int width, int height, int shift, unsigned char* dst)
{
if(!src || !dst)
return;

int value;
for(int i = 0; i < height; ++i)
{
for(int j = 0; j < width; ++j)
{
value = *src + shift;
if(value > 255) *dst = (unsigned char)255;
else *dst = (unsigned char)value;
++src;
++dst;

value = *src + shift;
if(value > 255) *dst = (unsigned char)255;
else *dst = (unsigned char)value;
++src;
++dst;

value = *src + shift;
if(value > 255) *dst = (unsigned char)255;
else *dst = (unsigned char)value;
++src;
++dst;

++src; // skip alpha
++dst;
}
}
}



void toOrtho()
{
// set viewport to be the entire window
glViewport((GLsizei)SCREEN_WIDTH, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT);

// set orthographic viewing frustum
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT, -1, 1);

// switch to modelview matrix in order to set scene
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 0, 0, 0, -1, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)
}



void toPerspective()
{
// set viewport to be the entire window
glViewport(0, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT);

// set perspective viewing frustum
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f, (float)(SCREEN_WIDTH)/SCREEN_HEIGHT, 1.0f, 1000.0f); // FOV, AspectRatio, NearClip, FarClip

// switch to modelview matrix in order to set scene
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 8, 0, 0, 0, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)

}

///////////////////////////////////////////////////////////////////////////////
// write 2d text using GLUT
// The projection matrix must be set to orthogonal before call this function.
///////////////////////////////////////////////////////////////////////////////
void drawString(const char *str, int x, int y, float color[4], void *font)
{
glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask
glDisable(GL_LIGHTING); // need to disable lighting for proper text color
glDisable(GL_TEXTURE_2D);

glColor4fv(color); // set text color
glRasterPos2i(x, y); // place text position

// loop all characters in the string
while(*str)
{
glutBitmapCharacter(font, *str);
++str;
}

glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glPopAttrib();
}

///////////////////////////////////////////////////////////////////////////////
// display info messages
///////////////////////////////////////////////////////////////////////////////
void showInfo()
{
// backup current model-view matrix
glPushMatrix(); // save current modelview matrix
glLoadIdentity(); // reset modelview matrix

// set to 2D orthogonal projection
glMatrixMode(GL_PROJECTION); // switch to projection matrix
glPushMatrix(); // save current projection matrix
glLoadIdentity(); // reset projection matrix
gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection

const int FONT_HEIGHT = 14;
float color[4] = {1, 1, 1, 1};

stringstream ss;
ss << "PBO: ";
if(pboUsed)
ss << "on" << ends;
else
ss << "off" << ends;

drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-FONT_HEIGHT, color, font);
ss.str(""); // clear buffer

ss << "Read Time: " << readTime << " ms" << ends;
drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(2*FONT_HEIGHT), color, font);
ss.str("");

ss << std::fixed << std::setprecision(3);
ss << "Process Time: " << processTime << " ms" << ends;
drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(3*FONT_HEIGHT), color, font);
ss.str("");

ss << "Press SPACE to toggle PBO." << ends;
drawString(ss.str().c_str(), 1, 1, color, font);

// unset floating format
ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield);

// restore projection matrix
glPopMatrix(); // restore to previous projection matrix

// restore modelview matrix
glMatrixMode(GL_MODELVIEW); // switch to modelview matrix
glPopMatrix(); // restore to previous modelview matrix
}



///////////////////////////////////////////////////////////////////////////////
// display transfer rates
///////////////////////////////////////////////////////////////////////////////
void showTransferRate()
{
static Timer timer;
static int count = 0;
static stringstream ss;
double elapsedTime;

// backup current model-view matrix
glPushMatrix(); // save current modelview matrix
glLoadIdentity(); // reset modelview matrix

// set to 2D orthogonal projection
glMatrixMode(GL_PROJECTION); // switch to projection matrix
glPushMatrix(); // save current projection matrix
glLoadIdentity(); // reset projection matrix
gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection

float color[4] = {1, 1, 0, 1};

// update fps every second
elapsedTime = timer.getElapsedTime();
if(elapsedTime < 1.0)
{
++count;
}
else
{
ss.str("");
ss << std::fixed << std::setprecision(1);
ss << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) / (1024 * 1024) << " Mp" << ends; // update fps string
ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield);
count = 0; // reset counter
timer.start(); // restart timer
}
drawString(ss.str().c_str(), 200, 286, color, font);

// restore projection matrix
glPopMatrix(); // restore to previous projection matrix

// restore modelview matrix
glMatrixMode(GL_MODELVIEW); // switch to modelview matrix
glPopMatrix(); // restore to previous modelview matrix
}

///////////////////////////////////////////////////////////////////////////////
// print transfer rates
///////////////////////////////////////////////////////////////////////////////
void printTransferRate()
{
const double INV_MEGA = 1.0 / (1024 * 1024);
static Timer timer;
static int count = 0;
static stringstream ss;
double elapsedTime;

// loop until 1 sec passed
elapsedTime = timer.getElapsedTime();
if(elapsedTime < 1.0)
{
++count;
}
else
{
cout << std::fixed << std::setprecision(1);
cout << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) * INV_MEGA << " Mpixels/s. (" << count / elapsedTime << " FPS)\n";
cout << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield);
count = 0; // reset counter
timer.start(); // restart timer
}
}

int DrawLesson5Scene(GLvoid) // Here's Where We Do All The Drawing
{
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
//glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(-1.5f,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
glRotatef(rtri,0.0f,1.0f,0.0f); // Rotate The Triangle On The Y axis ( NEW )
glBegin(GL_TRIANGLES); // Start Drawing A Triangle
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Front)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Left Of Triangle (Front)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Right Of Triangle (Front)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Right)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Left Of Triangle (Right)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Right Of Triangle (Right)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Back)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Left Of Triangle (Back)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f, -1.0f); // Right Of Triangle (Back)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Left)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f,-1.0f); // Left Of Triangle (Left)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Right Of Triangle (Left)
glEnd(); // Done Drawing The Pyramid

glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(1.5f,0.0f,-7.0f); // Move Right 1.5 Units And Into The Screen 7.0
glRotatef(rquad,1.0f,1.0f,1.0f); // Rotate The Quad On The X axis ( NEW )
glBegin(GL_QUADS); // Draw A Quad
glColor3f(0.0f,1.0f,0.0f); // Set The Color To Blue
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Top)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Top)
glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Quad (Top)
glVertex3f( 1.0f, 1.0f, 1.0f); // Bottom Right Of The Quad (Top)
glColor3f(1.0f,0.5f,0.0f); // Set The Color To Orange
glVertex3f( 1.0f,-1.0f, 1.0f); // Top Right Of The Quad (Bottom)
glVertex3f(-1.0f,-1.0f, 1.0f); // Top Left Of The Quad (Bottom)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Bottom)
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Bottom)
glColor3f(1.0f,0.0f,0.0f); // Set The Color To Red
glVertex3f( 1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Front)
glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Front)
glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Front)
glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Front)
glColor3f(1.0f,1.0f,0.0f); // Set The Color To Yellow
glVertex3f( 1.0f,-1.0f,-1.0f); // Top Right Of The Quad (Back)
glVertex3f(-1.0f,-1.0f,-1.0f); // Top Left Of The Quad (Back)
glVertex3f(-1.0f, 1.0f,-1.0f); // Bottom Left Of The Quad (Back)
glVertex3f( 1.0f, 1.0f,-1.0f); // Bottom Right Of The Quad (Back)
glColor3f(0.0f,0.0f,1.0f); // Set The Color To Blue
glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Left)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Left)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Left)
glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Left)
glColor3f(1.0f,0.0f,1.0f); // Set The Color To Violet
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Right)
glVertex3f( 1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Right)
glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Right)
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Right)
glEnd(); // Done Drawing The Quad

rtri+=0.2f; // Increase The Rotation Variable For The Triangle ( NEW )
rquad-=0.15f; // Decrease The Rotation Variable For The Quad ( NEW )
return TRUE; // Keep Going
}
int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing
{
static int shift = 0;
static int index = 0;
int nextIndex = 0; // pbo index used for next frame

// brightness shift amount
shift = ++shift % 200;

// increment current index first then get the next index
// "index" is used to read pixels from a framebuffer to a PBO
// "nextIndex" is used to process pixels in the other PBO
index = (index + 1) % 2;
nextIndex = (index + 1) % 2;

// set the framebuffer to read
glReadBuffer(GL_FRONT);
GLuint* srcTex;
if(pboUsed) // with PBO
{
// read framebuffer ///////////////////////////////

timer.start();

// copy pixels from framebuffer to PBO
// Use offset instead of ponter.
// OpenGL should perform asynch DMA transfer, so glReadPixels() will return immediately.
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[index]);
glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, 0);

// measure the time reading framebuffer
timer.stop();
readTime = timer.getElapsedTimeInMilliSec();
///////////////////////////////////////////////////


// process pixel data /////////////////////////////
// map the PBO that contain framebuffer pixels before processing it
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[nextIndex]);
GLubyte* src = (GLubyte*) glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB);
if(src)
{
// change brightness
add(src, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer);
glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB); // release pointer to the mapped buffer
}

glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
}
else // without PBO
{
// read framebuffer ///////////////////////////////
timer.start();

// read framebuffer ///////////////////////////////
glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer);

// measure the time reading framebuffer
timer.stop();
readTime = timer.getElapsedTimeInMilliSec();
///////////////////////////////////////////////////

// change brightness
add(colorBuffer, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer);
}


// render to the framebuffer //////////////////////////
glDrawBuffer(GL_BACK);
toPerspective(); // set to perspective on the left side of the window

// clear buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

////// tramsform camera
//glTranslatef(0, 0, cameraDistance);
//glRotatef(cameraAngleX, 1, 0, 0); // pitch
//glRotatef(cameraAngleY, 0, 1, 0); // heading

//// draw a cube
//draw();
DrawLesson5Scene();

// draw the read color buffer to the right side of the window
toOrtho(); // set to orthographic on the right side of the window
glRasterPos2i(0, 0);
glDrawPixels(SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer);


showInfo();
printTransferRate();
//glutSwapBuffers();
return TRUE; // Keep Going
}

/*--------------------------------------------------
* Setup SDL
*--------------------------------------------------*/
bool init_SDL()
{
//Init all SDL Parts
if(SDL_Init(SDL_INIT_EVERYTHING) == -1)
{
return false;
}

//screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL | SDL_DOUBLEBUF | SDL_FULLSCREEN ); //FULLSCREEN
screen = SDL_SetVideoMode( SCREEN_WIDTH*2, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL | SDL_DOUBLEBUF);
SDL_WM_SetCaption("Simple SDL Demo", NULL);


return true;
}

/*--------------------------------------------------
* Init OpenGL
*--------------------------------------------------*/
void init_GL()
{
// get OpenGL info
glInfo glInfo;
glInfo.getInfo();
glInfo.printSelf();

#ifdef _WIN32
// check PBO is supported by your video card
if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object"))
{
// get pointers to GL functions
glGenBuffersARB = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB");
glBindBufferARB = (PFNGLBINDBUFFERARBPROC)wglGetProcAddress("glBindBufferARB");
glBufferDataARB = (PFNGLBUFFERDATAARBPROC)wglGetProcAddress("glBufferDataARB");
glBufferSubDataARB = (PFNGLBUFFERSUBDATAARBPROC)wglGetProcAddress("glBufferSubDataARB");
glDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)wglGetProcAddress("glDeleteBuffersARB");
glGetBufferParameterivARB = (PFNGLGETBUFFERPARAMETERIVARBPROC)wglGetProcAddress("glGetBufferParameterivARB");
glMapBufferARB = (PFNGLMAPBUFFERARBPROC)wglGetProcAddress("glMapBufferARB");
glUnmapBufferARB = (PFNGLUNMAPBUFFERARBPROC)wglGetProcAddress("glUnmapBufferARB");

// check once again PBO extension
if(glGenBuffersARB && glBindBufferARB && glBufferDataARB && glBufferSubDataARB &&
glMapBufferARB && glUnmapBufferARB && glDeleteBuffersARB && glGetBufferParameterivARB)
{
pboSupported = pboUsed = true;
//cout << "Video card supports GL_ARB_pixel_buffer_object." << endl;
}
else
{
pboSupported = pboUsed = false;
// cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl;
}
}

#else // for linux, do not need to get function pointers, it is up-to-date
if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object"))
{
pboSupported = pboUsed = true;
cout << "Video card supports GL_ARB_pixel_buffer_object." << endl;
}
else
{
pboSupported = pboUsed = false;
cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl;
}
#endif

if(pboSupported)
{
// create 2 pixel buffer objects, you need to delete them when program exits.
// glBufferDataARB with NULL pointer reserves only memory space.
glGenBuffersARB(PBO_COUNT, pboIds);
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[0]);
glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB);
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[1]);
glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB);

glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
}


glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations

//glClearColor(0.8, 0.7, 0.9, 1.0);
glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}


/*--------------------------------------------------
* Init Everything
*--------------------------------------------------*/
bool init()
{
// allocate buffers to store frames
colorBuffer = new GLubyte[DATA_SIZE];
memset(colorBuffer, 255, DATA_SIZE);

if(init_SDL() == false)
{
std::cout << "Setting Up SDL Failed - Now Exiting or Crashing" << std::endl;
return false;
}
else
std::cout<< "SDL Initialized " << std::endl;

init_GL();
std::cout << "OpenGL Initialized" << std::endl;

quit = false;

return true;
}


/*-----------------------------------------------------------------
* Clean Up RAM Before Quitting
*----------------------------------------------------------------- */
void clean_up()
{
// deallocate frame buffer
delete [] colorBuffer;
colorBuffer = 0;

// clean up PBOs
if(pboSupported)
{
glDeleteBuffersARB(PBO_COUNT, pboIds);
}

//Close All SDL Subsystems
SDL_Quit();
}

/*--------------------------------------------------
* Draw Scene Code
*--------------------------------------------------*/
void draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(43.0, SCREEN_WIDTH/SCREEN_HEIGHT, 1, 50);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

//DRAW CODE HERE

SDL_GL_SwapBuffers();
}

/*--------------------------------------------------
* Handle input Code
*--------------------------------------------------*/
void handle_input()
{
if(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
//ESCAPE
case SDLK_ESCAPE:
quit = true;
break;
//SPACE
default:
break;
}
break;
//EXIT SYSTEM
case SDL_QUIT:
quit = true;
break;
}
}
}


/*-----------------------------------------------------------------
* Main Method
*----------------------------------------------------------------- */
int main(int argc, char *args[])
{
if(init() == false)
{
std::cout << "Problem Initialising" << std::endl;
return 1;
}


do{
//GAME MAIN LOOP GOES HERE
handle_input();
//draw();
DrawGLScene();
SDL_GL_SwapBuffers();

}while(!quit);

clean_up();
return 0;


}

================================================================================================================================================================


2. Second technique is using GLUT Library (Read time: 0.01ms approx.)
===================================================================

///////////////////////////////////////////////////////////////////////////////
// main.cpp
// ========
// testing Pixel Buffer Object for packing (read-back) pixel data from
// framebuffer to a PBO using GL_ARB_pixel_buffer_object extension
//
// AUTHOR: Song Ho Ahn (song.ahn@gmail.com)
// CREATED: 2007-11-30
// UPDATED: 2008-06-12
///////////////////////////////////////////////////////////////////////////////

// in order to get function prototypes from glext.h, define GL_GLEXT_PROTOTYPES before including glext.h
#define GL_GLEXT_PROTOTYPES

#include <cstdlib>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include "glut.h"
#endif

#include "glext.h"
#include <iostream>
#include <sstream>
#include <iomanip>

#include "glInfo.h" // glInfo struct
#include "Timer.h"

using std::stringstream;
using std::cout;
using std::endl;
using std::ends;


// GLUT CALLBACK functions
void displayCB();
void reshapeCB(int w, int h);
void timerCB(int millisec);
void idleCB();
void keyboardCB(unsigned char key, int x, int y);
void mouseCB(int button, int stat, int x, int y);
void mouseMotionCB(int x, int y);

void initGL();
int initGLUT(int argc, char **argv);
bool initSharedMem();
void clearSharedMem();
void initLights();
void setCamera(float posX, float posY, float posZ, float targetX, float targetY, float targetZ);
void drawString(const char *str, int x, int y, float color[4], void *font);
void drawString3D(const char *str, float pos[3], float color[4], void *font);
void showInfo();
void showTransferRate();
void printTransferRate();
void draw();
void add(unsigned char* src, int width, int height, int shift, unsigned char* dst);
void toOrtho();
void toPerspective();


// constants
const int SCREEN_WIDTH = 256;
const int SCREEN_HEIGHT = 256;
const int CHANNEL_COUNT = 4;
const int DATA_SIZE = SCREEN_WIDTH * SCREEN_HEIGHT * CHANNEL_COUNT;
const GLenum PIXEL_FORMAT = GL_BGRA;
const int PBO_COUNT = 2;

// global variables
void *font = GLUT_BITMAP_8_BY_13;
GLuint pboIds[PBO_COUNT]; // IDs of PBOs
bool mouseLeftDown;
bool mouseRightDown;
float mouseX, mouseY;
float cameraAngleX;
float cameraAngleY;
float cameraDistance;
bool pboSupported;
bool pboUsed;
int drawMode = 0;
Timer timer, t1;
float readTime, processTime;
GLubyte* colorBuffer = 0;


// function pointers for PBO Extension
// Windows needs to get function pointers from ICD OpenGL drivers,
// because opengl32.dll does not support extensions higher than v1.1.
#ifdef _WIN32
PFNGLGENBUFFERSARBPROC pglGenBuffersARB = 0; // VBO Name Generation Procedure
PFNGLBINDBUFFERARBPROC pglBindBufferARB = 0; // VBO Bind Procedure
PFNGLBUFFERDATAARBPROC pglBufferDataARB = 0; // VBO Data Loading Procedure
PFNGLBUFFERSUBDATAARBPROC pglBufferSubDataARB = 0; // VBO Sub Data Loading Procedure
PFNGLDELETEBUFFERSARBPROC pglDeleteBuffersARB = 0; // VBO Deletion Procedure
PFNGLGETBUFFERPARAMETERIVARBPROC pglGetBufferParameterivARB = 0; // return various parameters of VBO
PFNGLMAPBUFFERARBPROC pglMapBufferARB = 0; // map VBO procedure
PFNGLUNMAPBUFFERARBPROC pglUnmapBufferARB = 0; // unmap VBO procedure
#define glGenBuffersARB pglGenBuffersARB
#define glBindBufferARB pglBindBufferARB
#define glBufferDataARB pglBufferDataARB
#define glBufferSubDataARB pglBufferSubDataARB
#define glDeleteBuffersARB pglDeleteBuffersARB
#define glGetBufferParameterivARB pglGetBufferParameterivARB
#define glMapBufferARB pglMapBufferARB
#define glUnmapBufferARB pglUnmapBufferARB
#endif


///////////////////////////////////////////////////////////////////////////////
// draw a cube with immediate mode
// 54 calls = 24 glVertex*() calls + 24 glColor*() calls + 6 glNormal*() calls
///////////////////////////////////////////////////////////////////////////////
void draw()
{
glBegin(GL_QUADS);
// face v0-v1-v2-v3
glNormal3f(0,0,1);
glColor3f(1,1,1);
glVertex3f(1,1,1);
glColor3f(1,1,0);
glVertex3f(-1,1,1);
glColor3f(1,0,0);
glVertex3f(-1,-1,1);
glColor3f(1,0,1);
glVertex3f(1,-1,1);

// face v0-v3-v4-v6
glNormal3f(1,0,0);
glColor3f(1,1,1);
glVertex3f(1,1,1);
glColor3f(1,0,1);
glVertex3f(1,-1,1);
glColor3f(0,0,1);
glVertex3f(1,-1,-1);
glColor3f(0,1,1);
glVertex3f(1,1,-1);

// face v0-v5-v6-v1
glNormal3f(0,1,0);
glColor3f(1,1,1);
glVertex3f(1,1,1);
glColor3f(0,1,1);
glVertex3f(1,1,-1);
glColor3f(0,1,0);
glVertex3f(-1,1,-1);
glColor3f(1,1,0);
glVertex3f(-1,1,1);

// face v1-v6-v7-v2
glNormal3f(-1,0,0);
glColor3f(1,1,0);
glVertex3f(-1,1,1);
glColor3f(0,1,0);
glVertex3f(-1,1,-1);
glColor3f(0,0,0);
glVertex3f(-1,-1,-1);
glColor3f(1,0,0);
glVertex3f(-1,-1,1);

// face v7-v4-v3-v2
glNormal3f(0,-1,0);
glColor3f(0,0,0);
glVertex3f(-1,-1,-1);
glColor3f(0,0,1);
glVertex3f(1,-1,-1);
glColor3f(1,0,1);
glVertex3f(1,-1,1);
glColor3f(1,0,0);
glVertex3f(-1,-1,1);

// face v4-v7-v6-v5
glNormal3f(0,0,-1);
glColor3f(0,0,1);
glVertex3f(1,-1,-1);
glColor3f(0,0,0);
glVertex3f(-1,-1,-1);
glColor3f(0,1,0);
glVertex3f(-1,1,-1);
glColor3f(0,1,1);
glVertex3f(1,1,-1);
glEnd();
}



///////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
initSharedMem();

// init GLUT and GL
initGLUT(argc, argv);
initGL();

// get OpenGL info
glInfo glInfo;
glInfo.getInfo();
glInfo.printSelf();

#ifdef _WIN32
// check PBO is supported by your video card
if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object"))
{
// get pointers to GL functions
glGenBuffersARB = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB");
glBindBufferARB = (PFNGLBINDBUFFERARBPROC)wglGetProcAddress("glBindBufferARB");
glBufferDataARB = (PFNGLBUFFERDATAARBPROC)wglGetProcAddress("glBufferDataARB");
glBufferSubDataARB = (PFNGLBUFFERSUBDATAARBPROC)wglGetProcAddress("glBufferSubDataARB");
glDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)wglGetProcAddress("glDeleteBuffersARB");
glGetBufferParameterivARB = (PFNGLGETBUFFERPARAMETERIVARBPROC)wglGetProcAddress("glGetBufferParameterivARB");
glMapBufferARB = (PFNGLMAPBUFFERARBPROC)wglGetProcAddress("glMapBufferARB");
glUnmapBufferARB = (PFNGLUNMAPBUFFERARBPROC)wglGetProcAddress("glUnmapBufferARB");

// check once again PBO extension
if(glGenBuffersARB && glBindBufferARB && glBufferDataARB && glBufferSubDataARB &&
glMapBufferARB && glUnmapBufferARB && glDeleteBuffersARB && glGetBufferParameterivARB)
{
pboSupported = pboUsed = true;
cout << "Video card supports GL_ARB_pixel_buffer_object." << endl;
}
else
{
pboSupported = pboUsed = false;
cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl;
}
}

#else // for linux, do not need to get function pointers, it is up-to-date
if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object"))
{
pboSupported = pboUsed = true;
cout << "Video card supports GL_ARB_pixel_buffer_object." << endl;
}
else
{
pboSupported = pboUsed = false;
cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl;
}
#endif

if(pboSupported)
{
// create 2 pixel buffer objects, you need to delete them when program exits.
// glBufferDataARB with NULL pointer reserves only memory space.
glGenBuffersARB(PBO_COUNT, pboIds);
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[0]);
glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB);
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[1]);
glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB);

glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
}

// start timer, the elapsed time will be used for updateVertices()
timer.start();

// the last GLUT call (LOOP)
// window will be shown and display callback is triggered by events
// NOTE: this call never return main().
glutMainLoop(); /* Start GLUT event-processing loop */

return 0;
}


///////////////////////////////////////////////////////////////////////////////
// initialize GLUT for windowing
///////////////////////////////////////////////////////////////////////////////
int initGLUT(int argc, char **argv)
{
// GLUT stuff for windowing
// initialization openGL window.
// it is called before any other GLUT routine
glutInit(&argc, argv);

glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_ALPHA); // display mode

glutInitWindowSize(SCREEN_WIDTH*2, SCREEN_HEIGHT); // window size

glutInitWindowPosition(100, 100); // window location

// finally, create a window with openGL context
// Window will not displayed until glutMainLoop() is called
// it returns a unique ID
int handle = glutCreateWindow(argv[0]); // param is the title of window

// register GLUT callback functions
glutDisplayFunc(displayCB);
//glutTimerFunc(33, timerCB, 33); // redraw only every given millisec
glutIdleFunc(idleCB); // redraw only every given millisec
glutReshapeFunc(reshapeCB);
glutKeyboardFunc(keyboardCB);
glutMouseFunc(mouseCB);
glutMotionFunc(mouseMotionCB);

return handle;
}



///////////////////////////////////////////////////////////////////////////////
// initialize OpenGL
// disable unused features
///////////////////////////////////////////////////////////////////////////////
void initGL()
{
glShadeModel(GL_SMOOTH); // shading mathod: GL_SMOOTH or GL_FLAT
glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // 4-byte pixel alignment

// enable /disable features
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
//glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
//glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
glEnable(GL_CULL_FACE);

// track material ambient and diffuse from surface color, call it before glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);

glClearColor(0, 0, 0, 0); // background color
glClearStencil(0); // clear stencil buffer
glClearDepth(1.0f); // 0 is near, 1 is far
glDepthFunc(GL_LEQUAL);

initLights();
//setCamera(0, 0, 8, 0, 0, 0);
}



///////////////////////////////////////////////////////////////////////////////
// write 2d text using GLUT
// The projection matrix must be set to orthogonal before call this function.
///////////////////////////////////////////////////////////////////////////////
void drawString(const char *str, int x, int y, float color[4], void *font)
{
glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask
glDisable(GL_LIGHTING); // need to disable lighting for proper text color
glDisable(GL_TEXTURE_2D);

glColor4fv(color); // set text color
glRasterPos2i(x, y); // place text position

// loop all characters in the string
while(*str)
{
glutBitmapCharacter(font, *str);
++str;
}

glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glPopAttrib();
}



///////////////////////////////////////////////////////////////////////////////
// draw a string in 3D space
///////////////////////////////////////////////////////////////////////////////
void drawString3D(const char *str, float pos[3], float color[4], void *font)
{
glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask
glDisable(GL_LIGHTING); // need to disable lighting for proper text color

glColor4fv(color); // set text color
glRasterPos3fv(pos); // place text position

// loop all characters in the string
while(*str)
{
glutBitmapCharacter(font, *str);
++str;
}

glEnable(GL_LIGHTING);
glPopAttrib();
}



///////////////////////////////////////////////////////////////////////////////
// initialize global variables
///////////////////////////////////////////////////////////////////////////////
bool initSharedMem()
{
mouseLeftDown = mouseRightDown = false;

// allocate buffers to store frames
colorBuffer = new GLubyte[DATA_SIZE];
memset(colorBuffer, 255, DATA_SIZE);

return true;
}



///////////////////////////////////////////////////////////////////////////////
// clean up shared memory
///////////////////////////////////////////////////////////////////////////////
void clearSharedMem()
{
// deallocate frame buffer
delete [] colorBuffer;
colorBuffer = 0;

// clean up PBOs
if(pboSupported)
{
glDeleteBuffersARB(PBO_COUNT, pboIds);
}
}



///////////////////////////////////////////////////////////////////////////////
// initialize lights
///////////////////////////////////////////////////////////////////////////////
void initLights()
{
// set up light colors (ambient, diffuse, specular)
GLfloat lightKa[] = {.2f, .2f, .2f, 1.0f}; // ambient light
GLfloat lightKd[] = {.7f, .7f, .7f, 1.0f}; // diffuse light
GLfloat lightKs[] = {1, 1, 1, 1}; // specular light
glLightfv(GL_LIGHT0, GL_AMBIENT, lightKa);
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightKd);
glLightfv(GL_LIGHT0, GL_SPECULAR, lightKs);

// position the light
float lightPos[4] = {0, 0, 20, 1}; // positional light
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);

glEnable(GL_LIGHT0); // MUST enable each light source after configuration
}



///////////////////////////////////////////////////////////////////////////////
// set camera position and lookat direction
///////////////////////////////////////////////////////////////////////////////
void setCamera(float posX, float posY, float posZ, float targetX, float targetY, float targetZ)
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(posX, posY, posZ, targetX, targetY, targetZ, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)
}



///////////////////////////////////////////////////////////////////////////////
// display info messages
///////////////////////////////////////////////////////////////////////////////
void showInfo()
{
// backup current model-view matrix
glPushMatrix(); // save current modelview matrix
glLoadIdentity(); // reset modelview matrix

// set to 2D orthogonal projection
glMatrixMode(GL_PROJECTION); // switch to projection matrix
glPushMatrix(); // save current projection matrix
glLoadIdentity(); // reset projection matrix
gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection

const int FONT_HEIGHT = 14;
float color[4] = {1, 1, 1, 1};

stringstream ss;
ss << "PBO: ";
if(pboUsed)
ss << "on" << ends;
else
ss << "off" << ends;

drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-FONT_HEIGHT, color, font);
ss.str(""); // clear buffer

ss << "Read Time: " << readTime << " ms" << ends;
drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(2*FONT_HEIGHT), color, font);
ss.str("");

ss << std::fixed << std::setprecision(3);
ss << "Process Time: " << processTime << " ms" << ends;
drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(3*FONT_HEIGHT), color, font);
ss.str("");

ss << "Press SPACE to toggle PBO." << ends;
drawString(ss.str().c_str(), 1, 1, color, font);

// unset floating format
ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield);

// restore projection matrix
glPopMatrix(); // restore to previous projection matrix

// restore modelview matrix
glMatrixMode(GL_MODELVIEW); // switch to modelview matrix
glPopMatrix(); // restore to previous modelview matrix
}



///////////////////////////////////////////////////////////////////////////////
// display transfer rates
///////////////////////////////////////////////////////////////////////////////
void showTransferRate()
{
static Timer timer;
static int count = 0;
static stringstream ss;
double elapsedTime;

// backup current model-view matrix
glPushMatrix(); // save current modelview matrix
glLoadIdentity(); // reset modelview matrix

// set to 2D orthogonal projection
glMatrixMode(GL_PROJECTION); // switch to projection matrix
glPushMatrix(); // save current projection matrix
glLoadIdentity(); // reset projection matrix
gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection

float color[4] = {1, 1, 0, 1};

// update fps every second
elapsedTime = timer.getElapsedTime();
if(elapsedTime < 1.0)
{
++count;
}
else
{
ss.str("");
ss << std::fixed << std::setprecision(1);
ss << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) / (1024 * 1024) << " Mp" << ends; // update fps string
ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield);
count = 0; // reset counter
timer.start(); // restart timer
}
drawString(ss.str().c_str(), 200, 286, color, font);

// restore projection matrix
glPopMatrix(); // restore to previous projection matrix

// restore modelview matrix
glMatrixMode(GL_MODELVIEW); // switch to modelview matrix
glPopMatrix(); // restore to previous modelview matrix
}



///////////////////////////////////////////////////////////////////////////////
// print transfer rates
///////////////////////////////////////////////////////////////////////////////
void printTransferRate()
{
const double INV_MEGA = 1.0 / (1024 * 1024);
static Timer timer;
static int count = 0;
static stringstream ss;
double elapsedTime;

// loop until 1 sec passed
elapsedTime = timer.getElapsedTime();
if(elapsedTime < 1.0)
{
++count;
}
else
{
cout << std::fixed << std::setprecision(1);
cout << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) * INV_MEGA << " Mpixels/s. (" << count / elapsedTime << " FPS)\n";
cout << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield);
count = 0; // reset counter
timer.start(); // restart timer
}
}


///////////////////////////////////////////////////////////////////////////////
// change the brightness
///////////////////////////////////////////////////////////////////////////////
void add(unsigned char* src, int width, int height, int shift, unsigned char* dst)
{
if(!src || !dst)
return;

int value;
for(int i = 0; i < height; ++i)
{
for(int j = 0; j < width; ++j)
{
value = *src + shift;
if(value > 255) *dst = (unsigned char)255;
else *dst = (unsigned char)value;
++src;
++dst;

value = *src + shift;
if(value > 255) *dst = (unsigned char)255;
else *dst = (unsigned char)value;
++src;
++dst;

value = *src + shift;
if(value > 255) *dst = (unsigned char)255;
else *dst = (unsigned char)value;
++src;
++dst;

++src; // skip alpha
++dst;
}
}
}


void toOrtho()
{
// set viewport to be the entire window
glViewport((GLsizei)SCREEN_WIDTH, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT);

// set orthographic viewing frustum
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT, -1, 1);

// switch to modelview matrix in order to set scene
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 0, 0, 0, -1, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)
}



void toPerspective()
{
// set viewport to be the entire window
glViewport(0, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT);

// set perspective viewing frustum
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f, (float)(SCREEN_WIDTH)/SCREEN_HEIGHT, 1.0f, 1000.0f); // FOV, AspectRatio, NearClip, FarClip

// switch to modelview matrix in order to set scene
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 8, 0, 0, 0, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)

}



//=============================================================================
// CALLBACKS
//=============================================================================

void displayCB()
{
static int shift = 0;
static int index = 0;
int nextIndex = 0; // pbo index used for next frame

// brightness shift amount
shift = ++shift % 200;

// increment current index first then get the next index
// "index" is used to read pixels from a framebuffer to a PBO
// "nextIndex" is used to process pixels in the other PBO
index = (index + 1) % 2;
nextIndex = (index + 1) % 2;

// set the framebuffer to read
glReadBuffer(GL_FRONT);

if(pboUsed) // with PBO
{
// read framebuffer ///////////////////////////////
t1.start();

// copy pixels from framebuffer to PBO
// Use offset instead of ponter.
// OpenGL should perform asynch DMA transfer, so glReadPixels() will return immediately.
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[index]);
glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, 0);

// measure the time reading framebuffer
t1.stop();
readTime = t1.getElapsedTimeInMilliSec();
///////////////////////////////////////////////////

// process pixel data /////////////////////////////
t1.start();

// map the PBO that contain framebuffer pixels before processing it
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[nextIndex]);
GLubyte* src = (GLubyte*)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB);
if(src)
{
// change brightness
add(src, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer);
glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB); // release pointer to the mapped buffer
}

// measure the time reading framebuffer
t1.stop();
processTime = t1.getElapsedTimeInMilliSec();
///////////////////////////////////////////////////

glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
}

else // without PBO
{
// read framebuffer ///////////////////////////////
t1.start();

glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer);

// measure the time reading framebuffer
t1.stop();
readTime = t1.getElapsedTimeInMilliSec();
///////////////////////////////////////////////////

// covert to greyscale ////////////////////////////
t1.start();

// change brightness
add(colorBuffer, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer);

// measure the time reading framebuffer
t1.stop();
processTime = t1.getElapsedTimeInMilliSec();
///////////////////////////////////////////////////
}

// render to the framebuffer //////////////////////////
glDrawBuffer(GL_BACK);
toPerspective(); // set to perspective on the left side of the window

// clear buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

// tramsform camera
glTranslatef(0, 0, cameraDistance);
glRotatef(cameraAngleX, 1, 0, 0); // pitch
glRotatef(cameraAngleY, 0, 1, 0); // heading

// draw a cube
draw();

// draw the read color buffer to the right side of the window
toOrtho(); // set to orthographic on the right side of the window
glRasterPos2i(0, 0);
glDrawPixels(SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer);

// draw info messages
showInfo();
printTransferRate();

glutSwapBuffers();
}


void reshapeCB(int w, int h)
{
toPerspective();
}


void timerCB(int millisec)
{
glutTimerFunc(millisec, timerCB, millisec);
glutPostRedisplay();
}


void idleCB()
{
glutPostRedisplay();
}


void keyboardCB(unsigned char key, int x, int y)
{
switch(key)
{
case 27: // ESCAPE
clearSharedMem();
//exit(0);
break;

case ' ':
if(pboSupported)
pboUsed = !pboUsed;
cout << "PBO mode: " << (pboUsed ? "on" : "off") << endl;
break;

case 'd': // switch rendering modes (fill -> wire -> point)
case 'D':
drawMode = ++drawMode % 3;
if(drawMode == 0) // fill mode
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
}
else if(drawMode == 1) // wireframe mode
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
}
else // point mode
{
glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
}
break;

default:
;
}

glutPostRedisplay();
}


void mouseCB(int button, int state, int x, int y)
{
mouseX = x;
mouseY = y;

if(button == GLUT_LEFT_BUTTON)
{
if(state == GLUT_DOWN)
{
mouseLeftDown = true;
}
else if(state == GLUT_UP)
mouseLeftDown = false;
}

else if(button == GLUT_RIGHT_BUTTON)
{
if(state == GLUT_DOWN)
{
mouseRightDown = true;
}
else if(state == GLUT_UP)
mouseRightDown = false;
}
}


void mouseMotionCB(int x, int y)
{
if(mouseLeftDown)
{
cameraAngleY += (x - mouseX);
cameraAngleX += (y - mouseY);
mouseX = x;
mouseY = y;
}
if(mouseRightDown)
{
cameraDistance += (y - mouseY) * 0.2f;
mouseY = y;
}
}

================================================================================================================================================================


3. Third technique is using plain Windows Code (WinMain) - Read Time: 0.01ms
==========================================================================

/*
* This Code Was Created By Jeff Molofee 2000
* A HUGE Thanks To Fredric Echols For Cleaning Up
* And Optimizing The Base Code, Making It More Flexible!
* If You've Found This Code Useful, Please Let Me Know.
* Visit My Site At nehe.gamedev.net
*/

// in order to get function prototypes from glext.h, define GL_GLEXT_PROTOTYPES before including glext.h
#define GL_GLEXT_PROTOTYPES


#include <windows.h> // Header File For Windows
#include <gl\gl.h> // Header File For The OpenGL32 Library
#include <gl\glu.h> // Header File For The GLu32 Library
#include "glut.h"
//#include <gl\glaux.h> // Header File For The Glaux Library
#include "oglext\glext.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include "glInfo.h" // glInfo struct
#include "Timer.h"


using std::stringstream;
using std::cout;
using std::endl;
using std::ends;


// VBO Extension Definitions, From glext.h
#define GL_ARRAY_BUFFER_ARB 0x8892
#define GL_STATIC_DRAW_ARB 0x88E4
typedef void (APIENTRY * PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
typedef void (APIENTRY * PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
typedef void (APIENTRY * PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
typedef void (APIENTRY * PFNGLBUFFERDATAARBPROC) (GLenum target, int size, const GLvoid *data, GLenum usage);

typedef void (APIENTRY * PFNGLBUFFERSUBDATAARBPROC) (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid const *);
typedef void (APIENTRY * PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum, GLenum, GLint *);
typedef GLvoid* (APIENTRY * PFNGLMAPBUFFERARBPROC) (GLenum, GLenum);
typedef GLboolean* (APIENTRY * PFNGLUNMAPBUFFERARBPROC) (GLenum);


HDC hDC=NULL; // Private GDI Device Context
HGLRC hRC=NULL; // Permanent Rendering Context
HWND hWnd=NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application

bool keys[256]; // Array Used For The Keyboard Routine
bool active=TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen=TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default

GLfloat rtri; // Angle For The Triangle ( NEW )
GLfloat rquad; // Angle For The Quad ( NEW )


// function pointers for PBO Extension
// Windows needs to get function pointers from ICD OpenGL drivers,
// because opengl32.dll does not support extensions higher than v1.1.
#ifdef _WIN32
PFNGLGENBUFFERSARBPROC pglGenBuffersARB = 0; // VBO Name Generation Procedure
PFNGLBINDBUFFERARBPROC pglBindBufferARB = 0; // VBO Bind Procedure
PFNGLBUFFERDATAARBPROC pglBufferDataARB = 0; // VBO Data Loading Procedure
PFNGLBUFFERSUBDATAARBPROC pglBufferSubDataARB = 0; // VBO Sub Data Loading Procedure
PFNGLDELETEBUFFERSARBPROC pglDeleteBuffersARB = 0; // VBO Deletion Procedure
PFNGLGETBUFFERPARAMETERIVARBPROC pglGetBufferParameterivARB = 0; // return various parameters of VBO
PFNGLMAPBUFFERARBPROC pglMapBufferARB = 0; // map VBO procedure
PFNGLUNMAPBUFFERARBPROC pglUnmapBufferARB = 0; // unmap VBO procedure
#define glGenBuffersARB pglGenBuffersARB
#define glBindBufferARB pglBindBufferARB
#define glBufferDataARB pglBufferDataARB
#define glBufferSubDataARB pglBufferSubDataARB
#define glDeleteBuffersARB pglDeleteBuffersARB
#define glGetBufferParameterivARB pglGetBufferParameterivARB
#define glMapBufferARB pglMapBufferARB
#define glUnmapBufferARB pglUnmapBufferARB
#endif

// constants
const int SCREEN_WIDTH = 256;
const int SCREEN_HEIGHT = 256;
const int CHANNEL_COUNT = 4;
const int DATA_SIZE = SCREEN_WIDTH * SCREEN_HEIGHT * CHANNEL_COUNT;
const GLenum PIXEL_FORMAT = GL_BGRA;
const int PBO_COUNT = 2;

// global variables
void *font = GLUT_BITMAP_8_BY_13;
bool pboSupported;
GLubyte* colorBuffer = 0;
bool pboUsed;
GLuint pboIds[PBO_COUNT]; // IDs of PBOs

float cameraAngleX;
float cameraAngleY;
float cameraDistance;

Timer timer, t1;
float readTime, processTime;

// GLUT CALLBACK functions
void displayCB();
void reshapeCB(int w, int h);
void timerCB(int millisec);
void idleCB();
void keyboardCB(unsigned char key, int x, int y);
void mouseCB(int button, int stat, int x, int y);
void mouseMotionCB(int x, int y);

bool mouseLeftDown;
bool mouseRightDown;
float mouseX, mouseY;
int drawMode = 0;

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For WndProc


///////////////////////////////////////////////////////////////////////////////
// initialize global variables
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// clean up shared memory
///////////////////////////////////////////////////////////////////////////////
void clearSharedMem()
{
// deallocate frame buffer
delete [] colorBuffer;
colorBuffer = 0;

// clean up PBOs
if(pboSupported)
{
glDeleteBuffersARB(PBO_COUNT, pboIds);
}
}


bool initSharedMem()
{
mouseLeftDown = mouseRightDown = false;

// allocate buffers to store frames
colorBuffer = new GLubyte[DATA_SIZE];
memset(colorBuffer, 255, DATA_SIZE);

return true;
}


///////////////////////////////////////////////////////////////////////////////
// write 2d text using GLUT
// The projection matrix must be set to orthogonal before call this function.
///////////////////////////////////////////////////////////////////////////////
void drawString(const char *str, int x, int y, float color[4], void *font)
{
glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask
glDisable(GL_LIGHTING); // need to disable lighting for proper text color
glDisable(GL_TEXTURE_2D);

glColor4fv(color); // set text color
glRasterPos2i(x, y); // place text position

// loop all characters in the string
while(*str)
{
glutBitmapCharacter(font, *str);
++str;
}

glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glPopAttrib();
}

///////////////////////////////////////////////////////////////////////////////
// display info messages
///////////////////////////////////////////////////////////////////////////////
void showInfo()
{
// backup current model-view matrix
glPushMatrix(); // save current modelview matrix
glLoadIdentity(); // reset modelview matrix

// set to 2D orthogonal projection
glMatrixMode(GL_PROJECTION); // switch to projection matrix
glPushMatrix(); // save current projection matrix
glLoadIdentity(); // reset projection matrix
gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection

const int FONT_HEIGHT = 14;
float color[4] = {1, 1, 1, 1};

stringstream ss;
ss << "PBO: ";
if(pboUsed)
ss << "on" << ends;
else
ss << "off" << ends;

drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-FONT_HEIGHT, color, font);
ss.str(""); // clear buffer

ss << "Read Time: " << readTime << " ms" << ends;
drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(2*FONT_HEIGHT), color, font);
ss.str("");

ss << std::fixed << std::setprecision(3);
ss << "Process Time: " << processTime << " ms" << ends;
drawString(ss.str().c_str(), 1, SCREEN_HEIGHT-(3*FONT_HEIGHT), color, font);
ss.str("");

ss << "Press SPACE to toggle PBO." << ends;
drawString(ss.str().c_str(), 1, 1, color, font);

// unset floating format
ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield);

// restore projection matrix
glPopMatrix(); // restore to previous projection matrix

// restore modelview matrix
glMatrixMode(GL_MODELVIEW); // switch to modelview matrix
glPopMatrix(); // restore to previous modelview matrix
}



///////////////////////////////////////////////////////////////////////////////
// display transfer rates
///////////////////////////////////////////////////////////////////////////////
void showTransferRate()
{
static Timer timer;
static int count = 0;
static stringstream ss;
double elapsedTime;

// backup current model-view matrix
glPushMatrix(); // save current modelview matrix
glLoadIdentity(); // reset modelview matrix

// set to 2D orthogonal projection
glMatrixMode(GL_PROJECTION); // switch to projection matrix
glPushMatrix(); // save current projection matrix
glLoadIdentity(); // reset projection matrix
gluOrtho2D(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT); // set to orthogonal projection

float color[4] = {1, 1, 0, 1};

// update fps every second
elapsedTime = timer.getElapsedTime();
if(elapsedTime < 1.0)
{
++count;
}
else
{
ss.str("");
ss << std::fixed << std::setprecision(1);
ss << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) / (1024 * 1024) << " Mp" << ends; // update fps string
ss << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield);
count = 0; // reset counter
timer.start(); // restart timer
}
drawString(ss.str().c_str(), 200, 286, color, font);

// restore projection matrix
glPopMatrix(); // restore to previous projection matrix

// restore modelview matrix
glMatrixMode(GL_MODELVIEW); // switch to modelview matrix
glPopMatrix(); // restore to previous modelview matrix
}



///////////////////////////////////////////////////////////////////////////////
// print transfer rates
///////////////////////////////////////////////////////////////////////////////
void printTransferRate()
{
const double INV_MEGA = 1.0 / (1024 * 1024);
static Timer timer;
static int count = 0;
static stringstream ss;
double elapsedTime;

// loop until 1 sec passed
elapsedTime = timer.getElapsedTime();
if(elapsedTime < 1.0)
{
++count;
}
else
{
cout << std::fixed << std::setprecision(1);
cout << "Transfer Rate: " << (count / elapsedTime) * (SCREEN_WIDTH * SCREEN_HEIGHT) * INV_MEGA << " Mpixels/s. (" << count / elapsedTime << " FPS)\n";
cout << std::resetiosflags(std::ios_base::fixed | std::ios_base::floatfield);
count = 0; // reset counter
timer.start(); // restart timer
}
}


GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And Initialize The GL Window
{
if (height==0) // Prevent A Divide By Zero By
{
height=1; // Making Height Equal One
}

glViewport(0,0,width,height); // Reset The Current Viewport

glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix

// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
}

int InitGL(GLvoid) // All Setup For OpenGL Goes Here
{

initSharedMem();

// get OpenGL info
glInfo glInfo;
glInfo.getInfo();
glInfo.printSelf();

#ifdef _WIN32
// check PBO is supported by your video card
if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object"))
{
// get pointers to GL functions
glGenBuffersARB = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB");
glBindBufferARB = (PFNGLBINDBUFFERARBPROC)wglGetProcAddress("glBindBufferARB");
glBufferDataARB = (PFNGLBUFFERDATAARBPROC)wglGetProcAddress("glBufferDataARB");
glBufferSubDataARB = (PFNGLBUFFERSUBDATAARBPROC)wglGetProcAddress("glBufferSubDataARB");
glDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)wglGetProcAddress("glDeleteBuffersARB");
glGetBufferParameterivARB = (PFNGLGETBUFFERPARAMETERIVARBPROC)wglGetProcAddress("glGetBufferParameterivARB");
glMapBufferARB = (PFNGLMAPBUFFERARBPROC)wglGetProcAddress("glMapBufferARB");
glUnmapBufferARB = (PFNGLUNMAPBUFFERARBPROC)wglGetProcAddress("glUnmapBufferARB");

// check once again PBO extension
if(glGenBuffersARB && glBindBufferARB && glBufferDataARB && glBufferSubDataARB &&
glMapBufferARB && glUnmapBufferARB && glDeleteBuffersARB && glGetBufferParameterivARB)
{
pboSupported = pboUsed = true;
//cout << "Video card supports GL_ARB_pixel_buffer_object." << endl;
}
else
{
pboSupported = pboUsed = false;
// cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl;
}
}

#else // for linux, do not need to get function pointers, it is up-to-date
if(glInfo.isExtensionSupported("GL_ARB_pixel_buffer_object"))
{
pboSupported = pboUsed = true;
cout << "Video card supports GL_ARB_pixel_buffer_object." << endl;
}
else
{
pboSupported = pboUsed = false;
cout << "Video card does NOT support GL_ARB_pixel_buffer_object." << endl;
}
#endif

if(pboSupported)
{
// create 2 pixel buffer objects, you need to delete them when program exits.
// glBufferDataARB with NULL pointer reserves only memory space.
glGenBuffersARB(PBO_COUNT, pboIds);
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[0]);
glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB);
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[1]);
glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, DATA_SIZE, 0, GL_STREAM_READ_ARB);

glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
}


glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
return TRUE; // Initialization Went OK
}

///////////////////////////////////////////////////////////////////////////////
// change the brightness
///////////////////////////////////////////////////////////////////////////////
void add(unsigned char* src, int width, int height, int shift, unsigned char* dst)
{
if(!src || !dst)
return;

int value;
for(int i = 0; i < height; ++i)
{
for(int j = 0; j < width; ++j)
{
value = *src + shift;
if(value > 255) *dst = (unsigned char)255;
else *dst = (unsigned char)value;
++src;
++dst;

value = *src + shift;
if(value > 255) *dst = (unsigned char)255;
else *dst = (unsigned char)value;
++src;
++dst;

value = *src + shift;
if(value > 255) *dst = (unsigned char)255;
else *dst = (unsigned char)value;
++src;
++dst;

++src; // skip alpha
++dst;
}
}
}


///////////////////////////////////////////////////////////////////////////////
// draw a cube with immediate mode
// 54 calls = 24 glVertex*() calls + 24 glColor*() calls + 6 glNormal*() calls
///////////////////////////////////////////////////////////////////////////////
void draw()
{
glBegin(GL_QUADS);
// face v0-v1-v2-v3
glNormal3f(0,0,1);
glColor3f(1,1,1);
glVertex3f(1,1,1);
glColor3f(1,1,0);
glVertex3f(-1,1,1);
glColor3f(1,0,0);
glVertex3f(-1,-1,1);
glColor3f(1,0,1);
glVertex3f(1,-1,1);

// face v0-v3-v4-v6
glNormal3f(1,0,0);
glColor3f(1,1,1);
glVertex3f(1,1,1);
glColor3f(1,0,1);
glVertex3f(1,-1,1);
glColor3f(0,0,1);
glVertex3f(1,-1,-1);
glColor3f(0,1,1);
glVertex3f(1,1,-1);

// face v0-v5-v6-v1
glNormal3f(0,1,0);
glColor3f(1,1,1);
glVertex3f(1,1,1);
glColor3f(0,1,1);
glVertex3f(1,1,-1);
glColor3f(0,1,0);
glVertex3f(-1,1,-1);
glColor3f(1,1,0);
glVertex3f(-1,1,1);

// face v1-v6-v7-v2
glNormal3f(-1,0,0);
glColor3f(1,1,0);
glVertex3f(-1,1,1);
glColor3f(0,1,0);
glVertex3f(-1,1,-1);
glColor3f(0,0,0);
glVertex3f(-1,-1,-1);
glColor3f(1,0,0);
glVertex3f(-1,-1,1);

// face v7-v4-v3-v2
glNormal3f(0,-1,0);
glColor3f(0,0,0);
glVertex3f(-1,-1,-1);
glColor3f(0,0,1);
glVertex3f(1,-1,-1);
glColor3f(1,0,1);
glVertex3f(1,-1,1);
glColor3f(1,0,0);
glVertex3f(-1,-1,1);

// face v4-v7-v6-v5
glNormal3f(0,0,-1);
glColor3f(0,0,1);
glVertex3f(1,-1,-1);
glColor3f(0,0,0);
glVertex3f(-1,-1,-1);
glColor3f(0,1,0);
glVertex3f(-1,1,-1);
glColor3f(0,1,1);
glVertex3f(1,1,-1);
glEnd();
}

void toOrtho()
{
// set viewport to be the entire window
glViewport((GLsizei)SCREEN_WIDTH, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT);

// set orthographic viewing frustum
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, SCREEN_WIDTH, 0, SCREEN_HEIGHT, -1, 1);

// switch to modelview matrix in order to set scene
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 0, 0, 0, -1, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)
}



void toPerspective()
{
// set viewport to be the entire window
glViewport(0, 0, (GLsizei)SCREEN_WIDTH, (GLsizei)SCREEN_HEIGHT);

// set perspective viewing frustum
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f, (float)(SCREEN_WIDTH)/SCREEN_HEIGHT, 1.0f, 1000.0f); // FOV, AspectRatio, NearClip, FarClip

// switch to modelview matrix in order to set scene
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 8, 0, 0, 0, 0, 1, 0); // eye(x,y,z), focal(x,y,z), up(x,y,z)

}

int DrawLesson5Scene(GLvoid) // Here's Where We Do All The Drawing
{
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
//glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(-1.5f,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
glRotatef(rtri,0.0f,1.0f,0.0f); // Rotate The Triangle On The Y axis ( NEW )
glBegin(GL_TRIANGLES); // Start Drawing A Triangle
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Front)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Left Of Triangle (Front)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Right Of Triangle (Front)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Right)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f( 1.0f,-1.0f, 1.0f); // Left Of Triangle (Right)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Right Of Triangle (Right)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Back)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f( 1.0f,-1.0f, -1.0f); // Left Of Triangle (Back)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f, -1.0f); // Right Of Triangle (Back)
glColor3f(1.0f,0.0f,0.0f); // Red
glVertex3f( 0.0f, 1.0f, 0.0f); // Top Of Triangle (Left)
glColor3f(0.0f,0.0f,1.0f); // Blue
glVertex3f(-1.0f,-1.0f,-1.0f); // Left Of Triangle (Left)
glColor3f(0.0f,1.0f,0.0f); // Green
glVertex3f(-1.0f,-1.0f, 1.0f); // Right Of Triangle (Left)
glEnd(); // Done Drawing The Pyramid

glLoadIdentity(); // Reset The Current Modelview Matrix
glTranslatef(1.5f,0.0f,-7.0f); // Move Right 1.5 Units And Into The Screen 7.0
glRotatef(rquad,1.0f,1.0f,1.0f); // Rotate The Quad On The X axis ( NEW )
glBegin(GL_QUADS); // Draw A Quad
glColor3f(0.0f,1.0f,0.0f); // Set The Color To Blue
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Top)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Top)
glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Quad (Top)
glVertex3f( 1.0f, 1.0f, 1.0f); // Bottom Right Of The Quad (Top)
glColor3f(1.0f,0.5f,0.0f); // Set The Color To Orange
glVertex3f( 1.0f,-1.0f, 1.0f); // Top Right Of The Quad (Bottom)
glVertex3f(-1.0f,-1.0f, 1.0f); // Top Left Of The Quad (Bottom)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Bottom)
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Bottom)
glColor3f(1.0f,0.0f,0.0f); // Set The Color To Red
glVertex3f( 1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Front)
glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Front)
glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Front)
glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Front)
glColor3f(1.0f,1.0f,0.0f); // Set The Color To Yellow
glVertex3f( 1.0f,-1.0f,-1.0f); // Top Right Of The Quad (Back)
glVertex3f(-1.0f,-1.0f,-1.0f); // Top Left Of The Quad (Back)
glVertex3f(-1.0f, 1.0f,-1.0f); // Bottom Left Of The Quad (Back)
glVertex3f( 1.0f, 1.0f,-1.0f); // Bottom Right Of The Quad (Back)
glColor3f(0.0f,0.0f,1.0f); // Set The Color To Blue
glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Left)
glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Left)
glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Left)
glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Left)
glColor3f(1.0f,0.0f,1.0f); // Set The Color To Violet
glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Right)
glVertex3f( 1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Right)
glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Right)
glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Right)
glEnd(); // Done Drawing The Quad

rtri+=0.2f; // Increase The Rotation Variable For The Triangle ( NEW )
rquad-=0.15f; // Decrease The Rotation Variable For The Quad ( NEW )
return TRUE; // Keep Going
}
int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing
{
static int shift = 0;
static int index = 0;
int nextIndex = 0; // pbo index used for next frame

// brightness shift amount
shift = ++shift % 200;

// increment current index first then get the next index
// "index" is used to read pixels from a framebuffer to a PBO
// "nextIndex" is used to process pixels in the other PBO
index = (index + 1) % 2;
nextIndex = (index + 1) % 2;

// set the framebuffer to read
glReadBuffer(GL_FRONT);

if(pboUsed) // with PBO
{
// read framebuffer ///////////////////////////////

timer.start();

// copy pixels from framebuffer to PBO
// Use offset instead of ponter.
// OpenGL should perform asynch DMA transfer, so glReadPixels() will return immediately.
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[index]);
glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, 0);

// measure the time reading framebuffer
timer.stop();
readTime = timer.getElapsedTimeInMilliSec();
///////////////////////////////////////////////////


// process pixel data /////////////////////////////
// map the PBO that contain framebuffer pixels before processing it
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboIds[nextIndex]);
GLubyte* src = (GLubyte*)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB);
if(src)
{
// change brightness
add(src, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer);
glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB); // release pointer to the mapped buffer
}

glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);
}
else // without PBO
{
// read framebuffer ///////////////////////////////
timer.start();

// read framebuffer ///////////////////////////////
glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer);

// measure the time reading framebuffer
timer.stop();
readTime = timer.getElapsedTimeInMilliSec();
///////////////////////////////////////////////////

// change brightness
add(colorBuffer, SCREEN_WIDTH, SCREEN_HEIGHT, shift, colorBuffer);
}


// render to the framebuffer //////////////////////////
glDrawBuffer(GL_BACK);
toPerspective(); // set to perspective on the left side of the window

// clear buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

////// tramsform camera
//glTranslatef(0, 0, cameraDistance);
//glRotatef(cameraAngleX, 1, 0, 0); // pitch
//glRotatef(cameraAngleY, 0, 1, 0); // heading

//// draw a cube
//draw();
DrawLesson5Scene();

// draw the read color buffer to the right side of the window
toOrtho(); // set to orthographic on the right side of the window
glRasterPos2i(0, 0);
glDrawPixels(SCREEN_WIDTH, SCREEN_HEIGHT, PIXEL_FORMAT, GL_UNSIGNED_BYTE, colorBuffer);

// draw info messages
showInfo();
printTransferRate();

//glutSwapBuffers();
return TRUE; // Keep Going
}

GLvoid KillGLWindow(GLvoid) // Properly Kill The Window
{
if (fullscreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}

if (hRC) // Do We Have A Rendering Context?
{
if (!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And RC Contexts?
{
MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}

if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
{
MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}
hRC=NULL; // Set RC To NULL
}

if (hDC && !ReleaseDC(hWnd,hDC)) // Are We Able To Release The DC
{
MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hDC=NULL; // Set DC To NULL
}

if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
{
MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hWnd=NULL; // Set hWnd To NULL
}

if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister Class
{
MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hInstance=NULL; // Set hInstance To NULL
}
}

/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* width - Width Of The GL Window Or Fullscreen Mode *
* height - Height Of The GL Window Or Fullscreen Mode *
* bits - Number Of Bits To Use For Color (8/16/24/32) *
* fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */

BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExstyle; // Window Extended style
DWORD dwstyle; // Window style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
WindowRect.left=(long)0; // Set Left Value To 0
WindowRect.right=(long)width; // Set Right Value To Requested Width
WindowRect.top=(long)0; // Set Top Value To 0
WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height

fullscreen=fullscreenflag; // Set The Global Fullscreen Flag

hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window.
wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = "OpenGL"; // Set The Class Name

if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if (fullscreen) // Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
return FALSE; // Return FALSE
}
}
}

if (fullscreen) // Are We Still In Fullscreen Mode?
{
dwExstyle=WS_EX_APPWINDOW; // Window Extended style
dwstyle=WS_POPUP; // Windows style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExstyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended style
dwstyle=WS_OVERLAPPEDWINDOW; // Windows style
}

AdjustWindowRectEx(&WindowRect, dwstyle, FALSE, dwExstyle); // Adjust Window To True Requested Size

// Create The Window
if (!(hWnd=CreateWindowEx( dwExstyle, // Extended style For The Window
"OpenGL", // Class Name
title, // Window Title
dwstyle | // Defined Window style
WS_CLIPSIBLINGS | // Required Window style
WS_CLIPCHILDREN, // Required Window style
0, 0, // Window Position
WindowRect.right-WindowRect.left, // Calculate Window Width
WindowRect.bottom-WindowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL))) // Dont Pass Anything To WM_CREATE
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
bits, // Select Our Color Depth
8, 0, 8, 0, 8, 0, // Color Bits Ignored
8, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
//sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
//1, // Version Number
//PFD_DRAW_TO_WINDOW | // Format Must Support Window
//PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
//PFD_DOUBLEBUFFER, // Must Support Double Buffering
//PFD_TYPE_RGBA, // Request An RGBA Format
//bits, // Select Our Color Depth
//0, 0, 0, 0, 0, 0, // Color Bits Ignored
//0, // No Alpha Buffer
//0, // Shift Bit Ignored
//0, // No Accumulation Buffer
//0, 0, 0, 0, // Accumulation Bits Ignored
//16, // 16Bit Z-Buffer (Depth Buffer)
//0, // No Stencil Buffer
//0, // No Auxiliary Buffer
//PFD_MAIN_PLANE, // Main Drawing Layer
//0, // Reserved
//0, 0, 0
};


if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

ShowWindow(hWnd,SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen

if (!InitGL()) // Initialize Our Newly Created GL Window
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

return TRUE; // Success
}

LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg) // Check For Windows Messages
{
case WM_ACTIVATE: // Watch For Window Activate Message
{
if (!HIWORD(wParam)) // Check Minimization State
{
active=TRUE; // Program Is Active
}
else
{
active=FALSE; // Program Is No Longer Active
}

return 0; // Return To The Message Loop
}

case WM_SYSCOMMAND: // Intercept System Commands
{
switch (wParam) // Check System Calls
{
case SC_SCREENSAVE: // Screensaver Trying To Start?
case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
return 0; // Prevent From Happening
}
break; // Exit
}

case WM_CLOSE: // Did We Receive A Close Message?
{
PostQuitMessage(0); // Send A Quit Message
return 0; // Jump Back
}

case WM_KEYDOWN: // Is A Key Being Held Down?
{
keys[wParam] = TRUE; // If So, Mark It As TRUE
return 0; // Jump Back
}

case WM_KEYUP: // Has A Key Been Released?
{
keys[wParam] = FALSE; // If So, Mark It As FALSE
return 0; // Jump Back
}

case WM_SIZE: // Resize The OpenGL Window
{
ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height
return 0; // Jump Back
}
}

// Pass All Unhandled Messages To DefWindowProc
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}


///////////////////////////////////////////////////////////////////////////////
// initialize GLUT for windowing
///////////////////////////////////////////////////////////////////////////////
int initGLUT(int argc, char **argv)
{
// GLUT stuff for windowing
// initialization openGL window.
// it is called before any other GLUT routine
glutInit(&argc, argv);

glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_ALPHA); // display mode

glutInitWindowSize(SCREEN_WIDTH*2, SCREEN_HEIGHT); // window size

glutInitWindowPosition(100, 100); // window location

// finally, create a window with openGL context
// Window will not displayed until glutMainLoop() is called
// it returns a unique ID
int handle = glutCreateWindow(argv[0]); // param is the title of window

// register GLUT callback functions
//glutDisplayFunc(DrawGLScene);
//glutTimerFunc(33, timerCB, 33); // redraw only every given millisec
glutIdleFunc(idleCB); // redraw only every given millisec
//glutReshapeFunc(reshapeCB);
//glutKeyboardFunc(keyboardCB);
//glutMouseFunc(mouseCB);
//glutMotionFunc(mouseMotionCB);

return handle;
}

int WINAPI WinMain( HINSTANCE hInstance, // Instance
HINSTANCE hPrevInstance, // Previous Instance
LPSTR lpCmdLine, // Command Line Parameters
int nCmdShow) // Window Show State
///////////////////////////////////////////////////////////////////////////////
//int main(int argc, char **argv)
{
// init GLUT and GL
//initGLUT(argc, argv);
//initGL();
InitGL();

//// the last GLUT call (LOOP)
// // window will be shown and display callback is triggered by events
// // NOTE: this call never return main().
// glutMainLoop(); /* Start GLUT event-processing loop */



MSG msg; // Windows Message Structure
BOOL done=FALSE; // Bool Variable To Exit Loop

// Ask The User Which Screen Mode They Prefer
if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
{
fullscreen=FALSE; // Windowed Mode
}


// Create Our OpenGL Window
if (!CreateGLWindow("NeHe's Solid Object Tutorial",512,256,32,fullscreen))
{
return 0; // Quit If Window Was Not Created
}

while(!done) // Loop That Runs While done=FALSE
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting?
{
if (msg.message==WM_QUIT) // Have We Received A Quit Message?
{
done=TRUE; // If So done=TRUE
}
else // If Not, Deal With Window Messages
{
TranslateMessage(&msg); // Translate The Message
DispatchMessage(&msg); // Dispatch The Message
}
}
else // If There Are No Messages
{
// Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene()
if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received?
{
done=TRUE; // ESC or DrawGLScene Signalled A Quit
}
else // Not Time To Quit, Update Screen
{
SwapBuffers(hDC); // Swap Buffers (Double Buffering)
}

if (keys[VK_F1]) // Is F1 Being Pressed?
{
keys[VK_F1]=FALSE; // If So Make Key FALSE
KillGLWindow(); // Kill Our Current Window
fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode
// Recreate Our OpenGL Window
if (!CreateGLWindow("NeHe's Solid Object Tutorial",512,256,32,fullscreen))
{
return 0; // Quit If Window Was Not Created
}
}
}
}

// Shutdown
KillGLWindow(); // Kill The Window
return (msg.wParam); // Exit The Program
//return 0;
}


void reshapeCB(int w, int h)
{
toPerspective();
}


void timerCB(int millisec)
{
glutTimerFunc(millisec, timerCB, millisec);
glutPostRedisplay();
}


void idleCB()
{
glutPostRedisplay();
}


void keyboardCB(unsigned char key, int x, int y)
{
switch(key)
{
case 27: // ESCAPE
clearSharedMem();
//exit(0);
break;

case ' ':
if(pboSupported)
pboUsed = !pboUsed;
cout << "PBO mode: " << (pboUsed ? "on" : "off") << endl;
break;

case 'd': // switch rendering modes (fill -> wire -> point)
case 'D':
drawMode = ++drawMode % 3;
if(drawMode == 0) // fill mode
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
}
else if(drawMode == 1) // wireframe mode
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
}
else // point mode
{
glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
}
break;

default:
;
}

glutPostRedisplay();
}


void mouseCB(int button, int state, int x, int y)
{
mouseX = x;
mouseY = y;

if(button == GLUT_LEFT_BUTTON)
{
if(state == GLUT_DOWN)
{
mouseLeftDown = true;
}
else if(state == GLUT_UP)
mouseLeftDown = false;
}

else if(button == GLUT_RIGHT_BUTTON)
{
if(state == GLUT_DOWN)
{
mouseRightDown = true;
}
else if(state == GLUT_UP)
mouseRightDown = false;
}
}


void mouseMotionCB(int x, int y)
{
if(mouseLeftDown)
{
cameraAngleY += (x - mouseX);
cameraAngleX += (y - mouseY);
mouseX = x;
mouseY = y;
}
if(mouseRightDown)
{
cameraDistance += (y - mouseY) * 0.2f;
mouseY = y;
}
}

===============================================================================

The primary difference between all these three technique is the way the windows of the application are created.

I want to achieve the same speed performance on SDL application. Any help in this regard will be highly appreciated. Eagerly waiting for your early response.

Share this post


Link to post
Share on other sites
First of all thanks for your reply. I just want to know that what values do I need to initialize in SDL before creating a SDL window in order to get PBO to work. Currently I am using the following lines of code to bring SDL window. But when I use PBO it does not have any performance benefits as was with when I create window using GLUT or plain Windows programming using WinMain.


/*--------------------------------------------------
* Setup SDL
*--------------------------------------------------*/
bool init_SDL()
{
//Init all SDL Parts
if(SDL_Init(SDL_INIT_EVERYTHING) == -1)
{
return false;
}

//screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL | SDL_DOUBLEBUF | SDL_FULLSCREEN ); //FULLSCREEN
screen = SDL_SetVideoMode( SCREEN_WIDTH*2, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL | SDL_DOUBLEBUF);
SDL_WM_SetCaption("Simple SDL Demo", NULL);


return true;
}


Is there any way to change the pixelformatdescriptor of SDL? or some other better way to get results. Eagerly waiting for your reply. Thanks.

Share this post


Link to post
Share on other sites
I am unsure about the specifics of PBO, but it *might* help if you add SDL_HWSURFACE | SDL_OPENGL. As far as I know the SDL_HWSURFACE would direct SDL to use hardware acceleration on the screen.

Why aren't you happy with GLUT alone then? IMO if it works for your purpose then stick with it. I personally cannot see any advantages of using SDL over GLUT except for maybe cross-platforming (Which GLUT already does).

Hope that helps. =)

Share this post


Link to post
Share on other sites
Flags like SDL_DOUBLEBUF and SDL_HWSURFACE have no effect on an OpenGL rendering context. Also, you don't define the bit depth in SDL_SetVideoMode for OpenGL, just pass 0. The only flag you need is SDL_OPENGL and optionally SDL_FULLSCREEN if you want fullscreen. You configure other things like bit depth, double buffering, etc with SDL_GL_SetAttribute (which you must call before SDL_SetVideoMode). To create an OpenGL rendering context with SDL, the correct order of calls is:

SDL_Init(SDL_INIT_VIDEO);

//setup OpenGL parameters
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 0 );
//and so on, set other attributes here

SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, SDL_OPENGL);


You can read more here.

Once you have a valid OpenGL rendering context, then you can use OpenGL features such as PBO. Since you never actually define your rendering context correctly, my guess is the speed difference is due to OpenGL having to convert from whatever the default format is to match the format of the PBO. Thus the performance hit. Use SDL_GL_SetAttribute properly to make your framebuffer format match your PBO format and I bet you will see a big improvement in performance.

Share this post


Link to post
Share on other sites
First of all thanks for your kind reply. I have tried what you said and it resolves my issue, the glReadPixels now takes only 0-1 ms. But unfortunately by setting the rendering context, the frame rate of the rest of the scene suddenly drops by a factor of 5 like previously it was 42 and now it is showing maximum frame rate of 34. So what should I do next to resolve it. Are there any other setting besides the parameters that you have shown. Eagerly waiting for your early response. Thanks.

Share this post


Link to post
Share on other sites
I'm glad that you resolved your initial issue. As for the drop in frame rate, I will admit that I have not reviewed your code in depth, so I can not make a direct recommendation. On one hand, I probably would not worry about a drop of 5 frames per second. On the other hand, your code does not appear to be doing anything terribly complex, so it is strange to see a drop. Did you benchmark your updated code with the GLUT version? What type of GPU are you running this on?

Share this post


Link to post
Share on other sites
Thanks for your reply. In fact the code that I have posted earlier is only a sample code that I have used for illustration of my previous issue. I am in fact running a game that includes sea environment, terrain and some harbors area. And by defining the openGL rendering context parameters for SDL it drops to 34 FPS maximum and this causes the scene to jerk at some time due to sea rendering. But if I run the code without defining the openGL context parameters for SDL it gives FPS of 40 maximum. The GPU that I have is nVidia 8500 GT. But I think that it does not have any effect on it because I have also run this code in my office where it is showing the similar behavior where I have nVidia 8800 GTS. Waiting for your reply. Thanks.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      627743
    • Total Posts
      2978894
  • Similar Content

    • By DelicateTreeFrog
      Hello! As an exercise for delving into modern OpenGL, I'm creating a simple .obj renderer. I want to support things like varying degrees of specularity, geometry opacity, things like that, on a per-material basis. Different materials can also have different textures. Basic .obj necessities. I've done this in old school OpenGL, but modern OpenGL has its own thing going on, and I'd like to conform as closely to the standards as possible so as to keep the program running correctly, and I'm hoping to avoid picking up bad habits this early on.
      Reading around on the OpenGL Wiki, one tip in particular really stands out to me on this page:
      For something like a renderer for .obj files, this sort of thing seems almost ideal, but according to the wiki, it's a bad idea. Interesting to note!
      So, here's what the plan is so far as far as loading goes:
      Set up a type for materials so that materials can be created and destroyed. They will contain things like diffuse color, diffuse texture, geometry opacity, and so on, for each material in the .mtl file. Since .obj files are conveniently split up by material, I can load different groups of vertices/normals/UVs and triangles into different blocks of data for different models. When it comes to the rendering, I get a bit lost. I can either:
      Between drawing triangle groups, call glUseProgram to use a different shader for that particular geometry (so a unique shader just for the material that is shared by this triangle group). or
      Between drawing triangle groups, call glUniform a few times to adjust different parameters within the "master shader", such as specularity, diffuse color, and geometry opacity. In both cases, I still have to call glBindTexture between drawing triangle groups in order to bind the diffuse texture used by the material, so there doesn't seem to be a way around having the CPU do *something* during the rendering process instead of letting the GPU do everything all at once.
      The second option here seems less cluttered, however. There are less shaders to keep up with while one "master shader" handles it all. I don't have to duplicate any code or compile multiple shaders. Arguably, I could always have the shader program for each material be embedded in the material itself, and be auto-generated upon loading the material from the .mtl file. But this still leads to constantly calling glUseProgram, much more than is probably necessary in order to properly render the .obj. There seem to be a number of differing opinions on if it's okay to use hundreds of shaders or if it's best to just use tens of shaders.
      So, ultimately, what is the "right" way to do this? Does using a "master shader" (or a few variants of one) bog down the system compared to using hundreds of shader programs each dedicated to their own corresponding materials? Keeping in mind that the "master shaders" would have to track these additional uniforms and potentially have numerous branches of ifs, it may be possible that the ifs will lead to additional and unnecessary processing. But would that more expensive than constantly calling glUseProgram to switch shaders, or storing the shaders to begin with?
      With all these angles to consider, it's difficult to come to a conclusion. Both possible methods work, and both seem rather convenient for their own reasons, but which is the most performant? Please help this beginner/dummy understand. Thank you!
    • By JJCDeveloper
      I want to make professional java 3d game with server program and database,packet handling for multiplayer and client-server communicating,maps rendering,models,and stuffs Which aspect of java can I learn and where can I learn java Lwjgl OpenGL rendering Like minecraft and world of tanks
    • By AyeRonTarpas
      A friend of mine and I are making a 2D game engine as a learning experience and to hopefully build upon the experience in the long run.

      -What I'm using:
          C++;. Since im learning this language while in college and its one of the popular language to make games with why not.     Visual Studios; Im using a windows so yea.     SDL or GLFW; was thinking about SDL since i do some research on it where it is catching my interest but i hear SDL is a huge package compared to GLFW, so i may do GLFW to start with as learning since i may get overwhelmed with SDL.  
      -Questions
      Knowing what we want in the engine what should our main focus be in terms of learning. File managements, with headers, functions ect. How can i properly manage files with out confusing myself and my friend when sharing code. Alternative to Visual studios: My friend has a mac and cant properly use Vis studios, is there another alternative to it?  
    • By ferreiradaselva
      Both functions are available since 3.0, and I'm currently using `glMapBuffer()`, which works fine.
      But, I was wondering if anyone has experienced advantage in using `glMapBufferRange()`, which allows to specify the range of the mapped buffer. Could this be only a safety measure or does it improve performance?
      Note: I'm not asking about glBufferSubData()/glBufferData. Those two are irrelevant in this case.
    • By xhcao
      Before using void glBindImageTexture(    GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format), does need to make sure that texture is completeness. 
  • Popular Now