#ifndef __RENDERER_UTIL_H__
#define __RENDERER_UTIL_H__

#include "3dmath.h"

namespace VRUT
{

	/**
	*	count luminance of color - 0.2125 * color.red + 0.7154 * color.green + 0.0721 * color.blue;
	*	\param[in] color - color
	*	\return luminance of color
	*/
	inline float Luminance(Vector4 color)
	{
		return 0.2125f * color.x + 0.7154f * color.y + 0.0721f * color.z;
	}

	/**
	*	mix of x and y in and a set ration x and y - x * (1 - a) + y * a;
	*	\return mix
	*/
	inline float Mix(float x, float y, float a)
	{
		return x * (1 - a) + y * a;
	}

	inline void ClampColor(Vector4 &color)
	{
		/*color.x=__min(color.x, 1.0f);
		color.y=__min(color.y, 1.0f);
		color.z=__min(color.z, 1.0f);
		color.w=__min(color.w, 1.0f);*/
	}

	inline Vector4 TransformColor(Vector4 color)
	{
		float maxC = __max(color.x, __max(color.y, color.z));
		if (maxC == 0)
		{
			color = Vector4(1.0f, 1.0f, 1.0f, 1.0f) * (1.0f - color.w);
		}
		else
		{
			float transp = color.w;
			color /= maxC;
			color.w = transp;
			color = (color * color.w + Vector4(1.0f, 1.0f, 1.0f, 1.0f) * (1.0f - color.w)) * (1.0f - color.w);
			color.w = 1.0f - transp;
		}
		return color;
	}

	inline float Distance2(const Vector3 & u, const Vector3 & v)
	{
		return u.x * v.x + u.y * v.y + u.z * v.z;
	}

	// http://martin.ankerl.com/2012/01/25/optimized-approximative-pow-in-c-and-cpp/
	inline double fastPow(double a, double b)
	{
		// calculate approximation with fraction of the exponent
		int e = (int) b;
		union
		{
			double d;
			int x[2];
		} u = {a};
		u.x[1] = (int) ((b - e) * (u.x[1] - 1072632447) + 1072632447);
		u.x[0] = 0;

		// exponentiation by squaring with the exponent's integer part
		// double r = u.d makes everything much slower, not sure why
		double r = 1.0;
		while (e)
		{
			if (e & 1)
			{
				r *= a;
			}
			a *= a;
			e >>= 1;
		}

		return r * u.d;
	}

#define IntDivCeil(a, b) (((a) + (b) - 1) / (b))
#define IntDivCeilLog(a, b) (((a) + (1 << (b)) - 1) >> (b))
#define IntMod2k(a, b) ((a) & ((b) - 1))

}

#endif  /* __RENDERER_UTIL_H__ */
