⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 vector3.h

📁 在程序中根据3D地形的高度图动态地生成光照图,其中已包含了3D地形混合纹理生成的代码,使用C++和OpenGL进行编写.
💻 H
字号:
#ifndef VECTOR3_H
#define VECTOR3_H

#include <cstddef>
#include <cmath>
#include <gl\glut.h>

//------------------------------
// 3维向量类
//------------------------------
class Vector3
{
public:

	// 公共数据和操作
	GLfloat x;
	GLfloat y;
	GLfloat z;

	// 默认构造函数
	explicit Vector3(GLfloat nx = 0.0f,GLfloat ny = 0.0f,GLfloat nz = 0.0f):x(nx),y(ny),z(nz){}

	// 拷贝构造函数
	Vector3(const Vector3 &rhs):x(rhs.x),y(rhs.y),z(rhs.z){}

	// 标准对象操作
	// 重载赋值运算符,并返回引用,以实现左值
	Vector3 &operator =(const Vector3 &rhs);

	// 重载"=="操作符
	GLboolean operator ==(const Vector3 &rhs) const 
	{
		return x == rhs.x && y == rhs.y && z == rhs.z;
	}

	GLboolean operator !=(const Vector3 &rhs) const
	{
		return x != rhs.x || y != rhs.y || z != rhs.z;
	}

	// 向量运算
	// 置为零向量
	GLvoid Zero()
	{
		x = y = z = 0.0f;
	}

	// 重载一元"-"运算符
	Vector3 operator -() const 
	{
		return Vector3(-x,-y,-z);
	}

	// 重载二元"+"和"-"运算符
	Vector3 operator +(const Vector3 &rhs) const 
	{
		return Vector3(x + rhs.x ,y + rhs.y,z + rhs.z);
	}

	Vector3 operator -(const Vector3 &rhs) const 
	{
		return Vector3(x - rhs.x ,y - rhs.y,z - rhs.z);
	}

	// 与标量的乘法和除法
	Vector3 operator *(GLfloat a) const 
	{
		return Vector3(x*a,y*a,z*a);
	}

	Vector3 operator /(GLfloat a) const
	{
		// 不检测除零
		GLfloat fOneOverA = 1.0f/a;		
		return Vector3(x*fOneOverA,y*fOneOverA,z*fOneOverA);
	}

	// 重载自反运算符
	Vector3 &operator +=(const Vector3 &rhs);
	Vector3 &operator -=(const Vector3 &rhs);
	Vector3 &operator *=(GLfloat a);
	Vector3 &operator /=(GLfloat a);

	// 向量标准化
	GLvoid Normalize();

	// 向量点乘,重载标准的乘法运算符
	GLfloat operator *(const Vector3 &rhs) const 
	{
		return x*rhs.x + y*rhs.y + z*rhs.z;
	}

};

// 非成员函数
// 求模
inline GLfloat VectorMag(const Vector3 &a)
{
	return sqrt(a.x*a.x + a.y*a.y + a.z*a.z);
}

// 计算两向量的叉乘
inline Vector3 CrossProduct(const Vector3 &lhs,const Vector3 &rhs)
{
	return Vector3( lhs.y*rhs.z - lhs.z*rhs.y,
		lhs.z*rhs.x - lhs.x*rhs.z,
		lhs.x*rhs.y - lhs.y*rhs.x );
}

// 计算标量左乘
inline Vector3 operator *(GLfloat k,const Vector3 &rhs)
{
	return Vector3(k*rhs.x,k*rhs.y,k*rhs.z);
}

// 计算两点间的距离
inline GLfloat Distance(const Vector3 &lhs,const Vector3 &rhs)
{
	GLfloat dx = lhs.x - rhs.x;
	GLfloat dy = lhs.y - rhs.y;
	GLfloat dz = lhs.z - rhs.z;
	return sqrt(dx*dx + dy*dy + dz*dz);
}

// 全局零向量对象
extern const Vector3 kZeroVector;

#endif

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -