Blob Blame History Raw
#ifndef GEOMETRY_H
#define GEOMETRY_H


#include "math.h"


#ifndef PI
#define PI 3.14159265358979323846
#endif


#define PRECISION  1e-5
#define PRECISION2 1e-10


typedef struct { double x, y; } Vec;


static inline Vec vec(double x, double y) { return (Vec){x, y}; }
static inline Vec vecxy(double xy) { return vec(xy, xy); }
static inline Vec vzero() { return vecxy(0); }
static inline Vec vone() { return vecxy(1); }

static inline Vec vadd(Vec a, Vec b) { return vec(a.x + b.x, a.y + b.y); }
static inline Vec vsub(Vec a, Vec b) { return vec(a.x - b.x, a.y - b.y); }
static inline Vec vmul(Vec v, double k) { return vec(v.x*k, v.y*k); }
static inline Vec vdiv(Vec v, double k) { return vec(v.x/k, v.y/k); }
static inline Vec vmulv(Vec a, Vec b) { return vec(a.x*b.x, a.y*b.y); }
static inline Vec vdivv(Vec a, Vec b) { return vec(a.x/b.x, a.y/b.y); }
static inline Vec vlintr(Vec a, Vec b, double k) { return vadd(vmul(a, 1-k), vmul(b, k)); }
static inline Vec vlintrv(Vec a, Vec b, Vec k) { return vadd(vmulv(a, vsub(vone(), k)), vmulv(b, k)); }

static inline Vec vneg(Vec v) { return vec(-v.x, -v.y); }
static inline Vec vnegx(Vec v) { return vec(-v.x, v.y); }
static inline Vec vnegy(Vec v) { return vec(v.x, -v.y); }
static inline Vec vabs(Vec v) { return vec(fabs(v.x), fabs(v.y)); }
static inline Vec vabsx(Vec v) { return vec(fabs(v.x), v.y); }
static inline Vec vabsy(Vec v) { return vec(v.x, fabs(v.y)); }

static inline double vdot(Vec a, Vec b) { return a.x*b.x + a.y*b.y; }
static inline double vlen2(Vec v) { return vdot(v, v); }
static inline double vlen(Vec v) { return sqrt(vlen2(v)); }
static inline double vdist2(Vec a, Vec b) { return vlen2(vsub(b, a)); }
static inline double vdist(Vec a, Vec b) { return sqrt(vdist2(b, a)); }

static inline Vec vrot90(Vec v) { return vec(-v.y, v.x); }
static inline Vec vrot180(Vec v) { return vneg(v); }
static inline Vec vrot270(Vec v) { return vec(v.y, -v.x); }
static inline Vec vtranspose(Vec v) { return vec(v.y, v.x); }

static inline Vec vturn(Vec v, Vec dx) { return vec(vdot(v, vnegy(dx)), vdot(v, vtranspose(dx))); }
static inline Vec vunturn(Vec v, Vec dx) { return vec(vdot(v, dx), vdot(v, vrot90(dx))); }
static inline Vec vtrans(Vec v, Vec dx, Vec o) { return vadd(vturn(v, dx), o); }
static inline Vec vuntrans(Vec v, Vec dx, Vec o) { return vunturn(vsub(v, o), dx); }

static inline Vec vcossin(double rad) { return vec(cos(rad), sin(rad)); }
static inline Vec vcossind(double deg) { return vcossin(PI/180*deg); }
static inline double vangle(Vec v) { return atan2(v.y, v.x); }
static inline double vangled(Vec v) { return 180/PI*vangle(v); }

static inline Vec vrot(Vec v, double rad) { return vturn(v, vcossin(rad)); }
static inline Vec vrotd(Vec v, double deg) { return vturn(v, vcossind(deg)); }


#endif