#include "MathLib.h"
#include "Program.h"

int randn(int n) {
  return rand()%n + 1;
}


float fastsqrt(float val) {
  int tmp = *(int *)&val;
  tmp -= 1<<23; /* Remove last bit to not let it go to mantissa */
  /* tmp is now an approximation to logbase2(val) */
  tmp >>= 1;    /* divide by 2 */
  tmp += 1<<29; /* add 64 to exponent: (e+127)/2 =(e/2)+63, */
                /* that represents (e/2)-64 but we want e/2 */
  return *(float *)&tmp;
}


float DistanceBetweenPoints(float x, float y, float tx, float ty) {
  float dx, dy;
  float dist;
  dx = tx - x; dx = dx*dx;
  dy = ty - y; dy = dy*dy;
  dist = dx + dy;
  dist = fastsqrt(dist);

  return dist;
}



float FixRadAngle(float v) {
  float total;
  total = AngleToRad(360);
  while (v < -total) v += total;
  while (v > total) v -= total;
  return v;
}


float mabs(float v) {
  return (v < 0 ? -v : v);
}

bool InsideRect(float a, float b, float x, float y, float fx, float fy) {
  if ((a>x)&&(a<fx)&&(b>y)&&(b<fy)) return true;
  return false;
}

float AngleToRad(float a) {
  return a * DEGTORAD;
}

float RadToAngle(float a) {
  return a / DEGTORAD;
}


float GlobalZoomXFactor=1;
float GlobalZoomYFactor=1;
float GlobalZoom=1.0;



void UpdateGlobalZoomFactor() {
  GlobalZoomXFactor = (SCREEN_W / (768.0 * AspectRatio));
  GlobalZoomYFactor = (SCREEN_H / 768.0);
}

float RSX(float v) {
  return v * ((float)SCREEN_W*GlobalZoom / ((768.0) * AspectRatio));
}

float RSY(float v) {
  return v * ((float)SCREEN_H*GlobalZoom / (768.0));
}

float SRX(float v) {
  return v / ((float)SCREEN_W*GlobalZoom / ((768.0) * AspectRatio));
}

float SRY(float v) {
  return v / ((float)SCREEN_H*GlobalZoom / (768.0));
}

float BSX(float v) {
  return (v/1024.0) * SCREEN_W;
}

float BSY(float v) {
  return (v/768.0) * SCREEN_H;
}

int sgn(float v) {
  if (v >= 0) return 1;
  else return -1;
}

Vec2D Perpendicular(Vec2D v) {
  float t;
  t = -v.x;
  v.x = v.y;
  v.y = t;
  return v;
}


void BoolSwitch(bool v) {
  v = (v == 1 ? 0 : 1);
}

float SnapFloat(float v, float l1, float l2) {
  if (v < l1) v = l1;
  if (v > l2) v = l2;
  return v;
}
