/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2008.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: src/sgx/graphics/light.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/graphics/graphics.hpp"

// TODO: Ambient lighting
#define SGX_GFX_MAX_LIGHTS	16
	

//
// Creation: Null driver
//
CSGXLight *CSGXGraphicsEngine::CreateLight()
{
	return new CSGXLight();
}

CSGXLight::CSGXLight()
{
	active.setState(FALSE);
	pos.setState(sgxVector3(0,0,0));
	color.setState(sgxColorRGB(0,0,0));
	range.setState(20.0f);
	exposition.setState(1.0f);
	type.setState(eTypeOmni);

	// Make them dirty so that if the engine's initial state
	// happens to include the same parameters, they are still
	// applied to the graphics code
	active.ForceDirty();
	pos.ForceDirty();
	color.ForceDirty();
	range.ForceDirty();
	exposition.ForceDirty();
	type.ForceDirty();
}

//
// Light control in the engine
//

// TODO: Split internal light structure (with state), from
// user-accessible one. cengineligh { csgxlight info; state data; }
CSGXLight &
CSGXGraphicsEngine::getLight(const tUINT32 &idx) const
{
	tUINT32 i = sgxRange<tUINT32>(idx, 0, getMaxLights());
	return *m_Lights[i];
}
	
void 
CSGXGraphicsEngine::destroyLights()
{
	m_Lights.clear();
}
	
tUINT32	
CSGXGraphicsEngine::getMaxLights() const
{
	return SGX_GFX_MAX_LIGHTS;
}

tUINT32	
CSGXGraphicsEngine::getLightsInRange(sgxVector<CSGXLight *> lights, const sgxVector3 &pos) const
{
	lights.reserve(m_Lights.size());

	sgxVector<CSGXLight *>::const_iterator cit = m_Lights.begin();

	for(;cit!=m_Lights.end();++cit) {

		if ((*cit)->active.getState()) {
			sgxVector3 dir = (*cit)->pos.getState();
			dir -= pos;
			tREAL32 dist_squared = dir.x*dir.x + dir.y*dir.y + dir.z*dir.z;
			tREAL32 range2 = (*cit)->range.getState();

			range2 *= range2;

			if (range2 >= dist_squared) {
				lights.push_back(*cit);
			}

		}

	}

	return lights.size();	
}

