#include "StdAfx.h"
#include "GLUtil.h"

#include <sstream>



void GLUtil::TraceGLError(void)
{
	GLenum err = glGetError();
	if(err == GL_NO_ERROR)
		return;

	OutputDebugStringA( glGetErrorMessage(err) );
	OutputDebugStringA("\n");
}

void GLUtil::TraceVersion(void)
{
	std::ostringstream ss;
	ss << "version=" << glGetString(GL_VERSION) << std::endl;
	ss << "renderer=" << glGetString(GL_RENDERER) << std::endl;
	ss << "vendor=" << glGetString(GL_VENDOR) << std::endl;
	OutputDebugStringA(ss.str().c_str());
}

//! 現在のコンテキストからカラーバッファを取得する
void GLUtil::GetColorBuffer(QImage& bmp, bool flipY, GLint x, GLint y, GLint w, GLint h)
{
	bmp.swap(QImage(w, h, QImage::Format_RGB888));

	if(w == 0 && h == 0)
		return;

	glPixelStorei( GL_UNPACK_ALIGNMENT , 1 );
	glPixelStorei( GL_PACK_ALIGNMENT , 1 );

	std::vector<unsigned char> buf(w * h * 3);
	glReadPixels(x, y, w, h, GL_RGB, GL_UNSIGNED_BYTE, &buf[0]);

	for(size_t x = 0; x < w; ++x)
	{
		for(size_t y = 0; y < h; ++y)
		{
			int i0 = (x + y * w) * 3;
			unsigned char r = buf[i0+0];
			unsigned char g = buf[i0+1];
			unsigned char b = buf[i0+2];

			uint c = RGBtoIndex(r, g, b);

			if(flipY)
				bmp.setPixel(x, h - y - 1, c);
			else
				bmp.setPixel(x, y, c);
		}
	}
}

uint GLUtil::RGBtoIndex(unsigned char r, unsigned char g, unsigned char b)
{
	uint c = 0;
	c = c * 0x100 + r;
	c = c * 0x100 + g;
	c = c * 0x100 + b;
	return c;
}

void GLUtil::GetColorBuffer(QImage& bmp, bool flipY)
{
	GLint viewport[4];
	glGetIntegerv( GL_VIEWPORT , viewport );
	GLint x = viewport[0];
	GLint y = viewport[1];
	GLint w = viewport[2];
	GLint h = viewport[3];

	GetColorBuffer(bmp, flipY, x, y, w, h);
}
