src/Vector.hh
author terom
Sat, 06 Dec 2008 16:17:05 +0000
changeset 221 fbc5db6fce45
parent 185 25becd2cb026
child 247 b87f68be579f
permissions -rw-r--r--
reorganize the weapons code and input handling code
#ifndef VECTOR_HH
#define VECTOR_HH

#include <iostream>
#include <cmath>

/**
 * A 2D Vector class. Implements standard vector operations.
 */
template <typename T>
class _Vector {
public:
    T x;
    T y;

    /**
     * Default constructor.
     */
    _Vector() : x(0), y(0) {}
    
    /**
     * Constuctor.
     *
     * @param x Initial x-coordinate
     * @param y Initial y-coordinate
     */
    _Vector(T x, T y) : x(x), y(y) {}

    /**
     * Copy constructor.
     *
     * @param v Vector to be copied.
     */
    _Vector(const _Vector &v) : x(v.x), y(v.y) {}

    // Operator declarations
    void operator=(const _Vector &v) {
        this->x = v.x;
        this->y = v.y;
    }
    _Vector operator+(const _Vector &v) const {
        return _Vector(this->x+v.x, this->y+v.y);
    }
    _Vector operator-(const _Vector &v) const {
        return _Vector(this->x-v.x, this->y-v.y);
    }
    _Vector operator*(const T &scalar) const {
        return _Vector(this->x*scalar, this->y*scalar);
    }
    T operator*(const _Vector &v) const {
        return (this->x*v.x + this->y*v.y);
    }
    _Vector operator/(const T &d) const {
        return _Vector(this->x/d, this->y/d);
    }
    void operator+=(const _Vector &v) {
        *this = *this + v;
    }
    void operator-=(const _Vector &v) {
        *this = *this - v;
    }
    void operator*=(const T &scalar) {
        *this = *this * scalar;
    }
    void operator/=(const T &scalar) {
        *this = *this / scalar;
    }

    // Other operations
    T length() const {
        return sqrt(sqrLength());
    }
    T sqrLength() const {
        return (this->x * this->x) + (this->y * this->y);
    }
    _Vector roundToInt() const {
        return _Vector((int)(x), (int)(y));
    }

    // test Vectors as booleans
    // XXX: comparing floats against zero... is a bad idea?
    bool zero(void) const {
        return x == 0 && y == 0;
    }
};

// Unary operators
template<typename T>
_Vector<T> operator*(const T &scalar, const _Vector<T> v) {
    return (v * scalar);
} 

// Comparison operators
template<typename T>
bool operator==(const _Vector<T> &v1, const _Vector<T> &v2) {
    return ((v1.x == v2.x) && (v1.y == v2.y));
}
template<typename T>
bool operator!=(const _Vector<T> &v1, const _Vector<T> &v2) {
    return !(v1 == v2);
}

// Output operator
template<typename T>
std::ostream& operator<<(std::ostream &s, const _Vector<T> &v) {
    return s<<"("<<v.x<<", "<<v.y<<")";
}

// Standard vector
typedef _Vector<float> Vector;

#endif