/* vector3.cpp 3D vector algebra. Requires the GL/glut library CS537 George Kamberov */ #include #include #include #include #include"vector3.h" vector3::vector3() //creates a zero vector { for (int i=0; i<3; i++) c[i] =0.0; } vector3::vector3(double x, double y, double z) { c[0]=x; c[1]=y; c[2]=z; } vector3::vector3(double* array) //converts an array into a vector { for (int i=0; i<3; i++) c[i] =array[i]; } /* vector agebra */ vector3 operator* (double s, const vector3 vector) //scaling { vector3 u; for (int i=0; i<3; i++) u.c[i] =s*vector.c[i]; return u; } vector3 cross_prod(const vector3 u, const vector3 v) //cross product { vector3 w; w.c[0] = u.c[1]*v.c[2] - u.c[2]*v.c[1]; w.c[1] = u.c[2]*v.c[0] -u.c[0]*v.c[2] ; w.c[2] = u.c[0]*v.c[1] - u.c[1]*v.c[0]; return w; } double dot_prod(const vector3 u, const vector3 v) //scalar product { double prdct; prdct = u.c[1]*v.c[1] + u.c[2]*v.c[2] + u.c[0]*v.c[0]; return prdct; } double norm(const vector3 u) { return sqrt( u.c[1]*u.c[1] + u.c[2]*u.c[2] + u.c[0]*u.c[0]); } vector3 normalize(const vector3 u) { return (1/(sqrt( u.c[1]*u.c[1] + u.c[2]*u.c[2] + u.c[0]*u.c[0])))*u; } vector3 operator- (const vector3 u, const vector3 v) { vector3 w; for (int i=0; i<3;i++) w.c[i] = u.c[i]-v.c[i]; return w; } /* comparisons */ bool operator== (const vector3 u, const vector3 v) { for (int i=0; i<3;i++) if (u.c[i]!=v.c[i]) return false; return true; } bool operator!= (const vector3 u, const vector3 v) { for (int i=0; i<3;i++) if (u.c[i]!=v.c[i]) return true; return false; } bool colinear(const vector3 u, const vector3 v) { vector3 zero; if (cross_prod(u,v)==zero) return true; return false; } /* Misc */ ostream& operator<< (ostream& co, const vector3& v) { co << "[" << v.c[0] << ", " << v.c[1] << ", " << v.c[2] << "]" << endl; return co; } /* frames */ frame::frame(vector3 nv, vector3 up) { double norm; vector3 w=cross_prod(up,nv); if (colinear(nv, up)) {cout << "Error: Colinear up and view directions. \n"; exit(1);} norm = sqrt(dot_prod(nv,nv)); n =( 1./norm)*nv; norm = sqrt(dot_prod(w,w)); u = ( 1./norm)*w; v=cross_prod(n,u); }