#include <../source/TAL/objbase.h>
#include <../source/PAL/dataman.h>

u8_p		V_GLOBAL
vglReadPixels(u32_t width,u32_t height)
{
	u8_t *pixels;
	u32_t w3,stride_adjust;
	u32_t half;
	void *buffer;
	u8_t *upper, *lower;
	CALLER_NAME(vglReadPixels)
	if(!width || !height)
	{
#ifdef	CHECKED_BUILD
		conlPrintf(LOG_ERROR,"%s(%u,%u): incorrect parameter(s).\n",
			caller_name,width,height);
#endif	/* CHECKED_BUILD */
		return NULL;
	}
	pixels=(u8_t*)memAlloc(width * height * 4);
	w3 = width * 3;
	stride_adjust = INT_ALIGN(w3) - w3;
	glPixelStorei(GL_UNPACK_LSB_FIRST,GL_FALSE);
	glPixelStorei(GL_UNPACK_ROW_LENGTH,0);
	glPixelStorei(GL_UNPACK_SKIP_ROWS,0);
	glPixelStorei(GL_UNPACK_SKIP_PIXELS,0);
	glPixelStorei(GL_UNPACK_ALIGNMENT,1);
	glReadPixels(0,0,width,height,GL_RGBA,GL_UNSIGNED_BYTE,pixels);
	buffer = memAlloc(width * 4);
	half = height / 2;
	upper = pixels;
	lower = upper + (height - 1) * width * 4;
	while(half--)
	{
		memCopy32(buffer,upper,width);
		memCopy32(upper,lower,width);
		memCopy32(lower,buffer,width);
		upper += width * 4;
		lower -= width * 4;
	}
	memFree(buffer);
	return pixels;
}

/*
 *	Utility function to produce screenshots.
 */
vboolean	V_GLOBAL
vglSaveFramebuffer(char *file_name,u32_t width,u32_t height,
	u32_t mmWidth,u32_t mmHeight)
{
	CALLER_NAME(vglSaveFramebuffer)
	vboolean result;
	u8_t *pixels;
	if(!file_name || !file_name[0] || !width || !height)
	{
#ifdef	CHECKED_BUILD
		conlPrintf(LOG_ERROR,"%s(%s,%u,%u,%u,%u): incorrect parameter(s).\n",
			caller_name,strSafe(file_name),width,height,mmWidth,mmHeight);
#endif	/* CHECKED_BUILD */
		return false;
	}
	pixels = vglReadPixels(width, height);
	result = rgbaSaveEx(file_name,width,height,pixels,mmWidth,mmHeight);
	memFree(pixels);
	memSetOpaque(12);
	return result;
}
