常用数学类型及函数
游戏中常用数学类型及运算不多,大概就以下几种,不够以后再增加吧。
/********************************************************************
Copyright(C), 2012-2013,
FileName:GameMath.h
Description:
Author:cloud
Created:2014/10/17
history:
17:10:2014 16:58 by
*********************************************************************/
#pragma once
#include "glm.hpp"
#include "ext.hpp"
namespace cloud
{
#ifndef MAX
#define MAX(x,y) (((x)>(y))?(x):(y))
#endif
#ifndef MIN
#define MIN(x,y) (((x)<(y))?(x):(y))
#endif
void setRandomSeedByTime();
inline int getRandomInt(int min,int max)
{
int trueMin = MIN(min,max);
int trueMax = MAX(min,max);
int r = rand() % (trueMax - trueMin + 1);
return trueMin + r;
}
inline float getRandomFloat(float min,float max)
{
float trueMin = MIN(min,max);
float trueMax = MAX(min,max);
float rNum = (float)rand() / (float)RAND_MAX;
return rNum * (trueMax - trueMin) + trueMin;
}
inline bool getRandomBoolean(int truePos = 50)
{
int poss = rand() % 100 + 1;
return (poss <= truePos);
}
int getGCD(int a,int b); // 得到最大公约数
inline float angleToRadian(float angle)
{
return (3.1416f * angle / 180.0f);
}
inline float radianToAngle(float radian)
{
return 180.0f / 3.1416f * radian;
}
class Vec2
{
public:
inline Vec2() : x(0),y(0){}
inline Vec2(float X,float Y) : x(X),y(Y){}
float x;
float y;
inline static Vec2 createUnitDirectionByAngle(float radian)
{
return Vec2(cosf(radian),sinf(radian));
}
// arithmetic operations
inline Vec2 operator + ( const Vec2& rkVector ) const
{
return Vec2(
x + rkVector.x,
y + rkVector.y);
}
inline Vec2 operator - ( const Vec2& rkVector ) const
{
return Vec2(
x - rkVector.x,
y - rkVector.y);
}
inline Vec2 operator * ( const float fScalar ) const
{
return Vec2(
x * fScalar,
y * fScalar);
}
inline Vec2 operator * ( const Vec2& rhs) const
{
return Vec2(
x * rhs.x,
y * rhs.y);
}
inline Vec2 operator / ( const float fScalar ) const
{
assert( fScalar != 0.0 );
float fInv = 1.0f / fScalar;
return Vec2(
x * fInv,
y * fInv);
}
inline Vec2 operator / ( const Vec2& rhs) const
{
return Vec2(
x / rhs.x,
y / rhs.y);
}
inline const Vec2& operator + () const
{
return *this;
}
inline Vec2 operator - () const
{
return Vec2(-x, -y);
}
// overloaded operators to help Vector2
inline friend Vec2 operator * ( const float fScalar, const Vec2& rkVector )
{
return Vec2(
fScalar * rkVector.x,
fScalar * rkVector.y);
}
inline friend Vec2 operator / ( const float fScalar, const Vec2& rkVector )
{
return Vec2(
fScalar / rkVector.x,
fScalar / rkVector.y);
}
inline friend Vec2 operator + (const Vec2& lhs, const float rhs)
{
return Vec2(
lhs.x + rhs,
lhs.y + rhs);
}
inline friend Vec2 operator + (const float lhs, const Vec2& rhs)
{
return Vec2(
lhs + rhs.x,
lhs + rhs.y);
}
inline friend Vec2 operator - (const Vec2& lhs, const float rhs)
{
return Vec2(
lhs.x - rhs,
lhs.y - rhs);
}
inline friend Vec2 operator - (const float lhs, const Vec2& rhs)
{
return Vec2(
lhs - rhs.x,
lhs - rhs.y);
}
// arithmetic updates
inline Vec2& operator += ( const Vec2& rkVector )
{
x += rkVector.x;
y += rkVector.y;
return *this;
}
inline Vec2& operator += ( const float fScaler )
{
x += fScaler;
y += fScaler;
return *this;
}
inline Vec2& operator -= ( const Vec2& rkVector )
{
x -= rkVector.x;
y -= rkVector.y;
return *this;
}
inline Vec2& operator -= ( const float fScaler )
{
x -= fScaler;
y -= fScaler;
return *this;
}
inline Vec2& operator *= ( const float fScalar )
{
x *= fScalar;
y *= fScalar;
return *this;
}
inline Vec2& operator *= ( const Vec2& rkVector )
{
x *= rkVector.x;
y *= rkVector.y;
return *this;
}
inline Vec2& operator /= ( const float fScalar )
{
assert( fScalar != 0.0 );
float fInv = 1.0f / fScalar;
x *= fInv;
y *= fInv;
return *this;
}
inline Vec2& operator /= ( const Vec2& rkVector )
{
x /= rkVector.x;
y /= rkVector.y;
return *this;
}
inline Vec2 swapXY() const
{
return Vec2(y,x);
}
/** Returns the length (magnitude) of the vector.
@warning
This operation requires a square root and is expensive in
terms of CPU operations. If you don't need to know the exact
length (e.g. for just comparing lengths) use squaredLength()
instead.
*/
inline float length () const
{
return (float)sqrt( x * x + y * y );
}
/** Returns the square of the length(magnitude) of the vector.
@remarks
This method is for efficiency - calculating the actual
length of a vector requires a square root, which is expensive
in terms of the operations required. This method returns the
square of the length of the vector, i.e. the same as the
length but before the square root is taken. Use this if you
want to find the longest / shortest vector without incurring
the square root.
*/
inline float squaredLength () const
{
return x * x + y * y;
}
/** Calculates the dot (scalar) product of this vector with another.
@remarks
The dot product can be used to calculate the angle between 2
vectors. If both are unit vectors, the dot product is the
cosine of the angle; otherwise the dot product must be
divided by the product of the lengths of both vectors to get
the cosine of the angle. This result can further be used to
calculate the distance of a point from a plane.
@param
vec Vector with which to calculate the dot product (together
with this one).
@returns
A float representing the dot product value.
*/
inline float dotProduct(const Vec2& vec) const
{
return x * vec.x + y * vec.y;
}
/** Normalises the vector.
@remarks
This method normalises the vector such that it's
length / magnitude is 1. The result is called a unit vector.
@note
This function will not crash for zero-sized vectors, but there
will be no changes made to their components.
@returns The previous length of the vector.
*/
inline float normalise()
{
float fLength = (float)sqrt( x * x + y * y);
// Will also work for zero-sized vectors, but will change nothing
if ( fLength > 1e-08f )
{
float fInvLength = 1.0f / fLength;
x *= fInvLength;
y *= fInvLength;
}
return fLength;
}
inline Vec2 directionVector() const
{
float fLength = (float)sqrt( x * x + y * y);
return ( fLength > 1e-08f ) ? Vec2(x/fLength,y/fLength) : Vec2::ZERO;
}
/** Returns a vector at a point half way between this and the passed
in vector.
*/
inline Vec2 midPoint( const Vec2& vec ) const
{
return Vec2(
( x + vec.x ) * 0.5f,
( y + vec.y ) * 0.5f );
}
/** Returns true if the vector's scalar components are all greater
that the ones of the vector it is compared against.
*/
inline bool operator < ( const Vec2& rhs ) const
{
if( x < rhs.x && y < rhs.y )
return true;
return false;
}
/** Returns true if the vector's scalar components are all smaller
that the ones of the vector it is compared against.
*/
inline bool operator > ( const Vec2& rhs ) const
{
if( x > rhs.x && y > rhs.y )
return true;
return false;
}
/** Sets this vector's components to the minimum of its own and the
ones of the passed in vector.
@remarks
'Minimum' in this case means the combination of the lowest
value of x, y and z from both vectors. Lowest is taken just
numerically, not magnitude, so -1 < 0.
*/
inline void makeFloor( const Vec2& cmp )
{
if( cmp.x < x ) x = cmp.x;
if( cmp.y < y ) y = cmp.y;
}
/** Sets this vector's components to the maximum of its own and the
ones of the passed in vector.
@remarks
'Maximum' in this case means the combination of the highest
value of x, y and z from both vectors. Highest is taken just
numerically, not magnitude, so 1 > -3.
*/
inline void makeCeil( const Vec2& cmp )
{
if( cmp.x > x ) x = cmp.x;
if( cmp.y > y ) y = cmp.y;
}
/** Generates a vector perpendicular to this vector (eg an 'up' vector).
@remarks
This method will return a vector which is perpendicular to this
vector. There are an infinite number of possibilities but this
method will guarantee to generate one of them. If you need more
control you should use the Quaternion class.
*/
inline Vec2 perpendicular(void) const
{
return Vec2 (-y, x);
}
/** Calculates the 2 dimensional cross-product of 2 vectors, which results
in a single floating point value which is 2 times the area of the triangle.
*/
inline float crossProduct( const Vec2& rkVector ) const
{
return x * rkVector.y - y * rkVector.x;
}
/** Returns true if this vector is zero length. */
inline bool isZeroLength(void) const
{
float sqlen = (x * x) + (y * y);
return (sqlen < (1e-06 * 1e-06));
}
/** As normalise, except that this vector is unaffected and the
normalised vector is returned as a copy. */
inline Vec2 normalisedCopy(void) const
{
Vec2 ret = *this;
ret.normalise();
return ret;
}
/** Calculates a reflection vector to the plane with the given normal .
@remarks NB assumes 'this' is pointing AWAY FROM the plane, invert if it is not.
*/
inline Vec2 reflect(const Vec2& normal) const
{
return Vec2( *this - ( 2 * this->dotProduct(normal) * normal ) );
}
inline Vec2 rotate(float angle) const
{
float radian = angleToRadian(angle);
float cosV = cosf(radian);
float sinV = sinf(radian);
return Vec2(cosV*x-sinV*y,cosV*y+sinV*x);
}
bool equals(const Vec2& target) const;
// special points
static const Vec2 ZERO;
static const Vec2 UNIT_X;
static const Vec2 UNIT_Y;
static const Vec2 NEGATIVE_UNIT_X;
static const Vec2 NEGATIVE_UNIT_Y;
static const Vec2 UNIT_SCALE;
};
inline bool isRectOverlap(const Vec2& r1LeftBottom,const Vec2& r1Size,const Vec2& r2LeftBottom,const Vec2& r2Size)
{
float l1 = r1LeftBottom.x, b1 = r1LeftBottom.y, r1 = l1 + r1Size.x, t1 = b1 + r1Size.y;
float l2 = r2LeftBottom.x, b2 = r2LeftBottom.y, r2 = l2 + r2Size.x, t2 = b2 + r2Size.y;
bool isOut = r2 < l1 || l2 > r1 || t2 < b1 || b2 > t1;
return (!isOut);
}
struct SVec2
{
inline SVec2(): x(0),y(0){}
inline SVec2(int X,int Y): x(X),y(Y){}
inline SVec2(const Vec2& v) : x((int)v.x),y((int)v.y){}
int x;
int y;
};
class Size
{
public:
float width;
float height;
public:
operator Vec2() const
{
return Vec2(width, height);
}
public:
Size();
Size(float width, float height);
Size(const Size& other);
explicit Size(const Vec2& point);
Size& operator= (const Size& other);
Size& operator= (const Vec2& point);
Size operator+(const Size& right) const;
Size operator-(const Size& right) const;
Size operator*(float a) const;
Size operator/(float a) const;
void setSize(float width, float height);
bool equals(const Size& target) const;
static const Size ZERO;
};
typedef Vec2 Point;
struct Color
{
Color();
Color(float _r, float _g, float _b, float _a);
bool operator==(const Color& right) const;
bool operator!=(const Color& right) const;
bool equals(const Color &other)
{
return (*this == other);
}
float r;
float g;
float b;
float a;
static const Color WHITE;
static const Color YELLOW;
static const Color BLUE;
static const Color GREEN;
static const Color RED;
static const Color MAGENTA;
static const Color BLACK;
static const Color ORANGE;
static const Color GRAY;
};
//
class Rect
{
public:
Vec2 origin;
Size size;
public:
Rect();
Rect(float x, float y, float width, float height);
Rect(const Rect& other);
Rect& operator= (const Rect& other);
void setRect(float x, float y, float width, float height);
float getMinX() const; /// return the leftmost x-value of current rect
float getMidX() const; /// return the midpoint x-value of current rect
float getMaxX() const; /// return the rightmost x-value of current rect
float getMinY() const; /// return the bottommost y-value of current rect
float getMidY() const; /// return the midpoint y-value of current rect
float getMaxY() const; /// return the topmost y-value of current rect
bool equals(const Rect& rect) const;
bool containsPoint(const Vec2& point) const;
bool intersectsRect(const Rect& rect) const;
Rect unionWithRect(const Rect & rect) const;
static const Rect ZERO;
};
//
typedef glm::mat4 Mat4;
}
/********************************************************************
Copyright(C), 2012-2013,
FileName:GameMath.cpp
Description:
Author:cloud
Created:2014/10/17
history:
17:10:2014 17:04 by
*********************************************************************/
#include "GameMath.h"
namespace cloud
{
void setRandomSeedByTime()
{
time_t curTime;
time(&curTime);
srand((unsigned int)curTime);
}
int getGCD(int a,int b)
{
while(b!=0)
{
int r = b;
b = a % b;
a = r;
}
return a;
}
//
bool Vec2::equals(const Vec2& target) const
{
return (fabs(this->x - target.x) < FLT_EPSILON)
&& (fabs(this->y - target.y) < FLT_EPSILON);
}
const Vec2 Vec2::ZERO( 0, 0);
const Vec2 Vec2::UNIT_X( 1, 0);
const Vec2 Vec2::UNIT_Y( 0, 1);
const Vec2 Vec2::NEGATIVE_UNIT_X( -1, 0);
const Vec2 Vec2::NEGATIVE_UNIT_Y( 0, -1);
const Vec2 Vec2::UNIT_SCALE(1, 1);
//
Size::Size(void) : width(0), height(0)
{
}
Size::Size(float w, float h) : width(w), height(h)
{
}
Size::Size(const Size& other) : width(other.width), height(other.height)
{
}
Size::Size(const Vec2& point) : width(point.x), height(point.y)
{
}
Size& Size::operator= (const Size& other)
{
setSize(other.width, other.height);
return *this;
}
Size& Size::operator= (const Vec2& point)
{
setSize(point.x, point.y);
return *this;
}
Size Size::operator+(const Size& right) const
{
return Size(this->width + right.width, this->height + right.height);
}
Size Size::operator-(const Size& right) const
{
return Size(this->width - right.width, this->height - right.height);
}
Size Size::operator*(float a) const
{
return Size(this->width * a, this->height * a);
}
Size Size::operator/(float a) const
{
assert(a!=0);
return Size(this->width / a, this->height / a);
}
void Size::setSize(float w, float h)
{
this->width = w;
this->height = h;
}
bool Size::equals(const Size& target) const
{
return (fabs(this->width - target.width) < FLT_EPSILON)
&& (fabs(this->height - target.height) < FLT_EPSILON);
}
const Size Size::ZERO = Size(0, 0);
//
Color::Color()
: r(0.0f)
, g(0.0f)
, b(0.0f)
, a(0.0f)
{}
Color::Color(float _r, float _g, float _b, float _a)
: r(_r)
, g(_g)
, b(_b)
, a(_a)
{}
bool Color::operator==(const Color& right) const
{
return (r == right.r && g == right.g && b == right.b && a == right.a);
}
bool Color::operator!=(const Color& right) const
{
return !(*this == right);
}
/**
* Color constants
*/
const Color Color::WHITE (255, 255, 255, 255);
const Color Color::YELLOW (255, 255, 0, 255);
const Color Color::GREEN ( 0, 255, 0, 255);
const Color Color::BLUE ( 0, 0, 255, 255);
const Color Color::RED (255, 0, 0, 255);
const Color Color::MAGENTA(255, 0, 255, 255);
const Color Color::BLACK ( 0, 0, 0, 255);
const Color Color::ORANGE (255, 127, 0, 255);
const Color Color::GRAY (166, 166, 166, 255);
//
Rect::Rect(void)
{
setRect(0.0f, 0.0f, 0.0f, 0.0f);
}
Rect::Rect(float x, float y, float width, float height)
{
setRect(x, y, width, height);
}
Rect::Rect(const Rect& other)
{
setRect(other.origin.x, other.origin.y, other.size.width, other.size.height);
}
Rect& Rect::operator= (const Rect& other)
{
setRect(other.origin.x, other.origin.y, other.size.width, other.size.height);
return *this;
}
void Rect::setRect(float x, float y, float width, float height)
{
// CGRect can support width<0 or height<0
// CCASSERT(width >= 0.0f && height >= 0.0f, "width and height of Rect must not less than 0.");
origin.x = x;
origin.y = y;
size.width = width;
size.height = height;
}
bool Rect::equals(const Rect& rect) const
{
return (origin.equals(rect.origin) &&
size.equals(rect.size));
}
float Rect::getMaxX() const
{
return origin.x + size.width;
}
float Rect::getMidX() const
{
return origin.x + size.width / 2.0f;
}
float Rect::getMinX() const
{
return origin.x;
}
float Rect::getMaxY() const
{
return origin.y + size.height;
}
float Rect::getMidY() const
{
return origin.y + size.height / 2.0f;
}
float Rect::getMinY() const
{
return origin.y;
}
bool Rect::containsPoint(const Vec2& point) const
{
bool bRet = false;
if (point.x >= getMinX() && point.x <= getMaxX()
&& point.y >= getMinY() && point.y <= getMaxY())
{
bRet = true;
}
return bRet;
}
bool Rect::intersectsRect(const Rect& rect) const
{
return !( getMaxX() < rect.getMinX() ||
rect.getMaxX() < getMinX() ||
getMaxY() < rect.getMinY() ||
rect.getMaxY() < getMinY());
}
Rect Rect::unionWithRect(const Rect & rect) const
{
float thisLeftX = origin.x;
float thisRightX = origin.x + size.width;
float thisTopY = origin.y + size.height;
float thisBottomY = origin.y;
if (thisRightX < thisLeftX)
{
std::swap(thisRightX, thisLeftX); // This rect has negative width
}
if (thisTopY < thisBottomY)
{
std::swap(thisTopY, thisBottomY); // This rect has negative height
}
float otherLeftX = rect.origin.x;
float otherRightX = rect.origin.x + rect.size.width;
float otherTopY = rect.origin.y + rect.size.height;
float otherBottomY = rect.origin.y;
if (otherRightX < otherLeftX)
{
std::swap(otherRightX, otherLeftX); // Other rect has negative width
}
if (otherTopY < otherBottomY)
{
std::swap(otherTopY, otherBottomY); // Other rect has negative height
}
float combinedLeftX = std::min(thisLeftX, otherLeftX);
float combinedRightX = std::max(thisRightX, otherRightX);
float combinedTopY = std::max(thisTopY, otherTopY);
float combinedBottomY = std::min(thisBottomY, otherBottomY);
return Rect(combinedLeftX, combinedBottomY, combinedRightX - combinedLeftX, combinedTopY - combinedBottomY);
}
const Rect Rect::ZERO = Rect(0, 0, 0, 0);
}