Changeset 240


Ignore:
Timestamp:
Jan 19, 2011, 9:33:51 PM (10 years ago)
Author:
sam
Message:

Various vector operators including casts and scalar-vector operations.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/matrix.h

    r239 r240  
    2020
    2121#define VECTOR_OP(elems, op) \
    22     inline Vec##elems<T> operator op(Vec##elems<T> const &val) const \
     22    template<typename U> \
     23    inline Vec##elems<T> operator op(Vec##elems<U> const &val) const \
    2324    { \
    2425        Vec##elems<T> ret; \
     
    3839
    3940#define OPERATORS(elems) \
    40     T& operator[](int n) { return *(&x + n); } \
    41     T const& operator[](int n) const { return *(&x + n); } \
     41    inline T& operator[](int n) { return *(&x + n); } \
     42    inline T const& operator[](int n) const { return *(&x + n); } \
    4243    \
    4344    VECTOR_OP(elems, -) \
     
    5152    SCALAR_OP(elems, /) \
    5253    \
     54    template<typename U> \
     55    inline operator Vec##elems<U>() const \
     56    { \
     57        Vec##elems<U> ret; \
     58        for (int n = 0; n < elems; n++) \
     59            ret[n] = static_cast<U>((*this)[n]); \
     60        return ret; \
     61    } \
     62    \
    5363    inline float len() const \
    5464    { \
     
    6171template <typename T> struct Vec2
    6272{
    63     Vec2() { x = y = 0; }
    64     Vec2(T _x, T _y) { x = _x; y = _y; }
     73    inline Vec2() { x = y = 0; }
     74    inline Vec2(T val) { x = y = val; }
     75    inline Vec2(T _x, T _y) { x = _x; y = _y; }
    6576
    6677    OPERATORS(2)
     
    7586template <typename T> struct Vec3
    7687{
    77     Vec3() { x = y = z = 0; }
    78     Vec3(T _x, T _y, T _z) { x = _x; y = _y; z = _z; }
     88    inline Vec3() { x = y = z = 0; }
     89    inline Vec3(T val) { x = y = z = val; }
     90    inline Vec3(T _x, T _y, T _z) { x = _x; y = _y; z = _z; }
    7991
    8092    OPERATORS(3)
     
    88100typedef Vec3<int> Int3;
    89101
     102#define SCALAR_GLOBAL(elems, op, U) \
     103    template<typename T> \
     104    static inline Vec##elems<U> operator op(U const &val, \
     105                                            Vec##elems<T> const &that) \
     106    { \
     107        Vec##elems<U> ret; \
     108        for (int n = 0; n < elems; n++) \
     109            ret[n] = val op that[n]; \
     110        return ret; \
     111    }
     112
     113#define SCALAR_GLOBAL2(elems, op) \
     114    SCALAR_GLOBAL(elems, op, int) \
     115    SCALAR_GLOBAL(elems, op, float)
     116
     117#define GLOBALS(elems) \
     118    SCALAR_GLOBAL2(elems, -) \
     119    SCALAR_GLOBAL2(elems, +) \
     120    SCALAR_GLOBAL2(elems, *) \
     121    SCALAR_GLOBAL2(elems, /)
     122
     123GLOBALS(2)
     124GLOBALS(3)
     125
    90126#endif // __DH_MATRIX_H__
    91127
Note: See TracChangeset for help on using the changeset viewer.