其他分享
首页 > 其他分享> > cocos2d-x math之Vec3封装

cocos2d-x math之Vec3封装

作者:互联网

Vec3.h代码如下:

#ifndef MATH_VEC3_H
#define MATH_VEC3_H

#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

class Mat4;
class Quaternion;

/**
 * Defines a 3-element floating point vector.
 *
 * When using a vector to represent a surface normal,
 * the vector should typically be normalized.
 * Other uses of directional vectors may wish to leave
 * the magnitude of the vector intact. When used as a point,
 * the elements of the vector represent a position in 3D space.
 */
class  Vec3
{
public:

	/**
	 * The x-coordinate.
	 */
	float x;

	/**
	 * The y-coordinate.
	 */
	float y;

	/**
	 * The z-coordinate.
	 */
	float z;

	/**
	 * Constructs a new vector initialized to all zeros.
	 */
	Vec3();

	/**
	 * Constructs a new vector initialized to the specified values.
	 *
	 * @param xx The x coordinate.
	 * @param yy The y coordinate.
	 * @param zz The z coordinate.
	 */
	Vec3(float xx, float yy, float zz);

	/**
	 * 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, z.
	 */
	Vec3(const float* array);

	/**
	 * Constructs a vector that describes the direction between the specified points.
	 *
	 * @param p1 The first point.
	 * @param p2 The second point.
	 */
	Vec3(const Vec3& p1, const Vec3& p2);

	/**
	 * Constructs a new vector that is a copy of the specified vector.
	 *
	 * @param copy The vector to copy.
	 */
	Vec3(const Vec3& copy);

	/**
	 * Creates a new vector from an integer interpreted as an RGB value.
	 * E.g. 0xff0000 represents red or the vector (1, 0, 0).
	 *
	 * @param color The integer to interpret as an RGB value.
	 *
	 * @return A vector corresponding to the interpreted RGB color.
	 */
	static Vec3 fromColor(unsigned int color);

	/**
	 * Destructor.
	 */
	~Vec3();

	/**
	 * 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 Vec3& v1, const Vec3& v2);


	/**
	 * Adds the elements of the specified vector to this one.
	 *
	 * @param v The vector to add.
	 */
	inline void add(const Vec3& v);


	/**
	* Adds the elements of this vector to the specified values.
	*
	* @param xx The add x coordinate.
	* @param yy The add y coordinate.
	* @param zz The add z coordinate.
	*/
	inline void add(float xx, float yy, float zz);

	/**
	 * 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 Vec3& v1, const Vec3& v2, Vec3* dst);

	/**
	 * Clamps this vector within the specified range.
	 *
	 * @param min The minimum value.
	 * @param max The maximum value.
	 */
	void clamp(const Vec3& min, const Vec3& 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 Vec3& v, const Vec3& min, const Vec3& max, Vec3* dst);

	/**
	 * Sets this vector to the cross product between itself and the specified vector.
	 *
	 * @param v The vector to compute the cross product with.
	 */
	void cross(const Vec3& v);

	/**
	 * Computes the cross product of 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 cross(const Vec3& v1, const Vec3& v2, Vec3* 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 Vec3& 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
	 */
	float distanceSquared(const Vec3& 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.
	 */
	float dot(const Vec3& 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 Vec3& v1, const Vec3& v2);

	/**
	 * Computes the length of this vector.
	 *
	 * @return The length of the vector.
	 *
	 * @see lengthSquared
	 */
	inline 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 Vec3 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.
	 */
	Vec3 getNormalized() const;

	/**
	 * Scales all elements of this vector by the specified value.
	 *
	 * @param scalar The scalar value.
	 */
	inline void scale(float scalar);

	/**
	 * Sets the elements of this vector to the specified values.
	 *
	 * @param xx The new x coordinate.
	 * @param yy The new y coordinate.
	 * @param zz The new z coordinate.
	 */
	inline void set(float xx, float yy, float zz);

	/**
	 * 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, z.
	 */
	inline 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 Vec3& v);

	/**
	 * Sets this vector to the directional vector between the specified points.
	 */
	inline void set(const Vec3& p1, const Vec3& 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 Vec3& 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 Vec3& v1, const Vec3& v2, Vec3* 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).
	 */
	void smooth(const Vec3& target, float elapsedTime, float responseTime);

	static void crossVec3(const float* v1, const float* v2, float* dst);

	/**
	 * Linear interpolation between two vectors A and B by alpha which
	 * is in the range [0,1]
	 */
	inline Vec3 lerp(const Vec3& target, float alpha) const;

	/**
	 * 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 Vec3 operator+(const Vec3& v) const;

	/**
	 * Adds the given vector to this vector.
	 *
	 * @param v The vector to add.
	 * @return This vector, after the addition occurs.
	 */
	inline Vec3& operator+=(const Vec3& v);

	/**
	 * Calculates the difference of this vector with the given vector.
	 *
	 * Note: this does not modify this vector.
	 *
	 * @param v The vector to subtract.
	 * @return The vector difference.
	 */
	inline const Vec3 operator-(const Vec3& v) const;

