#include "main.h"

triangle *object;
int lines=0;

int initobject( char *file ){
  /*float values[9];*/
  FILE *fp=NULL;
  unsigned int color;
  int ch,i;

  if( file != NULL )
    fp = fopen(file, "rb" );
  else
    fp = fopen("test.tri", "rb" );

  if( fp == NULL){
    perror( "Failed to load file " );
    return 0;
  }

  lines = 0;

  while( (ch=fgetc(fp)) != EOF )
    { if( ch == '\n' ) lines++; }

  object = malloc( sizeof(triangle)*lines );

  rewind( fp );

  for( i = 0; i < lines; i++ ){
    fscanf(fp, "%f %f %f", &object[i].vertices[0].x, &object[i].vertices[0].y, 
&object[i].vertices[0].z);
    fscanf(fp, "%f %f %f", &object[i].vertices[1].x, &object[i].vertices[1].y, 
&object[i].vertices[1].z);
    fscanf(fp, "%f %f %f", &object[i].vertices[2].x, &object[i].vertices[2].y, 
&object[i].vertices[2].z);
    fscanf(fp, "%x", &color );


    object[i].normal = calc_normals( object[i] );

    object[i].r = (color & 0xFF0000) >> 16;
    object[i].g = (color & 0xFF00) >> 8;
    object[i].b = (color & 0xFF );
  }

  return 1;
}

void drawObject()
{
   int i,j;


  for( i = 0; i < lines; i++ ){
    glColor3f( (float)object[i].r/255.0f, (float)object[i].g/255.0f, (float)object[i].b/255.0f );

    glBegin( GL_TRIANGLES );
        glNormal3f( object[i].normal.x, object[i].normal.y, object[i].normal.z );

        for( j = 0; j < 3; j++ ){
          glVertex3f(object[i].vertices[j].x, object[i].vertices[j].y, object[i].vertices[j].z);
        }
    glEnd();

#ifdef DEBUG
    glBegin( GL_LINES );
        glColor3f( 1.0f,0.0f, 0.0f );
        glVertex3f( ((object[i].vertices[0].x+object[i].vertices[1].x+object[i].vertices[2].x)/3),
                ((object[i].vertices[0].y+object[i].vertices[1].y+object[i].vertices[2].y)/3),
                ((object[i].vertices[0].z+object[i].vertices[1].z+object[i].vertices[2].z)/3));
        glVertex3f( ((object[i].vertices[0].x+object[i].vertices[1].x+object[i].vertices[2].x)/3)
                +object[i].normal.x,
                ((object[i].vertices[0].y+object[i].vertices[1].y+object[i].vertices[2].y)/3)
                +object[i].normal.y,
                ((object[i].vertices[0].z+object[i].vertices[1].z+object[i].vertices[2].z)/3)
                +object[i].normal.z);
    glEnd();
#endif

  }
  return;
}

