```/* <![CDATA[ */
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef VECTOR2_H_
6#define VECTOR2_H_
7
8#include <stdlib.h>
9#include <cmath>
10#include <limits>
11
12// A small class that encapsulates a 2D vector.  Provides a few simple
13// operations.
14
15class Vector2 {
16 public:
17  Vector2() : x_(0.0), y_(0.0) {}
18  Vector2(double x, double y) : x_(x), y_(y) {}
19  ~Vector2() {}
20
21  // Create a new vector that represents a - b.
22  static Vector2 Difference(const Vector2& a, const Vector2& b) {
23    Vector2 diff(a.x() - b.x(), a.y() - b.y());
24    return diff;
25  }
26
27  // The magnitude of this vector.
28  double Magnitude() const {
29    return sqrt(x_ * x_ + y_ * y_);
30  }
31
32  // Add |vec| to this vector.  Works in-place.
33  void Add(const Vector2& vec) {
34    x_ += vec.x();
35    y_ += vec.y();
36  }
37
38  // Normalize this vector in-place.  If the vector is degenerate (size 0)
39  // then do nothing.
40  void Normalize() {
41    double mag = Magnitude();
42    if (fabs(mag) < std::numeric_limits<double>::epsilon())
43      return;
44    Scale(1.0 / mag);
45  }
46
47  // Scale the vector in-place by |scale|.
48  void Scale(double scale) {
49    x_ *= scale;
50    y_ *= scale;
51  }
52
53  // Clamp a vector to a maximum magnitude.  Works on the vector in-place.
54  // @param max_mag The maximum magnitude of the vector.
55  void Clamp(double max_mag) {
56    double mag = Magnitude();
57    if (mag > max_mag) {
58      Scale(max_mag / mag);  // Does Normalize() followed by Scale(max_mag).
59    }
60  }
61
62  // Compute the "heading" of a vector - this is the angle in radians between
63  // the vector and the x-axis.
66    double angle = atan2(y_, x_);
67    return angle;
68  }
69
70  // Accessors and mutators for the coordinate values.
71  double x() const { return x_; }
72  void set_x(double x) { x_ = x; }
73
74  double y() const { return y_; }
75  void set_y(double y) { y_ = y; }
76
77  double x_;
78  double y_;
79};
80
81#endif  // VECTOR2_H_
82```