	/**
	 * Subtracts the given vector from this vector.
	 *
	 * @param v The vector to subtract.
	 * @return This vector, after the subtraction occurs.
	 */
	inline Vec3& operator-=(const Vec3& v);

	/**
	 * Calculates the negation of this vector.
	 *
	 * Note: this does not modify this vector.
	 *
	 * @return The negation of this vector.
	 */
	inline const Vec3 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 Vec3 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 Vec3& 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 Vec3 operator/(float s) const;

	/** 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 Vec3& rhs) const
	{
		if (x < rhs.x && y < rhs.y && z < rhs.z)
			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 Vec3& rhs) const
	{
		if (x > rhs.x && y > rhs.y && z > rhs.z)
			return true;
		return false;
	}

	/**
	 * 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 Vec3& 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 Vec3& v) const;

	/** equals to Vec3(0,0,0) */
	static const Vec3 ZERO;
	/** equals to Vec3(1,1,1) */
	static const Vec3 ONE;
	/** equals to Vec3(1,0,0) */
	static const Vec3 UNIT_X;
	/** equals to Vec3(0,1,0) */
	static const Vec3 UNIT_Y;
	/** equals to Vec3(0,0,1) */
	static const Vec3 UNIT_Z;
};

/**
 * 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 Vec3 operator*(float x, const Vec3& v);

//typedef Vec3 Point3;


#include "Vec3.inl"

#endif // MATH_VEC3_H

Vec3.inl代码如下:

#include "Vec3.h"




inline bool Vec3::isZero() const
{
	return x == 0.0f && y == 0.0f && z == 0.0f;
}

inline bool Vec3::isOne() const
{
	return x == 1.0f && y == 1.0f && z == 1.0f;
}

inline void Vec3::add(const Vec3& v)
{
	x += v.x;
	y += v.y;
	z += v.z;
}

inline void Vec3::add(float xx, float yy, float zz)
{
	x += xx;
	y += yy;
	z += zz;
}

inline float Vec3::length() const
{
	return std::sqrt(x * x + y * y + z * z);
}

inline float Vec3::lengthSquared() const
{
	return (x * x + y * y + z * z);
}

inline void Vec3::negate()
{
	x = -x;
	y = -y;
	z = -z;
}

inline void Vec3::scale(float scalar)
{
	x *= scalar;
	y *= scalar;
	z *= scalar;
}

inline Vec3 Vec3::lerp(const Vec3 &target, float alpha) const
{
	return *this * (1.f - alpha) + target * alpha;
}

inline void Vec3::set(float xx, float yy, float zz)
{
	this->x = xx;
	this->y = yy;
	this->z = zz;
}

inline void Vec3::set(const float* array)
{
	GP_ASSERT(array);

	x = array[0];
	y = array[1];
	z = array[2];
}

inline void Vec3::set(const Vec3& v)
{
	this->x = v.x;
	this->y = v.y;
	this->z = v.z;
}

inline void Vec3::set(const Vec3& p1, const Vec3& p2)
{
	x = p2.x - p1.x;
	y = p2.y - p1.y;
	z = p2.z - p1.z;
}

inline void Vec3::setZero()
{
	x = y = z = 0.0f;
}

inline void Vec3::subtract(const Vec3& v)
{
	x -= v.x;
	y -= v.y;
	z -= v.z;
}

inline const Vec3 Vec3::operator+(const Vec3& v) const
{
	Vec3 result(*this);
	result.add(v);
	return result;
}

inline Vec3& Vec3::operator+=(const Vec3& v)
{
	add(v);
	return *this;
}

inline const Vec3 Vec3::operator-(const Vec3& v) const
{
	Vec3 result(*this);
	result.subtract(v);
	return result;
}

inline Vec3& Vec3::operator-=(const Vec3& v)
{
	subtract(v);
	return *this;
}

inline const Vec3 Vec3::operator-() const
{
	Vec3 result(*this);
	result.negate();
	return result;
}

inline const Vec3 Vec3::operator*(float s) const
{
	Vec3 result(*this);
	result.scale(s);
	return result;
}

inline Vec3& Vec3::operator*=(float s)
{
	scale(s);
	return *this;
}

inline const Vec3 Vec3::operator/(const float s) const
{
	return Vec3(this->x / s, this->y / s, this->z / s);
}

inline bool Vec3::operator==(const Vec3& v) const
{
	return x == v.x && y == v.y && z == v.z;
}

inline bool Vec3::operator!=(const Vec3& v) const
{
	return x != v.x || y != v.y || z != v.z;
}

inline const Vec3 operator*(float x, const Vec3& v)
{
	Vec3 result(v);
	result.scale(x);
	return result;
}

Vec3.cpp代码如下:

#include "Vec3.h"



Vec3::Vec3()
	: x(0.0f), y(0.0f), z(0.0f)
{
}

Vec3::Vec3(float xx, float yy, float zz)
	: x(xx), y(yy), z(zz)
{
}

Vec3::Vec3(const float* array)
{
	set(array);
}

Vec3::Vec3(const Vec3& p1, const Vec3& p2)
{
	set(p1, p2);
}

Vec3::Vec3(const Vec3& copy)
{
	set(copy);
}

Vec3 Vec3::fromColor(unsigned int color)
{
	float components[3];
	int componentIndex = 0;
	for (int i = 2; i >= 0; --i)
	{
		int component = (color >> i * 8) & 0x0000ff;

		components[componentIndex++] = static_cast<float>(component) / 255.0f;
	}

	Vec3 value(components);
	return value;
}

Vec3::~Vec3()
{
}

float Vec3::angle(const Vec3& v1, const Vec3& v2)
{
	float dx = v1.y * v2.z - v1.z * v2.y;
	float dy = v1.z * v2.x - v1.x * v2.z;
	float dz = v1.x * v2.y - v1.y * v2.x;

	return std::atan2(std::sqrt(dx * dx + dy * dy + dz * dz) + MATH_FLOAT_SMALL, dot(v1, v2));
}

void Vec3::add(const Vec3& v1, const Vec3& v2, Vec3* dst)
{
	GP_ASSERT(dst);

	dst->x = v1.x + v2.x;
	dst->y = v1.y + v2.y;
	dst->z = v1.z + v2.z;
}

void Vec3::clamp(const Vec3& min, const Vec3& max)
{
	GP_ASSERT(!(min.x > max.x || min.y > max.y || min.z > max.z));

	// 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;

	// Clamp the z value.
	if (z < min.z)
		z = min.z;
	if (z > max.z)
		z = max.z;
}

void Vec3::clamp(const Vec3& v, const Vec3& min, const Vec3& max, Vec3* dst)
{
	GP_ASSERT(dst);
	GP_ASSERT(!(min.x > max.x || min.y > max.y || min.z > max.z));

	// 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;

	// Clamp the z value.
	dst->z = v.z;
	if (dst->z < min.z)
		dst->z = min.z;
	if (dst->z > max.z)
		dst->z = max.z;
}

void Vec3::cross(const Vec3& v)
{
	cross(*this, v, this);
}

void Vec3::cross(const Vec3& v1, const Vec3& v2, Vec3* dst)
{
	GP_ASSERT(dst);

	// NOTE: This code assumes Vec3 struct members are contiguous floats in memory.
	// We might want to revisit this (and other areas of code that make this assumption)
	// later to guarantee 100% safety/compatibility.
	Vec3::crossVec3(&v1.x, &v2.x, &dst->x);
}

float Vec3::distance(const Vec3& v) const
{
	float dx = v.x - x;
	float dy = v.y - y;
	float dz = v.z - z;

	return std::sqrt(dx * dx + dy * dy + dz * dz);
}

float Vec3::distanceSquared(const Vec3& v) const
{
	float dx = v.x - x;
	float dy = v.y - y;
	float dz = v.z - z;

	return (dx * dx + dy * dy + dz * dz);
}

float Vec3::dot(const Vec3& v) const
{
	return (x * v.x + y * v.y + z * v.z);
}

float Vec3::dot(const Vec3& v1, const Vec3& v2)
{
	return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z);
}

void Vec3::normalize()
{
	float n = x * x + y * y + z * z;
	// 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;
	z *= n;
}

Vec3 Vec3::getNormalized() const
{
	Vec3 v(*this);
	v.normalize();
	return v;
}

void Vec3::subtract(const Vec3& v1, const Vec3& v2, Vec3* dst)
{
	GP_ASSERT(dst);

	dst->x = v1.x - v2.x;
	dst->y = v1.y - v2.y;
	dst->z = v1.z - v2.z;
}

void Vec3::smooth(const Vec3& target, float elapsedTime, float responseTime)
{
	if (elapsedTime > 0)
	{
		*this += (target - *this) * (elapsedTime / (elapsedTime + responseTime));
	}
}

void Vec3::crossVec3(const float* v1, const float* v2, float* dst)
{
#ifdef USE_NEON32
	MathUtilNeon::crossVec3(v1, v2, dst);
#elif defined (USE_NEON64)
	MathUtilNeon64::crossVec3(v1, v2, dst);
#elif defined (INCLUDE_NEON32)
	if (isNeon32Enabled()) MathUtilNeon::crossVec3(v1, v2, dst);
	else MathUtilC::crossVec3(v1, v2, dst);
#else
	Vec3::crossVec3(v1, v2, dst);
#endif
}

const Vec3 Vec3::ZERO(0.0f, 0.0f, 0.0f);
const Vec3 Vec3::ONE(1.0f, 1.0f, 1.0f);
const Vec3 Vec3::UNIT_X(1.0f, 0.0f, 0.0f);
const Vec3 Vec3::UNIT_Y(0.0f, 1.0f, 0.0f);
const Vec3 Vec3::UNIT_Z(0.0f, 0.0f, 1.0f);

 

 

 

 

 

 

 

 

 

 

 

标签:const,float,param,vector,Vec3,cocos2d,inline,math
来源: https://blog.51cto.com/u_15273495/2914436