//	ColourHelpers.cpp - Some useful colour conversion functions.
//  ----------------------------------------------------------------------------
//	This file is part of 'NiallsAVLib', base code for any kind of audiovisual
//	apps.
//	Copyright (C) 2012  Niall Moody
//	
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//
//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//
//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.
//	----------------------------------------------------------------------------

#include "ColourHelpers.h"

//------------------------------------------------------------------------------
ThreeFloats ColourHelpers::hslToRgb(const ThreeFloats& col)
{
	float q, p;
	ThreeFloats retval;

	if(col.y == 0.0f)
		retval = col.z;
	else
	{
		if(col.z < 0.5f)
			q = col.z * (col.z + col.y);
		else
			q = col.z + col.y - col.z * col.y;

		p = 2.0f * col.z - q;

		retval.x = hueToRgb(p, q, (col.x + (1.0f/3.0f)));
		retval.y = hueToRgb(p, q, col.x);
		retval.z = hueToRgb(p, q, (col.x - (1.0f/3.0f)));
	}

	return retval;
}

//------------------------------------------------------------------------------
float ColourHelpers::hueToRgb(float p, float q, float t)
{
	float retval = p;

	if(t < 0.0f)
		t += 1.0f;
	if(t > 1.0f)
		t -= 1.0f;

	if(t < (1.0f/6.0f))
		retval = p + (q - p) * 6.0f * t;
	else if(t < 0.5f)
		retval = q;
	else if(t < (2.0f/3.0f))
		retval = p + (q - p) * ((2.0f/3.0f) - t) * 6.0f;

	return retval;
}
