Newer
Older
cg / sources / light.cpp
#include "light.h"

Light::Light() {
  //TODO: this class should be abstract
  printf("light not initialized\n");
}

Light::Light(GLenum _num, Vec _pos, Material _mat) {
  init(_num, _pos, _mat);
}

void Light::init(GLenum _num, Vec _pos, Material _mat) {
  num = _num;
  pos = _pos.clone();
  mat = _mat.clone();
  rot = new Vec(0,0,0);
  showtrace = true;
  sphere = gluNewQuadric();  
  
  //glLightfv(num, GL_AMBIENT, mat->ambient->v());
  glLightfv(num, GL_DIFFUSE, mat->ambient->v());
  glLightfv(num, GL_SPECULAR, mat->specular->v());
  //TODO
  //glLightf(num,GL_QUADRATIC_ATTENUATION,.001f);

  show();  
}

void Light::trace(bool _s) {
  showtrace = _s;
}

void Light::show() {
  enabled = true;
  glEnable(num);
}

void Light::hide() {
  enabled = false;
  glDisable(num);
}

void Light::setPosition(Vec newpos) {
  delete pos;
  pos = newpos.clone();
}

void Light::translate(Vec d) {
	pos->add((Vec)d);
}

void Light::rotate(Vec a) {
  rot->add((Vec)a);
}


void Light::draw() {
  //save camera position
  glPushMatrix();

  glTranslatef(pos->x(), pos->y(), pos->z());

  float p[] = {0.0f, 0.0f, 0.0f, 1.0f};
  glLightfv(num, GL_POSITION, p);
 
  if (showtrace) {
	//sphere
	float c[] = {1,1,1,1};
	glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, c);
	gluSphere(sphere, 1, 10, 10);
  }
  
  glPopMatrix();
}

SpotLight::SpotLight(GLenum _num, Vec _pos, Material _mat, float _angle) {
  Light::init(_num, _pos, _mat);

  cutoff_angle = _angle;
  cone = gluNewQuadric();  

  show();
}

void SpotLight::draw() {
	if ( enabled ) {
		//save camera position
		glPushMatrix();

		glRotatef(rot->x(), 1.0f, 0.0f, 0.0f);
		glRotatef(rot->y(), 0.0f, 1.0f, 0.0f);
		glRotatef(rot->z(), 0.0f, 0.0f, 1.0f);

		glTranslatef(pos->x(), pos->y(), pos->z());
		glLightf(num, GL_SPOT_CUTOFF, cutoff_angle);	

		float p[] = {0.0f, 0.0f, 0.0f, 1.0f};
		glLightfv(num, GL_POSITION, p);

		GLfloat dir[] = {0.0f, -1.0f, 0.0f, 1.0f};
		glLightfv(num, GL_SPOT_DIRECTION, dir);

		if (showtrace) {
			//line
			glBegin(GL_LINES);
				glVertex3fv(p);
				glVertex3fv(dir);
			glEnd();
			//cone
			glTranslatef(0,5.5,0);
			glRotatef(90, 1, 0, 0);
			gluCylinder (cone, 0, 1, 5, 10, 20);

		}
		glPopMatrix();
	}
}