Extra2D/include/scene/components/sprite_renderer.h

127 lines
3.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#pragma once
#include <scene/component.h>
#include <renderer/render_types.h>
#include <types/math/color.h>
#include <assets/handle.h>
namespace extra2d {
// 前向声明
class Material;
class Texture;
/**
* @brief 精灵渲染组件
*
* 负责渲染2D精灵通过事件提交渲染命令
*
* 使用材质作为纹理和着色器的中间层:
* - 材质包含着色器、参数和纹理
* - 如果只想使用默认着色器,可以设置纹理,组件会自动处理
*
* 使用示例:
* @code
* // 方式1使用完整材质推荐
* auto material = makePtr<Material>();
* material->setShader(customShader);
* material->setTexture("uTexture", textureHandle, 0);
* material->setColor("uTintColor", Color::Red);
* Handle<Material> matHandle = assets->load<Material>("material.mat");
* sprite->setMaterial(matHandle);
*
* // 方式2只设置纹理使用默认材质
* sprite->setTexture(textureHandle);
* @endcode
*/
class SpriteRenderer : public Component {
public:
static constexpr const char* TYPE_NAME = "SpriteRenderer";
/**
* @brief 构造函数
*/
SpriteRenderer();
/**
* @brief 获取组件类型名称
* @return 类型名称
*/
const char* getTypeName() const override { return TYPE_NAME; }
/**
* @brief 组件附加到节点时调用
* @param owner 所属节点
*/
void onAttach(Node* owner) override;
// ========================================
// 材质设置(推荐方式)
// ========================================
/**
* @brief 设置材质
*
* 材质包含着色器、参数和纹理
* @param material 材质句柄
*/
void setMaterial(Handle<Material> material);
/**
* @brief 获取材质
* @return 材质句柄
*/
Handle<Material> getMaterial() const { return material_; }
// ========================================
// 纹理设置(便捷方式)
// ========================================
/**
* @brief 设置纹理
*
* 如果没有设置材质,渲染时会使用默认材质并绑定此纹理
* 如果设置了材质,此设置被忽略(材质中的纹理优先)
* @param texture 纹理句柄
*/
void setTexture(Handle<Texture> texture);
/**
* @brief 获取纹理
* @return 纹理句柄
*/
Handle<Texture> getTexture() const { return texture_; }
// ========================================
// 颜色(顶点颜色)
// ========================================
/**
* @brief 设置颜色
* @param color 颜色
*/
void setColor(const Color& color);
/**
* @brief 获取颜色
* @return 颜色
*/
Color getColor() const { return color_; }
// ========================================
// 渲染
// ========================================
/**
* @brief 渲染时调用
*/
void render() override;
private:
Handle<Material> material_; // 材质句柄
Handle<Texture> texture_; // 纹理句柄(便捷方式)
Color color_ = Color::White; // 顶点颜色
};
} // namespace extra2d