#ifndef QUADAREALIGHT_HXX
#define QUADAREALIGHT_HXX

#define RECTANGULAR_QAL

#include "Light.hxx"

class QuadAreaLight : public Light
{
public:
	Vec3f normal;         // normal
	float area;           // size of the light
	Vec3f intensity;      // emission (red, green, blue)
	Vec3f C1, C2, C3, C4; // Four courner points
	Vec3f D1, D2;         // Vectors spanning the coordinate system (diagonals)
	Vec3f H1, H2, V1;     // Edge vectors
	float r1, r2;         // Random scales
	float scale;          // Dot product of ray.dir and normal

	/********************
	        --H1->
	    3-----------4
	  ^ |°D2.    °° |
	 V1 |   ..°°    |
	  | |.D1    °.. |
	    2-----------1
	        --H2->
	********************/

	QuadAreaLight(Scene *scene, Vec3f intensity, Vec3f C1, Vec3f C2, Vec3f C3, Vec3f C4)
		: Light(scene),intensity(intensity),C1(C1),C2(C2),C3(C3),C4(C4)
	{
		D1 = C2 - C4;
		D2 = C3 - C1;

		H1 = C3 - C4;
		H2 = C2 - C1;

		V1 = C3 - C2;

		normal = Cross(D1, D2);
		area   = Length(normal);

		Normalize(normal);
	};  

	virtual bool Illuminate(Ray &ray, Vec3f &intensity)
	{
		// Create random position on quadrangle
		r1 = drand48();
		r2 = drand48();

#ifdef RECTANGULAR_QAL
		Vec3f position = C2 + r1 * V1 + r2 * H2;
#else
		Vec3f position = r2 * (r1 * (H1 - H2) + C3 - C2) + H2 * r1 + C2;
#endif

		ray.dir = position - ray.org;
		ray.t   = Length(ray.dir);

		intensity = this->intensity / Dot(ray.dir, ray.dir) * area;

		Normalize(ray.dir);
		scale = Dot(ray.dir, normal);

		if (scale >= 0)
			intensity *= scale;
		else
			intensity = Vec3f(0,0,0);

		return true;
	};
};

#endif
