Extra2D/include/scene/components/transform_component.h

168 lines
3.4 KiB
C++

#pragma once
#include <scene/component.h>
#include <types/math/transform.h>
#include <types/math/vec2.h>
#include <types/math/mat4.h>
namespace extra2d {
/**
* @brief 变换组件
*
* 管理节点的位置、旋转、缩放和锚点
* 支持世界变换计算和脏标记优化
*/
class TransformComponent : public Component {
public:
static constexpr const char* TYPE_NAME = "Transform";
/**
* @brief 构造函数
*/
TransformComponent();
/**
* @brief 获取组件类型名称
* @return 类型名称
*/
const char* getTypeName() const override { return TYPE_NAME; }
// ========================================
// 本地变换
// ========================================
/**
* @brief 设置位置
* @param pos 位置
*/
void setPosition(const Vec2& pos);
/**
* @brief 设置旋转角度
* @param rot 角度(度)
*/
void setRotation(float rot);
/**
* @brief 设置缩放
* @param scale 缩放
*/
void setScale(const Vec2& scale);
/**
* @brief 获取位置
* @return 位置
*/
Vec2 getPosition() const { return local_.pos; }
/**
* @brief 获取旋转角度
* @return 角度(度)
*/
float getRotation() const { return local_.rot; }
/**
* @brief 获取缩放
* @return 缩放
*/
Vec2 getScale() const { return local_.scale; }
// ========================================
// 锚点
// ========================================
/**
* @brief 设置锚点
* @param anchor 锚点 [0,1]
*/
void setAnchor(const Vec2& anchor);
/**
* @brief 设置锚点
* @param x X锚点
* @param y Y锚点
*/
void setAnchorPoint(float x, float y);
/**
* @brief 获取锚点
* @return 锚点
*/
Vec2 getAnchor() const { return anchor_; }
// ========================================
// 尺寸
// ========================================
/**
* @brief 设置尺寸
* @param size 尺寸
*/
void setSize(const Vec2& size);
/**
* @brief 设置尺寸
* @param width 宽度
* @param height 高度
*/
void setSize(float width, float height);
/**
* @brief 获取尺寸
* @return 尺寸
*/
Vec2 getSize() const { return size_; }
/**
* @brief 获取锚点偏移量(像素单位)
* @return 锚点偏移
*/
Vec2 getAnchorOffset() const;
// ========================================
// 世界变换
// ========================================
/**
* @brief 获取世界变换
* @return 世界变换
*/
Transform getWorldTransform() const;
/**
* @brief 获取世界矩阵
* @return 世界矩阵
*/
Mat4 getWorldMatrix() const;
// ========================================
// 脏标记管理
// ========================================
/**
* @brief 设置脏标记
*/
void setDirty();
/**
* @brief 是否脏
* @return 是否脏
*/
bool isDirty() const { return dirty_; }
private:
/**
* @brief 更新世界变换
*/
void updateWorldTransform() const;
Transform local_;
mutable Transform world_;
mutable bool dirty_ = true;
Vec2 anchor_ = Vec2(0.5f, 0.5f);
Vec2 size_ = Vec2(100.0f, 100.0f);
};
} // namespace extra2d