/* -----------------------------------------------------------------------------
	GSFramework
	Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
------------------------------------------------------------------------------*/


		#include "picture/pict_tools.h"
		#include "picture/pict.h"

		using namespace GS;


namespace GS {
	namespace PictureTools {

bool	Compare(const Picture &a, const Picture &b, float threshold)
{
	if	((a.GetWidth() != b.GetWidth()) || (a.GetHeight() != b.GetHeight()))
		return false;

	float dt = 0.f;
	for	(uint y = 0; y < a.GetHeight(); ++y)
		for	(uint x = 0; x < a.GetWidth(); ++x)
			for	(int c = 0; c < 4; ++c)
				dt += (a.GetDataOffset(x, y)[c] - b.GetDataOffset(x, y)[c]) / 255.f;

	return asbool(dt <= threshold);
}

	} // PictureTools
} // GS

//------------------------------------------------------------------------------
bool			Picture::Fill(float r, float g, float b, float a, const iRect *rect, bool lock_alpha)
{
	uint *data = (uint *)GetData();

	if	(GetBpp() != 32)
		return false;
	if	(!data)
		return false;

	// Convert color.
	uint fill = GetPixelFormat().Format(r, g, b, a);

	uchar	ur = uchar(r * 255),
			ug = uchar(g * 255),
			ub = uchar(b * 255)/*,
			ua = uchar(a * 255)*/;

	if	(rect)
	{
		Rect <int> _rect = rect->Intersection(GetRect());

		if	((_rect.sy >= _rect.ey) || (_rect.sx >= _rect.ex))
			return false;

		data += _rect.sx + _rect.sy * width;
		for	(int y = 0; y < _rect.GetHeight(); ++y)
		{
			if	(lock_alpha)
			{
				uchar *scan = (uchar *)data;
				for	(int x = 0; x < _rect.GetWidth(); ++x)
				{
					scan[GetPixelFormat().rshift >> 3] = ur;
					scan[GetPixelFormat().gshift >> 3] = ug;
					scan[GetPixelFormat().bshift >> 3] = ub;
					// scan[GetPixelFormat().ashift >> 3] = ua;
					scan += 4;
				}
			}
			else
			{
				uint *scan = data;
				for	(int x = 0; x < _rect.GetWidth(); ++x)
					*scan++ = fill;
			}
			data += width;
		}
	}
	else
	{
		if	(lock_alpha)
		{
			uchar *scan = (uchar *)data;
			for	(uint n = 0; n < GetWidth() * GetHeight(); n++)
			{
				scan[GetPixelFormat().rshift >> 3] = ur;
				scan[GetPixelFormat().gshift >> 3] = ug;
				scan[GetPixelFormat().bshift >> 3] = ub;
				// scan[GetPixelFormat().ashift >> 3] = ua;
				scan += 4;
			}
		}
		else
			for	(uint n = 0; n < GetWidth() * GetHeight(); n++)
				data[n] = fill;
	}
	return true;
}
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
bool				Picture::ToGrayscale()
{
	if	(!(GetWidth() && GetHeight()))
		return false;
	if	(GetBpp() != 32)
		return false;

	uchar *ptr = GetData();
	for	(uint y = 0; y < GetHeight(); y++)
		for	(uint x = 0; x < GetWidth(); x++)
		{
			int v = (ptr[0] + ptr[1] + ptr[2]) / 3;
			ptr[0] = ptr[1] = ptr[2] = (uchar)v;
			ptr += 4;
		}
	return true;
}
//------------------------------------------------------------------------------
