vec2.h代码如下:
#ifndef MATH_VEC2_H
#define MATH_VEC2_H
#include <algorithm>
#include <functional>
#include <cmath>
#define MATH_FLOAT_SMALL 1.0e-37f
#define MATH_TOLERANCE 2e-37f
#ifndef CCASSERT
#if COCOS2D_DEBUG > 0
// todo: minggo
// #if CC_ENABLE_SCRIPT_BINDING
// extern bool CC_DLL cc_assert_script_compatible(const char *msg);
// #define CCASSERT(cond, msg) do { \
// if (!(cond)) { \
// if (!cc_assert_script_compatible(msg) && strlen(msg)) \
// cocos2d::log("Assert failed: %s", msg); \
// CC_ASSERT(cond); \
// } \
// } while (0)
// #else
#define CCASSERT(cond, msg) CC_ASSERT(cond)
// #endif
#else
#define CCASSERT(cond, msg)
#endif
#define GP_ASSERT(cond) CCASSERT(cond, "")
#endif // CCASSERT
/** Clamp a value between from and to.
*/
inline float clampf(float value, float min_inclusive, float max_inclusive)
{
if (min_inclusive > max_inclusive) {
std::swap(min_inclusive, max_inclusive);
}
return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive;
}
class Mat4;
/**
* Defines a 2-element floating point vector.
*/
class Vec2
{
public:
/**
* The x coordinate.
*/
float x;
/**
* The y coordinate.
*/
float y;
/**
* Constructs a new vector initialized to all zeros.
*/
Vec2();
/**
* Constructs a new vector initialized to the specified values.
*
* @param xx The x coordinate.
* @param yy The y coordinate.
*/
Vec2(float xx, float yy);
/**
* Constructs a new vector from the values in the specified array.
*
* @param array An array containing the elements of the vector in the order x, y.
*/
Vec2(const float* array);
/**
* Constructs a vector that describes the direction between the specified points.
*
* @param p1 The first point.
* @param p2 The second point.
*/
Vec2(const Vec2& p1, const Vec2& p2);
/**
* Constructs a new vector that is a copy of the specified vector.
*
* @param copy The vector to copy.
*/
Vec2(const Vec2& copy);
/**
* Destructor.
*/
~Vec2();
/**
* Indicates whether this vector contains all zeros.
*
* @return true if this vector contains all zeros, false otherwise.
*/
inline bool isZero() const;
/**
* Indicates whether this vector contains all ones.
*
* @return true if this vector contains all ones, false otherwise.
*/
inline bool isOne() const;
/**
* Returns the angle (in radians) between the specified vectors.
*
* @param v1 The first vector.
* @param v2 The second vector.
*
* @return The angle between the two vectors (in radians).
*/
static float angle(const Vec2& v1, const Vec2& v2);
/**
* Adds the elements of the specified vector to this one.
*
* @param v The vector to add.
*/
inline void add(const Vec2& v);
/**
* Adds the specified vectors and stores the result in dst.
*
* @param v1 The first vector.
* @param v2 The second vector.
* @param dst A vector to store the result in.
*/
static void add(const Vec2& v1, const Vec2& v2, Vec2* dst);
/**
* Clamps this vector within the specified range.
*
* @param min The minimum value.
* @param max The maximum value.
*/
void clamp(const Vec2& min, const Vec2& max);
/**
* Clamps the specified vector within the specified range and returns it in dst.
*
* @param v The vector to clamp.
* @param min The minimum value.
* @param max The maximum value.
* @param dst A vector to store the result in.
*/
static void clamp(const Vec2& v, const Vec2& min, const Vec2& max, Vec2* dst);
/**
* Returns the distance between this vector and v.
*
* @param v The other vector.
*
* @return The distance between this vector and v.
*
* @see distanceSquared
*/
float distance(const Vec2& v) const;
/**
* Returns the squared distance between this vector and v.
*
* When it is not necessary to get the exact distance between
* two vectors (for example, when simply comparing the
* distance between different vectors), it is advised to use
* this method instead of distance.
*
* @param v The other vector.
*
* @return The squared distance between this vector and v.
*
* @see distance
*/
inline float distanceSquared(const Vec2& v) const;
/**
* Returns the dot product of this vector and the specified vector.
*
* @param v The vector to compute the dot product with.
*
* @return The dot product.
*/
inline float dot(const Vec2& v) const;
/**
* Returns the dot product between the specified vectors.
*
* @param v1 The first vector.
* @param v2 The second vector.
*
* @return The dot product between the vectors.
*/
static float dot(const Vec2& v1, const Vec2& v2);
/**
* Computes the length of this vector.
*
* @return The length of the vector.
*
* @see lengthSquared
*/
float length() const;
/**
* Returns the squared length of this vector.
*
* When it is not necessary to get the exact length of a
* vector (for example, when simply comparing the lengths of
* different vectors), it is advised to use this method
* instead of length.
*
* @return The squared length of the vector.
*
* @see length
*/
inline float lengthSquared() const;
/**
* Negates this vector.
*/
inline void negate();
/**
* Normalizes this vector.
*
* This method normalizes this Vec2 so that it is of
* unit length (in other words, the length of the vector
* after calling this method will be 1.0f). If the vector
* already has unit length or if the length of the vector
* is zero, this method does nothing.
*
* @return This vector, after the normalization occurs.
*/
void normalize();
/**
Get the normalized vector.
*/
Vec2 getNormalized() const;
/**
* Scales all elements of this vector by the specified value.
*
* @param scalar The scalar value.
*/
inline void scale(float scalar);
/**
* Scales each element of this vector by the matching component of scale.
*
* @param scale The vector to scale by.
*/
inline void scale(const Vec2& scale);
/**
* Rotates this vector by angle (specified in radians) around the given point.
*
* @param point The point to rotate around.
* @param angle The angle to rotate by (in radians).
*/
void rotate(const Vec2& point, float angle);
/**
* Sets the elements of this vector to the specified values.
*
* @param xx The new x coordinate.
* @param yy The new y coordinate.
*/
inline void set(float xx, float yy);
/**
* Sets the elements of this vector from the values in the specified array.
*
* @param array An array containing the elements of the vector in the order x, y.
*/
void set(const float* array);
/**
* Sets the elements of this vector to those in the specified vector.
*
* @param v The vector to copy.
*/
inline void set(const Vec2& v);
/**
* Sets this vector to the directional vector between the specified points.
*
* @param p1 The first point.
* @param p2 The second point.
*/
inline void set(const Vec2& p1, const Vec2& p2);
/**
* Sets the elements of this vector to zero.
*/
inline void setZero();
/**
* Subtracts this vector and the specified vector as (this - v)
* and stores the result in this vector.
*
* @param v The vector to subtract.
*/
inline void subtract(const Vec2& v);
/**
* Subtracts the specified vectors and stores the result in dst.
* The resulting vector is computed as (v1 - v2).
*
* @param v1 The first vector.
* @param v2 The second vector.
* @param dst The destination vector.
*/
static void subtract(const Vec2& v1, const Vec2& v2, Vec2* dst);
/**
* Updates this vector towards the given target using a smoothing function.
* The given response time determines the amount of smoothing (lag). A longer
* response time yields a smoother result and more lag. To force this vector to
* follow the target closely, provide a response time that is very small relative
* to the given elapsed time.
*
* @param target target value.
* @param elapsedTime elapsed time between calls.
* @param responseTime response time (in the same units as elapsedTime).
*/
inline void smooth(const Vec2& target, float elapsedTime, float responseTime);
/**
* Calculates the sum of this vector with the given vector.
*
* Note: this does not modify this vector.
*
* @param v The vector to add.
* @return The vector sum.
*/
inline const Vec2 operator+(const Vec2& v) const;
/**
* Adds the given vector to this vector.
*
* @param v The vector to add.
* @return This vector, after the addition occurs.
*/
inline Vec2& operator+=(const Vec2& v);
/**
* Calculates the sum of this vector with the given vector.
*
* Note: this does not modify this vector.
*
* @param v The vector to add.
* @return The vector sum.
*/
inline const Vec2 operator-(const Vec2& v) const;
/**
* Subtracts the given vector from this vector.
*
* @param v The vector to subtract.
* @return This vector, after the subtraction occurs.
*/
inline Vec2& operator-=(const Vec2& v);
/**
* Calculates the negation of this vector.
*
* Note: this does not modify this vector.
*
* @return The negation of this vector.
*/
inline const Vec2 operator-() const;
/**
* Calculates the scalar product of this vector with the given value.
*
* Note: this does not modify this vector.
*
* @param s The value to scale by.
* @return The scaled vector.
*/
inline const Vec2 operator*(float s) const;
/**
* Scales this vector by the given value.
*
* @param s The value to scale by.
* @return This vector, after the scale occurs.
*/
inline Vec2& operator*=(float s);
/**
* Returns the components of this vector divided by the given constant
*
* Note: this does not modify this vector.
*
* @param s the constant to divide this vector with
* @return a smaller vector
*/
inline const Vec2 operator/(float s) const;
/**
* Determines if this vector is less than the given vector.
*
* @param v The vector to compare against.
*
* @return True if this vector is less than the given vector, false otherwise.
*/
inline bool operator<(const Vec2& v) const;
/**
* Determines if this vector is greater than the given vector.
*
* @param v The vector to compare against.
*
* @return True if this vector is greater than the given vector, false otherwise.
*/
inline bool operator>(const Vec2& v) const;
/**
* Determines if this vector is equal to the given vector.
*
* @param v The vector to compare against.
*
* @return True if this vector is equal to the given vector, false otherwise.
*/
inline bool operator==(const Vec2& v) const;
/**
* Determines if this vector is not equal to the given vector.
*
* @param v The vector to compare against.
*
* @return True if this vector is not equal to the given vector, false otherwise.
*/
inline bool operator!=(const Vec2& v) const;
//code added compatible for Point
public:
/**
* @js NA
* @lua NA
*/
inline void setPoint(float xx, float yy);
/**
* @js NA
*/
bool equals(const Vec2& target) const;
/** @returns if points have fuzzy equality which means equal with some degree of variance.
@since v2.1.4
* @js NA
* @lua NA
*/
bool fuzzyEquals(const Vec2& target, float variance) const;
/** Calculates distance between point an origin
@return float
@since v2.1.4
* @js NA
* @lua NA
*/
inline float getLength() const {
return sqrtf(x*x + y * y);
};
/** Calculates the square length of a Vec2 (not calling sqrt() )
@return float
@since v2.1.4
* @js NA
* @lua NA
*/
inline float getLengthSq() const {
return dot(*this); //x*x + y*y;
};
/** Calculates the square distance between two points (not calling sqrt() )
@return float
@since v2.1.4
* @js NA
* @lua NA
*/
inline float getDistanceSq(const Vec2& other) const {
return (*this - other).getLengthSq();
};
/** Calculates the distance between two points
@return float
@since v2.1.4
* @js NA
* @lua NA
*/
inline float getDistance(const Vec2& other) const {
return (*this - other).getLength();
};
/** @returns the angle in radians between this vector and the x axis
@since v2.1.4
* @js NA
* @lua NA
*/
inline float getAngle() const {
return atan2f(y, x);
};
/** @returns the angle in radians between two vector directions
@since v2.1.4
* @js NA
* @lua NA
*/
float getAngle(const Vec2& other) const;
/** Calculates cross product of two points.
@return float
@since v2.1.4
* @js NA
* @lua NA
*/
inline float cross(const Vec2& other) const {
return x * other.y - y * other.x;
};
/** Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0
@return Vec2
@since v2.1.4
* @js NA
* @lua NA
*/
inline Vec2 getPerp() const {
return Vec2(-y, x);
};
/** Calculates midpoint between two points.
@return Vec2
@since v3.0
* @js NA
* @lua NA
*/
inline Vec2 getMidpoint(const Vec2& other) const
{
return Vec2((x + other.x) / 2.0f, (y + other.y) / 2.0f);
}
/** Clamp a point between from and to.
@since v3.0
* @js NA
* @lua NA
*/
inline Vec2 getClampPoint(const Vec2& min_inclusive, const Vec2& max_inclusive) const
{
return Vec2(clampf(x, min_inclusive.x, max_inclusive.x), clampf(y, min_inclusive.y, max_inclusive.y));
}
/** Run a math operation function on each point component
* absf, floorf, ceilf, roundf
* any function that has the signature: float func(float);
* For example: let's try to take the floor of x,y
* p.compOp(floorf);
@since v3.0
* @js NA
* @lua NA
*/
inline Vec2 compOp(std::function<float(float)> function) const
{
return Vec2(function(x), function(y));
}
/** Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0
@return Vec2
@since v2.1.4
* @js NA
* @lua NA
*/
inline Vec2 getRPerp() const {
return Vec2(y, -x);
};
/** Calculates the projection of this over other.
@return Vec2
@since v2.1.4
* @js NA
* @lua NA
*/
inline Vec2 project(const Vec2& other) const {
return other * (dot(other) / other.dot(other));
};
/** Complex multiplication of two points ("rotates" two points).
@return Vec2 vector with an angle of this.getAngle() + other.getAngle(),
and a length of this.getLength() * other.getLength().
@since v2.1.4
* @js NA
* @lua NA
*/
inline Vec2 rotate(const Vec2& other) const {
return Vec2(x*other.x - y * other.y, x*other.y + y * other.x);
};
/** Unrotates two points.
@return Vec2 vector with an angle of this.getAngle() - other.getAngle(),
and a length of this.getLength() * other.getLength().
@since v2.1.4
* @js NA
* @lua NA
*/
inline Vec2 unrotate(const Vec2& other) const {
return Vec2(x*other.x + y * other.y, y*other.x - x * other.y);
};
/** Linear Interpolation between two points a and b
@returns
alpha == 0 ? a
alpha == 1 ? b
otherwise a value between a..b
@since v2.1.4
* @js NA
* @lua NA
*/
inline Vec2 lerp(const Vec2& other, float alpha) const {
return *this * (1.f - alpha) + other * alpha;
};
/** Rotates a point counter clockwise by the angle around a pivot
@param pivot is the pivot, naturally
@param angle is the angle of rotation ccw in radians
@returns the rotated point
@since v2.1.4
* @js NA
* @lua NA
*/
Vec2 rotateByAngle(const Vec2& pivot, float angle) const;
/**
* @js NA
* @lua NA
*/
//返回向量坐标 x=cos(a) , y=sin(a)
static inline Vec2 forAngle(const float a)
{
return Vec2(cosf(a), sinf(a));
}
/** A general line-line intersection test
@param A the startpoint for the first line L1 = (A - B)
@param B the endpoint for the first line L1 = (A - B)
@param C the startpoint for the second line L2 = (C - D)
@param D the endpoint for the second line L2 = (C - D)
@param S the range for a hitpoint in L1 (p = A + S*(B - A))
@param T the range for a hitpoint in L2 (p = C + T*(D - C))
@return whether these two lines intersects.
Note that to truly test intersection for segments we have to make
sure that S & T lie within [0..1] and for rays, make sure S & T > 0
the hit point is C + T * (D - C);
the hit point also is A + S * (B - A);
@since 3.0
* @js NA
* @lua NA
*/
/**
线段相交检测 v3.0
参数:
A 为线段L1起点. L1 = (A - B)
B 为L1终点 . L1 = (A - B)
C 为线段L2起点. L2 = (C - D)
D 为L2终点 . L2 = (C - D)
S 为L1上计算各点的插值参数,计算方法为:p = A + S*(B - A)
T 为L2上计算各点的插值参数,计算方法为:p = C + T*(D - C)
*/
//直线AB与直线CD是否相交
static bool isLineIntersect(const Vec2& A, const Vec2& B,
const Vec2& C, const Vec2& D,
float *S = nullptr, float *T = nullptr);
/**
returns true if Line A-B overlap with segment C-D
@since v3.0
* @js NA
* @lua NA
*/
//直线AB与线段CD是否重叠
static bool isLineOverlap(const Vec2& A, const Vec2& B,
const Vec2& C, const Vec2& D);
/**
returns true if Line A-B parallel with segment C-D
@since v3.0
* @js NA
* @lua NA
*/
//直线AB与线段CD是否平行
static bool isLineParallel(const Vec2& A, const Vec2& B,
const Vec2& C, const Vec2& D);
/**
returns true if Segment A-B overlap with segment C-D
@since v3.0
* @js NA
* @lua NA
*/
//线段AB与线段CD是否重叠
static bool isSegmentOverlap(const Vec2& A, const Vec2& B,
const Vec2& C, const Vec2& D,
Vec2* S = nullptr, Vec2* E = nullptr);
/**
returns true if Segment A-B intersects with segment C-D
@since v3.0
* @js NA
* @lua NA
*/
//线段AB与线段CD是否相交
static bool isSegmentIntersect(const Vec2& A, const Vec2& B, const Vec2& C, const Vec2& D);
/**
returns the intersection point of line A-B, C-D
@since v3.0
* @js NA
* @lua NA
*/
//返回直线AB与直线CD的交点
static Vec2 getIntersectPoint(const Vec2& A, const Vec2& B, const Vec2& C, const Vec2& D);
/** equals to Vec2(0,0) */
static const Vec2 ZERO;
/** equals to Vec2(1,1) */
static const Vec2 ONE;
/** equals to Vec2(1,0) */
static const Vec2 UNIT_X;
/** equals to Vec2(0,1) */
static const Vec2 UNIT_Y;
/** equals to Vec2(0.5, 0.5) */
static const Vec2 ANCHOR_MIDDLE;
/** equals to Vec2(0, 0) */
static const Vec2 ANCHOR_BOTTOM_LEFT;
/** equals to Vec2(0, 1) */
static const Vec2 ANCHOR_TOP_LEFT;
/** equals to Vec2(1, 0) */
static const Vec2 ANCHOR_BOTTOM_RIGHT;
/** equals to Vec2(1, 1) */
static const Vec2 ANCHOR_TOP_RIGHT;
/** equals to Vec2(1, 0.5) */
static const Vec2 ANCHOR_MIDDLE_RIGHT;
/** equals to Vec2(0, 0.5) */
static const Vec2 ANCHOR_MIDDLE_LEFT;
/** equals to Vec2(0.5, 1) */
static const Vec2 ANCHOR_MIDDLE_TOP;
/** equals to Vec2(0.5, 0) */
static const Vec2 ANCHOR_MIDDLE_BOTTOM;
};
/**
* Calculates the scalar product of the given vector with the given value.
*
* @param x The value to scale by.
* @param v The vector to scale.
* @return The scaled vector.
*/
inline const Vec2 operator*(float x, const Vec2& v);
typedef Vec2 Point;
#include "Vec2.inl"
#endif // MATH_VEC2_H
vect2.inl代码如下:
#include "Vec2.h"
inline Vec2::Vec2()
: x(0.0f), y(0.0f)
{
}
inline Vec2::Vec2(float xx, float yy)
: x(xx), y(yy)
{
}
inline Vec2::Vec2(const float* array)
{
set(array);
}
inline Vec2::Vec2(const Vec2& p1, const Vec2& p2)
{
set(p1, p2);
}
inline Vec2::Vec2(const Vec2& copy)
{
set(copy);
}
inline Vec2::~Vec2()
{
}
inline bool Vec2::isZero() const
{
return x == 0.0f && y == 0.0f;
}
bool Vec2::isOne() const
{
return x == 1.0f && y == 1.0f;
}
inline void Vec2::add(const Vec2& v)
{
x += v.x;
y += v.y;
}
inline float Vec2::distanceSquared(const Vec2& v) const
{
float dx = v.x - x;
float dy = v.y - y;
return (dx * dx + dy * dy);
}
inline float Vec2::dot(const Vec2& v) const
{
return (x * v.x + y * v.y);
}
inline float Vec2::lengthSquared() const
{
return (x * x + y * y);
}
inline void Vec2::negate()
{
x = -x;
y = -y;
}
inline void Vec2::scale(float scalar)
{
x *= scalar;
y *= scalar;
}
inline void Vec2::scale(const Vec2& scale)
{
x *= scale.x;
y *= scale.y;
}
inline void Vec2::set(float xx, float yy)
{
this->x = xx;
this->y = yy;
}
inline void Vec2::set(const Vec2& v)
{
this->x = v.x;
this->y = v.y;
}
inline void Vec2::set(const Vec2& p1, const Vec2& p2)
{
x = p2.x - p1.x;
y = p2.y - p1.y;
}
void Vec2::setZero()
{
x = y = 0.0f;
}
inline void Vec2::subtract(const Vec2& v)
{
x -= v.x;
y -= v.y;
}
inline void Vec2::smooth(const Vec2& target, float elapsedTime, float responseTime)
{
if (elapsedTime > 0)
{
*this += (target - *this) * (elapsedTime / (elapsedTime + responseTime));
}
}
inline const Vec2 Vec2::operator+(const Vec2& v) const
{
Vec2 result(*this);
result.add(v);
return result;
}
inline Vec2& Vec2::operator+=(const Vec2& v)
{
add(v);
return *this;
}
inline const Vec2 Vec2::operator-(const Vec2& v) const
{
Vec2 result(*this);
result.subtract(v);
return result;
}
inline Vec2& Vec2::operator-=(const Vec2& v)
{
subtract(v);
return *this;
}
inline const Vec2 Vec2::operator-() const
{
Vec2 result(*this);
result.negate();
return result;
}
inline const Vec2 Vec2::operator*(float s) const
{
Vec2 result(*this);
result.scale(s);
return result;
}
inline Vec2& Vec2::operator*=(float s)
{
scale(s);
return *this;
}
inline const Vec2 Vec2::operator/(const float s) const
{
return Vec2(this->x / s, this->y / s);
}
inline bool Vec2::operator<(const Vec2& v) const
{
if (x == v.x)
{
return y < v.y;
}
return x < v.x;
}
inline bool Vec2::operator>(const Vec2& v) const
{
if (x == v.x)
{
return y > v.y;
}
return x > v.x;
}
inline bool Vec2::operator==(const Vec2& v) const
{
return x == v.x && y == v.y;
}
inline bool Vec2::operator!=(const Vec2& v) const
{
return x != v.x || y != v.y;
}
inline const Vec2 operator*(float x, const Vec2& v)
{
Vec2 result(v);
result.scale(x);
return result;
}
void Vec2::setPoint(float xx, float yy)
{
this->x = xx;
this->y = yy;
}
vec2.cpp源代码如下:
#include "Vec2.h"
//如果A - B段与C - D段相交,则返回true。S->E是重叠部分
// returns true if segment A-B intersects with segment C-D. S->E is the overlap part
bool isOneDimensionSegmentOverlap(float A, float B, float C, float D, float *S, float * E)
{
float ABmin = std::min(A, B);
float ABmax = std::max(A, B);
float CDmin = std::min(C, D);
float CDmax = std::max(C, D);
if (ABmax < CDmin || CDmax < ABmin)
{
// ABmin->ABmax->CDmin->CDmax or CDmin->CDmax->ABmin->ABmax
return false;
}
else
{
if (ABmin >= CDmin && ABmin <= CDmax)
{
// CDmin->ABmin->CDmax->ABmax or CDmin->ABmin->ABmax->CDmax
if (S != nullptr) *S = ABmin;
if (E != nullptr) *E = CDmax < ABmax ? CDmax : ABmax;
}
else if (ABmax >= CDmin && ABmax <= CDmax)
{
// ABmin->CDmin->ABmax->CDmax
if (S != nullptr) *S = CDmin;
if (E != nullptr) *E = ABmax;
}
else
{
// ABmin->CDmin->CDmax->ABmax
if (S != nullptr) *S = CDmin;
if (E != nullptr) *E = CDmax;
}
return true;
}
}
// 2个向量的叉积.axb=(a.x*b.y)-(a.y*b.x)
// cross product of 2 vector. A->B X C->D
float crossProduct2Vector(const Vec2& A, const Vec2& B, const Vec2& C, const Vec2& D)
{
return (D.y - C.y) * (B.x - A.x) - (D.x - C.x) * (B.y - A.y);
}
//求两向量夹角
float Vec2::angle(const Vec2& v1, const Vec2& v2)
{
float dz = v1.x * v2.y - v1.y * v2.x;
return atan2f(fabsf(dz) + MATH_FLOAT_SMALL, dot(v1, v2));
}
void Vec2::add(const Vec2& v1, const Vec2& v2, Vec2* dst)
{
GP_ASSERT(dst);
dst->x = v1.x + v2.x;
dst->y = v1.y + v2.y;
}
void Vec2::clamp(const Vec2& min, const Vec2& max)
{
GP_ASSERT(!(min.x > max.x || min.y > max.y));
// Clamp the x value.
if (x < min.x)
x = min.x;
if (x > max.x)
x = max.x;
// Clamp the y value.
if (y < min.y)
y = min.y;
if (y > max.y)
y = max.y;
}
void Vec2::clamp(const Vec2& v, const Vec2& min, const Vec2& max, Vec2* dst)
{
GP_ASSERT(dst);
GP_ASSERT(!(min.x > max.x || min.y > max.y));
// Clamp the x value.
dst->x = v.x;
if (dst->x < min.x)
dst->x = min.x;
if (dst->x > max.x)
dst->x = max.x;
// Clamp the y value.
dst->y = v.y;
if (dst->y < min.y)
dst->y = min.y;
if (dst->y > max.y)
dst->y = max.y;
}
float Vec2::distance(const Vec2& v) const
{
float dx = v.x - x;
float dy = v.y - y;
return std::sqrt(dx * dx + dy * dy);
}
float Vec2::dot(const Vec2& v1, const Vec2& v2)
{
return (v1.x * v2.x + v1.y * v2.y);
}
float Vec2::length() const
{
return std::sqrt(x * x + y * y);
}
void Vec2::normalize()
{
float n = x * x + y * y;
// Already normalized.
if (n == 1.0f)
return;
n = std::sqrt(n);
// Too close to zero.
if (n < MATH_TOLERANCE)
return;
n = 1.0f / n;
x *= n;
y *= n;
}
Vec2 Vec2::getNormalized() const
{
Vec2 v(*this);
v.normalize();
return v;
}
//二维向量旋转
void Vec2::rotate(const Vec2& point, float angle)
{
float sinAngle = std::sin(angle);
float cosAngle = std::cos(angle);
//绕原点旋转
if (point.isZero())
{
float tempX = x * cosAngle - y * sinAngle;
y = y * cosAngle + x * sinAngle;
x = tempX;
}//绕任一轴旋转
else
{
float tempX = x - point.x;
float tempY = y - point.y;
x = tempX * cosAngle - tempY * sinAngle + point.x;
y = tempY * cosAngle + tempX * sinAngle + point.y;
}
}
void Vec2::set(const float* array)
{
GP_ASSERT(array);
x = array[0];
y = array[1];
}
void Vec2::subtract(const Vec2& v1, const Vec2& v2, Vec2* dst)
{
GP_ASSERT(dst);
dst->x = v1.x - v2.x;
dst->y = v1.y - v2.y;
}
bool Vec2::equals(const Vec2& target) const
{
return (std::abs(this->x - target.x) < FLT_EPSILON)
&& (std::abs(this->y - target.y) < FLT_EPSILON);
}
//模糊相等
bool Vec2::fuzzyEquals(const Vec2& b, float var) const
{
if (x - var <= b.x && b.x <= x + var)
if (y - var <= b.y && b.y <= y + var)
return true;
return false;
}
float Vec2::getAngle(const Vec2& other) const
{
Vec2 a2 = getNormalized();
Vec2 b2 = other.getNormalized();
float angle = atan2f(a2.cross(b2), a2.dot(b2));
if (std::abs(angle) < FLT_EPSILON) return 0.f;
return angle;
}
Vec2 Vec2::rotateByAngle(const Vec2& pivot, float angle) const
{
return pivot + (*this - pivot).rotate(Vec2::forAngle(angle));
}
bool Vec2::isLineIntersect(const Vec2& A, const Vec2& B,
const Vec2& C, const Vec2& D,
float *S, float *T)
{
// FAIL: Line undefined
if ((A.x == B.x && A.y == B.y) || (C.x == D.x && C.y == D.y))
{
return false;
}
const float denom = crossProduct2Vector(A, B, C, D);
if (denom == 0)
{
// Lines parallel or overlap
return false;
}
if (S != nullptr) *S = crossProduct2Vector(C, D, C, A) / denom;
if (T != nullptr) *T = crossProduct2Vector(A, B, C, A) / denom;
return true;
}
bool Vec2::isLineParallel(const Vec2& A, const Vec2& B,
const Vec2& C, const Vec2& D)
{
// FAIL: Line undefined
if ((A.x == B.x && A.y == B.y) || (C.x == D.x && C.y == D.y))
{
return false;
}
if (crossProduct2Vector(A, B, C, D) == 0)
{
// line overlap
if (crossProduct2Vector(C, D, C, A) == 0 || crossProduct2Vector(A, B, C, A) == 0)
{
return false;
}
return true;
}
return false;
}
bool Vec2::isLineOverlap(const Vec2& A, const Vec2& B,
const Vec2& C, const Vec2& D)
{
// FAIL: Line undefined
if ((A.x == B.x && A.y == B.y) || (C.x == D.x && C.y == D.y))
{
return false;
}
if (crossProduct2Vector(A, B, C, D) == 0 &&
(crossProduct2Vector(C, D, C, A) == 0 || crossProduct2Vector(A, B, C, A) == 0))
{
return true;
}
return false;
}
bool Vec2::isSegmentOverlap(const Vec2& A, const Vec2& B, const Vec2& C, const Vec2& D, Vec2* S, Vec2* E)
{
if (isLineOverlap(A, B, C, D))
{
return isOneDimensionSegmentOverlap(A.x, B.x, C.x, D.x, &S->x, &E->x) &&
isOneDimensionSegmentOverlap(A.y, B.y, C.y, D.y, &S->y, &E->y);
}
return false;
}
bool Vec2::isSegmentIntersect(const Vec2& A, const Vec2& B, const Vec2& C, const Vec2& D)
{
float S, T;
if (isLineIntersect(A, B, C, D, &S, &T) &&
(S >= 0.0f && S <= 1.0f && T >= 0.0f && T <= 1.0f))
{
return true;
}
return false;
}
Vec2 Vec2::getIntersectPoint(const Vec2& A, const Vec2& B, const Vec2& C, const Vec2& D)
{
float S, T;
if (isLineIntersect(A, B, C, D, &S, &T))
{
// Vec2 of intersection
Vec2 P;
P.x = A.x + S * (B.x - A.x);
P.y = A.y + S * (B.y - A.y);
return P;
}
return Vec2::ZERO;
}
const Vec2 Vec2::ZERO(0.0f, 0.0f);
const Vec2 Vec2::ONE(1.0f, 1.0f);
const Vec2 Vec2::UNIT_X(1.0f, 0.0f);
const Vec2 Vec2::UNIT_Y(0.0f, 1.0f);
const Vec2 Vec2::ANCHOR_MIDDLE(0.5f, 0.5f);
const Vec2 Vec2::ANCHOR_BOTTOM_LEFT(0.0f, 0.0f);
const Vec2 Vec2::ANCHOR_TOP_LEFT(0.0f, 1.0f);
const Vec2 Vec2::ANCHOR_BOTTOM_RIGHT(1.0f, 0.0f);
const Vec2 Vec2::ANCHOR_TOP_RIGHT(1.0f, 1.0f);
const Vec2 Vec2::ANCHOR_MIDDLE_RIGHT(1.0f, 0.5f);
const Vec2 Vec2::ANCHOR_MIDDLE_LEFT(0.0f, 0.5f);
const Vec2 Vec2::ANCHOR_MIDDLE_TOP(0.5f, 1.0f);
const Vec2 Vec2::ANCHOR_MIDDLE_BOTTOM(0.5f, 0.0f);