Files
dl_old/dl/math/dl_transform.h
2026-05-14 21:17:14 +08:00

134 lines
2.6 KiB
C++

/**
* @file dl_transform.h
* @brief 具有矩阵的坐标系
*
*
* @version 1.1
* @author lveyou
* @date 21-08-11
*
* @note 使用z向上的右手坐标系,x朝前
* @note Transform为变换统称。Translation为平移、Rotation为旋转、Scaling为缩放
* @note 从正z向原点看,物体逆时针旋转(与2d一致)
*
* @note 接口顺序为TRS,但变换顺序为SRT
*
* @note a *= b 等价于 a = a * b ,先b后a
*/
#pragma once
#include "dl_matrix.h"
namespace dl
{
//! 3d坐标系
class Transform
{
public:
/**
* @brief 创建3d变换
* @note Actor自带,总数有上限,失败返回nullptr
*/
static Transform* Create()
{
Transform* ret = new Transform;
return ret;
}
Position3 GetPosition() { return _translation; }
Position3 GetRotate() { return _rotation; }
Position3 GetScale() { return _scaling; }
Transform* GetParent() { return _parent; }
void SetPosition(const Position3& position)
{
_translation = position;
_bNeedUpdate = true;
}
void SetRotate(const Position3& rotate)
{
_rotation = rotate;
_bNeedUpdate = true;
}
void SetScale(const Position3& scale)
{
_scaling = scale;
_bNeedUpdate = true;
}
void SetScaleX(Float scale)
{
_scaling.x = scale;
_bNeedUpdate = true;
}
void SetScaleY(Float scale)
{
_scaling.y = scale;
_bNeedUpdate = true;
}
void SetScaleZ(Float scale)
{
_scaling.z = scale;
_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;//使用时更新
};
}