/********************************************************************
 FILENAME: TRIG.CPP
 AUTHOR  : JAKE HILL
 DATE    : 12/1/94

 Copyright (c) 1994 by Jake Hill:
 If you use any part of this code in your own project, please credit
 me in your documentation and source code.  Thanks.
********************************************************************/
#include "TRIG.HPP"

#include <dos.h>
#include <math.h>

float pi = 3.141592654;

// These are the lookup tables.
long sin_table[1024];
long tan_table[1024];
long cos_table[1024];
long inv_cos_table[1024];
long far inv_dist_table[10000];

// returns x * sin( a )
short xSinA( short x, unsigned short a )
{
   long tx = x;
   return (short) ( ( tx * sine(a) ) >> 16);
};

// returns x * cos( a )
short xCosA( short x, unsigned short a )
{
   long tx = x;
   return (short) ( ( tx * cosine(a) ) >> 16);
};

// returns sin( angle )
// This function is only used during the trig initialization process.
long Sine( long angle )
{
   double radians = ( angle * pi ) / 32768L;
   return  (long) (sin( radians ) * 65536L);
};

// returns cos( angle )
// This function is only used during the trig initialization process.
long Cosine( long angle )
{
   double radians = ( angle * pi ) / 32768L;
   return (long) (cos( radians ) * 65536L);
};

// returns tan( angle )
// This function is only used during the trig initialization process.
long Tangent( long angle )
{
   double radians = ( angle * pi ) / 32768L;
   return (long) (tan( radians ) * 65536L);
};

// returns 1/ ( cos(angle) )
// This function is only used during the trig initialization process.
long InvCosine( long angle )
{
   double radians = ( angle * pi ) / 32768L;

//   if ( cos( radians ) == 0 ) return 0;
   if ( cos( radians ) == 0 ) return 65536L;
   return (long) (65536L / cos( radians ));
};

// Generate a lookup table for distances based on width of screen.
// These values are used in the perspective calculations in order
// to avoid doing a 32 bit division during the rendering process.
// This function should be used whenever the screen width is changed.
void GenInvDistTable(long screen_width)
{
   long numerator = (screen_width / 2) * 65536L;

   for (long z=0; z<10000; z++)
      inv_dist_table[z] = numerator / (z+1);
}

// Initialize all of the lookup tables for use in the renderer.
void InitTrig(void)
{
   GenInvDistTable(320);

   for (long i=0; i<1024L; i++)
   {
      sin_table[i] = Sine( i*64L );
      cos_table[i] = Cosine( i*64L );
      tan_table[i] = Tangent( i*64L );
      inv_cos_table[i] = InvCosine( i*64L );
   }
};
