D3D12学习笔记1.4——向量函数

本文介绍了使用DirectX进行向量运算的方法,包括加减乘、点积、叉积、向量长度、归一化、投影与正交分解等操作,并展示了如何通过代码实现这些向量运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

·本期我们将引入向量的运算函数。下面是实际操作

#include "iostream"
#include "windows.h"
#include "DirectXMath.h"
#include "DirectXPackedVector.h"

using namespace std;
using namespace DirectX;
using namespace DirectX::PackedVector;

//重载<<运算符
ostream& XM_CALLCONV operator<<(ostream& os, FXMVECTOR v)
{

	XMFLOAT3 dest;
	XMStoreFloat3(&dest, v);
	os << "(" << dest.x << "," << dest.y << "," << dest.z << ")";
	return os;

}

int main()
{
	//设置bool类型输出格式,以“1”或“0”为输出的结果改为“true”或“false”
	cout.setf(ios_base::boolalpha);

	//检查是否支持SSE2指令集
	if (!XMVerifyCPUSupport()) {
		cout << "Unpatched!\n";
		return 0;
	}

	XMVECTOR n = XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
	XMVECTOR u = XMVectorSet(1.0f, 2.0f, 3.0f, 0.0f);
	XMVECTOR v = XMVectorSet(-2.0f, 0.0f, -3.0f, 0.0f);
	XMVECTOR w = XMVectorSet(0.707f, 0.707f, 0.0f, 0.0f);

	//加减乘

	XMVECTOR a = u + v;

	XMVECTOR b = u - v;

	XMVECTOR c = 10.0f * u;

	// ||u||
	XMVECTOR L = XMVector3Length(u);

	// d=u/||u||
	XMVECTOR d = XMVector4Normalize(u);

	// s=u dot v 点积,计算值将存入vector中的每一坐标,值均相等
	XMVECTOR s = XMVector3Dot(u,v);

	//e=u x v 叉乘
	XMVECTOR e = XMVector3Cross(u,v);

	//求出proj_n(w) 和 perp_n(w)
	XMVECTOR projW;
	XMVECTOR perpW;
	XMVector3ComponentsFromNormal(&projW, &perpW, w, n);

	//projW+perpW==w? 判断正交向量位移后是否可得原向量w
	bool equal = XMVector3Equal(projW + perpW, w) != 0;
	bool notequal = XMVector3NotEqual(projW + perpW, w) != 0;

	//projW与perpW之间的夹角应为90度
	
	//获取角度虚向量
	XMVECTOR angleVec = XMVector3AngleBetweenVectors(projW, perpW);

	//将角度向量转化为弧度(浮点数)
	float angleRadians = XMVectorGetX(angleVec);

	//将弧度转换为角度(浮点数)
	float angleDegrees = XMConvertToDegrees(angleRadians);

	cout << "u=" << u << endl;
	cout << "v=" << v << endl;
	cout << "w=" << w<< endl;
	cout << "n=" << n << endl;
	cout << "a=u+v=" << a << endl;
	cout << "b=u-v=" << b << endl;
	cout << "c=10*u=" << c << endl;
	cout << "d=u/||u||=" << d << endl;
	cout << "e=u x v=" << e << endl;
	cout << "L=||u||=" << L << endl;
	cout << "s=u.v=" << s << endl;
	cout << "projW=" << projW << endl;
	cout << "perpW=" << perpW << endl;
	cout << "projW+perpW==w=" << equal << endl;
	cout << "projW+perpW!=w=" << notequal << endl;
	cout << "angle=" << angleDegrees << endl;









}

需要注意的是在此之前一定要了解之前所说的一些概念,比如点积、叉积的意义,以及正交向量proj和perp的含义,明白相关数学知识会更好的理解这些函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

言行物恒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值