/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2009.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: sgx/src/drivers/common/opengl/oglgrabframe.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/graphics/graphics.hpp"

#include "drivers/common/opengl/opengl.hpp"

CSGXTexture *
COpenGLEngine::grabFrame(const tBOOL resizeToSquarePowerOf2)
{
	// Always captures the main buffer
// TODO: Might be eRGBA if the glut init format was rgba
	tUINT32 w = getScreenWidth();
	tUINT32 h = getScreenHeight();

	if (resizeToSquarePowerOf2) {
		tUINT32 squared_size = sgxMax(getScreenWidth(), getScreenHeight());
		w = h = sgxRoundUpToPower2(squared_size);
	}
	CImageData data(w, h, CImageData::eRGB);
	
	if (!data.getBitmap()) {
		return NULL;
	}

	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glReadPixels(0, 0, data.getWidth(), data.getHeight(), GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)data.getBitmap());
	//data.flipVertical();
	CSGXTexture *pTexture = CSGXTextureManager::get()->createTexture(data);
	// TODO: Fix regions
	pTexture->clearRegions();
	pTexture->addPixelRegion(0, 0, getScreenWidth(), getScreenHeight());
	return pTexture;
}

#if 0

template <typename T>
SGX_INLINE tBOOL sgxIsPower2(T v)
{
	return FALSE;
}

CSGXTexture *
COpenGLEngine::grabFrame(const tUINT32 width, const tUINT32 height)
{
	sgxAssert(sgxIsPower2(width) && "Width must be a power of 2");
	sgxAssert(sgxIsPower2(height) && "Height must be a power of 2");
#endif
