#include <math.h>
#include <GL/glut.h>
#include "modelado.h"
#include "matematicas.h"

float dameX(float R, int N, int n) {
	float x = (float)R*cos(n*(2*PI)/N);
	return x;
}

float dameZ(float R, int N, int n) {
	float z = (float)R*sin(n*(2*PI)/N);
	return z;
}

void paralelo(float R, int N, float y) {
	float x, z;
	int i;

	glBegin(GL_LINE_LOOP);
		for(i = 0; i < N; i++) {
			x = dameX(R, N, i);
			z = dameZ(R, N, i);
			glVertex3f(x, y, z);
		}
	glEnd();
}

void tira(float R, float dR, float y, float dy, float N) {
  int i;
  float x, z;

  glDisable(GL_LIGHTING);
  glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
  glBegin(GL_QUAD_STRIP);
  for(i = 0; i <= N; i++) {
    x = dameX(R, N, i);
    z = dameZ(R, N, i);
    glVertex3f(x, y, z);
    x = dameX(R+dR, N, i);
    z = dameZ(R+dR, N, i);
    glVertex3f(x, y+dy, z);
  }
  glEnd();
  glEnable(GL_LIGHTING);
}

Vector3D normal(float R, float dR, float y, float dy, int N, int n) {
	Punto3D p, q, r;
	Vector3D v, w, normal;

	p.x = dameX(R, N, n);
	p.y = y;
	p.z = dameZ(R, N, n);
	if(R == 0.0f) {
		q.x = dameX(R+dR, N, (n+1)%N);
		q.y = y+dy;
		q.z = dameZ(R+dR, N, (n+1)%N);
	}
	else {
		q.x = dameX(R, N, (n+1)%N);
		q.y = y;
		q.z = dameZ(R, N, (n+1)%N);
	}
	r.x = dameX(R+dR, N, n);
	r.y = y+dy;
	r.z = dameZ(R+dR, N, n);
	v = vector(p, q);
	w = vector(p, r);
	normal = productoVectorial(w, v);

	return (normal);
}

void cinta(float R, float dR, float y, float dy, float N) {
  int i;
  float x, z;
  Vector3D n;

  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  glBegin(GL_TRIANGLE_STRIP);
  for(i = 0; i <= N; i++) {
    x = dameX(R, N, i);
    z = dameZ(R, N, i);
    n = normal(R, dR, y, dy, N, i);
    //glTexCoord2f(x/R, y+0.5f);
    glNormal3f(n.a, n.b, n.c);
    glVertex3f(x, y, z);
    //glTexCoord2f(x/R, y+dy+0.5f);
    x = dameX(R+dR, N, i);
    z = dameZ(R+dR, N, i);
    n = normal(R+dR, dR, y, dy, N, i);
    glNormal3f(n.a, n.b, n.c);
    glVertex3f(x, y+dy, z);
  }
  glEnd();
}

void formaAlambre(float H, int N, float(*f)(float y)) {
  int i;
  float y, r1, r2;
  
  for(i = 0; i < N; i++) {
    y = i*H/N-(H/2);
    r1 = f(y);
    r2 = f(y+(H/N));
    tira(r1, r2-r1, y, H/N, N);
  }
}

void cilindroAlambre(int N) {
	formaAlambre(1.0f, N, fcl);
}

void conoAlambre(int N) {
	formaAlambre(1.0f, N, fc);
}

float fc(float y) {
	return (y+0.5f);
}

void conoSolido(int N) {
	formaSolida(1.0f, N, fc);
}

float fcl(float y) {
	return(0.5);
}

void cilindroSolido(int N) {
	formaSolida(1.0f, N, fcl);
}

void formaSolida(float H, int N, float(*f)(float y)) {
  int i;
  float y, r1, r2;
  
  for(i = 0; i < N; i++) {
    y = i*H/N-(H/2);
    r1 = f(y);
    r2 = f(y+(H/N));
    cinta(r1, r2-r1, y, H/N, N);
    //tira(r1, r2-r1, y, H/N, N);
  }
}


void escena(void) {
}

