Files
dl_old/dl/math/dl_transform.h
T
2025-09-20 17:51:25 +08:00

131 lines
3.0 KiB
C++

/**
* @file dl_transform.h
* @brief 具有矩阵的坐标系
*
*
* @version 1.1
* @author lveyou
* @date 21-08-11
*
* @note 使用y向上的右手坐标系
* @note Transform为变换统称。Translation为平移、Rotation为旋转、Scaling为缩放
*
* @note 使用右手坐标系,因为2d是右手坐标系(vulkan是右手坐标系)
* @note Transform为变换统称。Translation为平移、Rotation为旋转、Scaling为缩放
* @note 接口顺序为TRS,但变换顺序为SRT
* @note 我们使用右手坐标系(+Z 指向上方)
*
* @note 从正z向原点看,物体逆时针旋转(与2d一致)
*
* @note 无须对应到CBV,Actor必须变换到世界坐标系,才对应CBV
* @note 上传之前使用XMMatrixTranspose转置矩阵
* @note 对于XMMatrix来说,左边为先变换,且 a *= b等价于 a = a * b
* @note TODO 以上作废
*
* @note glm为矩阵右乘法,即与函数调用顺序相反(现在不使用glm)
*/
#pragma once
#include "dl_matrix.h"
namespace dl
{
constexpr Position3 AXIS_X = { 1.0f, 0.0f, 0.0f };
constexpr Position3 AXIS_Y = { 0.0f, 1.0f, 0.0f };
constexpr Position3 AXIS_Z = { 0.0f, 0.0f, 1.0f };
//! 3d坐标系
class Transform
{
public:
/**
* @brief 创建3d变换
* @note Actor自带,总数有上限,失败返回nullptr
*/
static Transform* Create()
{
Transform* ret = new Transform;
return ret;
}
Position3 GetTranslation() { return _translation; }
Position3 GetRotation() { return _rotation; }
Transform* GetParent() { return _parent; }
void SetTranslation(const Position3& translation)
{
_translation = translation;
_bNeedUpdate = true;
}
void SetRotation(const Position3& rotation)
{
_rotation = rotation;
_bNeedUpdate = true;
}
void SetScaling(const Position3& scaling)
{
_scaling = scaling;
_bNeedUpdate = true;
}
void SetParent(Transform* parent) { _parent = parent; }
Position3 ToWorld(const Position3& pos);
//! 返回变换矩阵(到父节点)
Matrix4 GetMatrix()
{
if (_bNeedUpdate)
{//需要更新时,重新计算并缓存
_mat = Mat::CreateTranslation(_translation);
//D3DXMatrixRotationYawPitchRoll也只是按y、x、z顺序组合
_mat *= Mat::CreateRotation(AXIS_Y, _rotation[1]);
_mat *= Mat::CreateRotation(AXIS_X, _rotation[0]);
_mat *= Mat::CreateRotation(AXIS_Z, _rotation[2]);
_mat *= Mat::CreateScaling(_scaling);
_bNeedUpdate = false;
}
//不需要则直接使用
return _mat;
}
//! 返回到世界的变换矩阵
Matrix4 GetMatrixToWorld()
{
Matrix4 mat = GetMatrix();
//一直转到世界
Transform* t = GetParent();
while (t)
{
mat = t->GetMatrix() * mat;
t = t->GetParent();
}
return mat;
}
private:
Transform() :
_translation{},
_rotation{},
_scaling{ 1.0f, 1.0f, 1.0f },
_parent{ nullptr },
_bNeedUpdate{ true }
{}
Position3 _translation;
Position3 _rotation;
Position3 _scaling;
Transform* _parent;
bool _bNeedUpdate; //!< 是否需要更新,只有在写入cbv时才计算
Matrix4 _mat;//使用时更新
};
}