/***************************************************************************
                          vectorMath.c  -  vector math
                             -------------------
    begin                : Wed Apr 16 2003
    copyright            : (C) 2003 by Nick Winters
    email                : n_winters99 yahoo.com
 ***************************************************************************/

#include "includes.h"

float vec_dot(vec3 u, vec3 v) {
  // dot product
  return u.x*v.x + u.y*v.y + u.z*v.z;
}

vec3 vec_cross(vec3 u, vec3 v) {
  // cross product
  //  | i   j   k   |
  //  | ux  uy  uz  |
  //  | vx  vy  vz  |
  //  (uy*vz-uz*vy)i - (ux*vz-uz*vx)j + (ux*vy-uy*vx)k
  //  (uy*vz-uz*vy)i + (uz*vx-ux*vz)j + (ux*vy-uy*vx)k
  vec3 ans;
  ans.x = u.y*v.z-u.z*v.y;
  ans.y = u.z*v.x-u.x*v.z;
  ans.z = u.x*v.y-u.y*v.x;
  return ans;
}

float vec_mag(vec3 u) {
  // magnitude
  return (float)sqrt(u.x*u.x + u.y*u.y + u.z*u.z);
}

float vec_mag_squared(vec3 u) {
  // magnitude squared
  return u.x*u.x + u.y*u.y + u.z*u.z;
}

void vec_normalize(vec3 *u) {
  // normalizes the vector passed in
  float n;
  n = vec_mag(*u);
  if (n) {
    u->x = u->x/n;
    u->y = u->y/n;
    u->z = u->z/n;
  } else {
    u->x = 0.0;
    u->y = 0.0;
    u->z = 1.0;
  }    
}

vec3 vec_between_points(vec3 u, vec3 v) {
  // returns the vector from point u to point v
  vec3 ans;
  ans.x = v.x-u.x;
  ans.y = v.y-u.y;
  ans.z = v.z-u.z;
  return ans;
}

vec3 vec_scalar_multiple(vec3 u, float s) {
  // returns the vector from point u to point v
  u.x *= s;
  u.y *= s;
  u.z *= s;
  return u;
}

vec3 vec_add(vec3 u, vec3 v) {
  u.x += v.x;
  u.y += v.y;
  u.z += v.z;
  return u;
}  

vec3 vec_subtract(vec3 u, vec3 v) {
  u.x -= v.x;
  u.y -= v.y;
  u.z -= v.z;
  return u;
}  
