//	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;
}

//------------------------------------------------------------------------------
ThreeFloats ColourHelpers::rgbToHsl(const ThreeFloats& col)
{
	ThreeFloats retval;

    float max, min;

	if(col.x > col.y)
		max = col.x;
	else
		max = col.y;
	if(col.z > max)
		max = col.z;

	if(col.x < col.y)
		min = col.x;
	else
		min = col.y;
	if(col.z < min)
		min = col.z;

	retval = (max + min)*0.5f;

    if(max == min)
	{
        retval.x = 0.0f;
		retval.y = 0.0f;
    }
	else
	{
        float d = max - min;
        retval.y = retval.z > 0.5f ? d/(2.0f-max-min) : d/(max+min);
        if(max == col.x)
			retval.x = (col.y-col.z)/d+(retval.y<retval.z ? 6.0f : 0.0f);
		else if(max == col.y)
            retval.x = (col.z-col.x)/d+2.0f;
		else
            retval.x = (col.x-col.y)/d+4.0f;
        retval.x /= 6.0f;
		if(retval.x > 1.0f)
			retval.x -= 1.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;
}
