CMU462 Library Documentation  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 <ostream>
5 #include <cmath>
6 
7 namespace CMU462 {
8 
12 class Vector2D {
13  public:
14 
15  // components
16  double x, y;
17 
22  Vector2D() : x( 0.0 ), y( 0.0 ) { }
23 
28  Vector2D( double x, double y ) : x( x ), y( y ) { }
29 
34  Vector2D( const Vector2D& v ) : x( v.x ), y( v.y ) { }
35 
36  // additive inverse
37  inline Vector2D operator-( void ) const {
38  return Vector2D( -x, -y );
39  }
40 
41  // addition
42  inline Vector2D operator+( const Vector2D& v ) const {
43  Vector2D u = *this;
44  u += v;
45  return u;
46  }
47 
48  // subtraction
49  inline Vector2D operator-( const Vector2D& v ) const {
50  Vector2D u = *this;
51  u -= v;
52  return u;
53  }
54 
55  // right scalar multiplication
56  inline Vector2D operator*( double r ) const {
57  Vector2D vr = *this;
58  vr *= r;
59  return vr;
60  }
61 
62  // scalar division
63  inline Vector2D operator/( double r ) const {
64  Vector2D vr = *this;
65  vr /= r;
66  return vr;
67  }
68 
69  // add v
70  inline void operator+=( const Vector2D& v ) {
71  x += v.x;
72  y += v.y;
73  }
74 
75  // subtract v
76  inline void operator-=( const Vector2D& v ) {
77  x -= v.x;
78  y -= v.y;
79  }
80 
81  // scalar multiply by r
82  inline void operator*=( double r ) {
83  x *= r;
84  y *= r;
85  }
86 
87  // scalar divide by r
88  inline void operator/=( double r ) {
89  x /= r;
90  y /= r;
91  }
92 
96  inline double norm( void ) const {
97  return sqrt( x*x + y*y );
98  }
99 
103  inline double norm2( void ) const {
104  return x*x + y*y;
105  }
106 
110  inline Vector2D unit( void ) const {
111  return *this / this->norm();
112  }
113 
114 
115 }; // clasd Vector2D
116 
117 // left scalar multiplication
118 inline Vector2D operator*( double r, const Vector2D& v ) {
119  return v*r;
120 }
121 
122 // inner product
123 inline double dot( const Vector2D& v1, const Vector2D& v2 ) {
124  return v1.x*v2.x + v1.y*v2.y;
125 }
126 
127 // cross product
128 inline double cross( const Vector2D& v1, const Vector2D& v2 ) {
129  return v1.x*v2.y - v1.y*v2.x;
130 }
131 
132 // prints components
133 std::ostream& operator<<( std::ostream& os, const Vector2D& v );
134 
135 } // namespace CMU462
136 
137 #endif // CMU462_VECTOR2D_H
Vector2D()
Constructor.
Definition: vector2D.h:22
double norm2(void) const
Returns norm squared.
Definition: vector2D.h:103
double norm(void) const
Returns norm.
Definition: vector2D.h:96
Vector2D(double x, double y)
Constructor.
Definition: vector2D.h:28
Definition: color.cpp:10
Defines 2D vectors.
Definition: vector2D.h:12
Vector2D(const Vector2D &v)
Constructor.
Definition: vector2D.h:34
Vector2D unit(void) const
Returns unit vector parallel to this one.
Definition: vector2D.h:110