CMU462 Library  1.0
15-462/15-662: Computer Graphics (Fall 2015)
vector2D.h
1 #ifndef CMU462_VECTOR2D_H
2 #define CMU462_VECTOR2D_H
3 
4 #include "CMU462.h"
5 
6 #include <ostream>
7 #include <cmath>
8 
9 namespace CMU462 {
10 
14 class Vector2D {
15  public:
16 
17  // components
18  double x, y;
19 
24  Vector2D() : x( 0.0 ), y( 0.0 ) { }
25 
30  Vector2D( double x, double y ) : x( x ), y( y ) { }
31 
36  Vector2D( const Vector2D& v ) : x( v.x ), y( v.y ) { }
37 
38  // additive inverse
39  inline Vector2D operator-( void ) const {
40  return Vector2D( -x, -y );
41  }
42 
43  // addition
44  inline Vector2D operator+( const Vector2D& v ) const {
45  Vector2D u = *this;
46  u += v;
47  return u;
48  }
49 
50  // subtraction
51  inline Vector2D operator-( const Vector2D& v ) const {
52  Vector2D u = *this;
53  u -= v;
54  return u;
55  }
56 
57  // right scalar multiplication
58  inline Vector2D operator*( double r ) const {
59  Vector2D vr = *this;
60  vr *= r;
61  return vr;
62  }
63 
64  // scalar division
65  inline Vector2D operator/( double r ) const {
66  Vector2D vr = *this;
67  vr /= r;
68  return vr;
69  }
70 
71  // add v
72  inline void operator+=( const Vector2D& v ) {
73  x += v.x;
74  y += v.y;
75  }
76 
77  // subtract v
78  inline void operator-=( const Vector2D& v ) {
79  x -= v.x;
80  y -= v.y;
81  }
82 
83  // scalar multiply by r
84  inline void operator*=( double r ) {
85  x *= r;
86  y *= r;
87  }
88 
89  // scalar divide by r
90  inline void operator/=( double r ) {
91  x /= r;
92  y /= r;
93  }
94 
98  inline double norm( void ) const {
99  return sqrt( x*x + y*y );
100  }
101 
105  inline double norm2( void ) const {
106  return x*x + y*y;
107  }
108 
112  inline Vector2D unit( void ) const {
113  return *this / this->norm();
114  }
115 
116 
117 }; // clasd Vector2D
118 
119 // left scalar multiplication
120 inline Vector2D operator*( double r, const Vector2D& v ) {
121  return v*r;
122 }
123 
124 // inner product
125 inline double dot( const Vector2D& v1, const Vector2D& v2 ) {
126  return v1.x*v2.x + v1.y*v2.y;
127 }
128 
129 // cross product
130 inline double cross( const Vector2D& v1, const Vector2D& v2 ) {
131  return v1.x*v2.y - v1.y*v2.x;
132 }
133 
134 // prints components
135 std::ostream& operator<<( std::ostream& os, const Vector2D& v );
136 
137 } // namespace CMU462
138 
139 #endif // CMU462_VECTOR2D_H
Vector2D()
Constructor.
Definition: vector2D.h:24
double norm2(void) const
Returns norm squared.
Definition: vector2D.h:105
double norm(void) const
Returns norm.
Definition: vector2D.h:98
Vector2D(double x, double y)
Constructor.
Definition: vector2D.h:30
Definition: CMU462.h:8
Defines 2D vectors.
Definition: vector2D.h:14
Vector2D(const Vector2D &v)
Constructor.
Definition: vector2D.h:36
Vector2D unit(void) const
Returns unit vector parallel to this one.
Definition: vector2D.h:112