/*
* vector2d.h
* DIN Is Noise is copyright (c) 2006-2024 Jagannathan Sampath
* For more information, please visit http://dinisnoise.org/
*/

#ifndef __vector2d
#define __vector2d

#include <math.h>
#include "point.h"

template <class T> inline void direction (point<T>& p1p2, point<T>& p1, point<T>& p2) {
  p1p2.x = p2.x - p1.x;
  p1p2.y = p2.y - p1.y;
}

template<class T> inline void direction (T& dx, T& dy, const T& x1, const T& y1, const T& x2, const T& y2) {
  dx = x2 - x1;
  dy = y2 - y1;
}

template <class T> inline void perpendicular (point<T>& r, point<T>& p) {
  r.x = p.y;
  r.y = -p.x;
}


template <class T> inline void perpendicular (T& px, T& py, const T& vx, const T& vy) {
  px = vy;
  py = -vx;
}

template <class T> inline int is_zero_vec (const T& x1, const T& y1, const T& e = 0.0001) {
	return (equals (x1, (T)0.0, e) && equals (y1, (T)0.0, e));
}

template <class T> inline double magnitude (const T& x1, const T& y1, const T& x2, const T& y2) {
  T dx = x2 - x1, dy = y2 - y1;
  return sqrt ((double) (dx * dx + dy * dy));
}

template <class T> inline double magnitude (const T& vx, const T& vy) {
  return sqrt ((double) (vx * vx + vy * vy));
}

template <class T> inline double magnitude (point<T>& p) {
  return sqrt ((double) (p.x * p.x + p.y * p.y));
}

template <class T> inline double magnitude2 (const T& x1, const T& y1, const T& x2, const T& y2) {
  T dx = x2 - x1, dy = y2 - y1;
  return (dx * dx + dy * dy);
}

template <class T> inline T magnitude2 (const T& vx, const T& vy) {
  return (vx * vx + vy * vy);
}


template<class S, class T> inline double unit_vector (S& ux, S& uy, const T& x1, const T& y1, const T& x2, const T& y2, const S& zx = 0, const S& zy = 0) {
  // unit vector joining x1,y1 & x2,y2
  T dx, dy; direction (dx, dy, x1, y1, x2, y2);
  double mag = magnitude (dx, dy);
  if (mag > 0) {
    ux = (S) (dx / mag);
    uy = (S) (dy / mag);
  } else {
    ux = zx;
		uy = zy;
  }
  return mag;
}

template <class T> inline double unit_vector (T& ux, T& uy, const T& vx, const T& vy) {
  double mag = magnitude (vx, vy);
  if (mag > 0) {
    ux = vx / mag;
    uy = vy / mag;
  } else {
    ux = uy = 0;
  }
  return mag;
}

template <class T> inline double unit_vector (point<T>& u, point<T>& v) {
  double mag = magnitude (v.x, v.y);
  if (mag > 0) {
    u.x = v.x / mag;
    u.y = v.y / mag;
  } else {
    u.x = u.y = 0;
  }
  return mag;
}


template <typename T> inline void rotate_vector (T& vx, T& vy, float angle) {
  T rx = vx * cos (angle) - vy * sin (angle);
  T ry = vx * sin (angle) + vy * cos (angle);
  vx = rx;
  vy = ry;
}

#endif
