refactor: reorganize docs into plan/ and add skills/

This commit is contained in:
2026-03-18 17:49:22 +08:00
parent fc7c8f6797
commit 9bad996ecf
143 changed files with 13263 additions and 0 deletions

View File

@@ -0,0 +1,116 @@
# Array
**命名空间**: `XCEngine::Containers`
**类型**: `class` (template)
**描述**: 模板动态数组容器,提供自动扩容的数组实现。
## 概述
`Array<T>` 是一个模板动态数组容器,提供了类似 `std::vector` 的功能,但针对游戏引擎进行了优化。
## 类型别名
| 别名 | 类型 | 描述 |
|------|------|------|
| `Iterator` | `T*` | 迭代器类型 |
| `ConstIterator` | `const T*` | 常量迭代器类型 |
## 公共方法
### 构造/析构
| 方法 | 描述 |
|------|------|
| `Array() = default` | 默认构造函数 |
| `explicit Array(size_t capacity)` | 指定容量的构造函数 |
| `Array(size_t count, const T& value)` | 初始化列表构造函数 |
| `Array(std::initializer_list<T> init)` | initializer_list 构造 |
| `~Array()` | 析构函数 |
### 拷贝/移动构造
| 方法 | 描述 |
|------|------|
| `Array(const Array& other)` | 拷贝构造函数 |
| `Array(Array&& other) noexcept` | 移动构造函数 |
| `Array& operator=(const Array& other)` | 拷贝赋值运算符 |
| `Array& operator=(Array&& other) noexcept` | 移动赋值运算符 |
### 元素访问
| 方法 | 描述 |
|------|------|
| `T& operator[](size_t index)` | 下标访问 |
| `const T& operator[](size_t index) const` | 常量下标访问 |
| `T* Data()` | 获取原始数据指针 |
| `const T* Data() const` | 获取常量数据指针 |
| `T& Front()` | 获取第一个元素 |
| `const T& Front() const` | 获取常量第一个元素 |
| `T& Back()` | 获取最后一个元素 |
| `const T& Back() const` | 获取常量最后一个元素 |
### 容量管理
| 方法 | 描述 |
|------|------|
| `size_t Size() const` | 获取元素数量 |
| `size_t Capacity() const` | 获取容量 |
| `bool Empty() const` | 检查是否为空 |
| `void Clear()` | 清空所有元素 |
| `void Reserve(size_t capacity)` | 预留容量 |
| `void Resize(size_t newSize)` | 调整大小 |
| `void Resize(size_t newSize, const T& value)` | 调整大小并填充默认值 |
### 元素操作
| 方法 | 描述 |
|------|------|
| `void PushBack(const T& value)` | 尾部添加(拷贝) |
| `void PushBack(T&& value)` | 尾部添加(移动) |
| `T& EmplaceBack(Args&&... args)` | 就地构造尾部添加 |
| `void PopBack()` | 尾部移除 |
### 迭代器
| 方法 | 描述 |
|------|------|
| `Iterator begin()` | 获取开始迭代器 |
| `Iterator end()` | 获取结束迭代器 |
| `ConstIterator begin() const` | 获取常量开始迭代器 |
| `ConstIterator end() const` | 获取常量结束迭代器 |
### 内存分配器
| 方法 | 描述 |
|------|------|
| `void SetAllocator(Memory::IAllocator* allocator)` | 设置内存分配器 |
## 使用示例
```cpp
#include <XCEngine/Containers/Array.h>
// 基本用法
Containers::Array<int> arr;
arr.PushBack(1);
arr.PushBack(2);
arr.PushBack(3);
// 使用 initializer_list
Containers::Array<int> arr2 = {1, 2, 3, 4, 5};
// 迭代
for (auto& elem : arr) {
printf("%d\n", elem);
}
// 使用 EmplaceBack
arr.EmplaceBack(4);
```
## 相关文档
- [HashMap](./container-hashmap.md) - 哈希表容器
- [Memory 模块](../memory/memory-overview.md) - 内存分配器

View File

@@ -0,0 +1,137 @@
# HashMap
**命名空间**: `XCEngine::Containers`
**类型**: `class` (template)
**描述**: 模板哈希表容器,提供键值对存储和快速查找。
## 概述
`HashMap<Key, Value>` 是一个模板哈希表容器,实现了分离链接法的哈希表,支持键值对的插入、查找和删除操作。
## 公共类型
### Pair
| 成员 | 类型 | 描述 |
|------|------|------|
| `first` | `Key` | 键 |
| `second` | `Value` | 值 |
### 迭代器
| 别名 | 类型 | 描述 |
|------|------|------|
| `Iterator` | `typename Array<Pair>::Iterator` | 迭代器类型 |
| `ConstIterator` | `typename Array<Pair>::ConstIterator` | 常量迭代器类型 |
## 公共方法
### 构造/析构
| 方法 | 描述 |
|------|------|
| `HashMap()` | 默认构造16 个桶) |
| `explicit HashMap(size_t bucketCount, Memory::IAllocator* allocator = nullptr)` | 指定桶数量和分配器 |
| `~HashMap()` | 析构函数 |
### 拷贝/移动构造
| 方法 | 描述 |
|------|------|
| `HashMap(const HashMap& other)` | 拷贝构造 |
| `HashMap(HashMap&& other) noexcept` | 移动构造 |
| `HashMap& operator=(const HashMap& other)` | 拷贝赋值 |
| `HashMap& operator=(HashMap&& other) noexcept` | 移动赋值 |
### 元素访问
| 方法 | 描述 |
|------|------|
| `Value& operator[](const Key& key)` | 下标访问(不存在时插入) |
### 查找
| 方法 | 描述 |
|------|------|
| `Value* Find(const Key& key)` | 查找键对应的值指针 |
| `const Value* Find(const Key& key) const` | 常量查找 |
| `bool Contains(const Key& key) const` | 检查是否包含键 |
### 插入/删除
| 方法 | 描述 |
|------|------|
| `bool Insert(const Key& key, const Value& value)` | 插入(拷贝值) |
| `bool Insert(const Key& key, Value&& value)` | 插入(移动值) |
| `bool Insert(Pair&& pair)` | 插入(移动键值对) |
| `bool Erase(const Key& key)` | 删除键对应的元素 |
| `void Clear()` | 清空所有元素 |
### 容量
| 方法 | 描述 |
|------|------|
| `size_t Size() const` | 获取元素数量 |
| `bool Empty() const` | 检查是否为空 |
### 迭代器
| 方法 | 描述 |
|------|------|
| `Iterator begin()` | 获取开始迭代器 |
| `Iterator end()` | 获取结束迭代器 |
| `ConstIterator begin() const` | 获取常量开始迭代器 |
| `ConstIterator end() const` | 获取常量结束迭代器 |
### 内存分配器
| 方法 | 描述 |
|------|------|
| `void SetAllocator(Memory::IAllocator* allocator)` | 设置内存分配器 |
## 实现细节
| 常量/成员 | 类型 | 描述 |
|------|------|------|
| `DefaultBucketCount` | `static constexpr size_t` | 默认桶数量16 |
| `m_loadFactor` | `float` | 负载因子阈值0.75 |
## 使用示例
```cpp
#include <XCEngine/Containers/HashMap.h>
// 基本用法
Containers::HashMap<Containers::String, int> map;
map.Insert("one", 1);
map.Insert("two", 2);
// 使用下标访问
map["three"] = 3;
// 查找
int* val = map.Find("one");
if (val) {
printf("Found: %d\n", *val);
}
// 使用 Contains
if (map.Contains("two")) {
printf("two exists\n");
}
// 删除
map.Erase("one");
// 迭代
for (auto& pair : map) {
printf("%s: %d\n", pair.first.CStr(), pair.second);
}
```
## 相关文档
- [Array](./container-array.md) - 动态数组
- [Memory 模块](../memory/memory-overview.md) - 内存分配器

View File

@@ -0,0 +1,55 @@
# Containers 容器模块概览
**命名空间**: `XCEngine::Containers`
**类型**: `module`
**描述**: XCEngine 的容器模块,提供常用的数据结构实现。
## 概述
Containers 模块提供了图形引擎常用的数据结构,包括动态数组、字符串和哈希表。这些容器都使用自定义内存分配器接口,支持内存跟踪和优化。
## 模块内容
### 容器类
| 组件 | 文件 | 描述 |
|------|------|------|
| [Array](./container-array.md) | `Array.h` | 模板动态数组,支持自动扩容 |
| [String](./container-string.md) | `String.h` | 动态字符串类 |
| [HashMap](./container-hashmap.md) | `HashMap.h` | 模板哈希表 |
## 设计特点
1. **自定义内存分配器支持** - 所有容器都支持通过 `IAllocator` 接口分配内存
2. **迭代器支持** - Array 和 HashMap 都提供 STL 风格的迭代器
3. **移动语义** - 完整支持 C++11 移动语义
4. **异常安全** - 内存分配失败时提供良好的错误处理
## 使用示例
```cpp
#include <XCEngine/Containers/Containers.h>
// 使用 Array
Containers::Array<int> arr;
arr.PushBack(1);
arr.PushBack(2);
arr.PushBack(3);
// 使用 String
Containers::String str;
str = "Hello, ";
str += "World!";
// 使用 HashMap
Containers::HashMap<Containers::String, int> map;
map.Insert("key1", 100);
map.Insert("key2", 200);
int* value = map.Find("key1");
```
## 相关文档
- [Memory 模块](../memory/memory-overview.md) - 内存分配器接口

View File

@@ -0,0 +1,132 @@
# String
**命名空间**: `XCEngine::Containers`
**类型**: `class`
**描述**: 动态字符串类,提供 UTF-8 编码的字符串操作。
## 概述
`String` 是一个自定义动态字符串类,提供常见的字符串操作功能,支持拷贝构造、移动构造和多种字符串操作方法。
## 类型别名
| 别名 | 类型 | 描述 |
|------|------|------|
| `SizeType` | `size_t` | 大小类型 |
## 常量
| 常量 | 值 | 描述 |
|------|-----|------|
| `static constexpr SizeType npos` | `static_cast<SizeType>(-1)` | 无效位置标识 |
## 公共方法
### 构造/析构
| 方法 | 描述 |
|------|------|
| `String()` | 默认构造空字符串 |
| `String(const char* str)` | 从 C 字符串构造 |
| `String(const char* str, SizeType len)` | 从指定长度的 C 字符串构造 |
| `String(const String& other)` | 拷贝构造 |
| `String(String&& other) noexcept` | 移动构造 |
| `~String()` | 析构函数 |
### 赋值运算符
| 方法 | 描述 |
|------|------|
| `String& operator=(const String& other)` | 拷贝赋值 |
| `String& operator=(String&& other) noexcept` | 移动赋值 |
| `String& operator=(const char* str)` | C 字符串赋值 |
### 连接运算符
| 方法 | 描述 |
|------|------|
| `String& operator+=(const String& other)` | 追加字符串 |
| `String& operator+=(const char* str)` | 追加 C 字符串 |
| `String& operator+=(char c)` | 追加字符 |
### 字符串操作
| 方法 | 描述 |
|------|------|
| `String Substring(SizeType pos, SizeType len = npos) const` | 获取子串 |
| `String Trim() const` | 去除首尾空白 |
| `String ToLower() const` | 转换为小写 |
| `String ToUpper() const` | 转换为大写 |
| `SizeType Find(const char* str, SizeType pos = 0) const` | 查找子串位置 |
| `bool StartsWith(const String& prefix) const` | 检查是否以指定前缀开头 |
| `bool StartsWith(const char* prefix) const` | 检查是否以指定前缀开头 |
| `bool EndsWith(const String& suffix) const` | 检查是否以指定后缀结尾 |
| `bool EndsWith(const char* suffix) const` | 检查是否以指定后缀结尾 |
### 元素访问
| 方法 | 描述 |
|------|------|
| `const char* CStr() const` | 获取 C 字符串指针 |
| `SizeType Length() const` | 获取字符串长度 |
| `SizeType Capacity() const` | 获取容量 |
| `bool Empty() const` | 检查是否为空 |
| `char& operator[](SizeType index)` | 下标访问 |
| `const char& operator[](SizeType index) const` | 常量下标访问 |
### 容量管理
| 方法 | 描述 |
|------|------|
| `void Clear()` | 清空字符串 |
| `void Reserve(SizeType capacity)` | 预留容量 |
| `void Resize(SizeType newSize)` | 调整大小 |
| `void Resize(SizeType newSize, char fillChar)` | 调整大小并填充 |
## 友元函数
| 函数 | 描述 |
|------|------|
| `operator+(const String& lhs, const String& rhs)` | 字符串连接 |
| `operator==(const String& lhs, const String& rhs)` | 相等比较 |
| `operator!=(const String& lhs, const String& rhs)` | 不等比较 |
## std::hash 特化
```cpp
namespace std {
template<>
struct hash<XCEngine::Containers::String> {
size_t operator()(const XCEngine::Containers::String& str) const noexcept;
};
}
```
## 使用示例
```cpp
#include <XCEngine/Containers/String.h>
// 基本用法
Containers::String str = "Hello";
str += ", World!";
// 字符串操作
Containers::String sub = str.Substring(0, 5); // "Hello"
bool hasPrefix = str.StartsWith("Hello");
bool hasSuffix = str.EndsWith("!");
// 查找
SizeType pos = str.Find("World"); // 返回 7
// 转换
Containers::String upper = str.ToUpper();
Containers::String lower = str.ToLower();
```
## 相关文档
- [Array](./container-array.md) - 动态数组
- [HashMap](./container-hashmap.md) - 哈希表

View File

@@ -0,0 +1,77 @@
# Event
**命名空间**: `XCEngine::Core`
**类型**: `class` (template)
**描述**: 事件系统模板类,提供类型安全的多订阅者事件/委托系统。
## 概述
`Event<Args...>` 是一个类型安全的事件发布-订阅系统。它支持多个回调订阅、退订和线程安全的调用。非常适合用于游戏引擎中的事件驱动通信。
## 模板参数
| 参数 | 描述 |
|------|------|
| `Args...` | 事件回调的参数类型 |
## 类型别名
| 别名 | 类型 | 描述 |
|------|------|------|
| `Callback` | `std::function<void(Args...)>` | 回调函数类型 |
| `Listener` | `std::pair<uint64_t, Callback>` | 监听器条目 |
| `Iterator` | `std::vector<Listener>::iterator` | 迭代器类型 |
## 公共方法
### 订阅/退订
| 方法 | 描述 |
|------|------|
| `uint64_t Subscribe(Callback callback)` | 订阅事件,返回订阅 ID |
| `void Unsubscribe(uint64_t id)` | 退订事件(延迟生效) |
| `void ProcessUnsubscribes()` | 处理积压的退订请求 |
| `void Clear()` | 清空所有订阅 |
### 调用
| 方法 | 描述 |
|------|------|
| `void Invoke(Args... args)` | 调用所有订阅的回调 |
### 迭代
| 方法 | 描述 |
|------|------|
| `Iterator begin()` | 获取开始迭代器 |
| `Iterator end()` | 获取结束迭代器 |
## 使用示例
```cpp
// 定义事件(无参数)
Event<> frameStartEvent;
// 定义事件(带参数)
Event<int, float> damageEvent;
// 订阅
uint64_t id = damageEvent.Subscribe([](int damage, float time) {
printf("Damage: %d at time %f\n", damage, time);
});
// 触发事件
damageEvent.Invoke(100, 3.14f);
// 退订
damageEvent.Unsubscribe(id);
// 清空
frameStartEvent.Clear();
```
## 相关文档
- [Core 模块概览](./core-overview.md) - Core 模块总览

View File

@@ -0,0 +1,75 @@
# FileWriter
**命名空间**: `XCEngine::Core`
**类型**: `class`
**描述**: 文件写入工具类,提供简单的文件写入操作封装。
## 概述
`FileWriter` 是一个轻量级的文件写入工具,封装了 `FILE*` 接口提供便捷的字符串和二进制数据写入功能。它支持追加模式和自动资源管理RAII
## 公共方法
### 构造/析构
| 方法 | 描述 |
|------|------|
| `FileWriter()` | 默认构造(不打开文件) |
| `FileWriter(const char* filePath, bool append = false)` | 构造并打开文件 |
| `~FileWriter()` | 析构函数,自动关闭文件 |
### 文件操作
| 方法 | 描述 |
|------|------|
| `bool Open(const char* filePath, bool append = false)` | 打开文件append=true 时为追加模式 |
| `void Close()` | 关闭文件 |
| `bool IsOpen() const` | 检查文件是否已打开 |
### 数据写入
| 方法 | 描述 |
|------|------|
| `bool Write(const char* data, size_t length)` | 写入指定长度的字符串 |
| `bool Write(const Containers::String& str)` | 写入 String 内容 |
| `bool Flush()` | 刷新缓冲区,确保数据写入磁盘 |
## 使用示例
```cpp
#include <XCEngine/Core/FileWriter.h>
// 方式1构造时打开
FileWriter writer("output.txt", false);
if (writer.IsOpen()) {
writer.Write("Hello, World!\n");
writer.Write("Line 2\n");
writer.Flush();
}
// 方式2先构造再打开
FileWriter writer2;
if (writer2.Open("log.txt")) {
writer2.Write("Application started\n");
writer2.Close();
}
// 追加模式
FileWriter appendWriter("log.txt", true);
if (appendWriter.IsOpen()) {
appendWriter.Write("Another log entry\n");
appendWriter.Flush();
}
// 使用 String 写入
Containers::String content = "Content written from String";
FileWriter writer3("data.txt");
writer3.Write(content);
```
## 相关文档
- [Logger](../debug/debug-logger.md) - 日志系统
- [FileLogSink](../debug/debug-filelogsink.md) - 文件日志输出

View File

@@ -0,0 +1,94 @@
# Core 模块概览
**命名空间**: `XCEngine::Core`
**类型**: `module`
**描述**: XCEngine 的核心基础模块,提供类型别名、智能指针、事件系统等基础功能。
## 概述
Core 模块包含了引擎所需的基础类型和工具,是其他所有模块的依赖基础。
## 模块内容
### 类型
| 组件 | 文件 | 描述 |
|------|------|------|
| [Types](./core-types.md) | `Types.h` | 类型别名定义 |
### 智能指针
| 组件 | 文件 | 描述 |
|------|------|------|
| [SmartPtr](./core-smartptr.md) | `SmartPtr.h` | 智能指针别名和工厂函数 |
| [RefCounted](./core-refcounted.md) | `RefCounted.h` | 引用计数基类 |
### 事件系统
| 组件 | 文件 | 描述 |
|------|------|------|
| [Event](./core-event.md) | `Event.h` | 事件系统模板 |
### 文件操作
| 组件 | 文件 | 描述 |
|------|------|------|
| [FileWriter](./core-filewriter.md) | `FileWriter.h` | 文件写入工具 |
## 类型别名
```cpp
using int8 = int8_t;
using int16 = int16_t;
using int32 = int32_t;
using int64 = int64_t;
using uint8 = uint8_t;
using uint16 = uint16_t;
using uint32 = uint32_t;
using uint64 = uint64_t;
using byte = uint8_t;
```
## 智能指针别名
```cpp
template<typename T>
using Ref = std::shared_ptr<T>;
template<typename T>
using UniqueRef = std::unique_ptr<T>;
template<typename T, typename... Args>
Ref<T> MakeRef(Args&&... args);
template<typename T, typename... Args>
UniqueRef<T> MakeUnique(Args&&... args);
```
## 使用示例
```cpp
#include <XCEngine/Core/Core.h>
// 使用类型别名
Core::uint32 value = 100;
Core::byte data[4];
// 使用智能指针
auto ref = MakeRef<MyClass>();
auto unique = MakeUnique<MyClass>();
// 使用事件系统
Event<int, float> myEvent;
myEvent.Subscribe([](int a, float b) {
printf("Event: %d, %f\n", a, b);
});
myEvent.Invoke(42, 3.14f);
```
## 相关文档
- [Containers 模块](../containers/container-overview.md) - 容器类型
- [Memory 模块](../memory/memory-overview.md) - 内存管理

View File

@@ -0,0 +1,50 @@
# RefCounted
**命名空间**: `XCEngine::Core`
**类型**: `class`
**描述**: 引用计数基类,提供线程安全的引用计数生命周期管理。
## 概述
`RefCounted` 是一个简单的引用计数基类。当引用计数归零时,对象会自动删除。它提供了 `AddRef``Release` 方法,线程安全地管理引用计数。
## 公共方法
### 构造/析构
| 方法 | 描述 |
|------|------|
| `RefCounted()` | 构造函数,初始引用计数为 1 |
| `virtual ~RefCounted()` | 虚析构函数 |
### 引用计数
| 方法 | 描述 |
|------|------|
| `void AddRef()` | 增加引用计数 |
| `void Release()` | 减少引用计数(归零时自动 delete this |
| `uint32_t GetRefCount() const` | 获取当前引用计数 |
## 使用示例
```cpp
class MyObject : public RefCounted {
public:
MyObject() { /* ... */ }
~MyObject() { /* ... */ }
void DoSomething() { /* ... */ }
};
// 使用
MyObject* obj = new MyObject(); // refCount = 1
obj->AddRef(); // refCount = 2
obj->Release(); // refCount = 1
obj->Release(); // refCount = 0, 自动 delete
```
## 相关文档
- [SmartPtr](./core-smartptr.md) - 智能指针

View File

@@ -0,0 +1,54 @@
# SmartPtr
**命名空间**: `XCEngine::Core`
**类型**: `header-only`
**描述**: 智能指针类型别名和工厂函数,提供 `std::shared_ptr``std::unique_ptr` 的简化接口。
## 概述
`Core::SmartPtr` 提供了 `std::shared_ptr``std::unique_ptr` 的类型别名和工厂函数,使智能指针的使用更加简洁。
## 类型别名
| 别名 | 底层类型 | 描述 |
|------|----------|------|
| `Core::Ref<T>` | `std::shared_ptr<T>` | 共享引用智能指针 |
| `Core::UniqueRef<T>` | `std::unique_ptr<T>` | 独占所有权的智能指针 |
## 工厂函数
| 函数 | 返回值 | 描述 |
|------|--------|------|
| `Core::MakeRef<T>(Args&&... args)` | `Ref<T>` | 创建共享指针 |
| `Core::MakeUnique<T>(Args&&... args)` | `UniqueRef<T>` | 创建独占指针 |
## 使用示例
```cpp
#include <XCEngine/Core/Core.h>
// 使用 Ref共享指针
Core::Ref<MyClass> ref = Core::MakeRef<MyClass>(arg1, arg2);
// 使用 UniqueRef独占指针
Core::UniqueRef<MyClass> unique = Core::MakeUnique<MyClass>();
// 传递所有权
Core::Ref<MyClass> ref2 = ref; // 引用计数 +1
// 检查有效性
if (ref) {
ref->DoSomething();
}
// 自定义删除器
Core::UniqueRef<FILE, decltype(&fclose)>
file(fopen("test.txt", "r"), &fclose);
```
## 相关文档
- [RefCounted](./core-refcounted.md) - 引用计数基类
- [Types](./core-types.md) - 类型别名

View File

@@ -0,0 +1,49 @@
# Types
**命名空间**: `XCEngine::Core`
**类型**: `header` (type aliases)
**头文件**: `XCEngine/Core/Types.h`
**描述**: 基础类型别名定义,提供跨平台一致的基础类型名称。
## 概述
`Types.h` 定义了一组类型别名,简化了标准库类型的使用,并提供跨平台一致性。
## 类型别名
| 别名 | 实际类型 | 描述 |
|------|----------|------|
| `int8` | `int8_t` | 8位有符号整数 |
| `int16` | `int16_t` | 16位有符号整数 |
| `int32` | `int32_t` | 32位有符号整数 |
| `int64` | `int64_t` | 64位有符号整数 |
| `uint8` | `uint8_t` | 8位无符号整数 |
| `uint16` | `uint16_t` | 16位无符号整数 |
| `uint32` | `uint32_t` | 32位无符号整数 |
| `uint64` | `uint64_t` | 64位无符号整数 |
| `byte` | `uint8_t` | 字节类型 |
## 使用示例
```cpp
#include <XCEngine/Core/Types.h>
// 使用类型别名
Core::int32 count = 100;
Core::uint64 id = 1234567890;
Core::byte flags = 0xFF;
// 数组定义
Core::uint8 buffer[1024];
// 函数参数
void ProcessData(Core::uint32 size, const Core::int8* data);
```
## 相关文档
- [SmartPtr](./core-smartptr.md) - 智能指针
- [RefCounted](./core-refcounted.md) - 引用计数基类

View File

@@ -0,0 +1,52 @@
# ConsoleLogSink
**命名空间**: `XCEngine::Debug`
**类型**: `class`
**描述**: 控制台日志输出槽,将日志输出到标准控制台,支持彩色输出。
## 概述
`ConsoleLogSink``ILogSink` 的控制台实现。它将日志输出到 stdout/stderr支持按日志级别设置不同颜色。
## 公共方法
### 构造/析构
| 方法 | 描述 |
|------|------|
| `ConsoleLogSink()` | 默认构造函数 |
| `~ConsoleLogSink()` | 析构函数 |
### ILogSink 实现
| 方法 | 描述 |
|------|------|
| `void Log(const LogEntry& entry) override` | 输出日志到控制台 |
| `void Flush() override` | 刷新标准输出流 |
### 配置
| 方法 | 描述 |
|------|------|
| `void SetColorOutput(bool enable)` | 启用/禁用彩色输出 |
| `void SetMinimumLevel(LogLevel level)` | 设置最小输出级别 |
## 使用示例
```cpp
// 创建并配置
auto sink = std::make_unique<ConsoleLogSink>();
sink->SetColorOutput(true);
sink->SetMinimumLevel(LogLevel::Debug);
// 添加到 Logger
Logger::Get().AddSink(std::move(sink));
```
## 相关文档
- [Logger](./debug-logger.md) - 日志记录器
- [ILogSink](./debug-ilogsink.md) - 日志输出接口
- [FileLogSink](./debug-filelogsink.md) - 文件输出

View File

@@ -0,0 +1,47 @@
# FileLogSink
**命名空间**: `XCEngine::Debug`
**类型**: `class`
**描述**: 文件日志输出槽,将日志持久化到磁盘文件。
## 概述
`FileLogSink``ILogSink` 的文件实现。它使用 `FileWriter` 将日志追加写入文件,支持自动换行和缓冲区刷新。
## 公共方法
### 构造/析构
| 方法 | 描述 |
|------|------|
| `FileLogSink(const Containers::String& filePath)` | 构造函数,指定文件路径 |
| `~FileLogSink()` | 析构函数 |
### ILogSink 实现
| 方法 | 描述 |
|------|------|
| `void Log(const LogEntry& entry) override` | 将日志追加写入文件 |
| `void Flush() override` | 刷新文件缓冲区 |
## 使用示例
```cpp
// 创建文件日志输出
auto fileSink = std::make_unique<FileLogSink>("logs/app.log");
// 添加到 Logger
Logger::Get().AddSink(std::move(fileSink));
// 日志将自动写入文件
XE_LOG(LogCategory::General, LogLevel::Info, "Game started");
```
## 相关文档
- [Logger](./debug-logger.md) - 日志记录器
- [ILogSink](./debug-ilogsink.md) - 日志输出接口
- [ConsoleLogSink](./debug-consolelogsink.md) - 控制台输出
- [Core/FileWriter](../core/core-filewriter.md) - 文件写入工具

View File

@@ -0,0 +1,47 @@
# ILogSink
**命名空间**: `XCEngine::Debug`
**类型**: `class` (abstract interface)
**描述**: 日志输出槽抽象接口,定义日志输出的标准协议。
## 概述
`ILogSink` 是日志系统的输出抽象接口。用户可以实现此接口来创建自定义的日志输出方式,如网络输出、数据库存储等。`Logger` 通过多个 Sink 分发日志。
## 公共方法
| 方法 | 描述 |
|------|------|
| `virtual void Log(const LogEntry& entry) = 0` | 输出单条日志 |
| `virtual void Flush() = 0` | 刷新缓冲区,确保日志写入 |
## 使用示例
```cpp
class CustomLogSink : public ILogSink {
public:
void Log(const LogEntry& entry) override {
// 自定义日志输出逻辑
printf("[%s] %s: %s\n",
LogLevelToString(entry.level),
LogCategoryToString(entry.category),
entry.message.CStr());
}
void Flush() override {
// 刷新缓冲区
fflush(stdout);
}
};
// 注册自定义 Sink
Logger::Get().AddSink(std::make_unique<CustomLogSink>());
```
## 相关文档
- [Logger](./debug-logger.md) - 日志记录器
- [ConsoleLogSink](./debug-consolelogsink.md) - 控制台输出
- [FileLogSink](./debug-filelogsink.md) - 文件输出

View File

@@ -0,0 +1,46 @@
# LogCategory
**命名空间**: `XCEngine::Debug`
**类型**: `enum class`
**描述**: 日志分类枚举,定义日志的来源模块。
## 概述
`LogCategory` 枚举定义了日志的分类,用于区分不同引擎模块的日志输出。
## 枚举值
| 值 | 说明 |
|----|------|
| `General` | 通用 |
| `Rendering` | 渲染 |
| `Physics` | 物理 |
| `Audio` | 音频 |
| `Scripting` | 脚本 |
| `Network` | 网络 |
| `Memory` | 内存 |
| `Threading` | 线程 |
| `FileSystem` | 文件系统 |
| `Custom` | 自定义 |
## 辅助函数
| 函数 | 描述 |
|------|------|
| `const char* LogCategoryToString(LogCategory category)` | 将日志分类转换为字符串 |
## 使用示例
```cpp
// 禁用网络日志
Logger::Get().SetCategoryEnabled(LogCategory::Network, false);
// 输出分类日志
XE_LOG(LogCategory::Rendering, LogLevel::Info, "Draw call submitted");
```
## 相关文档
- [Logger](./debug-logger.md) - 日志记录器

View File

@@ -0,0 +1,48 @@
# LogEntry
**命名空间**: `XCEngine::Debug`
**类型**: `struct`
**描述**: 日志条目结构体,包含单条日志的所有信息。
## 概述
`LogEntry` 是日志系统的核心数据结构,每次日志记录都生成一个 `LogEntry` 并分发给所有注册的 Sink。
## 结构体成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `level` | `LogLevel` | 日志级别 |
| `category` | `LogCategory` | 日志分类 |
| `message` | `Containers::String` | 日志消息内容 |
| `file` | `Containers::String` | 源代码文件路径 |
| `line` | `int32_t` | 源代码行号 |
| `function` | `Containers::String` | 函数名称 |
| `timestamp` | `uint64_t` | 时间戳(毫秒) |
| `threadId` | `uint32_t` | 线程 ID |
## 使用示例
```cpp
// 实现自定义 Sink 时访问 LogEntry
class MySink : public ILogSink {
public:
void Log(const LogEntry& entry) override {
printf("[%llu][%u] %s::%s: %s\n",
(unsigned long long)entry.timestamp,
(unsigned)entry.threadId,
LogCategoryToString(entry.category),
LogLevelToString(entry.level),
entry.message.CStr());
}
void Flush() override { }
};
```
## 相关文档
- [ILogSink](./debug-ilogsink.md) - 日志输出接口
- [Logger](./debug-logger.md) - 日志记录器

View File

@@ -0,0 +1,108 @@
# Logger
**命名空间**: `XCEngine::Debug`
**类型**: `class` (singleton)
**头文件**: `XCEngine/Debug/Logger.h`
**描述**: 全局日志记录器单例,提供多级别、多分类的日志输出。
## 概述
`Logger` 是 XCEngine 的核心日志系统单例。它支持多个日志输出目标Sink、日志级别过滤、分类开关并提供宏方便使用。
## 单例访问
| 方法 | 描述 |
|------|------|
| `static Logger& Get()` | 获取单例实例 |
## 公共方法
### 生命周期
| 方法 | 描述 |
|------|------|
| `void Initialize()` | 初始化日志系统 |
| `void Shutdown()` | 关闭日志系统 |
### Sink 管理
| 方法 | 描述 |
|------|------|
| `void AddSink(std::unique_ptr<ILogSink> sink)` | 添加日志输出目标 |
| `void RemoveSink(ILogSink* sink)` | 移除日志输出目标 |
### 日志记录
| 方法 | 描述 |
|------|------|
| `void Log(LogLevel level, LogCategory category, const Containers::String& message, const char* file = nullptr, int32_t line = 0, const char* function = nullptr)` | 通用日志记录 |
| `void Verbose(LogCategory category, const Containers::String& message)` | Verbose 级别日志 |
| `void Debug(LogCategory category, const Containers::String& message)` | Debug 级别日志 |
| `void Info(LogCategory category, const Containers::String& message)` | Info 级别日志 |
| `void Warning(LogCategory category, const Containers::String& message)` | Warning 级别日志 |
| `void Error(LogCategory category, const Containers::String& message)` | Error 级别日志 |
| `void Fatal(LogCategory category, const Containers::String& message)` | Fatal 级别日志 |
### 配置
| 方法 | 描述 |
|------|------|
| `void SetMinimumLevel(LogLevel level)` | 设置最小日志级别 |
| `void SetCategoryEnabled(LogCategory category, bool enabled)` | 开启/关闭指定分类 |
## 宏定义
### XE_LOG
```cpp
#define XE_LOG(category, level, message) \
XCEngine::Debug::Logger::Get().Log(level, category, message, __FILE__, __LINE__, __FUNCTION__)
```
通用日志宏,自动填充文件名、行号和函数名。
### XE_ASSERT
```cpp
#define XE_ASSERT(condition, message) \
if (!(condition)) { \
XCEngine::Debug::Logger::Get().Fatal(XCEngine::Debug::LogCategory::General, message); \
}
```
断言宏,条件失败时记录 Fatal 日志。
## 使用示例
```cpp
#include <XCEngine/Debug/Logger.h>
// 初始化
Logger::Get().Initialize();
Logger::Get().AddSink(std::make_unique<ConsoleLogSink>());
Logger::Get().AddSink(std::make_unique<FileLogSink>("app.log"));
// 设置日志级别
Logger::Get().SetMinimumLevel(LogLevel::Debug);
// 使用便捷方法
Logger::Get().Info(LogCategory::Rendering, "Render started");
Logger::Get().Warning(LogCategory::Memory, "High memory usage");
Logger::Get().Error(LogCategory::FileSystem, "Failed to load file");
// 使用宏(自动带位置信息)
XE_LOG(LogCategory::General, LogLevel::Info, "Application initialized");
// 使用断言
XE_ASSERT(ptr != nullptr, "Pointer must not be null");
```
## 相关文档
- [ILogSink](./debug-ilogsink.md) - 日志输出接口
- [ConsoleLogSink](./debug-consolelogsink.md) - 控制台输出
- [FileLogSink](./debug-filelogsink.md) - 文件输出
- [LogLevel](./debug-loglevel.md) - 日志级别枚举

View File

@@ -0,0 +1,40 @@
# LogLevel
**命名空间**: `XCEngine::Debug`
**类型**: `enum class`
**描述**: 日志级别枚举,定义日志的严重程度。
## 概述
`LogLevel` 枚举定义了从最详细到最严重的日志级别。`Logger` 根据设置的最小级别过滤日志。
## 枚举值
| 值 | 说明 | 数值 |
|----|------|------|
| `Verbose` | 详细调试信息 | 0 |
| `Debug` | 调试信息 | 1 |
| `Info` | 一般信息 | 2 |
| `Warning` | 警告信息 | 3 |
| `Error` | 错误信息 | 4 |
| `Fatal` | 致命错误 | 5 |
## 辅助函数
| 函数 | 描述 |
|------|------|
| `const char* LogLevelToString(LogLevel level)` | 将日志级别转换为字符串 |
## 使用示例
```cpp
// 设置最小日志级别
Logger::Get().SetMinimumLevel(LogLevel::Warning);
// 只有 Warning、Error、Fatal 级别的日志会被输出
```
## 相关文档
- [Logger](./debug-logger.md) - 日志记录器

View File

@@ -0,0 +1,83 @@
# Debug 模块概览
**命名空间**: `XCEngine::Debug`
**类型**: `module`
**描述**: XCEngine 的调试和日志模块,提供日志记录和性能分析功能。
## 概述
Debug 模块提供了一套完整的调试工具,包括日志系统和性能分析器。
## 模块内容
### 日志系统
| 组件 | 文件 | 描述 |
|------|------|------|
| [Logger](./debug-logger.md) | `Logger.h` | 日志记录器 |
| [ILogSink](./debug-ilogsink.md) | `ILogSink.h` | 日志输出接口 |
| [ConsoleLogSink](./debug-consolelogsink.md) | `ConsoleLogSink.h` | 控制台输出 |
| [FileLogSink](./debug-filelogsink.md) | `FileLogSink.h` | 文件输出 |
| [LogLevel](./debug-loglevel.md) | `LogLevel.h` | 日志级别枚举 |
| [LogCategory](./debug-logcategory.md) | `LogCategory.h` | 日志分类枚举 |
| [LogEntry](./debug-logentry.md) | `LogEntry.h` | 日志条目结构 |
### 性能分析
| 组件 | 文件 | 描述 |
|------|------|------|
| [Profiler](./debug-profiler.md) | `Profiler.h` | 性能分析器 |
## 日志级别
| 级别 | 描述 |
|------|------|
| `Verbose` | 详细调试信息 |
| `Debug` | 调试信息 |
| `Info` | 一般信息 |
| `Warning` | 警告信息 |
| `Error` | 错误信息 |
| `Fatal` | 致命错误 |
## 日志分类
| 分类 | 描述 |
|------|------|
| `General` | 通用 |
| `Rendering` | 渲染 |
| `Physics` | 物理 |
| `Audio` | 音频 |
| `Scripting` | 脚本 |
| `Network` | 网络 |
| `Memory` | 内存 |
| `Threading` | 线程 |
| `FileSystem` | 文件系统 |
| `Custom` | 自定义 |
## 使用示例
```cpp
#include <XCEngine/Debug/Logger.h>
// 初始化日志系统
Logger::Get().Initialize();
Logger::Get().AddSink(std::make_unique<ConsoleLogSink>());
Logger::Get().AddSink(std::make_unique<FileLogSink>("app.log"));
// 设置日志级别
Logger::Get().SetMinimumLevel(LogLevel::Debug);
// 记录日志
XE_LOG(LogCategory::Rendering, LogLevel::Info, "Render started");
// 使用宏记录日志
if (condition) {
XE_LOG(LogCategory::General, LogLevel::Error, "Something went wrong");
}
```
## 相关文档
- [Profiler](./debug-profiler.md) - 性能分析器

View File

@@ -0,0 +1,117 @@
# Profiler
**命名空间**: `XCEngine::Debug`
**类型**: `class` (singleton)
**描述**: 性能分析器单例,用于测量代码块执行时间并支持 Chrome Tracing 格式导出。
## 概述
`Profiler` 是 XCEngine 的性能分析工具。它通过栈式记录和采样方式跟踪函数执行时间,支持导出为 Chrome Tracing 格式(可通过 Chrome 的 `chrome://tracing` 查看)。
## 单例访问
| 方法 | 描述 |
|------|------|
| `static Profiler& Get()` | 获取单例实例 |
## 公共方法
### 生命周期
| 方法 | 描述 |
|------|------|
| `void Initialize()` | 初始化性能分析器 |
| `void Shutdown()` | 关闭性能分析器 |
### 性能测量
| 方法 | 描述 |
|------|------|
| `void BeginProfile(const char* name)` | 开始一个性能分析块 |
| `void EndProfile()` | 结束当前性能分析块 |
### 帧管理
| 方法 | 描述 |
|------|------|
| `void BeginFrame()` | 开始一帧的分析 |
| `void EndFrame()` | 结束一帧的分析 |
### 事件标记
| 方法 | 描述 |
|------|------|
| `void MarkEvent(const char* name, uint64_t timestamp, uint32_t threadId)` | 标记一个事件点 |
| `void SetMarker(const char* name, uint32_t color)` | 设置帧标记 |
### 导出
| 方法 | 描述 |
|------|------|
| `void ExportChromeTracing(const Containers::String& filePath)` | 导出为 Chrome Tracing JSON 格式 |
## 宏定义
### XE_PROFILE_BEGIN
```cpp
#define XE_PROFILE_BEGIN(name) XCEngine::Debug::Profiler::Get().BeginProfile(name)
```
开始分析指定名称的代码块。
### XE_PROFILE_END
```cpp
#define XE_PROFILE_END() XCEngine::Debug::Profiler::Get().EndProfile()
```
结束当前分析块。
### XE_PROFILE_FUNCTION
```cpp
#define XE_PROFILE_FUNCTION() XE_PROFILE_BEGIN(__FUNCTION__)
```
自动使用当前函数名进行分析。
## 使用示例
```cpp
// 初始化
Profiler::Get().Initialize();
// 使用宏自动管理生命周期
void RenderFrame() {
XE_PROFILE_FUNCTION();
{
XE_PROFILE_BEGIN("UpdateGeometry");
UpdateGeometry();
XE_PROFILE_END();
}
{
XE_PROFILE_BEGIN("DrawCalls");
DrawCalls();
XE_PROFILE_END();
}
}
// 帧管理
Profiler::Get().BeginFrame();
// ... 渲染帧 ...
Profiler::Get().EndFrame();
// 导出 Chrome Tracing 格式
Profiler::Get().ExportChromeTracing("profile.json");
Profiler::Get().Shutdown();
```
## 相关文档
- [Logger](./debug-logger.md) - 日志记录器

94
docs/api/index.md Normal file
View File

@@ -0,0 +1,94 @@
# XCEngine API 文档总索引
**描述**: XCEngine 图形引擎的完整 API 文档索引。
---
## 模块导航
| 模块 | 文档目录 | 描述 |
|------|----------|------|
| **RHI** | [rhi/](./rhi/rhi-overview.md) | 渲染硬件接口抽象层 |
| **D3D12** | [rhi/d3d12/](./rhi/d3d12/d3d12-overview.md) | DirectX 12 后端实现 |
| **OpenGL** | [rhi/opengl/](./rhi/opengl/opengl-overview.md) | OpenGL 后端实现 |
| **Containers** | [containers/](./containers/container-overview.md) | 容器数据结构 |
| **Memory** | [memory/](./memory/memory-overview.md) | 内存管理 |
| **Threading** | [threading/](./threading/threading-overview.md) | 多线程和任务系统 |
| **Core** | [core/](./core/core-overview.md) | 核心基础类型 |
| **Debug** | [debug/](./debug/debug-overview.md) | 调试和日志 |
| **Math** | [math/](./math/math-overview.md) | 数学库 |
| **Resources** | [resources/](./resources/resources-overview.md) | 资源管理系统 |
---
## 快速开始
### 创建渲染设备
```cpp
#include <XCEngine/RHI/RHIFactory.h>
#include <XCEngine/RHI/RHIDevice.h>
// 创建 D3D12 设备
RHI::RHIDevice* device = RHI::RHIFactory::CreateRHIDevice(RHI::RHIType::D3D12);
// 初始化
RHI::RHIDeviceDesc desc;
desc.windowHandle = hwnd;
device->Initialize(desc);
```
### 使用资源管理器
```cpp
#include <XCEngine/Resources/ResourceManager.h>
// 加载纹理
auto texture = Resources::ResourceManager::Get().Load<Resources::Texture>("textures/player.png");
// 加载网格
auto mesh = Resources::ResourceManager::Get().Load<Resources::Mesh>("models/player.fbx");
```
### 日志记录
```cpp
#include <XCEngine/Debug/Logger.h>
// 记录日志
XE_LOG(Debug::LogCategory::Rendering, Debug::LogLevel::Info, "Render started");
```
### 数学运算
```cpp
#include <XCEngine/Math/Matrix4.h>
// 创建变换矩阵
Math::Matrix4 transform = Math::Matrix4::TRS(position, rotation, scale);
```
---
## 文档统计
| 模块 | 文档数量 |
|------|----------|
| RHI 抽象层 | 17 |
| D3D12 后端 | 24 |
| OpenGL 后端 | 14 |
| Math | 17 |
| Resources | 17 |
| Threading | 10 |
| Memory | 6 |
| Debug | 9 |
| Core | 6 |
| Containers | 4 |
| **总计** | **124** |
---
## 相关文档
- [XCEngine 架构设计](../../docs/plan/XCEngine渲染引擎架构设计.md)
- [RHI 抽象层设计](../../docs/plan/RHI抽象层设计与实现.md)

View File

@@ -0,0 +1,67 @@
# AABB / OBB
轴对齐包围盒 (AABB) 和有向包围盒 (OBB)。
## 头文件
```cpp
#include <XCEngine/Math/AABB.h>
```
## 命名空间
`XCEngine::Math`
## AABB - 轴对齐包围盒
`AABB` 在 Math 库中通过 `Bounds` 类型实现,参见 [math-bounds.md](math-bounds.md)。
## OBB - 有向包围盒
OBB 是可以任意方向旋转的包围盒。
```cpp
struct OBB {
Vector3 center;
Vector3 extents; // 半长
Matrix4 transform; // 变换矩阵
};
```
### 构造函数
- `OBB()` - 默认构造
- `OBB(const Vector3& center, const Vector3& extents)` - 从中心和半长构造
### 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `GetAxis(index)` | `Vector3` | 获取局部轴 (0=X, 1=Y, 2=Z) |
| `GetMin()` | `Vector3` | 局部空间最小点 |
| `GetMax()` | `Vector3` | 局部空间最大点 |
| `Contains(point)` | `bool` | 点是否在 OBB 内 |
| `Intersects(OBB)` | `bool` | 与另一个 OBB 相交 (SAT) |
| `Intersects(Sphere)` | `bool` | 与球体相交 |
## 备注
- AABB 与轴对齐,检测简单但可能不够紧凑
- OBB 可旋转,检测使用分离轴定理 (SAT)
- OBB 适合动态旋转的物体
## 使用示例
```cpp
// OBB
OBB obb;
obb.center = Vector3(0.0f);
obb.extents = Vector3(1.0f);
obb.transform = Matrix4::TRS(pos, rot, scale);
Vector3 localAxis = obb.GetAxis(0);
if (obb.Contains(point)) { ... }
if (obb.Intersects(otherOBB)) { ... }
if (obb.Intersects(sphere)) { ... }
```

View File

@@ -0,0 +1,61 @@
# Bounds
轴对齐包围盒 (AABB),中心-范围表示。
## 头文件
```cpp
#include <XCEngine/Math/Bounds.h>
```
## 命名空间
`XCEngine::Math`
## 结构体定义
```cpp
struct Bounds {
Vector3 center = Vector3::Zero();
Vector3 extents = Vector3::Zero(); // 半长,不是最大点
};
```
## 构造函数
- `Bounds()` - 默认构造
- `Bounds(const Vector3& center, const Vector3& size)` - 从中心和大小构造
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `GetMin()` | `Vector3` | 最小点: `center - extents` |
| `GetMax()` | `Vector3` | 最大点: `center + extents` |
| `SetMinMax(min, max)` | `void` | 从最小/最大点设置 |
| `Contains(point)` | `bool` | 点是否在盒内 |
| `Intersects(other)` | `bool` | 与另一个 Bounds 相交 |
| `Encapsulate(point)` | `void` | 扩展包含点 |
| `Encapsulate(bounds)` | `void` | 扩展包含另一个 Bounds |
| `Expand(amount)` | `void` | 各方向扩展 amount |
| `Expand(amount)` | `void` | 按 Vector3 扩展 |
| `GetClosestPoint(point)` | `Vector3` | 盒上最接近给定点的点 |
| `GetVolume()` | `float` | 体积 |
## 使用示例
```cpp
Bounds bounds(center, extents);
// 包含点
if (bounds.Contains(point)) { ... }
// 扩展包围盒
bounds.Encapsulate(newPoint);
// 相交检测
if (bounds.Intersects(other)) { ... }
// 设置
bounds.SetMinMax(minPoint, maxPoint);
```

63
docs/api/math/math-box.md Normal file
View File

@@ -0,0 +1,63 @@
# Box
带变换的有向包围盒 (OBB) 结构体。
## 头文件
```cpp
#include <XCEngine/Math/Box.h>
```
## 命名空间
`XCEngine::Math`
## 结构体定义
```cpp
struct Box {
Vector3 center = Vector3::Zero();
Vector3 extents = Vector3::Zero(); // 半长
Matrix4x4 transform = Matrix4x4::Identity();
};
```
OBB 由中心点、半长向量和变换矩阵定义。
## 构造函数
- `Box()` - 默认构造
- `Box(const Vector3& center, const Vector3& extents)` - 从中心和半长构造
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `GetMin()` | `Vector3` | 局部空间最小点 (-extents) |
| `GetMax()` | `Vector3` | 局部空间最大点 (+extents) |
| `Contains(point)` | `bool` | 点是否在盒内(变换到局部空间检测) |
| `Intersects(Sphere)` | `bool` | 与球体相交 |
| `Intersects(Box)` | `bool` | 与另一个 OBB 相交SAT 算法) |
| `Intersects(Ray, t)` | `bool` | 与射线相交,输出距离 t |
## 使用示例
```cpp
Box box(Vector3(0.0f), Vector3(1.0f)); // 2x2x2 盒子
box.transform = Matrix4::TRS(position, rotation, scale);
// 点检测
if (box.Contains(testPoint)) { ... }
// 球体相交
if (box.Intersects(sphere)) { ... }
// OBB 相交
if (box.Intersects(otherBox)) { ... }
// 射线相交
float t;
if (box.Intersects(ray, t)) {
Vector3 hit = ray.GetPoint(t);
}
```

View File

@@ -0,0 +1,72 @@
# Color
颜色结构体,支持 RGBA 浮点分量。
## 头文件
```cpp
#include <XCEngine/Math/Color.h>
```
## 命名空间
`XCEngine::Math`
## 结构体定义
```cpp
struct Color {
float r = 1.0f;
float g = 1.0f;
float b = 1.0f;
float a = 1.0f;
};
```
分量范围: 0.0f ~ 1.0f
## 静态工厂方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `White()` | `Color` | (1, 1, 1, 1) |
| `Black()` | `Color` | (0, 0, 0, 1) |
| `Red()` | `Color` | (1, 0, 0, 1) |
| `Green()` | `Color` | (0, 1, 0, 1) |
| `Blue()` | `Color` | (0, 0, 1, 1) |
| `Yellow()` | `Color` | (1, 1, 0, 1) |
| `Cyan()` | `Color` | (0, 1, 1, 1) |
| `Magenta()` | `Color` | (1, 0, 1, 1) |
| `Clear()` | `Color` | (0, 0, 0, 0),透明黑 |
## 静态方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Lerp(a, b, t)` | `Color` | 颜色线性插值 |
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `ToRGBA()` | `uint32_t` | 转换为 32-bit RGBA (0xAABBGGRR) |
| `ToVector3()` | `Vector3` | 转换为 RGB (丢弃 alpha) |
| `ToVector4()` | `Vector4` | 转换为 RGBA |
## 运算符
| 运算符 | 描述 |
|--------|------|
| `operator+(Color, Color)` | 颜色相加 |
| `operator-(Color, Color)` | 颜色相减 |
| `operator*(Color, float)` | 颜色乘以标量 |
| `operator/(Color, float)` | 颜色除以标量 |
## 使用示例
```cpp
Color red = Color::Red();
Color lerped = Color::Lerp(red, Color::Blue(), 0.5f);
uint32_t rgba = lerped.ToRGBA();
Vector4 v4 = lerped.ToVector4();
```

View File

@@ -0,0 +1,61 @@
# Frustum
视锥体,用于视锥剔除。
## 头文件
```cpp
#include <XCEngine/Math/Frustum.h>
```
## 命名空间
`XCEngine::Math`
## 结构体定义
```cpp
class Frustum {
public:
Plane planes[6]; // 6 个裁剪平面
enum class PlaneIndex {
Left = 0,
Right = 1,
Bottom = 2,
Top = 3,
Near = 4,
Far = 5
};
};
```
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Contains(point)` | `bool` | 点是否在视锥内 |
| `Contains(Sphere)` | `bool` | 球体是否在视锥内 |
| `Contains(Bounds)` | `bool` | Bounds 是否在视锥内 |
| `Intersects(Bounds)` | `bool` | Bounds 是否与视锥相交 |
| `Intersects(Sphere)` | `bool` | 球体是否与视锥相交 |
## 使用示例
```cpp
Frustum frustum;
// 需要从相机矩阵构建视锥平面
// 视锥剔除
for (const auto& object : objects) {
if (frustum.Contains(object.bounds)) {
// 物体在视锥内,渲染
Render(object);
}
}
// 或使用相交检测
if (frustum.Intersects(bounds)) {
Render(object);
}
```

51
docs/api/math/math-h.md Normal file
View File

@@ -0,0 +1,51 @@
# Math - 数学常量
数学库全局常量和辅助函数。
## 头文件
```cpp
#include <XCEngine/Math/Math.h>
```
## 命名空间
`XCEngine::Math`
## 数学常量
| 常量 | 值 | 描述 |
|------|-----|------|
| `PI` | 3.14159265358979323846f | 圆周率 |
| `TWO_PI` | 6.28318530717958647692f | 2π |
| `HALF_PI` | 1.57079632679489661923f | π/2 |
| `DEG_TO_RAD` | PI / 180.0f | 度转弧度 |
| `RAD_TO_DEG` | 180.0f / PI | 弧度转度 |
| `EPSILON` | 1e-6f | 浮点比较容差 |
| `FLOAT_MAX` | 3.402823466e+38f | float 最大值 |
## 辅助函数
| 函数 | 返回值 | 描述 |
|------|--------|------|
| `Radians(degrees)` | `float` | 度转弧度 |
| `Degrees(radians)` | `float` | 弧度转度 |
## 使用示例
```cpp
using namespace XCEngine::Math;
float radians = 90.0f * DEG_TO_RAD; // 90度 -> 弧度
float degrees = PI * RAD_TO_DEG; // 弧度 -> 度
float rad2 = Radians(45.0f); // 使用函数
// 浮点比较
if (std::abs(a - b) < EPSILON) {
// a 和 b 相等
}
// 三角函数(来自 <cmath>
float sinVal = std::sin(angle);
float cosVal = std::cos(angle);
```

View File

@@ -0,0 +1,69 @@
# Matrix3 / Matrix3x3
3x3 矩阵结构体,用于表示 3D 旋转和缩放变换。
## 头文件
```cpp
#include <XCEngine/Math/Matrix3.h>
```
## 命名空间
`XCEngine::Math`
## 类型别名
```cpp
using Matrix3 = Matrix3x3;
```
## 存储方式
行优先存储 (row-major)
```
m[row][col]
m[0][0] m[0][1] m[0][2]
m[1][0] m[1][1] m[1][2]
m[2][0] m[2][1] m[2][2]
```
## 构造函数
- 默认构造函数初始化为零矩阵
## 静态工厂方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Identity()` | `Matrix3` | 单位矩阵 |
| `Zero()` | `Matrix3` | 零矩阵 |
| `RotationX(float radians)` | `Matrix3` | X 轴旋转矩阵 |
| `RotationY(float radians)` | `Matrix3` | Y 轴旋转矩阵 |
| `RotationZ(float radians)` | `Matrix3` | Z 轴旋转矩阵 |
| `Scale(const Vector3& scale)` | `Matrix3` | 缩放矩阵 |
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Transpose()` | `Matrix3` | 转置矩阵 |
| `Inverse()` | `Matrix3` | 逆矩阵 |
| `Determinant()` | `float` | 行列式 |
## 运算符
| 运算符 | 描述 |
|--------|------|
| `operator*(Matrix3, Matrix3)` | 矩阵乘法 |
| `operator*(Matrix3, Vector3)` | 矩阵-向量乘法 |
## 使用示例
```cpp
Matrix3 rotX = Matrix3::RotationX(Math::HALF_PI);
Matrix3 rotY = Matrix3::RotationY(0.0f);
Matrix3 scale = Matrix3::Scale(Vector3(2.0f, 2.0f, 2.0f));
Matrix3 combined = rotX * scale;
Vector3 transformed = combined * Vector3(1.0f, 0.0f, 0.0f);
```

View File

@@ -0,0 +1,101 @@
# Matrix4 / Matrix4x4
4x4 矩阵结构体,用于表示完整的 3D 变换(平移、旋转、缩放)、视图和投影变换。
## 头文件
```cpp
#include <XCEngine/Math/Matrix4.h>
```
## 命名空间
`XCEngine::Math`
## 类型别名
```cpp
using Matrix4 = Matrix4x4;
```
## 存储方式
行优先存储 (row-major)
```
m[0][0] m[0][1] m[0][2] m[0][3]
m[1][0] m[1][1] m[1][2] m[1][3]
m[2][0] m[2][1] m[2][2] m[2][3]
m[3][0] m[3][1] m[3][2] m[3][3]
```
## 静态工厂方法
### 基础变换
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Identity()` | `Matrix4` | 单位矩阵 |
| `Zero()` | `Matrix4` | 零矩阵 |
| `Translation(const Vector3& v)` | `Matrix4` | 平移矩阵 |
| `Scale(const Vector3& v)` | `Matrix4` | 缩放矩阵 |
| `Rotation(const Quaternion& q)` | `Matrix4` | 旋转矩阵(四元数) |
| `TRS(translation, rotation, scale)` | `Matrix4` | 完整变换 |
### 旋转
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `RotationX(float radians)` | `Matrix4` | X 轴旋转 |
| `RotationY(float radians)` | `Matrix4` | Y 轴旋转 |
| `RotationZ(float radians)` | `Matrix4` | Z 轴旋转 |
### 相机变换
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `LookAt(eye, target, up)` | `Matrix4` | 视图矩阵 |
| `Perspective(fov, aspect, near, far)` | `Matrix4` | 透视投影 |
| `Orthographic(left, right, bottom, top, near, far)` | `Matrix4` | 正交投影 |
## 实例方法
### 乘法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `operator*(Matrix4, Matrix4)` | `Matrix4` | 矩阵乘法 |
| `operator*(Matrix4, Vector4)` | `Vector4` | 矩阵-向量乘法 |
| `MultiplyPoint(v)` | `Vector3` | 点变换(带平移) |
| `MultiplyVector(v)` | `Vector3` | 方向变换(不带平移) |
### 分解
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Transpose()` | `Matrix4` | 转置矩阵 |
| `Inverse()` | `Matrix4` | 逆矩阵 |
| `Determinant()` | `float` | 行列式 |
| `GetTranslation()` | `Vector3` | 获取平移分量 |
| `GetRotation()` | `Quaternion` | 获取旋转分量 |
| `GetScale()` | `Vector3` | 获取缩放分量 |
| `Decompose(translation, rotation, scale)` | `void` | 分解所有分量 |
## 使用示例
```cpp
// MVP 矩阵
Matrix4 model = Matrix4::TRS(position, rotation, scale);
Matrix4 view = Matrix4::LookAt(cameraPos, target, Vector3::Up());
Matrix4 proj = Matrix4::Perspective(45.0f * DEG_TO_RAD, aspect, 0.1f, 100.0f);
Matrix4 mvp = proj * view * model;
// 变换点
Vector3 worldPos = model.MultiplyPoint(localPos);
Vector3 worldDir = model.MultiplyVector(localDir);
// 分解矩阵
Vector3 translation;
Quaternion rotation;
Vector3 scale;
model.Decompose(translation, rotation, scale);
```

View File

@@ -0,0 +1,100 @@
# Math 模块概览
**命名空间**: `XCEngine::Math`
**类型**: `module`
**描述**: XCEngine 的数学库模块,提供图形引擎常用的数学类型和函数。
## 概述
Math 模块提供了一套完整的图形数学库,包括向量、矩阵、四元数、变换和几何类型等。
## 模块内容
### 向量类型
| 组件 | 文件 | 描述 |
|------|------|------|
| [Vector2](./math-vector2.md) | `Vector2.h` | 二维向量 |
| [Vector3](./math-vector3.md) | `Vector3.h` | 三维向量 |
| [Vector4](./math-vector4.md) | `Vector4.h` | 四维向量 |
### 矩阵类型
| 组件 | 文件 | 描述 |
|------|------|------|
| [Matrix3](./math-matrix3.md) | `Matrix3.h` | 3x3 矩阵 |
| [Matrix4](./math-matrix4.md) | `Matrix4.h` | 4x4 矩阵 |
### 旋转/变换
| 组件 | 文件 | 描述 |
|------|------|------|
| [Quaternion](./math-quaternion.md) | `Quaternion.h` | 四元数 |
| [Transform](./math-transform.md) | `Transform.h` | 变换组件 |
### 几何类型
| 组件 | 文件 | 描述 |
|------|------|------|
| [Color](./math-color.md) | `Color.h` | 颜色 |
| [Ray](./math-ray.md) | `Ray.h` | 射线 |
| [Plane](./math-plane.md) | `Plane.h` | 平面 |
| [Sphere](./math-sphere.md) | `Sphere.h` | 球体 |
| [Box](./math-box.md) | `Box.h` | 盒子 |
| [Bounds](./math-bounds.md) | `Bounds.h` | 包围盒 |
| [AABB](./math-aabb.md) | `AABB.h` | 轴对齐包围盒 |
| [Frustum](./math-frustum.md) | `Frustum.h` | 视锥体 |
| [Rect](./math-rect.md) | `Rect.h` | 二维矩形 |
## 常量定义
| 常量 | 值 | 描述 |
|------|-----|------|
| `PI` | 3.14159265358979323846f | 圆周率 |
| `TWO_PI` | 6.28318530717958647692f | 2π |
| `HALF_PI` | 1.57079632679489661923f | π/2 |
| `DEG_TO_RAD` | PI / 180.0f | 度到弧度 |
| `RAD_TO_DEG` | 180.0f / PI | 弧度到度 |
| `EPSILON` | 1e-6f | 浮点精度 |
| `FLOAT_MAX` | 3.402823466e+38f | 浮点最大值 |
详细文档: [Math.h - 常量和辅助函数](./math-h.md)
## 辅助函数
| 函数 | 描述 |
|------|------|
| `Radians(float degrees)` | 度转弧度 |
| `Degrees(float radians)` | 弧度转度 |
## 使用示例
```cpp
#include <XCEngine/Math/Math.h>
#include <XCEngine/Math/Vector3.h>
#include <XCEngine/Math/Matrix4.h>
#include <XCEngine/Math/Quaternion.h>
using namespace XCEngine::Math;
// 向量运算
Vector3 a(1.0f, 0.0f, 0.0f);
Vector3 b(0.0f, 1.0f, 0.0f);
float dot = Vector3::Dot(a, b);
Vector3 cross = Vector3::Cross(a, b);
Vector3 normalized = Vector3::Normalize(a);
// 矩阵运算
Matrix4 model = Matrix4::TRS(position, rotation, scale);
Matrix4 view = Matrix4::LookAt(eye, target, up);
Matrix4 projection = Matrix4::Perspective(fov, aspect, near, far);
Matrix4 mvp = projection * view * model;
// 四元数运算
Quaternion q1 = Quaternion::FromEuler(0, 90, 0);
Quaternion q2 = Quaternion::FromAxisAngle(Vector3::Up(), Math::Radians(45.0f));
Quaternion combined = q1 * q2;
Vector3 rotated = q2 * Vector3::Forward();
```

View File

@@ -0,0 +1,66 @@
# Plane
3D 平面结构体,由法线和距离表示。
## 头文件
```cpp
#include <XCEngine/Math/Plane.h>
```
## 命名空间
`XCEngine::Math`
## 结构体定义
```cpp
struct Plane {
Vector3 normal = Vector3::Up(); // 单位法线
float distance = 0.0f; // 原点到平面的有符号距离
};
```
平面方程: `dot(normal, X) + distance = 0`
## 构造函数
- `Plane()` - 默认构造 (y=0 平面)
- `Plane(const Vector3& normal, float distance)` - 从法线和距离构造
## 静态工厂方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `FromPoints(a, b, c)` | `Plane` | 从三个不共线点创建 |
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `GetDistanceToPoint(point)` | `float` | 点到平面的有符号距离 |
| `GetClosestPoint(point)` | `Vector3` | 平面上最接近给定点的点 |
| `GetSide(point)` | `bool` | 点在平面的哪一侧 (true=正面) |
| `Intersects(Sphere)` | `bool` | 与球体相交 |
## 使用示例
```cpp
// 创建平面
Plane floor;
floor.normal = Vector3::Up();
floor.distance = 0.0f; // y=0 平面
// 或者从三点创建
Plane plane = Plane::FromPoints(p0, p1, p2);
// 检测点在哪侧
bool above = floor.GetSide(point);
float signedDist = floor.GetDistanceToPoint(point);
// 投影点到平面
Vector3 closest = floor.GetClosestPoint(point);
// 平面相交检测
if (plane.Intersects(sphere)) { ... }
```

View File

@@ -0,0 +1,86 @@
# Quaternion
四元数结构体,用于表示 3D 旋转,避免欧拉角的万向锁问题。
## 头文件
```cpp
#include <XCEngine/Math/Quaternion.h>
```
## 命名空间
`XCEngine::Math`
## 结构体定义
```cpp
struct Quaternion {
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
float w = 1.0f; // w 是标量分量
};
```
四元数格式: `(x, y, z, w)` = `(vec, w)`
## 静态工厂方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Identity()` | `Quaternion` | 返回 (0, 0, 0, 1),恒等旋转 |
| `FromAxisAngle(axis, radians)` | `Quaternion` | 从轴角创建 |
| `FromEulerAngles(pitch, yaw, roll)` | `Quaternion` | 从欧拉角创建(弧度) |
| `FromEulerAngles(euler)` | `Quaternion` | 从 Vector3 欧拉角创建 |
| `FromRotationMatrix(matrix)` | `Quaternion` | 从旋转矩阵创建 |
| `Slerp(a, b, t)` | `Quaternion` | 球面线性插值 |
| `LookRotation(forward, up)` | `Quaternion` | 看向方向 |
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `ToEulerAngles()` | `Vector3` | 转换为欧拉角(弧度) |
| `ToMatrix4x4()` | `Matrix4` | 转换为 4x4 旋转矩阵 |
| `Inverse()` | `Quaternion` | 共轭/逆四元数 |
| `Dot(other)` | `float` | 点积 |
| `Magnitude()` | `float` | 模长 |
| `Normalized()` | `Quaternion` | 归一化 |
| `Normalize(q)` | `Quaternion` | 归一化(静态) |
## 运算符
| 运算符 | 描述 |
|--------|------|
| `operator*(Quaternion, Quaternion)` | 组合旋转 |
## 与 Vector3 的乘法
```cpp
Vector3 operator*(const Quaternion& q, const Vector3& v);
```
用四元数旋转向量。
## 使用示例
```cpp
// 创建旋转
Quaternion rot = Quaternion::FromEulerAngles(0.0f, 90.0f * DEG_TO_RAD, 0.0f);
// 组合旋转
Quaternion combined = rot1 * rot2;
// 球面插值
Quaternion lerped = Quaternion::Slerp(rot1, rot2, 0.5f);
// 旋转向量
Vector3 rotated = rot * Vector3::Forward();
// 转换
Vector3 euler = rot.ToEulerAngles();
Matrix4 mat = rot.ToMatrix4x4();
// 看向目标
Quaternion lookAt = Quaternion::LookRotation(target - position);
```

58
docs/api/math/math-ray.md Normal file
View File

@@ -0,0 +1,58 @@
# Ray
3D 射线结构体,用于光线投射和拾取。
## 头文件
```cpp
#include <XCEngine/Math/Ray.h>
```
## 命名空间
`XCEngine::Math`
## 结构体定义
```cpp
struct Ray {
Vector3 origin; // 射线起点
Vector3 direction; // 归一化方向
};
```
## 构造函数
- `Ray()` - 默认构造
- `Ray(const Vector3& origin, const Vector3& direction)` - 从点和方向构造
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `GetPoint(t)` | `Vector3` | 获取射线上 t 距离处的点: `origin + direction * t` |
## 相交检测
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Intersects(Sphere, t)` | `bool` | 与球体相交,输出距离 t |
| `Intersects(Box, t)` | `bool` | 与 AABB 相交,输出距离 t |
| `Intersects(Plane, t)` | `bool` | 与平面相交,输出距离 t |
## 使用示例
```cpp
Ray ray(cameraPosition, rayDirection);
// 与球体相交
float t;
if (ray.Intersects(sphere, t)) {
Vector3 hitPoint = ray.GetPoint(t);
}
// 与平面相交
if (ray.Intersects(plane, t)) {
Vector3 hitPoint = ray.GetPoint(t);
}
```

137
docs/api/math/math-rect.md Normal file
View File

@@ -0,0 +1,137 @@
# Rect / RectInt / Viewport
2D 矩形和视口结构体。
## 头文件
```cpp
#include <XCEngine/Math/Rect.h>
```
## 命名空间
`XCEngine::Math`
---
## Rect - 浮点矩形
```cpp
struct Rect {
float x = 0.0f; // 左边界
float y = 0.0f; // 上边界
float width = 0.0f;
float height = 0.0f;
};
```
### 构造
- `Rect(float x, float y, float w, float h)`
### 边界访问
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `GetLeft()` | `float` | x |
| `GetRight()` | `float` | x + width |
| `GetTop()` | `float` | y |
| `GetBottom()` | `float` | y + height |
| `GetPosition()` | `Vector2` | (x, y) |
| `GetSize()` | `Vector2` | (width, height) |
| `GetCenter()` | `Vector2` | 中心点 |
### 检测方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Contains(px, py)` | `bool` | 点是否在矩形内 |
| `Contains(point)` | `bool` | Vector2 点检测 |
| `Intersects(other)` | `bool` | 与另一矩形相交 |
### 静态方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Intersect(a, b)` | `Rect` | 两矩形交集 |
| `Union(a, b)` | `Rect` | 两矩形并集 |
### 设置方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Set(x, y, w, h)` | `void` | 设置所有值 |
| `SetPosition(x, y)` | `void` | 设置位置 |
| `SetPosition(Vector2)` | `void` | 设置位置 |
---
## RectInt - 整数矩形
```cpp
struct RectInt {
int32_t x = 0;
int32_t y = 0;
int32_t width = 0;
int32_t height = 0;
};
```
与 Rect 类似,但使用 int32_t 类型。
### 边界访问
`GetLeft/Right/Top/Bottom/GetPosition/GetSize/GetCenter` - 返回 int32_t 或 Vector2。
### 检测
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Contains(px, py)` | `bool` | 整数点检测 |
| `Intersects(other)` | `bool` | 相交检测 |
---
## Viewport - 视口
用于渲染视口和屏幕映射。
```cpp
struct Viewport {
float x = 0.0f;
float y = 0.0f;
float width = 0.0f;
float height = 0.0f;
float minDepth = 0.0f;
float maxDepth = 1.0f;
};
```
### 构造
- `Viewport(float x, float y, float w, float h)`
- `Viewport(float x, float y, float w, float h, float minD, float maxD)`
### 方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `GetAspectRatio()` | `float` | 宽高比 (width/height) |
| `GetRect()` | `Rect` | 转换为 Rect |
---
## 使用示例
```cpp
// Rect
Rect screenRect(0.0f, 0.0f, 1920.0f, 1080.0f);
if (screenRect.Contains(mouseX, mouseY)) { ... }
// 矩形相交
Rect overlap = Rect::Intersect(rectA, rectB);
// Viewport
Viewport viewport(0, 0, 1920, 1080);
float aspect = viewport.GetAspectRatio(); // 16:9 = 1.78
```

View File

@@ -0,0 +1,47 @@
# Sphere
3D 球体结构体。
## 头文件
```cpp
#include <XCEngine/Math/Sphere.h>
```
## 命名空间
`XCEngine::Math`
## 结构体定义
```cpp
struct Sphere {
Vector3 center = Vector3::Zero();
float radius = 0.0f;
};
```
## 构造函数
- `Sphere()` - 默认构造
- `Sphere(const Vector3& center, float radius)` - 从中心和半径构造
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Contains(point)` | `bool` | 点是否在球体内(包括表面) |
| `Intersects(other)` | `bool` | 与另一个球体是否相交 |
## 使用示例
```cpp
Sphere sphere(Vector3(0.0f, 0.0f, 0.0f), 1.0f);
// 检测点
if (sphere.Contains(Vector3(0.5f, 0.0f, 0.0f))) { ... }
// 检测球体相交
Sphere other(Vector3(1.0f, 0.0f, 0.0f), 1.0f);
if (sphere.Intersects(other)) { ... }
```

View File

@@ -0,0 +1,67 @@
# Transform
3D 变换结构体,包含位置、旋转和缩放,用于层次化变换。
## 头文件
```cpp
#include <XCEngine/Math/Transform.h>
```
## 命名空间
`XCEngine::Math`
## Space 枚举
```cpp
enum class Space { Self, World };
```
## 结构体定义
```cpp
struct Transform {
Vector3 position = Vector3::Zero();
Quaternion rotation = Quaternion::Identity();
Vector3 scale = Vector3::One();
};
```
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `ToMatrix()` | `Matrix4` | 转换为 4x4 变换矩阵 |
| `Inverse()` | `Transform` | 逆变换 |
| `operator*(Transform, Transform)` | `Transform` | 组合变换 |
### 空间变换
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `TransformPoint(point)` | `Vector3` | 变换点(带平移) |
| `TransformDirection(direction)` | `Vector3` | 变换方向(不带平移) |
| `InverseTransformPoint(point)` | `Vector3` | 逆变换点 |
| `InverseTransformDirection(direction)` | `Vector3` | 逆变换方向 |
## 使用示例
```cpp
Transform world;
world.position = Vector3(10.0f, 0.0f, 0.0f);
world.rotation = Quaternion::Identity();
world.scale = Vector3::One();
Matrix4 matrix = world.ToMatrix();
// 组合父子变换
Transform parent, child;
parent.position = Vector3(5.0f, 0.0f, 0.0f);
child.position = Vector3(2.0f, 0.0f, 0.0f);
Transform worldTransform = parent * child;
// 变换点
Vector3 localPos(1.0f, 0.0f, 0.0f);
Vector3 worldPos = world.TransformPoint(localPos);
```

View File

@@ -0,0 +1,68 @@
# Vector2
2D 向量结构体,用于表示 2D 空间中的点、方向或颜色。
## 头文件
```cpp
#include <XCEngine/Math/Vector2.h>
```
## 命名空间
`XCEngine::Math`
## 结构体定义
```cpp
struct Vector2 {
float x = 0.0f;
float y = 0.0f;
};
```
## 静态工厂方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Zero()` | `Vector2` | 返回 (0, 0) |
| `One()` | `Vector2` | 返回 (1, 1) |
| `Up()` | `Vector2` | 返回 (0, 1),上方向 |
| `Down()` | `Vector2` | 返回 (0, -1),下方向 |
| `Right()` | `Vector2` | 返回 (1, 0),右方向 |
| `Left()` | `Vector2` | 返回 (-1, 0),左方向 |
## 静态数学方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Dot(a, b)` | `float` | 点积 |
| `Cross(a, b)` | `float` | 2D 叉积(返回标量) |
| `Normalize(v)` | `Vector2` | 归一化向量 |
| `Magnitude(v)` | `float` | 向量长度 |
| `SqrMagnitude(v)` | `float` | 长度平方(更快) |
| `Lerp(a, b, t)` | `Vector2` | 线性插值 |
| `MoveTowards(current, target, maxDistance)` | `Vector2` | 朝目标移动 |
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Magnitude()` | `float` | 获取向量长度 |
| `SqrMagnitude()` | `float` | 获取长度平方 |
| `Normalized()` | `Vector2` | 获取归一化副本 |
## 运算符
- 算术: `+`, `-`, `*` (scalar), `/` (scalar)
- 复合赋值: `+=`, `-=`, `*=`, `/=`
- 比较: `==`, `!=`
## 使用示例
```cpp
Vector2 pos(5.0f, 3.0f);
Vector2 dir = Vector2::Normalize(pos);
float len = pos.Magnitude();
Vector2 lerped = Vector2::Lerp(pos, Vector2::Zero(), 0.5f);
```

View File

@@ -0,0 +1,84 @@
# Vector3
3D 向量结构体,用于表示 3D 空间中的点、方向、颜色或法线。
## 头文件
```cpp
#include <XCEngine/Math/Vector3.h>
```
## 命名空间
`XCEngine::Math`
## 结构体定义
```cpp
struct Vector3 {
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
};
```
## 静态工厂方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Zero()` | `Vector3` | 返回 (0, 0, 0) |
| `One()` | `Vector3` | 返回 (1, 1, 1) |
| `Forward()` | `Vector3` | 返回 (0, 0, 1)前方向Z+ |
| `Back()` | `Vector3` | 返回 (0, 0, -1),后方向 |
| `Up()` | `Vector3` | 返回 (0, 1, 0),上方向 |
| `Down()` | `Vector3` | 返回 (0, -1, 0),下方向 |
| `Right()` | `Vector3` | 返回 (1, 0, 0),右方向 |
| `Left()` | `Vector3` | 返回 (-1, 0, 0),左方向 |
## 静态数学方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Dot(a, b)` | `float` | 点积 |
| `Cross(a, b)` | `Vector3` | 叉积(垂直于 a 和 b |
| `Normalize(v)` | `Vector3` | 归一化向量 |
| `Magnitude(v)` | `float` | 向量长度 |
| `SqrMagnitude(v)` | `float` | 长度平方 |
| `Lerp(a, b, t)` | `Vector3` | 线性插值 |
| `MoveTowards(current, target, maxDistance)` | `Vector3` | 朝目标移动 |
| `Project(vector, onNormal)` | `Vector3` | 投影到法线上 |
| `ProjectOnPlane(vector, planeNormal)` | `Vector3` | 投影到平面上 |
| `Angle(from, to)` | `float` | 两向量夹角(度) |
| `Reflect(inDirection, inNormal)` | `Vector3` | 反射 |
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Magnitude()` | `float` | 获取向量长度 |
| `SqrMagnitude()` | `float` | 获取长度平方 |
| `Normalized()` | `Vector3` | 获取归一化副本 |
## 运算符
- 算术: `+`, `-`, `*` (scalar/memberwise), `/` (scalar/memberwise)
- 复合赋值: `+=`, `-=`, `*=`, `/=`
- 下标: `operator[]` (0=x, 1=y, 2=z)
- 比较: `==`, `!=`
## 与 Quaternion 的乘法
```cpp
Vector3 operator*(const Quaternion& q, const Vector3& v);
```
用四元数旋转向量。
## 使用示例
```cpp
Vector3 pos(1.0f, 2.0f, 3.0f);
Vector3 dir = Vector3::Normalize(pos);
float len = pos.Magnitude();
Vector3 reflected = Vector3::Reflect(dir, Vector3::Up());
float angle = Vector3::Angle(Vector3::Forward(), dir);
```

View File

@@ -0,0 +1,62 @@
# Vector4
4D 向量结构体,用于表示齐次坐标、颜色 (RGBA) 或 SIMD 操作。
## 头文件
```cpp
#include <XCEngine/Math/Vector4.h>
```
## 命名空间
`XCEngine::Math`
## 结构体定义
```cpp
struct Vector4 {
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
float w = 0.0f;
};
```
## 构造方法
- `Vector4(float x, float y, float z, float w)` - 从四个分量构造
- `explicit Vector4(const Vector3& v, float w = 0.0f)` - 从 Vector3 构造
## 静态工厂方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Zero()` | `Vector4` | 返回 (0, 0, 0, 0) |
| `One()` | `Vector4` | 返回 (1, 1, 1, 1) |
## 静态数学方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `Dot(a, b)` | `float` | 4D 点积 |
| `Project(vector, onNormal)` | `Vector4` | 投影 |
## 实例方法
| 方法 | 返回值 | 描述 |
|------|--------|------|
| `ToVector3()` | `Vector3` | 转换到 Vector3丢弃 w |
## 运算符
- 算术: `+`, `-`, `*` (scalar)
- 下标: `operator[]`
- 比较: `==`, `!=`
## 使用示例
```cpp
Vector4 pos4(1.0f, 2.0f, 3.0f, 1.0f);
Vector3 pos3 = pos4.ToVector3();
```

View File

@@ -0,0 +1,74 @@
# IAllocator
**命名空间**: `XCEngine::Memory`
**类型**: `class` (abstract interface)
**描述**: 内存分配器抽象接口,定义标准分配协议。
## 概述
`IAllocator` 是 XCEngine 内存管理系统的核心抽象接口。它定义了分配、释放和重新分配内存的标准方法以及内存统计接口。所有专用分配器LinearAllocator、PoolAllocator、ProxyAllocator都实现此接口。
## 公共方法
### 内存操作
| 方法 | 描述 |
|------|------|
| `virtual void* Allocate(size_t size, size_t alignment = 0)` | 分配内存 |
| `virtual void Free(void* ptr)` | 释放内存 |
| `virtual void* Reallocate(void* ptr, size_t newSize)` | 重新分配内存 |
### 统计信息
| 方法 | 描述 |
|------|------|
| `virtual size_t GetTotalAllocated() const` | 获取已分配总字节数 |
| `virtual size_t GetTotalFreed() const` | 获取已释放总字节数 |
| `virtual size_t GetPeakAllocated() const` | 获取峰值分配字节数 |
| `virtual size_t GetAllocationCount() const` | 获取分配次数 |
### 元信息
| 方法 | 描述 |
|------|------|
| `virtual const char* GetName() const = 0` | 获取分配器名称 |
## 使用示例
```cpp
#include <XCEngine/Memory/IAllocator.h>
class MyAllocator : public IAllocator {
public:
void* Allocate(size_t size, size_t alignment = 0) override {
// 实现分配逻辑
return ::operator new(size);
}
void Free(void* ptr) override {
// 实现释放逻辑
::operator delete(ptr);
}
void* Reallocate(void* ptr, size_t newSize) override {
void* newPtr = Allocate(newSize);
// 拷贝旧数据...
Free(ptr);
return newPtr;
}
size_t GetTotalAllocated() const override { return m_allocated; }
size_t GetTotalFreed() const override { return m_freed; }
size_t GetPeakAllocated() const override { return m_peak; }
size_t GetAllocationCount() const override { return m_count; }
const char* GetName() const override { return "MyAllocator"; }
};
```
## 相关文档
- [MemoryManager](./memory-manager.md) - 内存管理器
- [LinearAllocator](./memory-linear-allocator.md) - 线性分配器
- [PoolAllocator](./memory-pool-allocator.md) - 内存池分配器

View File

@@ -0,0 +1,82 @@
# LinearAllocator
**命名空间**: `XCEngine::Memory`
**类型**: `class`
**描述**: 线性分配器,提供顺序分配和一次性释放的内存管理,适用于帧分配和临时对象。
## 概述
`LinearAllocator` 以顺序方式分配内存,每次分配都紧接在上一次分配之后。它不支持单个内存块的释放,只能通过 `Clear()` 一次性清空所有内存。这使得它非常适合作为帧分配器,每帧开始时 Clear 即可。
## 公共方法
### 构造/析构
| 方法 | 描述 |
|------|------|
| `explicit LinearAllocator(size_t size, IAllocator* parent = nullptr)` | 构造函数,预分配指定大小的缓冲区 |
| `~LinearAllocator()` | 析构函数,释放所有内存 |
### IAllocator 实现
| 方法 | 描述 |
|------|------|
| `void* Allocate(size_t size, size_t alignment = 8) override` | 顺序分配内存 |
| `void Free(void* ptr) override` | 空操作(不支持单个释放) |
| `void* Reallocate(void* ptr, size_t newSize) override` | 重新分配(总是分配新内存) |
### 线性操作
| 方法 | 描述 |
|------|------|
| `void Clear()` | 清空所有分配,下一次分配从头开始 |
| `void* GetMarker() const` | 获取当前分配位置标记 |
| `void SetMarker(void* marker)` | 恢复到指定标记位置 |
### 状态查询
| 方法 | 描述 |
|------|------|
| `size_t GetUsedSize() const` | 获取已使用的字节数 |
| `size_t GetCapacity() const` | 获取总容量 |
### 统计
| 方法 | 描述 |
|------|------|
| `size_t GetTotalAllocated() const` | 返回已使用字节数 |
| `size_t GetTotalFreed() const` | 返回 0 |
| `size_t GetPeakAllocated() const` | 返回容量大小 |
| `size_t GetAllocationCount() const` | 返回 0 |
## 使用示例
```cpp
// 创建 1MB 的线性分配器
auto allocator = std::make_unique<LinearAllocator>(1024 * 1024);
// 分配临时内存
void* ptr1 = allocator->Allocate(256);
void* ptr2 = allocator->Allocate(512);
void* ptr3 = allocator->Allocate(128);
// 保存标记
void* marker = allocator->GetMarker();
// 分配一些临时内存
void* temp = allocator->Allocate(64);
// 恢复到标记位置(释放 temp
allocator->SetMarker(marker);
// 每帧结束时清空
allocator->Clear();
```
## 相关文档
- [IAllocator](./memory-allocator.md) - 分配器接口
- [PoolAllocator](./memory-pool-allocator.md) - 内存池分配器
- [ProxyAllocator](./memory-proxy-allocator.md) - 代理分配器

View File

@@ -0,0 +1,99 @@
# MemoryManager
**命名空间**: `XCEngine::Memory`
**类型**: `class` (singleton)
**描述**: 全局内存管理器单例,提供系统分配器和各种专用分配器的创建。
## 概述
`MemoryManager` 是 XCEngine 内存管理系统的核心单例。它负责维护系统分配器,提供分配器工厂方法,并支持内存泄漏检测和报告。
## 单例访问
| 方法 | 描述 |
|------|------|
| `static MemoryManager& Get()` | 获取单例实例 |
## 公共方法
### 生命周期
| 方法 | 描述 |
|------|------|
| `void Initialize()` | 初始化内存管理器 |
| `void Shutdown()` | 关闭内存管理器 |
### 系统分配器
| 方法 | 描述 |
|------|------|
| `IAllocator* GetSystemAllocator()` | 获取系统默认分配器 |
### 分配器创建
| 方法 | 描述 |
|------|------|
| `std::unique_ptr<LinearAllocator> CreateLinearAllocator(size_t size)` | 创建线性分配器 |
| `std::unique_ptr<PoolAllocator> CreatePoolAllocator(size_t blockSize, size_t count)` | 创建内存池分配器 |
| `std::unique_ptr<ProxyAllocator> CreateProxyAllocator(const char* name)` | 创建代理分配器 |
### 内存管理
| 方法 | 描述 |
|------|------|
| `void SetTrackAllocations(bool track)` | 设置是否跟踪分配 |
| `void DumpMemoryLeaks()` | 输出内存泄漏报告 |
| `void GenerateMemoryReport()` | 生成内存使用报告 |
## 宏定义
### XE_ALLOC
```cpp
#define XE_ALLOC(allocator, size, ...) allocator->Allocate(size, ##__VA_ARGS__)
```
内存分配宏。
### XE_FREE
```cpp
#define XE_FREE(allocator, ptr) allocator->Free(ptr)
```
内存释放宏。
## 使用示例
```cpp
// 初始化
MemoryManager::Get().Initialize();
// 获取系统分配器
IAllocator* sysAlloc = MemoryManager::Get().GetSystemAllocator();
// 创建专用分配器
auto linearAlloc = MemoryManager::Get().CreateLinearAllocator(1024 * 1024);
auto poolAlloc = MemoryManager::Get().CreatePoolAllocator(sizeof(MyObject), 1000);
auto proxyAlloc = MemoryManager::Get().CreateProxyAllocator("GameFrame");
// 使用宏分配
void* ptr = XE_ALLOC(proxyAlloc, 256);
XE_FREE(proxyAlloc, ptr);
// 跟踪内存
MemoryManager::Get().SetTrackAllocations(true);
MemoryManager::Get().GenerateMemoryReport();
// 关闭
MemoryManager::Get().Shutdown();
```
## 相关文档
- [IAllocator](./memory-allocator.md) - 分配器接口
- [LinearAllocator](./memory-linear-allocator.md) - 线性分配器
- [PoolAllocator](./memory-pool-allocator.md) - 内存池分配器
- [ProxyAllocator](./memory-proxy-allocator.md) - 代理分配器

View File

@@ -0,0 +1,72 @@
# Memory 模块概览
**命名空间**: `XCEngine::Memory`
**类型**: `module`
**描述**: XCEngine 的内存管理模块,提供多种内存分配器实现。
## 概述
Memory 模块提供了一套完整的内存管理解决方案,包括基础分配器接口和各种专用分配器实现。
## 模块内容
### 分配器接口
| 组件 | 文件 | 描述 |
|------|------|------|
| [IAllocator](./memory-allocator.md) | `Allocator.h` | 内存分配器抽象接口 |
### 分配器实现
| 组件 | 文件 | 描述 |
|------|------|------|
| [LinearAllocator](./memory-linear-allocator.md) | `LinearAllocator.h` | 线性分配器,适合帧分配 |
| [PoolAllocator](./memory-pool-allocator.md) | `PoolAllocator.h` | 内存池分配器,适合固定大小对象 |
| [ProxyAllocator](./memory-proxy-allocator.md) | `ProxyAllocator.h` | 代理分配器,用于统计和跟踪 |
### 管理器
| 组件 | 文件 | 描述 |
|------|------|------|
| [MemoryManager](./memory-manager.md) | `MemoryManager.h` | 全局内存管理器 |
## 分配器类型对比
| 分配器 | 适用场景 | 特点 |
|--------|----------|------|
| `IAllocator` | 基类接口 | 定义标准分配协议 |
| `LinearAllocator` | 帧分配、临时对象 | 快速分配,只支持按顺序释放 |
| `PoolAllocator` | 同尺寸对象池 | 高效分配,消除碎片 |
| `ProxyAllocator` | 调试和统计 | 记录分配信息,跟踪内存使用 |
## 宏定义
| 宏 | 描述 |
|----|------|
| `XE_ALLOC(allocator, size, ...)` | 内存分配宏 |
| `XE_FREE(allocator, ptr)` | 内存释放宏 |
## 使用示例
```cpp
#include <XCEngine/Memory/MemoryManager.h>
// 获取系统分配器
IAllocator* sysAlloc = MemoryManager::Get().GetSystemAllocator();
// 创建线性分配器
auto linearAlloc = MemoryManager::Get().CreateLinearAllocator(1024 * 1024);
// 使用代理分配器跟踪统计
auto proxyAlloc = MemoryManager::Get().CreateProxyAllocator("FrameData");
// 分配内存
void* ptr = XE_ALLOC(linearAlloc, 1024);
XE_FREE(linearAlloc, ptr);
```
## 相关文档
- [Containers 模块](../containers/container-overview.md) - 使用分配器的容器

View File

@@ -0,0 +1,75 @@
# PoolAllocator
**命名空间**: `XCEngine::Memory`
**类型**: `class`
**描述**: 内存池分配器,为固定大小的对象提供高效分配,消除内存碎片。
## 概述
`PoolAllocator` 预分配一大块内存,并将其划分为等大小的内存块。它维护一个空闲块链表,分配时从链表中取出一块,释放时归还到链表。这使得分配和释放都是 O(1) 时间复杂度,非常适合需要频繁分配/释放同尺寸对象的场景(如对象池)。
## 公共方法
### 构造/析构
| 方法 | 描述 |
|------|------|
| `PoolAllocator(size_t blockSize, size_t poolSize, size_t alignment = 8)` | 构造函数 |
| `~PoolAllocator()` | 析构函数 |
### IAllocator 实现
| 方法 | 描述 |
|------|------|
| `void* Allocate(size_t size, size_t alignment = 0) override` | 分配一个内存块(忽略 size 参数) |
| `void Free(void* ptr) override` | 释放内存块 |
| `void* Reallocate(void* ptr, size_t newSize) override` | 不支持,返回 nullptr |
### 内存块管理
| 方法 | 描述 |
|------|------|
| `bool Contains(void* ptr) const` | 检查指针是否属于此池 |
| `size_t GetBlockSize() const` | 获取内存块大小 |
| `size_t GetFreeBlockCount() const` | 获取空闲块数量 |
| `size_t GetTotalBlockCount() const` | 获取总块数 |
### 统计
| 方法 | 描述 |
|------|------|
| `size_t GetTotalAllocated() const` | 已分配的字节数 |
| `size_t GetTotalFreed() const` | 空闲块占用的字节数 |
| `size_t GetPeakAllocated() const` | 总块数乘以块大小 |
| `size_t GetAllocationCount() const` | 当前已分配块数 |
## 使用示例
```cpp
// 创建一个能分配 100 个 64 字节块的内存池
PoolAllocator pool(sizeof(MyObject), 100, alignof(MyObject));
// 分配O(1)
void* block = pool.Allocate();
// 或者使用 Allocate(size) 但忽略 size
void* block2 = pool.Allocate(sizeof(MyObject));
// 检查空闲块
printf("Free blocks: %zu\n", pool.GetFreeBlockCount());
// 释放O(1)
pool.Free(block2);
// 检查指针是否属于此池
if (pool.Contains(block)) {
// ...
}
```
## 相关文档
- [IAllocator](./memory-allocator.md) - 分配器接口
- [LinearAllocator](./memory-linear-allocator.md) - 线性分配器
- [ProxyAllocator](./memory-proxy-allocator.md) - 代理分配器

View File

@@ -0,0 +1,71 @@
# ProxyAllocator
**命名空间**: `XCEngine::Memory`
**类型**: `class`
**描述**: 代理分配器,包装另一个分配器并记录分配统计信息,用于内存跟踪和调试。
## 概述
`ProxyAllocator` 是对另一个分配器的包装,它将所有分配请求转发给底层分配器,同时记录分配统计信息。这对于分析内存使用模式和调试内存问题非常有用。
## 公共方法
### 构造
| 方法 | 描述 |
|------|------|
| `ProxyAllocator(IAllocator* underlying, const char* name)` | 构造函数,指定底层分配器和名称 |
### IAllocator 实现
| 方法 | 描述 |
|------|------|
| `void* Allocate(size_t size, size_t alignment = 0) override` | 分配并统计 |
| `void Free(void* ptr) override` | 释放并统计 |
| `void* Reallocate(void* ptr, size_t newSize) override` | 重新分配并统计 |
### 统计
| 方法 | 描述 |
|------|------|
| `size_t GetTotalAllocated() const override` | 总分配字节数 |
| `size_t GetTotalFreed() const override` | 总释放字节数 |
| `size_t GetPeakAllocated() const override` | 峰值分配字节数 |
| `size_t GetAllocationCount() const override` | 分配次数 |
| `const Stats& GetStats() const` | 获取详细统计信息 |
## Stats 结构体
| 成员 | 类型 | 描述 |
|------|------|------|
| `totalAllocated` | `size_t` | 累计分配字节数 |
| `totalFreed` | `size_t` | 累计释放字节数 |
| `peakAllocated` | `size_t` | 峰值分配字节数 |
| `allocationCount` | `size_t` | 分配次数 |
| `memoryOverhead` | `size_t` | 额外开销(字节) |
## 使用示例
```cpp
// 包装系统分配器
IAllocator* sysAlloc = MemoryManager::Get().GetSystemAllocator();
ProxyAllocator proxy(sysAlloc, "FrameData");
// 使用代理分配器
void* ptr = proxy.Allocate(1024);
// 获取统计
const ProxyAllocator::Stats& stats = proxy.GetStats();
printf("Total allocated: %zu bytes\n", stats.totalAllocated);
printf("Peak allocated: %zu bytes\n", stats.peakAllocated);
printf("Allocation count: %zu\n", stats.allocationCount);
printf("Current in use: %zu bytes\n",
stats.totalAllocated - stats.totalFreed);
```
## 相关文档
- [IAllocator](./memory-allocator.md) - 分配器接口
- [MemoryManager](./memory-manager.md) - 内存管理器

View File

@@ -0,0 +1,99 @@
# AsyncLoader
**命名空间**: `XCEngine::Resources`
**类型**: `class` (singleton)
**描述**: 异步资源加载器单例,负责多线程后台资源加载和完成回调调度。
## 概述
`AsyncLoader` 是 XCEngine 的后台异步加载系统。它使用独立工作线程从磁盘加载资源,并在加载完成后通过回调通知调用者。它维护待处理队列和完成队列,通过双缓冲机制实现无锁的线程安全操作。
## 单例访问
| 方法 | 描述 |
|------|------|
| `static AsyncLoader& Get()` | 获取单例实例 |
## LoadRequest 结构体
异步加载请求结构体。
| 成员 | 类型 | 描述 |
|------|------|------|
| `path` | `Containers::String` | 资源路径 |
| `type` | `ResourceType` | 资源类型 |
| `callback` | `std::function<void(LoadResult)>` | 加载完成回调函数 |
| `settings` | `ImportSettings*` | 导入设置(可为 nullptr |
| `requestId` | `Core::uint64` | 请求唯一标识符 |
## 公共方法
### 生命周期
| 方法 | 描述 |
|------|------|
| `void Initialize(Core::uint32 workerThreadCount = 2)` | 初始化异步加载器,创建工作线程 |
| `void Shutdown()` | 关闭异步加载器,等待所有挂起任务完成 |
### 提交请求
| 方法 | 描述 |
|------|------|
| `void Submit(const Containers::String& path, ResourceType type, std::function<void(LoadResult)> callback)` | 提交异步加载请求 |
| `void Submit(const Containers::String& path, ResourceType type, ImportSettings* settings, std::function<void(LoadResult)> callback)` | 带设置的异步加载请求 |
### 进度查询
| 方法 | 描述 |
|------|------|
| `void Update()` | 更新函数,在主线程调用,处理完成的加载请求 |
| `bool IsLoading() const` | 是否有正在加载的资源 |
| `Core::uint32 GetPendingCount() const` | 获取待处理加载请求数量 |
| `float GetProgress() const` | 获取整体加载进度0.0f ~ 1.0f |
### 取消操作
| 方法 | 描述 |
|------|------|
| `void CancelAll()` | 取消所有待处理的加载请求 |
| `void Cancel(Core::uint64 requestId)` | 取消指定 ID 的加载请求 |
## 使用示例
```cpp
// 初始化(使用 4 个工作线程)
AsyncLoader::Get().Initialize(4);
// 提交多个异步加载请求
AsyncLoader::Get().Submit("textures/player.png", ResourceType::Texture,
[](LoadResult result) {
if (result.success) {
ResourceHandle<Texture> tex(result.resource);
printf("Texture loaded: %s\n", tex->GetPath().CStr());
}
});
AsyncLoader::Get().Submit("models/player.fbx", ResourceType::Mesh,
[](LoadResult result) {
if (result.success) {
ResourceHandle<Mesh> mesh(result.resource);
printf("Mesh loaded: %s\n", mesh->GetPath().CStr());
}
});
// 在主循环中调用 Update 处理完成回调
while (AsyncLoader::Get().IsLoading()) {
AsyncLoader::Get().Update(); // 在主线程分发回调
// 其他渲染逻辑...
}
// 关闭
AsyncLoader::Get().Shutdown();
```
## 相关文档
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器
- [IResourceLoader](./resources-iloader.md) - 资源加载器接口

View File

@@ -0,0 +1,131 @@
# AudioClip
**命名空间**: `XCEngine::Resources`
**类型**: `class`
**描述**: 音频片段资源类,管理音频样本数据、格式信息和播放参数。
## 概述
`AudioClip` 是 XCEngine 中的音频资源类,继承自 `IResource`。它管理音频的原始样本数据、采样率、通道数、位深度、时长、格式类型和播放参数。
## 头文件
```cpp
#include <XCEngine/Resources/AudioClip.h>
```
## 枚举类型
### AudioFormat
音频格式枚举。
| 值 | 描述 |
|----|------|
| `Unknown` | 未知格式 |
| `WAV` | WAV 格式 |
| `OGG` | OGG Vorbis 格式 |
| `MP3` | MP3 格式 |
| `FLAC` | FLAC 无损格式 |
### AudioType
音频类型枚举。
| 值 | 描述 |
|----|------|
| `SoundEffect` | 音效 |
| `Music` | 音乐 |
| `Voice` | 语音 |
| `Ambient` | 环境音 |
## 公共方法
### 基础属性
| 方法 | 描述 |
|------|------|
| `ResourceType GetType() const` | 返回 `ResourceType::AudioClip` |
| `const Containers::String& GetName() const` | 获取音频名称 |
| `const Containers::String& GetPath() const` | 获取音频路径 |
| `ResourceGUID GetGUID() const` | 获取全局唯一标识符 |
| `bool IsValid() const` | 检查音频是否有效 |
| `size_t GetMemorySize() const` | 获取内存大小 |
| `void Release()` | 释放音频引用 |
### 音频数据
| 方法 | 描述 |
|------|------|
| `void SetAudioData(const Containers::Array<Core::uint8>& data)` | 设置音频数据 |
| `const Containers::Array<Core::uint8>& GetAudioData() const` | 获取音频数据指针 |
### 音频参数
| 方法 | 描述 |
|------|------|
| `void SetSampleRate(Core::uint32 rate)` | 设置采样率Hz |
| `Core::uint32 GetSampleRate() const` | 获取采样率 |
| `void SetChannels(Core::uint32 channels)` | 设置通道数1=单声道, 2=立体声) |
| `Core::uint32 GetChannels() const` | 获取通道数 |
| `void SetBitsPerSample(Core::uint32 bits)` | 设置位深度8/16/24/32 |
| `Core::uint32 GetBitsPerSample() const` | 获取位深度 |
| `void SetDuration(float seconds)` | 设置时长(秒) |
| `float GetDuration() const` | 获取时长(秒) |
### 格式与类型
| 方法 | 描述 |
|------|------|
| `void SetAudioFormat(AudioFormat format)` | 设置音频格式 |
| `AudioFormat GetAudioFormat() const` | 获取音频格式 |
| `void SetAudioType(AudioType type)` | 设置音频类型 |
| `AudioType GetAudioType() const` | 获取音频类型 |
### 3D 和循环
| 方法 | 描述 |
|------|------|
| `void SetIs3D(bool is3D)` | 设置是否为 3D 音频 |
| `bool Is3D() const` | 检查是否为 3D 音频 |
| `void SetLoop(bool loop)` | 设置是否循环播放 |
| `bool IsLoop() const` | 检查是否循环播放 |
### RHI 资源
| 方法 | 描述 |
|------|------|
| `class IRHIAudioBuffer* GetRHIResource() const` | 获取 RHI 音频缓冲区 |
| `void SetRHIResource(class IRHIAudioBuffer* resource)` | 设置 RHI 音频缓冲区 |
## 使用示例
```cpp
// 加载音频
ResourceHandle<AudioClip> sfx = ResourceManager::Get().Load<AudioClip>("sounds/explosion.wav");
ResourceHandle<AudioClip> music = ResourceManager::Get().Load<AudioClip>("music/background.ogg");
// 设置参数
sfx->SetAudioType(AudioType::SoundEffect);
sfx->SetSampleRate(44100);
sfx->SetChannels(2);
sfx->SetBitsPerSample(16);
sfx->SetDuration(1.5f);
sfx->SetLoop(false);
// 3D 音频
sfx->SetIs3D(false);
music->SetIs3D(false);
// 获取信息
uint32_t sampleRate = sfx->GetSampleRate();
float duration = sfx->GetDuration();
bool loop = sfx->IsLoop();
```
## 相关文档
- [IResource](./resources-iresource.md) - 资源基类
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器

View File

@@ -0,0 +1,110 @@
# ResourceDependencyGraph
**命名空间**: `XCEngine::Resources`
**类型**: `class`
**描述**: 资源依赖图管理器,负责跟踪资源之间的依赖关系、引用计数和拓扑排序。
## 概述
`ResourceDependencyGraph` 维护了所有资源之间的依赖关系图。它支持添加/移除依赖节点、查询依赖关系、循环依赖检测、拓扑排序(用于正确的加载/卸载顺序)等功能。
## 公共方法
### 节点管理
| 方法 | 描述 |
|------|------|
| `void AddNode(ResourceGUID guid, ResourceType type)` | 添加依赖节点 |
| `void RemoveNode(ResourceGUID guid)` | 移除依赖节点 |
| `bool HasNode(ResourceGUID guid) const` | 检查节点是否存在 |
### 依赖关系
| 方法 | 描述 |
|------|------|
| `void AddDependency(ResourceGUID owner, ResourceGUID dependency)` | 添加依赖关系A 依赖 B |
| `void RemoveDependency(ResourceGUID owner, ResourceGUID dependency)` | 移除依赖关系 |
| `Containers::Array<ResourceGUID> GetDependencies(ResourceGUID guid) const` | 获取指定资源的直接依赖列表 |
| `Containers::Array<ResourceGUID> GetDependents(ResourceGUID guid) const` | 获取依赖指定资源的所有资源列表 |
| `Containers::Array<ResourceGUID> GetAllDependencies(ResourceGUID guid) const` | 获取所有递归依赖(包括传递依赖) |
### 引用计数
| 方法 | 描述 |
|------|------|
| `void IncrementRefCount(ResourceGUID guid)` | 增加引用计数 |
| `void DecrementRefCount(ResourceGUID guid)` | 减少引用计数 |
| `Core::uint32 GetRefCount(ResourceGUID guid) const` | 获取引用计数 |
### 循环检测
| 方法 | 描述 |
|------|------|
| `bool HasCircularDependency(ResourceGUID guid, Containers::Array<ResourceGUID>& outCycle) const` | 检测是否存在循环依赖 |
### 排序与卸载
| 方法 | 描述 |
|------|------|
| `Containers::Array<ResourceGUID> TopologicalSort() const` | 拓扑排序(按依赖顺序) |
| `bool Unload(ResourceGUID guid)` | 安全卸载(考虑依赖关系) |
### 清理
| 方法 | 描述 |
|------|------|
| `void Clear()` | 清空所有节点和依赖关系 |
## DependencyNode 结构体
| 成员 | 类型 | 描述 |
|------|------|------|
| `guid` | `ResourceGUID` | 资源全局唯一标识符 |
| `type` | `ResourceType` | 资源类型 |
| `dependencies` | `Containers::Array<ResourceGUID>` | 此资源依赖的其他资源 |
| `dependents` | `Containers::Array<ResourceGUID>` | 依赖此资源的其他资源 |
| `refCount` | `Core::uint32` | 引用计数 |
## 使用示例
```cpp
ResourceDependencyGraph graph;
// 添加节点
graph.AddNode(textureGuid, ResourceType::Texture);
graph.AddNode(materialGuid, ResourceType::Material);
graph.AddNode(shaderGuid, ResourceType::Shader);
// 设置依赖关系Material 依赖 Texture 和 Shader
graph.AddDependency(materialGuid, textureGuid);
graph.AddDependency(materialGuid, shaderGuid);
// 查询依赖
auto deps = graph.GetDependencies(materialGuid);
// deps 包含 textureGuid 和 shaderGuid
// 查询被依赖者
auto dependents = graph.GetDependents(textureGuid);
// dependents 包含 materialGuid
// 拓扑排序(正确的加载顺序)
auto loadOrder = graph.TopologicalSort();
// loadOrder 保证依赖在目标之前加载
// 循环依赖检测
Containers::Array<ResourceGUID> cycle;
if (graph.HasCircularDependency(guid, cycle)) {
printf("Circular dependency detected!");
}
// 引用计数
graph.IncrementRefCount(guid);
graph.DecrementRefCount(guid);
```
## 相关文档
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器
- [ResourceHandle](./resources-resourcehandle.md) - 资源句柄

View File

@@ -0,0 +1,118 @@
# ResourceFileSystem
**命名空间**: `XCEngine::Resources`
**类型**: `class`
**描述**: 资源文件系统,负责资源文件的查找、读取和虚拟文件系统(支持目录和归档包)管理。
## 概述
`ResourceFileSystem` 实现了虚拟资源文件系统,支持从多个目录和归档包(如 `.zip``.pak`)中查找和读取资源。它通过 `IArchive` 接口支持不同的归档格式,并提供资源信息缓存。
## IArchive 接口
抽象归档接口,用于封装单个归档包或目录的读取操作。
### 公共方法
| 方法 | 描述 |
|------|------|
| `virtual bool Open(const Containers::String& path)` | 打开归档 |
| `virtual void Close()` | 关闭归档 |
| `virtual bool Read(fileName, buffer, size, offset)` | 从归档中读取文件 |
| `virtual size_t GetSize(fileName)` | 获取文件大小 |
| `virtual bool Exists(fileName)` | 检查文件是否存在 |
| `virtual void Enumerate(pattern, outFiles)` | 枚举匹配的文件 |
| `virtual bool IsValid() const` | 是否有效 |
## ResourceInfo 结构体
| 成员 | 类型 | 描述 |
|------|------|------|
| `path` | `Containers::String` | 资源相对路径 |
| `size` | `size_t` | 文件大小(字节) |
| `modifiedTime` | `Core::uint64` | 修改时间戳 |
| `inArchive` | `bool` | 是否在归档包中 |
| `archivePath` | `Containers::String` | 所属归档路径 |
## 单例访问
| 方法 | 描述 |
|------|------|
| `static ResourceFileSystem& Get()` | 获取单例实例 |
## 公共方法
### 生命周期
| 方法 | 描述 |
|------|------|
| `void Initialize(const Containers::String& rootPath)` | 初始化,设置资源根目录 |
| `void Shutdown()` | 关闭,释放所有归档 |
### 归档和目录管理
| 方法 | 描述 |
|------|------|
| `bool AddArchive(const Containers::String& archivePath)` | 添加归档包(优先查找) |
| `bool AddDirectory(const Containers::String& directoryPath)` | 添加资源目录 |
| `void RemoveArchive(const Containers::String& archivePath)` | 移除归档包 |
### 资源查找
| 方法 | 描述 |
|------|------|
| `bool FindResource(const Containers::String& relativePath, Containers::String& outAbsolutePath)` | 查找资源的绝对路径 |
| `bool Exists(const Containers::String& relativePath)` | 检查资源是否存在 |
| `Containers::Array<Core::uint8> ReadResource(const Containers::String& relativePath)` | 读取资源文件内容(字节数组) |
### 资源信息
| 方法 | 描述 |
|------|------|
| `bool GetResourceInfo(const Containers::String& relativePath, ResourceInfo& outInfo)` | 获取资源信息 |
| `void EnumerateResources(const Containers::String& pattern, Containers::Array<ResourceInfo>& outResources)` | 枚举匹配的资源 |
## 使用示例
```cpp
#include <XCEngine/Resources/ResourceFileSystem.h>
// 初始化资源文件系统
ResourceFileSystem::Get().Initialize("resources/");
// 添加归档包(优先于目录)
ResourceFileSystem::Get().AddArchive("data/resources.pak");
// 添加额外资源目录
ResourceFileSystem::Get().AddDirectory("user_content/");
// 检查资源是否存在
if (ResourceFileSystem::Get().Exists("textures/player.png")) {
// 读取资源
auto data = ResourceFileSystem::Get().ReadResource("textures/player.png");
// 使用数据...
}
// 获取资源信息
ResourceInfo info;
if (ResourceFileSystem::Get().GetResourceInfo("shaders/default.vert", info)) {
printf("Size: %zu, InArchive: %s\n", info.size, info.inArchive ? "yes" : "no");
}
// 枚举资源
Containers::Array<ResourceInfo> textures;
ResourceFileSystem::Get().EnumerateResources("textures/*.png", textures);
for (const auto& tex : textures) {
printf("Found: %s\n", tex.path.CStr());
}
// 关闭
ResourceFileSystem::Get().Shutdown();
```
## 相关文档
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器
- [IResourceLoader](./resources-iloader.md) - 资源加载器

View File

@@ -0,0 +1,112 @@
# IResourceLoader
**命名空间**: `XCEngine::Resources`
**类型**: `class` (abstract)
**描述**: 资源加载器抽象接口,定义了资源加载的标准协议。每个资源类型需要提供对应的加载器实现。
## 概述
`IResourceLoader` 是资源加载系统的核心抽象接口。它定义了同步和异步加载资源的方法,以及资源类型的查询和依赖信息的获取。`ResourceManager` 通过注册加载器来支持不同类型资源的加载。
## 公共方法
### 资源信息
| 方法 | 描述 |
|------|------|
| `ResourceType GetResourceType() const` | 获取此加载器支持的资源类型 |
| `const Containers::String& GetResourceTypeName() const` | 获取资源类型的字符串名称 |
| `size_t GetResourceSize(const Containers::String& path) const` | 获取资源文件大小 |
### 同步加载
| 方法 | 描述 |
|------|------|
| `LoadResult Load(const Containers::String& path, ImportSettings* settings)` | 同步加载资源 |
| `bool Save(const Containers::String& path, IResource* resource)` | 保存资源到文件 |
### 异步加载
| 方法 | 描述 |
|------|------|
| `LoadResult LoadAsync(const Containers::String& path, ImportSettings* settings)` | 异步加载资源(内部使用) |
### 依赖管理
| 方法 | 描述 |
|------|------|
| `Containers::Array<Containers::String> GetDependencies(const Containers::String& path) const` | 获取资源依赖的文件路径列表 |
### 资源操作
| 方法 | 描述 |
|------|------|
| `bool Reload(IResource* resource, const Containers::String& path)` | 重新加载资源 |
| `void Unload(IResource* resource)` | 卸载资源 |
### 文件系统
| 方法 | 描述 |
|------|------|
| `bool Exists(const Containers::String& path) const` | 检查资源文件是否存在 |
| `Containers::String ResolvePath(const Containers::String& relativePath) const` | 解析资源路径 |
## LoadResult 结构体
加载操作的返回值结构体。
```cpp
struct LoadResult {
IResource* resource = nullptr; // 加载的资源对象
bool success = false; // 是否成功
Containers::String errorMessage; // 错误信息
size_t memorySize = 0; // 资源内存大小
Containers::Array<Containers::String> dependencies; // 依赖列表
};
```
### 布尔转换
| 转换 | 描述 |
|------|------|
| `explicit operator bool() const` | `success == true` 时返回 true |
## 使用示例
```cpp
class TextureLoader : public IResourceLoader {
public:
ResourceType GetResourceType() const override {
return ResourceType::Texture;
}
const Containers::String& GetResourceTypeName() const override {
static Containers::String name = "Texture";
return name;
}
LoadResult Load(const Containers::String& path,
ImportSettings* settings) override {
LoadResult result;
// 实现加载逻辑...
result.success = true;
result.resource = new Texture();
return result;
}
Containers::Array<Containers::String>
GetDependencies(const Containers::String& path) const override {
return {}; // 纹理通常无依赖
}
};
// 注册加载器
ResourceManager::Get().RegisterLoader(new TextureLoader());
```
## 相关文档
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器
- [AsyncLoader](./resources-asyncloader.md) - 异步加载器

View File

@@ -0,0 +1,164 @@
# ImportSettings
**命名空间**: `XCEngine::Resources`
**类型**: `class` (abstract)
**描述**: 资源导入设置抽象基类,定义资源导入时的配置选项接口。
## 概述
`ImportSettings` 是所有资源导入设置的抽象基类。它提供了克隆和 JSON 序列化接口,允许不同资源类型定义各自的导入选项。引擎内置了两个具体实现:`TextureImportSettings``MeshImportSettings`
## 公共方法
| 方法 | 描述 |
|------|------|
| `virtual Core::UniqueRef<ImportSettings> Clone() const = 0` | 克隆一份设置 |
| `virtual bool LoadFromJSON(const Containers::String& json)` | 从 JSON 加载设置 |
| `virtual Containers::String SaveToJSON() const` | 保存为 JSON 字符串 |
---
## TextureImportSettings
纹理导入设置,继承自 `ImportSettings`
**头文件**: `XCEngine/Resources/TextureImportSettings.h`
### 枚举类型
#### MipmapFilter
| 值 | 描述 |
|----|------|
| `Box` | Box 滤波器 |
| `Kaiser` | Kaiser 滤波器 |
#### CompressionQuality
| 值 | 描述 |
|----|------|
| `Low` | 低质量 |
| `Medium` | 中等质量 |
| `High` | 高质量 |
| `Ultra` | 超高质量 |
### 公共方法
| 方法 | 描述 |
|------|------|
| `void SetTextureType(TextureType type)` | 设置纹理类型 |
| `TextureType GetTextureType() const` | 获取纹理类型 |
| `void SetTargetFormat(TextureFormat format)` | 设置目标格式 |
| `TextureFormat GetTargetFormat() const` | 获取目标格式 |
| `void SetGenerateMipmaps(bool generate)` | 设置是否生成 Mipmap |
| `bool GetGenerateMipmaps() const` | 获取是否生成 Mipmap |
| `void SetMipmapFilter(MipmapFilter filter)` | 设置 Mipmap 滤波器 |
| `MipmapFilter GetMipmapFilter() const` | 获取 Mipmap 滤波器 |
| `void SetMaxAnisotropy(Core::uint32 anisotropy)` | 设置最大各向异性级别 |
| `Core::uint32 GetMaxAnisotropy() const` | 获取最大各向异性级别 |
| `void SetSRGB(bool srgb)` | 设置是否 sRGB |
| `bool GetSRGB() const` | 获取 sRGB 设置 |
| `void SetFlipVertical(bool flip)` | 设置是否垂直翻转 |
| `bool GetFlipVertical() const` | 获取垂直翻转设置 |
| `void SetFlipHorizontal(bool flip)` | 设置是否水平翻转 |
| `bool GetFlipHorizontal() const` | 获取水平翻转设置 |
| `void SetBorderColor(const Math::Vector3& color)` | 设置边框颜色 |
| `const Math::Vector3& GetBorderColor() const` | 获取边框颜色 |
| `void SetCompressionQuality(CompressionQuality quality)` | 设置压缩质量 |
| `CompressionQuality GetCompressionQuality() const` | 获取压缩质量 |
| `void SetUseHardwareCompression(bool use)` | 设置是否使用硬件压缩 |
| `bool GetUseHardwareCompression() const` | 获取硬件压缩设置 |
| `void SetMaxSize(Core::uint32 size)` | 设置最大纹理尺寸 |
| `Core::uint32 GetMaxSize() const` | 获取最大纹理尺寸 |
| `void SetGenerateNormalMap(bool generate)` | 设置是否生成法线贴图 |
| `bool GetGenerateNormalMap() const` | 获取法线贴图生成设置 |
| `void SetNormalMapStrength(float strength)` | 设置法线贴图强度 |
| `float GetNormalMapStrength() const` | 获取法线贴图强度 |
---
## MeshImportSettings
网格导入设置,继承自 `ImportSettings`
**头文件**: `XCEngine/Resources/MeshImportSettings.h`
### MeshImportFlags
| 值 | 描述 |
|----|------|
| `None` | 无特殊标志 |
| `FlipUVs` | 翻转 UV 坐标 |
| `FlipWindingOrder` | 翻转绕序 |
| `GenerateNormals` | 生成法线 |
| `GenerateTangents` | 生成切线 |
| `OptimizeMesh` | 优化网格 |
| `ImportSkinning` | 导入骨骼蒙皮 |
| `ImportAnimations` | 导入动画 |
| `ImportMaterials` | 导入材质 |
| `ImportCameras` | 导入相机 |
| `ImportLights` | 导入灯光 |
支持位运算组合(`operator|``operator&``operator~`)。
### 公共方法
| 方法 | 描述 |
|------|------|
| `void SetImportFlags(MeshImportFlags flags)` | 设置导入标志 |
| `MeshImportFlags GetImportFlags() const` | 获取导入标志 |
| `void AddImportFlag(MeshImportFlags flag)` | 添加单个导入标志 |
| `void RemoveImportFlag(MeshImportFlags flag)` | 移除单个导入标志 |
| `bool HasImportFlag(MeshImportFlags flag) const` | 检查是否包含某标志 |
| `void SetScale(float scale)` | 设置缩放 |
| `float GetScale() const` | 获取缩放 |
| `void SetOffset(const Math::Vector3& offset)` | 设置偏移 |
| `const Math::Vector3& GetOffset() const` | 获取偏移 |
| `void SetAxisConversion(bool convert)` | 设置轴转换 |
| `bool GetAxisConversion() const` | 获取轴转换设置 |
| `void SetMergeMeshes(bool merge)` | 设置是否合并网格 |
| `bool GetMergeMeshes() const` | 获取合并网格设置 |
| `void SetOptimizeThreshold(float threshold)` | 设置优化阈值 |
| `float GetOptimizeThreshold() const` | 获取优化阈值 |
| `void SetImportScale(float scale)` | 设置导入缩放 |
| `float GetImportScale() const` | 获取导入缩放 |
| `void SetThreshold(float threshold)` | 设置阈值 |
| `float GetThreshold() const` | 获取阈值 |
## 使用示例
```cpp
#include <XCEngine/Resources/TextureImportSettings.h>
#include <XCEngine/Resources/MeshImportSettings.h>
// 纹理导入设置
TextureImportSettings texSettings;
texSettings.SetTextureType(RHI::TextureType::Texture2D);
texSettings.SetGenerateMipmaps(true);
texSettings.SetSRGB(true);
texSettings.SetCompressionQuality(CompressionQuality::High);
texSettings.SetMaxAnisotropy(16);
// 加载设置
texSettings.LoadFromJSON(R"({"sRGB":true,"maxAnisotropy":8})");
// 保存设置
Containers::String json = texSettings.SaveToJSON();
// 网格导入设置
MeshImportSettings meshSettings;
meshSettings.SetImportFlags(MeshImportFlags::FlipUVs | MeshImportFlags::GenerateNormals);
meshSettings.SetScale(1.0f);
meshSettings.SetAxisConversion(true);
// 使用设置加载资源
ResourceHandle<Texture> tex = ResourceManager::Get().Load<Texture>("tex.png", &texSettings);
ResourceHandle<Mesh> mesh = ResourceManager::Get().Load<Mesh>("model.fbx", &meshSettings);
```
## 相关文档
- [IResourceLoader](./resources-iloader.md) - 资源加载器
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器

View File

@@ -0,0 +1,79 @@
# IResource
**命名空间**: `XCEngine::Resources`
**类型**: `class` (abstract)
**描述**: 资源基类接口所有具体资源类型Texture、Mesh、Material 等)都必须继承自此类。
## 概述
`IResource` 是 XCEngine 资源管理系统的核心抽象基类。它定义了所有资源共有的基本属性和行为包括资源类型、名称、路径、GUID、内存大小和有效性状态。
## 公共方法
### 基础属性
| 方法 | 描述 |
|------|------|
| `ResourceType GetType() const` | 获取资源类型 |
| `const Containers::String& GetName() const` | 获取资源名称 |
| `const Containers::String& GetPath() const` | 获取资源路径 |
| `ResourceGUID GetGUID() const` | 获取全局唯一标识符 |
| `bool IsValid() const` | 检查资源是否有效 |
| `size_t GetMemorySize() const` | 获取资源占用的内存大小(字节) |
### 生命周期
| 方法 | 描述 |
|------|------|
| `void Release()` | 释放资源引用 |
### 构造参数
```cpp
struct ConstructParams {
Containers::String name; // 资源名称
Containers::String path; // 资源路径
ResourceGUID guid; // 全局唯一标识符
size_t memorySize = 0; // 内存大小
};
```
### 初始化方法
| 方法 | 描述 |
|------|------|
| `void Initialize(const ConstructParams& params)` | 使用构造参数初始化资源 |
| `void SetInvalid()` | 将资源标记为无效 |
## 公共成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_name` | `Containers::String` | 资源名称 |
| `m_path` | `Containers::String` | 资源路径 |
| `m_guid` | `ResourceGUID` | 全局唯一标识符 |
| `m_isValid` | `bool` | 资源是否有效 |
| `m_memorySize` | `size_t` | 内存占用大小 |
## 使用示例
```cpp
class MyResource : public IResource {
public:
ResourceType GetType() const override { return ResourceType::Custom; }
const Containers::String& GetName() const override { return m_name; }
const Containers::String& GetPath() const override { return m_path; }
ResourceGUID GetGUID() const override { return m_guid; }
bool IsValid() const override { return m_isValid; }
size_t GetMemorySize() const override { return m_memorySize; }
void Release() override { /* 释放逻辑 */ }
};
```
## 相关文档
- [ResourceHandle](./resources-resourcehandle.md) - 资源句柄
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器
- [ResourceTypes](./resources-resourcetypes.md) - 资源类型定义

View File

@@ -0,0 +1,146 @@
# Material
**命名空间**: `XCEngine::Resources`
**类型**: `class`
**描述**: 材质资源类,管理渲染所需的着色器和属性参数。
## 概述
`Material` 是 XCEngine 中的材质资源类,继承自 `IResource`。它管理材质关联的着色器和各种属性参数(浮点数、向量、纹理等),并支持将属性数据打包到常量缓冲区。
## 头文件
```cpp
#include <XCEngine/Resources/Material.h>
```
## 枚举类型
### MaterialPropertyType
材质属性类型枚举。
| 值 | 描述 |
|----|------|
| `Float` | 单精度浮点数 |
| `Float2` | 二维浮点向量 |
| `Float3` | 三维浮点向量 |
| `Float4` | 四维浮点向量 |
| `Int` | 整数 |
| `Int2` | 二维整数向量 |
| `Int3` | 三维整数向量 |
| `Int4` | 四维整数向量 |
| `Bool` | 布尔值 |
| `Texture` | 纹理资源 |
| `Cubemap` | 立方体贴图资源 |
## 结构体
### MaterialProperty
材质属性结构体。
| 成员 | 类型 | 描述 |
|------|------|------|
| `name` | `Containers::String` | 属性名称 |
| `type` | `MaterialPropertyType` | 属性类型 |
| `value` | `union` | 属性值float/int/bool |
| `refCount` | `Core::uint32` | 引用计数 |
## 公共方法
### 基础属性
| 方法 | 描述 |
|------|------|
| `ResourceType GetType() const` | 返回 `ResourceType::Material` |
| `const Containers::String& GetName() const` | 获取材质名称 |
| `const Containers::String& GetPath() const` | 获取材质路径 |
| `ResourceGUID GetGUID() const` | 获取全局唯一标识符 |
| `bool IsValid() const` | 检查材质是否有效 |
| `size_t GetMemorySize() const` | 获取内存大小 |
| `void Release()` | 释放材质引用 |
### 着色器管理
| 方法 | 描述 |
|------|------|
| `void SetShader(const ResourceHandle<Shader>& shader)` | 设置材质着色器 |
| `Shader* GetShader() const` | 获取材质着色器 |
### 属性设置
| 方法 | 描述 |
|------|------|
| `void SetFloat(const Containers::String& name, float value)` | 设置浮点属性 |
| `void SetFloat2(const Containers::String& name, const Math::Vector2& value)` | 设置 Vector2 属性 |
| `void SetFloat3(const Containers::String& name, const Math::Vector3& value)` | 设置 Vector3 属性 |
| `void SetFloat4(const Containers::String& name, const Math::Vector4& value)` | 设置 Vector4 属性 |
| `void SetInt(const Containers::String& name, Core::int32 value)` | 设置整数属性 |
| `void SetBool(const Containers::String& name, bool value)` | 设置布尔属性 |
| `void SetTexture(const Containers::String& name, const ResourceHandle<Texture>& texture)` | 设置纹理属性 |
### 属性获取
| 方法 | 描述 |
|------|------|
| `float GetFloat(const Containers::String& name) const` | 获取浮点属性 |
| `Math::Vector2 GetFloat2(const Containers::String& name) const` | 获取 Vector2 属性 |
| `Math::Vector3 GetFloat3(const Containers::String& name) const` | 获取 Vector3 属性 |
| `Math::Vector4 GetFloat4(const Containers::String& name) const` | 获取 Vector4 属性 |
| `Core::int32 GetInt(const Containers::String& name) const` | 获取整数属性 |
| `bool GetBool(const Containers::String& name) const` | 获取布尔属性 |
| `ResourceHandle<Texture> GetTexture(const Containers::String& name) const` | 获取纹理属性 |
### 常量缓冲区
| 方法 | 描述 |
|------|------|
| `const Containers::Array<Core::uint8>& GetConstantBufferData() const` | 获取常量缓冲区数据 |
| `void UpdateConstantBuffer()` | 更新常量缓冲区数据 |
### 属性管理
| 方法 | 描述 |
|------|------|
| `bool HasProperty(const Containers::String& name) const` | 检查属性是否存在 |
| `void RemoveProperty(const Containers::String& name)` | 移除属性 |
| `void ClearAllProperties()` | 清空所有属性 |
## 使用示例
```cpp
// 加载材质
ResourceHandle<Material> mat = ResourceManager::Get().Load<Material>("materials/player.mat");
// 设置着色器
mat->SetShader(shaderHandle);
// 设置各种属性
mat->SetFloat("roughness", 0.5f);
mat->SetFloat3("albedo", Math::Vector3(1.0f, 0.8f, 0.6f));
mat->SetTexture("albedoMap", albedoTex);
mat->SetTexture("normalMap", normalTex);
mat->SetInt("normalScale", 1);
// 获取属性
float roughness = mat->GetFloat("roughness");
Math::Vector3 albedo = mat->GetFloat3("albedo");
// 检查属性
if (mat->HasProperty("metallic")) {
float metallic = mat->GetFloat("metallic");
}
// 更新常量缓冲区
mat->UpdateConstantBuffer();
auto cbData = mat->GetConstantBufferData();
```
## 相关文档
- [IResource](./resources-iresource.md) - 资源基类
- [Shader](./resources-shader.md) - 着色器资源
- [Texture](./resources-texture.md) - 纹理资源

View File

@@ -0,0 +1,148 @@
# Mesh
**命名空间**: `XCEngine::Resources`
**类型**: `class`
**描述**: 网格资源类,管理 3D 模型的顶点数据、索引数据和网格分段信息。
## 概述
`Mesh` 是 XCEngine 中的网格资源类,继承自 `IResource`。它管理网格的顶点数据位置、法线、UV、切线、颜色、骨骼权重等、索引数据和网格分段submesh
## 头文件
```cpp
#include <XCEngine/Resources/Mesh.h>
```
## 枚举类型
### VertexAttribute
顶点属性标志枚举(可组合)。
| 值 | 描述 |
|----|------|
| `Position` | 位置坐标 |
| `Normal` | 法线 |
| `Tangent` | 切线 |
| `Color` | 顶点颜色 |
| `UV0` | 第一组纹理坐标 |
| `UV1` | 第二组纹理坐标 |
| `UV2` | 第三组纹理坐标 |
| `UV3` | 第四组纹理坐标 |
| `BoneWeights` | 骨骼权重 |
| `BoneIndices` | 骨骼索引 |
## MeshSection 结构体
网格分段Submesh描述。
| 成员 | 类型 | 描述 |
|------|------|------|
| `baseVertex` | `Core::uint32` | 基础顶点索引 |
| `vertexCount` | `Core::uint32` | 顶点数量 |
| `startIndex` | `Core::uint32` | 起始索引 |
| `indexCount` | `Core::uint32` | 索引数量 |
| `materialID` | `Core::uint32` | 对应材质 ID |
## 公共方法
### 基础属性
| 方法 | 描述 |
|------|------|
| `ResourceType GetType() const` | 返回 `ResourceType::Mesh` |
| `const Containers::String& GetName() const` | 获取网格名称 |
| `const Containers::String& GetPath() const` | 获取网格路径 |
| `ResourceGUID GetGUID() const` | 获取全局唯一标识符 |
| `bool IsValid() const` | 检查网格是否有效 |
| `size_t GetMemorySize() const` | 获取内存大小 |
| `void Release()` | 释放网格引用 |
### 顶点数据
| 方法 | 描述 |
|------|------|
| `void SetVertexData(const void* data, size_t size, Core::uint32 vertexCount, Core::uint32 vertexStride, VertexAttribute attributes)` | 设置顶点数据 |
| `const void* GetVertexData() const` | 获取顶点数据指针 |
| `size_t GetVertexDataSize() const` | 获取顶点数据大小 |
| `Core::uint32 GetVertexCount() const` | 获取顶点数量 |
| `Core::uint32 GetVertexStride() const` | 获取顶点结构体大小(字节) |
| `VertexAttribute GetVertexAttributes() const` | 获取顶点属性标志 |
### 索引数据
| 方法 | 描述 |
|------|------|
| `void SetIndexData(const void* data, size_t size, Core::uint32 indexCount, bool use32Bit)` | 设置索引数据 |
| `const void* GetIndexData() const` | 获取索引数据指针 |
| `size_t GetIndexDataSize() const` | 获取索引数据大小 |
| `Core::uint32 GetIndexCount() const` | 获取索引数量 |
| `bool IsUse32BitIndex() const` | 是否使用 32 位索引 |
### 网格分段
| 方法 | 描述 |
|------|------|
| `void AddSection(const MeshSection& section)` | 添加网格分段 |
| `const Containers::Array<MeshSection>& GetSections() const` | 获取所有分段 |
## 使用示例
```cpp
// 加载网格
ResourceHandle<Mesh> mesh = ResourceManager::Get().Load<Mesh>("models/player.fbx");
// 手动设置顶点数据
struct Vertex {
float position[3];
float normal[3];
float uv[2];
};
Containers::Array<Vertex> vertices;
vertices.Resize(vertexCount);
// ... 填充顶点数据 ...
mesh->SetVertexData(
vertices.Data(),
vertices.Size() * sizeof(Vertex),
vertexCount,
sizeof(Vertex),
VertexAttribute::Position | VertexAttribute::Normal | VertexAttribute::UV0
);
// 设置索引数据
Containers::Array<uint32_t> indices;
indices.Resize(indexCount);
// ... 填充索引数据 ...
mesh->SetIndexData(
indices.Data(),
indices.Size() * sizeof(uint32_t),
indexCount,
true // 32 位索引
);
// 添加分段(一个网格可能有多个材质)
MeshSection section;
section.baseVertex = 0;
section.vertexCount = vertexCount;
section.startIndex = 0;
section.indexCount = indexCount;
section.materialID = 0;
mesh->AddSection(section);
// 访问数据
uint32_t vCount = mesh->GetVertexCount();
uint32_t iCount = mesh->GetIndexCount();
auto sections = mesh->GetSections();
```
## 相关文档
- [IResource](./resources-iresource.md) - 资源基类
- [Material](./resources-material.md) - 材质资源
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器

View File

@@ -0,0 +1,82 @@
# Resources 模块概览
**命名空间**: `XCEngine::Resources`
**类型**: `module`
**描述**: XCEngine 的资源管理系统,提供资源的异步加载、缓存和依赖管理。
## 概述
Resources 模块提供了一套完整的资源管理解决方案,支持同步和异步加载、资源缓存、依赖图管理等功能。
## 模块内容
### 核心组件
| 组件 | 文件 | 描述 |
|------|------|------|
| [IResource](./resources-iresource.md) | `IResource.h` | 资源基类 |
| [ResourceHandle](./resources-resourcehandle.md) | `ResourceHandle.h` | 资源句柄模板 |
| [IResourceLoader](./resources-iloader.md) | `IResourceLoader.h` | 资源加载器接口 |
| [ResourceManager](./resources-resourcemanager.md) | `ResourceManager.h` | 资源管理器 |
| [ResourceCache](./resources-resourcecache.md) | `ResourceCache.h` | 资源缓存 |
| [AsyncLoader](./resources-asyncloader.md) | `AsyncLoader.h` | 异步加载器 |
| [ResourceDependencyGraph](./resources-dependencygraph.md) | `ResourceDependencyGraph.h` | 依赖图 |
| [ResourceTypes](./resources-resourcetypes.md) | `ResourceTypes.h` | 资源类型定义 |
### 具体资源类型
| 组件 | 文件 | 描述 |
|------|------|------|
| [Texture](./resources-texture.md) | `Texture.h` | 纹理资源 |
| [Mesh](./resources-mesh.md) | `Mesh.h` | 网格资源 |
| [Material](./resources-material.md) | `Material.h` | 材质资源 |
| [Shader](./resources-shader.md) | `Shader.h` | 着色器资源 |
| [AudioClip](./resources-audioclip.md) | `AudioClip.h` | 音频资源 |
## 资源类型
| 类型 | 描述 |
|------|------|
| `Texture` | 纹理资源 |
| `Mesh` | 网格/模型资源 |
| `Material` | 材质资源 |
| `Shader` | 着色器资源 |
| `AudioClip` | 音频资源 |
| `Binary` | 二进制数据 |
| `AnimationClip` | 动画片段 |
| `Skeleton` | 骨骼 |
| `Font` | 字体 |
| `ParticleSystem` | 粒子系统 |
| `Scene` | 场景 |
| `Prefab` | 预制体 |
## 使用示例
```cpp
#include <XCEngine/Resources/ResourceManager.h>
// 初始化资源管理器
ResourceManager::Get().Initialize();
ResourceManager::Get().SetResourceRoot("resources/");
// 同步加载资源
ResourceHandle<Texture> tex = ResourceManager::Get().Load<Texture>("textures/player.png");
ResourceHandle<Mesh> mesh = ResourceManager::Get().Load<Mesh>("models/player.fbx");
ResourceHandle<Material> mat = ResourceManager::Get().Load<Material>("materials/player.mat");
// 异步加载
ResourceManager::Get().LoadAsync<Texture>("textures/terrain.png",
[](ResourceHandle<Texture> tex) {
// 加载完成回调
});
// 释放资源
tex.Reset();
mesh.Reset();
```
## 相关文档
- [RHI 模块](../rhi/rhi-overview.md) - GPU 资源创建

View File

@@ -0,0 +1,98 @@
# ResourceCache
**命名空间**: `XCEngine::Resources`
**类型**: `class`
**描述**: 资源缓存管理类,使用 LRU最近最少使用策略管理内存压力下的资源驱逐。
## 概述
`ResourceCache` 实现了资源的内存缓存管理。它跟踪每个资源的访问时间和访问次数,在内存压力下自动驱逐最近最少使用的资源,确保内存使用不超过预算。
## 公共方法
### 生命周期
| 方法 | 描述 |
|------|------|
| `ResourceCache()` | 默认构造函数 |
| `~ResourceCache()` | 析构函数 |
### 缓存操作
| 方法 | 描述 |
|------|------|
| `void Add(ResourceGUID guid, IResource* resource)` | 添加资源到缓存 |
| `void Remove(ResourceGUID guid)` | 从缓存中移除资源 |
| `IResource* Find(ResourceGUID guid) const` | 查找资源 |
| `void Touch(ResourceGUID guid)` | 更新资源的访问时间LRU |
### 内存管理
| 方法 | 描述 |
|------|------|
| `size_t GetSize() const` | 获取缓存中资源数量 |
| `size_t GetMemoryUsage() const` | 获取缓存内存使用量(字节) |
| `void SetMemoryBudget(size_t bytes)` | 设置内存预算 |
| `size_t GetMemoryBudget() const` | 获取内存预算 |
| `void OnMemoryPressure(size_t requiredBytes)` | 内存压力回调,驱逐资源以释放空间 |
| `void OnZeroRefCount(ResourceGUID guid)` | 当引用计数为零时的回调 |
### 缓存控制
| 方法 | 描述 |
|------|------|
| `void Flush()` | 清空缓存,释放所有资源 |
| `void Clear()` | 清空缓存但不释放资源 |
### LRU 信息
| 方法 | 描述 |
|------|------|
| `Containers::Array<ResourceGUID> GetLRUList(size_t count) const` | 获取最近最少使用的 GUID 列表 |
## CacheEntry 结构体
缓存条目结构体。
| 成员 | 类型 | 描述 |
|------|------|------|
| `resource` | `IResource*` | 资源指针 |
| `guid` | `ResourceGUID` | 全局唯一标识符 |
| `memorySize` | `size_t` | 内存大小 |
| `lastAccessTime` | `Core::uint64` | 上次访问时间戳 |
| `accessCount` | `Core::uint32` | 访问次数 |
### 静态方法
| 方法 | 描述 |
|------|------|
| `static Core::uint64 GetCurrentTick()` | 获取当前时间戳 |
## 使用示例
```cpp
ResourceCache cache;
cache.SetMemoryBudget(512 * 1024 * 1024); // 512MB 预算
// 添加资源
cache.Add(guid, resource);
// 访问资源(更新 LRU
cache.Touch(guid);
// 查找资源
IResource* res = cache.Find(guid);
// 内存压力时自动驱逐
cache.OnMemoryPressure(100 * 1024 * 1024); // 需要 100MB
// 获取最少使用的资源
auto lruList = cache.GetLRUList(10);
```
## 相关文档
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器
- [IResource](./resources-iresource.md) - 资源基类

View File

@@ -0,0 +1,100 @@
# ResourceHandle
**命名空间**: `XCEngine::Resources`
**类型**: `class` (template)
**描述**: 模板资源句柄类,提供资源的引用计数式安全访问,自动管理资源的加载和释放。
## 概述
`ResourceHandle<T>` 是一个模板句柄类,用于安全地持有对资源的引用。它通过 `ResourceManager` 自动管理引用计数:当句柄被创建时引用计数增加,当句柄被销毁或调用 `Reset()` 时引用计数减少。这确保了资源在其仍被使用时不会被卸载。
## 模板参数
| 参数 | 约束 | 描述 |
|------|------|------|
| `T` | 必须派生自 `IResource` | 资源类型 |
## 公共方法
### 构造/析构
| 方法 | 描述 |
|------|------|
| `ResourceHandle() = default` | 默认构造空句柄 |
| `explicit ResourceHandle(T* resource)` | 从裸指针构造(自动增加引用) |
| `ResourceHandle(const ResourceHandle& other)` | 拷贝构造(自动增加引用) |
| `ResourceHandle(ResourceHandle&& other) noexcept` | 移动构造 |
| `~ResourceHandle()` | 析构函数(自动调用 Reset |
### 赋值
| 方法 | 描述 |
|------|------|
| `ResourceHandle& operator=(const ResourceHandle& other)` | 拷贝赋值(自动管理引用) |
| `ResourceHandle& operator=(ResourceHandle&& other) noexcept` | 移动赋值 |
### 资源访问
| 方法 | 描述 |
|------|------|
| `T* Get() const` | 获取裸指针 |
| `T* operator->() const` | 通过指针访问资源成员 |
| `T& operator*() const` | 解引用获取资源引用 |
### 状态查询
| 方法 | 描述 |
|------|------|
| `bool IsValid() const` | 检查句柄是否持有有效资源 |
| `explicit operator bool() const` | 隐式布尔转换 |
### GUID 和类型
| 方法 | 描述 |
|------|------|
| `ResourceGUID GetGUID() const` | 获取资源的全局唯一标识符 |
| `ResourceType GetResourceType() const` | 获取资源类型 |
### 资源释放
| 方法 | 描述 |
|------|------|
| `void Reset()` | 释放当前资源引用 |
| `void Swap(ResourceHandle& other)` | 交换两个句柄的内容 |
## 比较运算
| 运算符 | 描述 |
|------|------|
| `operator==(ResourceHandle, ResourceHandle)` | 比较 GUID 是否相等 |
| `operator!=(ResourceHandle, ResourceHandle)` | 比较 GUID 是否不等 |
## 使用示例
```cpp
// 加载资源(引用计数 +1
ResourceHandle<Texture> tex = ResourceManager::Get().Load<Texture>("textures/player.png");
// 检查有效性
if (tex.IsValid()) {
// 安全访问资源
uint32_t width = tex->GetWidth();
}
// 拷贝句柄(引用计数 +1
ResourceHandle<Texture> tex2 = tex;
// 移动句柄
ResourceHandle<Texture> tex3 = std::move(tex2);
// 句柄离开作用域时自动释放(引用计数 -1
tex.Reset(); // 手动释放
```
## 相关文档
- [IResource](./resources-iresource.md) - 资源基类
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器
- [ResourceCache](./resources-resourcecache.md) - 资源缓存

View File

@@ -0,0 +1,166 @@
# ResourceManager
**命名空间**: `XCEngine::Resources`
**类型**: `class` (singleton)
**描述**: 资源管理器单例,负责资源的加载、缓存、引用计数管理和异步加载调度。
## 概述
`ResourceManager` 是 XCEngine 资源管理系统的核心单例类。它提供统一的资源加载接口、自动缓存管理、引用计数跟踪和异步加载支持。所有资源访问都应通过 `ResourceManager` 进行。
## 单例访问
| 方法 | 描述 |
|------|------|
| `static ResourceManager& Get()` | 获取单例实例 |
## 公共方法
### 生命周期
| 方法 | 描述 |
|------|------|
| `void Initialize()` | 初始化资源管理器 |
| `void Shutdown()` | 关闭资源管理器,卸载所有资源 |
### 资源根目录
| 方法 | 描述 |
|------|------|
| `void SetResourceRoot(const Containers::String& rootPath)` | 设置资源根目录 |
| `const Containers::String& GetResourceRoot() const` | 获取资源根目录 |
### 同步加载
| 方法 | 描述 |
|------|------|
| `ResourceHandle<T> Load(const Containers::String& path, ImportSettings* settings = nullptr)` | 同步加载资源(模板方法) |
### 异步加载
| 方法 | 描述 |
|------|------|
| `void LoadAsync(const Containers::String& path, ResourceType type, std::function<void(LoadResult)> callback)` | 异步加载资源 |
| `void LoadAsync(const Containers::String& path, ResourceType type, ImportSettings* settings, std::function<void(LoadResult)> callback)` | 带设置的异步加载 |
### 批量加载
| 方法 | 描述 |
|------|------|
| `void LoadGroup(const Containers::Array<Containers::String>& paths, std::function<void(ResourceHandle<T>)> callback)` | 批量异步加载同类资源 |
### 卸载管理
| 方法 | 描述 |
|------|------|
| `void Unload(const Containers::String& path)` | 按路径卸载资源 |
| `void Unload(ResourceGUID guid)` | 按 GUID 卸载资源 |
| `void UnloadUnused()` | 卸载所有无引用的资源 |
| `void UnloadAll()` | 卸载所有资源 |
### 引用计数
| 方法 | 描述 |
|------|------|
| `void AddRef(ResourceGUID guid)` | 增加引用计数(内部使用) |
| `void Release(ResourceGUID guid)` | 减少引用计数(内部使用) |
| `Core::uint32 GetRefCount(ResourceGUID guid) const` | 获取引用计数 |
### 查找
| 方法 | 描述 |
|------|------|
| `IResource* Find(const Containers::String& path)` | 按路径查找资源 |
| `IResource* Find(ResourceGUID guid)` | 按 GUID 查找资源 |
| `bool Exists(const Containers::String& path) const` | 检查资源是否存在 |
| `bool Exists(ResourceGUID guid) const` | 检查 GUID 对应资源是否存在 |
### 加载器管理
| 方法 | 描述 |
|------|------|
| `void RegisterLoader(IResourceLoader* loader)` | 注册资源加载器 |
| `void UnregisterLoader(ResourceType type)` | 注销加载器 |
| `IResourceLoader* GetLoader(ResourceType type) const` | 获取指定类型的加载器 |
### 内存管理
| 方法 | 描述 |
|------|------|
| `void SetMemoryBudget(size_t bytes)` | 设置内存预算 |
| `size_t GetMemoryUsage() const` | 获取当前内存使用量 |
| `size_t GetMemoryBudget() const` | 获取内存预算 |
| `void FlushCache()` | 清空缓存 |
### 路径解析
| 方法 | 描述 |
|------|------|
| `Containers::String ResolvePath(const Containers::String& relativePath) const` | 将相对路径解析为绝对路径 |
### 资源信息
| 方法 | 描述 |
|------|------|
| `Containers::Array<Containers::String> GetResourcePaths() const` | 获取所有已加载资源的路径列表 |
| `void UnloadGroup(const Containers::Array<ResourceGUID>& guids)` | 按 GUID 批量卸载 |
## 私有方法(内部使用)
| 方法 | 描述 |
|------|------|
| `IResource* FindInCache(ResourceGUID guid)` | 在缓存中查找资源 |
| `void AddToCache(ResourceGUID guid, IResource* resource)` | 添加到缓存 |
| `IResourceLoader* FindLoader(ResourceType type)` | 查找加载器 |
| `void ReloadResource(ResourceGUID guid)` | 重新加载资源 |
## 使用示例
```cpp
// 初始化
ResourceManager::Get().Initialize();
ResourceManager::Get().SetResourceRoot("resources/");
// 注册加载器
ResourceManager::Get().RegisterLoader(new TextureLoader());
ResourceManager::Get().RegisterLoader(new MeshLoader());
ResourceManager::Get().RegisterLoader(new MaterialLoader());
// 同步加载
ResourceHandle<Texture> tex = ResourceManager::Get().Load<Texture>("textures/player.png");
ResourceHandle<Mesh> mesh = ResourceManager::Get().Load<Mesh>("models/player.fbx");
// 异步加载
ResourceManager::Get().LoadAsync<Texture>("textures/terrain.png",
[](LoadResult result) {
if (result.success) {
ResourceHandle<Texture> tex(result.resource);
// 使用纹理...
}
});
// 批量加载
Containers::Array<Containers::String> paths = {"a.png", "b.png", "c.png"};
ResourceManager::Get().LoadGroup<Texture>(paths,
[](ResourceHandle<Texture> tex) {
if (tex.IsValid()) {
// 处理加载完成的纹理...
}
});
// 设置内存预算
ResourceManager::Get().SetMemoryBudget(1024 * 1024 * 1024); // 1GB
// 卸载
ResourceManager::Get().UnloadUnused();
ResourceManager::Get().Shutdown();
```
## 相关文档
- [IResource](./resources-iresource.md) - 资源基类
- [ResourceHandle](./resources-resourcehandle.md) - 资源句柄
- [ResourceCache](./resources-resourcecache.md) - 资源缓存
- [AsyncLoader](./resources-asyncloader.md) - 异步加载器

View File

@@ -0,0 +1,101 @@
# ResourceTypes
**命名空间**: `XCEngine::Resources`
**类型**: `enums` / `structs`
**描述**: 资源模块中使用的所有类型定义包括资源类型枚举、GUID 结构体等。
## 概述
本文档汇总了 Resources 模块中的所有类型定义包括资源类型枚举、GUID 结构体等基础类型。
---
## ResourceType
资源类型枚举。
| 值 | 描述 |
|----|------|
| `Unknown` | 未知类型 |
| `Texture` | 纹理资源 |
| `Mesh` | 网格/模型资源 |
| `Material` | 材质资源 |
| `Shader` | 着色器资源 |
| `AudioClip` | 音频资源 |
| `Binary` | 二进制数据 |
| `AnimationClip` | 动画片段 |
| `Skeleton` | 骨骼 |
| `Font` | 字体 |
| `ParticleSystem` | 粒子系统 |
| `Scene` | 场景 |
| `Prefab` | 预制体 |
---
## ResourceGUID
全局唯一标识符结构体,用于唯一标识每个资源。
```cpp
struct ResourceGUID {
uint64_t value = 0;
};
```
### 构造方法
| 方法 | 描述 |
|------|------|
| `ResourceGUID()` | 默认构造(值为 0 |
| `explicit ResourceGUID(uint64_t value)` | 从整数值构造 |
### 比较运算
| 运算符 | 描述 |
|------|------|
| `operator==(ResourceGUID, ResourceGUID)` | 判断相等 |
| `operator!=(ResourceGUID, ResourceGUID)` | 判断不等 |
### 哈希支持
`ResourceGUID` 可作为 HashMap 的键使用。
### 静态方法
| 方法 | 描述 |
|------|------|
| `static ResourceGUID Generate(const Containers::String& path)` | 从资源路径生成唯一 GUID |
---
## 辅助函数
| 函数 | 描述 |
|------|------|
| `const char* GetResourceTypeName(ResourceType type)` | 获取资源类型的字符串名称 |
---
## 使用示例
```cpp
// 使用 ResourceGUID
ResourceGUID texGuid = ResourceGUID::Generate("textures/player.png");
ResourceGUID meshGuid = ResourceGUID::Generate("models/player.fbx");
// GUID 比较
if (texGuid == meshGuid) {
// 相同资源
}
// 在 HashMap 中使用
Containers::HashMap<ResourceGUID, IResource*> cache;
cache[texGuid] = texture;
```
## 相关文档
- [IResource](./resources-iresource.md) - 资源基类
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器

View File

@@ -0,0 +1,149 @@
# Shader
**命名空间**: `XCEngine::Resources`
**类型**: `class`
**描述**: 着色器资源类,管理着色器源码、编译后的二进制和 uniform/attribute 信息。
## 概述
`Shader` 是 XCEngine 中的着色器资源类,继承自 `IResource`。它管理着色器源码、编译后的二进制数据、着色器类型、语言类型、uniform 列表和 attribute 列表,并持有对应的 RHI 着色器资源指针。
## 头文件
```cpp
#include <XCEngine/Resources/Shader.h>
```
## 枚举类型
### ShaderType
着色器类型枚举。
| 值 | 描述 |
|----|------|
| `Vertex` | 顶点着色器 |
| `Fragment` | 片元着色器 |
| `Geometry` | 几何着色器 |
| `Compute` | 计算着色器 |
| `Hull` | Hull 着色器(曲面细分控制) |
| `Domain` | Domain 着色器(曲面细分评估) |
### ShaderLanguage
着色器语言枚举。
| 值 | 描述 |
|----|------|
| `GLSL` | OpenGL Shading Language |
| `HLSL` | High-Level Shading Language |
| `SPIRV` | SPIR-V 二进制格式 |
## 结构体
### ShaderUniform
Uniform 变量描述。
| 成员 | 类型 | 描述 |
|------|------|------|
| `name` | `Containers::String` | Uniform 名称 |
| `location` | `Core::uint32` | 位置/绑定点 |
| `size` | `Core::uint32` | 大小(字节) |
| `type` | `Core::uint32` | 类型标识 |
### ShaderAttribute
顶点属性描述。
| 成员 | 类型 | 描述 |
|------|------|------|
| `name` | `Containers::String` | 属性名称 |
| `location` | `Core::uint32` | 位置索引 |
| `size` | `Core::uint32` | 大小(字节) |
| `type` | `Core::uint32` | 类型标识 |
## 公共方法
### 基础属性
| 方法 | 描述 |
|------|------|
| `ResourceType GetType() const` | 返回 `ResourceType::Shader` |
| `const Containers::String& GetName() const` | 获取着色器名称 |
| `const Containers::String& GetPath() const` | 获取着色器路径 |
| `ResourceGUID GetGUID() const` | 获取全局唯一标识符 |
| `bool IsValid() const` | 检查着色器是否有效 |
| `size_t GetMemorySize() const` | 获取内存大小 |
| `void Release()` | 释放着色器引用 |
### 类型与语言
| 方法 | 描述 |
|------|------|
| `void SetShaderType(ShaderType type)` | 设置着色器类型 |
| `ShaderType GetShaderType() const` | 获取着色器类型 |
| `void SetShaderLanguage(ShaderLanguage lang)` | 设置着色器语言 |
| `ShaderLanguage GetShaderLanguage() const` | 获取着色器语言 |
### 源码与编译
| 方法 | 描述 |
|------|------|
| `void SetSourceCode(const Containers::String& source)` | 设置源码 |
| `const Containers::String& GetSourceCode() const` | 获取源码 |
| `void SetCompiledBinary(const Containers::Array<Core::uint8>& binary)` | 设置编译后二进制 |
| `const Containers::Array<Core::uint8>& GetCompiledBinary() const` | 获取编译后二进制 |
### Uniform 和 Attribute
| 方法 | 描述 |
|------|------|
| `void AddUniform(const ShaderUniform& uniform)` | 添加 Uniform 描述 |
| `const Containers::Array<ShaderUniform>& GetUniforms() const` | 获取 Uniform 列表 |
| `void AddAttribute(const ShaderAttribute& attribute)` | 添加 Attribute 描述 |
| `const Containers::Array<ShaderAttribute>& GetAttributes() const` | 获取 Attribute 列表 |
### RHI 资源
| 方法 | 描述 |
|------|------|
| `class IRHIShader* GetRHIResource() const` | 获取 RHI 着色器资源 |
| `void SetRHIResource(class IRHIShader* resource)` | 设置 RHI 着色器资源 |
## 使用示例
```cpp
// 加载着色器
ResourceHandle<Shader> vs = ResourceManager::Get().Load<Shader>("shaders/vertex.glsl");
ResourceHandle<Shader> fs = ResourceManager::Get().Load<Shader>("shaders/fragment.glsl");
// 设置类型
vs->SetShaderType(ShaderType::Vertex);
fs->SetShaderType(ShaderType::Fragment);
// 设置语言
vs->SetShaderLanguage(ShaderLanguage::GLSL);
// 设置编译后二进制
vs->SetCompiledBinary(compiledSpirv);
// 添加 Uniform
ShaderUniform uniform;
uniform.name = "modelMatrix";
uniform.location = 0;
uniform.size = sizeof(float) * 16;
uniform.type = 0;
vs->AddUniform(uniform);
// 访问 RHI 资源
RHIShader* rhiShader = vs->GetRHIResource();
```
## 相关文档
- [IResource](./resources-iresource.md) - 资源基类
- [RHIShader](../rhi/rhi-shader.md) - RHI 着色器接口
- [Material](./resources-material.md) - 材质资源

View File

@@ -0,0 +1,152 @@
# Texture
**命名空间**: `XCEngine::Resources`
**类型**: `class`
**描述**: 纹理资源类,管理 2D/3D 纹理和立方体贴图的像素数据。
## 概述
`Texture` 是 XCEngine 中的纹理资源类,继承自 `IResource`。它管理纹理的尺寸、格式、像素数据,并支持 mipmap 生成等功能。
## 头文件
```cpp
#include <XCEngine/Resources/Texture.h>
```
## 枚举类型
### TextureType
纹理类型枚举。
| 值 | 描述 |
|----|------|
| `Texture2D` | 2D 纹理 |
| `Texture3D` | 3D 体积纹理 |
| `TextureCube` | 立方体贴图 |
| `Texture2DArray` | 2D 纹理数组 |
| `TextureCubeArray` | 立方体贴图数组 |
### TextureFormat
纹理像素格式枚举。
| 值 | 描述 |
|----|------|
| `Unknown` | 未知格式 |
| `R8_UNORM` | 单通道 8 位归一化 |
| `RG8_UNORM` | 双通道 8 位归一化 |
| `RGBA8_UNORM` | 四通道 8 位归一化 |
| `RGBA8_SRGB` | 四通道 8 位 sRGB |
| `R16_FLOAT` | 单通道 16 位浮点 |
| `RG16_FLOAT` | 双通道 16 位浮点 |
| `RGBA16_FLOAT` | 四通道 16 位浮点 |
| `R32_FLOAT` | 单通道 32 位浮点 |
| `RG32_FLOAT` | 双通道 32 位浮点 |
| `RGBA32_FLOAT` | 四通道 32 位浮点 |
| `D16_UNORM` | 16 位深度 |
| `D24_UNORM_S8_UINT` | 24 位深度 + 8 位模板 |
| `D32_FLOAT` | 32 位深度 |
| `D32_FLOAT_S8_X24_UINT` | 32 位深度 + 8+24 位模板 |
| `BC1_UNORM` | BC1 压缩 (DXT1) |
| `BC1_UNORM_SRGB` | BC1 sRGB |
| `BC2_UNORM` | BC2 压缩 (DXT3) |
| `BC2_UNORM_SRGB` | BC2 sRGB |
| `BC3_UNORM` | BC3 压缩 (DXT5) |
| `BC3_UNORM_SRGB` | BC3 sRGB |
| `BC4_UNORM` | BC4 压缩 |
| `BC5_UNORM` | BC5 压缩 |
| `BC6H_UF16` | BC6H 压缩 |
| `BC7_UNORM` | BC7 压缩 |
| `BC7_UNORM_SRGB` | BC7 sRGB |
### TextureUsage
纹理用途标志枚举(可组合)。
| 值 | 描述 |
|----|------|
| `None` | 无特殊用途 |
| `ShaderResource` | 着色器资源 |
| `RenderTarget` | 渲染目标 |
| `DepthStencil` | 深度模板 |
| `UnorderedAccess` | 无序访问 |
| `TransferSrc` | 传输源 |
| `TransferDst` | 传输目标 |
## 公共方法
### 基础属性
| 方法 | 描述 |
|------|------|
| `ResourceType GetType() const` | 返回 `ResourceType::Texture` |
| `const Containers::String& GetName() const` | 获取纹理名称 |
| `const Containers::String& GetPath() const` | 获取纹理路径 |
| `ResourceGUID GetGUID() const` | 获取全局唯一标识符 |
| `bool IsValid() const` | 检查纹理是否有效 |
| `size_t GetMemorySize() const` | 获取内存大小 |
| `void Release()` | 释放纹理引用 |
### 纹理属性
| 方法 | 描述 |
|------|------|
| `Core::uint32 GetWidth() const` | 获取纹理宽度(像素) |
| `Core::uint32 GetHeight() const` | 获取纹理高度(像素) |
| `Core::uint32 GetDepth() const` | 获取纹理深度3D 纹理) |
| `Core::uint32 GetMipLevels() const` | 获取 Mipmap 级别数 |
| `Core::uint32 GetArraySize() const` | 获取数组大小 |
| `TextureType GetTextureType() const` | 获取纹理类型 |
| `TextureFormat GetFormat() const` | 获取纹理格式 |
| `TextureUsage GetUsage() const` | 获取纹理用途标志 |
### 像素数据
| 方法 | 描述 |
|------|------|
| `const void* GetPixelData() const` | 获取像素数据指针 |
| `size_t GetPixelDataSize() const` | 获取像素数据大小 |
### 创建与操作
| 方法 | 描述 |
|------|------|
| `bool Create(Core::uint32 width, Core::uint32 height, Core::uint32 depth, Core::uint32 mipLevels, TextureType type, TextureFormat format, const void* data, size_t dataSize)` | 创建纹理 |
| `bool GenerateMipmaps()` | 生成 Mipmap |
## 使用示例
```cpp
// 加载纹理
ResourceHandle<Texture> tex = ResourceManager::Get().Load<Texture>("textures/player.png");
// 手动创建纹理
Texture tex;
bool created = tex.Create(
1024, // 宽度
1024, // 高度
1, // 深度
0, // Mipmap 级别0=全部)
TextureType::Texture2D, // 类型
TextureFormat::RGBA8_UNORM, // 格式
pixelData, // 像素数据
pixelDataSize // 数据大小
);
// 生成 Mipmap
tex.GenerateMipmaps();
// 访问纹理属性
uint32_t w = tex.GetWidth();
uint32_t h = tex.GetHeight();
```
## 相关文档
- [IResource](./resources-iresource.md) - 资源基类
- [ResourceManager](./resources-resourcemanager.md) - 资源管理器
- [RHITexture](../rhi/rhi-texture.md) - RHI 纹理接口

View File

@@ -0,0 +1,178 @@
# D3D12Buffer
DirectX 12 缓冲区的 D3D12 实现,封装了 `ID3D12Resource` (buffer 类型)。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12Buffer.h>
```
## 继承关系
```
RHIBuffer (interface)
└── D3D12Buffer (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12Buffer()`
默认构造函数。
#### `~D3D12Buffer() override`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `bool Initialize(ID3D12Device* device, uint64_t size, D3D12_RESOURCE_STATES initialState = D3D12_RESOURCE_STATE_COMMON, D3D12_HEAP_TYPE heapType = D3D12_HEAP_TYPE_DEFAULT)`
创建新缓冲区。
- `device`: D3D12 设备
- `size`: 缓冲区大小(字节)
- `initialState`: 初始资源状态
- `heapType`: 堆类型 (DEFAULT, UPLOAD, READBACK)
- 返回: 初始化是否成功
#### `bool InitializeFromExisting(ID3D12Resource* resource)`
从现有 D3D12 资源初始化。
- `resource`: 已存在的 `ID3D12Resource` 指针
#### `bool InitializeWithData(ID3D12Device* device, ID3D12GraphicsCommandList* commandList, const void* data, uint64_t size, D3D12_RESOURCE_STATES finalState)`
创建缓冲区并从内存数据初始化内容。
- `device`: D3D12 设备
- `commandList`: 命令列表(用于复制数据)
- `data`: 初始数据指针
- `size`: 数据大小
- `finalState`: 数据复制完成后的目标状态
#### `void Shutdown() override`
释放缓冲区资源。
### 数据操作
#### `void UpdateData(const void* data, uint64_t size)`
更新缓冲区数据(需要 UPLOAD 堆类型)。
#### `void SetData(const void* data, size_t size, size_t offset = 0) override`
设置缓冲区数据。
#### `void* Map() override`
映射缓冲区内存到 CPU 可访问。
#### `void Unmap() override`
解除缓冲区内存映射。
### 资源信息
#### `ID3D12Resource* GetResource() const`
获取底层 `ID3D12Resource` 指针。
#### `D3D12_RESOURCE_DESC GetDesc() const`
获取资源描述。
#### `D3D12_GPU_VIRTUAL_ADDRESS GetGPUVirtualAddress() const`
获取 GPU 虚拟地址。
#### `uint64_t GetGPUAddress() const`
获取 GPU 地址(等同于 `GetGPUVirtualAddress`)。
#### `uint64_t GetSize() const override`
获取缓冲区大小。
#### `ResourceStates GetState() const`
获取当前资源状态。
#### `void SetState(ResourceStates state)`
设置资源状态。
### 接口实现
#### `void* GetNativeHandle() override { return m_resource.Get(); }`
返回原生句柄。
#### `const std::string& GetName() const override`
获取对象名称。
#### `void SetName(const std::string& name) override`
设置对象名称。
#### `uint32_t GetStride() const override`
获取顶点步长。
#### `BufferType GetBufferType() const override`
获取缓冲区类型。
#### `void SetStride(uint32_t stride) override`
设置顶点步长。
#### `void SetBufferType(BufferType type) override`
设置缓冲区类型。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_resource` | `ComPtr<ID3D12Resource>` | D3D12 资源对象 |
| `m_state` | `ResourceStates` | 当前资源状态 |
| `m_name` | `std::string` | 对象名称 |
| `m_stride` | `uint32_t` | 顶点步长 |
| `m_bufferType` | `BufferType` | 缓冲区类型 |
## 使用示例
### 创建顶点缓冲区
```cpp
D3D12Buffer vertexBuffer;
struct Vertex { float pos[3]; float uv[2]; };
if (vertexBuffer.Initialize(
device->GetDevice(),
sizeof(Vertex) * vertexCount,
D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER,
D3D12_HEAP_TYPE_DEFAULT))
{
vertexBuffer.SetName(L"VertexBuffer");
vertexBuffer.SetStride(sizeof(Vertex));
vertexBuffer.SetBufferType(BufferType::Vertex);
}
```
### 创建并初始化索引缓冲区
```cpp
D3D12Buffer indexBuffer;
uint16_t indices[] = { 0, 1, 2, ... };
D3D12CommandList cmdList;
cmdList.Initialize(device->GetDevice());
indexBuffer.InitializeWithData(
device->GetDevice(),
cmdList.GetCommandList(),
indices,
sizeof(indices),
D3D12_RESOURCE_STATE_INDEX_BUFFER);
cmdList.Close();
```
### 更新 UPLOAD 缓冲区
```cpp
D3D12Buffer uploadBuffer;
uploadBuffer.Initialize(device, bufferSize, D3D12_RESOURCE_STATE_GENERIC_READ, D3D12_HEAP_TYPE_UPLOAD);
void* mapped = uploadBuffer.Map();
memcpy(mapped, data, dataSize);
uploadBuffer.Unmap();
```
## 备注
- `D3D12_HEAP_TYPE_DEFAULT`: GPU 专用显存,适合渲染使用
- `D3D12_HEAP_TYPE_UPLOAD`: CPU 可写 GPU 可读的堆,用于上传数据
- `D3D12_HEAP_TYPE_READBACK`: CPU 可读 GPU 回读数据的堆
- 创建后立即使用需注意资源状态转换

View File

@@ -0,0 +1,80 @@
# D3D12CommandAllocator
DirectX 12 命令分配器的 D3D12 实现,封装了 `ID3D12CommandAllocator`
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12CommandAllocator.h>
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12CommandAllocator()`
默认构造函数。
#### `~D3D12CommandAllocator()`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `bool Initialize(ID3D12Device* device, CommandQueueType type = CommandQueueType::Direct)`
初始化命令分配器。
- `device`: D3D12 设备
- `type`: 命令类型,必须与命令列表类型匹配
- 返回: 初始化是否成功
#### `void Shutdown()`
释放命令分配器。
### 操作
#### `void Reset()`
重置命令分配器,丢弃所有已记录的指令。
#### `bool IsReady() const`
检查分配器是否准备就绪GPU 不再使用)。
### 属性
#### `ID3D12CommandAllocator* GetCommandAllocator() const`
获取底层 `ID3D12CommandAllocator` 指针。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_commandAllocator` | `ComPtr<ID3D12CommandAllocator>` | D3D12 命令分配器 |
| `m_type` | `CommandQueueType` | 命令类型 |
## 使用示例
```cpp
// Create allocator
D3D12CommandAllocator allocator;
allocator.Initialize(device->GetDevice(), CommandQueueType::Direct);
// Create command list with allocator
D3D12CommandList cmdList;
cmdList.Initialize(device->GetDevice(), CommandQueueType::Direct,
allocator.GetCommandAllocator());
// Use command list...
cmdList->Close();
cmdQueue->ExecuteCommandListsInternal(1, &cmdList);
// Wait for GPU to finish
cmdQueue->WaitForIdle();
// Reset allocator for next frame
allocator.Reset();
cmdList->Reset(allocator.GetCommandAllocator(), nullptr);
```
## 备注
- 命令分配器必须在 GPU 完成所有关联命令后才能重置
- 每个帧通常有独立的命令分配器以支持帧间并行
- 命令分配器创建开销小,可以频繁创建销毁

View File

@@ -0,0 +1,269 @@
# D3D12CommandList
DirectX 12 图形命令列表的 D3D12 实现,封装了 `ID3D12GraphicsCommandList`
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12CommandList.h>
```
## 类概览
`D3D12CommandList` 继承自 `RHICommandList`,是 D3D12 渲染命令的录制和执行载体。它封装了 `ID3D12GraphicsCommandList`,并提供状态跟踪和资源管理功能。
## 公共成员函数
### 初始化与销毁
#### `bool Initialize(ID3D12Device* device, CommandQueueType type = CommandQueueType::Direct, ID3D12CommandAllocator* allocator = nullptr)`
初始化命令列表。
- `device`: D3D12 设备指针
- `type`: 命令队列类型 (Direct, Compute, Copy)
- `allocator`: 可选命令分配器
- 返回: 初始化是否成功
#### `void Shutdown()`
关闭并释放命令列表。
### 命令录制控制
#### `void Reset()`
重置命令列表,重新开始录制。
#### `void Close()`
关闭命令列表,停止录制。
#### `ID3D12GraphicsCommandList* GetCommandList() const`
获取底层 `ID3D12GraphicsCommandList` 指针。
### 资源状态转换
#### `void TransitionBarrier(void* resource, ResourceStates stateBefore, ResourceStates stateAfter)`
添加资源状态转换屏障。
#### `void UAVBarrier(void* resource = nullptr)`
添加无序访问视图屏障。
#### `void AliasBarrier(void* beforeResource = nullptr, void* afterResource = nullptr)`
添加别名化屏障。
### 管线状态设置
#### `void SetPipelineState(void* pso)`
设置图形管线状态对象。
#### `void SetRootSignature(ID3D12RootSignature* signature)`
设置根签名。
#### `void SetPrimitiveTopology(PrimitiveTopology topology)`
设置图元拓扑类型。
### 视口与裁剪矩形
#### `void SetViewport(const Viewport& viewport)`
设置单个视口。
#### `void SetViewports(uint32_t count, const Viewport* viewports)`
设置多个视口。
#### `void SetScissorRect(const Rect& rect)`
设置单个裁剪矩形。
#### `void SetScissorRects(uint32_t count, const Rect* rects)`
设置多个裁剪矩形。
### 渲染目标
#### `void SetRenderTargets(uint32_t count, void** renderTargets, void* depthStencil = nullptr)`
设置渲染目标视图。
#### `void SetRenderTargetsInternal(uint32_t count, ID3D12Resource** renderTargets, ID3D12Resource* depthStencil = nullptr)`
内部方法,直接使用 D3D12 资源指针。
#### `void SetRenderTargetsHandle(uint32_t count, const D3D12_CPU_DESCRIPTOR_HANDLE* renderTargetHandles, const D3D12_CPU_DESCRIPTOR_HANDLE* depthStencilHandle = nullptr)`
使用 CPU 描述符句柄设置渲染目标。
### 顶点缓冲区与索引缓冲区
#### `void SetVertexBuffer(uint32_t slot, void* buffer, uint64_t offset, uint32_t stride)`
设置单个顶点缓冲区。
#### `void SetVertexBuffers(uint32_t startSlot, uint32_t count, const uint64_t* buffers, const uint64_t* offsets, const uint32_t* strides)`
批量设置顶点缓冲区。
#### `void SetIndexBuffer(void* buffer, uint64_t offset, Format format)`
设置索引缓冲区。
### 描述符堆
#### `void SetDescriptorHeap(ID3D12DescriptorHeap* heap)`
设置描述符堆。
#### `void SetDescriptorHeaps(uint32_t count, ID3D12DescriptorHeap** heaps)`
设置多个描述符堆。
### 描述符表绑定
#### `void SetGraphicsDescriptorTable(uint32_t rootParameterIndex, D3D12_GPU_DESCRIPTOR_HANDLE baseHandle)`
设置图形渲染的描述符表。
#### `void SetComputeDescriptorTable(uint32_t rootParameterIndex, D3D12_GPU_DESCRIPTOR_HANDLE baseHandle)`
设置计算渲染的描述符表。
### 根参数绑定
#### `void SetGraphicsRootConstantBufferView(uint32_t rootParameterIndex, D3D12_GPU_VIRTUAL_ADDRESS bufferLocation)`
设置根常量缓冲区视图。
#### `void SetGraphicsRoot32BitConstants(uint32_t rootParameterIndex, uint32_t num32BitValuesToSet, const void* pSrcData, uint32_t destOffsetIn32BitValues)`
设置根参数 32 位常量。
#### `void SetGraphicsRootDescriptorTable(uint32_t rootParameterIndex, D3D12_GPU_DESCRIPTOR_HANDLE baseDescriptor)`
设置根描述符表。
#### `void SetGraphicsRootShaderResourceView(uint32_t rootParameterIndex, D3D12_GPU_VIRTUAL_ADDRESS shaderResource)`
设置根着色器资源视图。
### 渲染状态
#### `void SetStencilRef(uint32_t stencilRef)`
设置模板参考值。
#### `void SetBlendFactor(const float blendFactor[4])`
设置混合因子。
#### `void SetDepthBias(float depthBias, float slopeScaledDepthBias, float depthBiasClamp)`
设置深度偏移。
### 绘制命令
#### `void Draw(uint32_t vertexCount, uint32_t instanceCount = 1, uint32_t startVertex = 0, uint32_t startInstance = 0)`
绘制非索引图元。
#### `void DrawIndexed(uint32_t indexCount, uint32_t instanceCount = 1, uint32_t startIndex = 0, int32_t baseVertex = 0, uint32_t startInstance = 0)`
绘制索引图元。
#### `void DrawInstancedIndirect(void* argBuffer, uint64_t alignedByteOffset)`
间接绘制实例化图元。
#### `void DrawIndexedInstancedIndirect(void* argBuffer, uint64_t alignedByteOffset)`
间接绘制索引实例化图元。
### 清除命令
#### `void Clear(float r, float g, float b, float a, uint32_t buffers)`
清除渲染目标和/或深度模板缓冲区。
#### `void ClearRenderTarget(void* renderTarget, const float color[4])`
清除渲染目标。
#### `void ClearDepthStencil(void* depthStencil, float depth, uint8_t stencil)`
清除深度模板缓冲区。
#### `void ClearRenderTargetView(ID3D12Resource* renderTarget, const float color[4], uint32_t rectCount = 0, const D3D12_RECT* rects = nullptr)`
使用资源指针清除渲染目标。
#### `void ClearDepthStencilView(ID3D12Resource* depthStencil, uint32_t clearFlags, float depth = 1.0f, uint8_t stencil = 0, uint32_t rectCount = 0, const D3D12_RECT* rects = nullptr)`
使用资源指针清除深度模板。
#### `void ClearUnorderedAccessView(...)`
清除无序访问视图。
### 资源复制
#### `void CopyResource(void* dst, void* src)`
复制整个资源。
#### `void CopyBuffer(ID3D12Resource* dst, uint64_t dstOffset, ID3D12Resource* src, uint64_t srcOffset, uint64_t size)`
复制缓冲区数据。
#### `void CopyTexture(ID3D12Resource* dst, const D3D12_TEXTURE_COPY_LOCATION& dstLocation, ID3D12Resource* src, const D3D12_TEXTURE_COPY_LOCATION& srcLocation)`
复制纹理数据。
### 查询
#### `void BeginQuery(ID3D12QueryHeap* queryHeap, QueryType type, uint32_t index)`
开始查询。
#### `void EndQuery(ID3D12QueryHeap* queryHeap, QueryType type, uint32_t index)`
结束查询。
#### `void ResolveQueryData(ID3D12QueryHeap* queryHeap, QueryType type, uint32_t startIndex, uint32_t count, ID3D12Resource* resultBuffer, uint64_t resultOffset)`
解析查询数据。
### 计算着色器
#### `void Dispatch(uint32_t x, uint32_t y, uint32_t z)`
分发计算着色器。
#### `void DispatchIndirect(void* argBuffer, uint64_t alignedByteOffset)`
间接分发计算着色器。
### Bundle
#### `void ExecuteBundle(ID3D12GraphicsCommandList* bundle)`
执行 Bundle 命令列表。
### 资源状态管理
#### `ResourceStates GetResourceState(ID3D12Resource* resource) const`
获取资源当前状态。
#### `void TrackResource(ID3D12Resource* resource)`
跟踪资源状态变化。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_commandList` | `ComPtr<ID3D12GraphicsCommandList>` | D3D12 命令列表 |
| `m_type` | `CommandQueueType` | 命令队列类型 |
| `m_resourceStateMap` | `unordered_map<ID3D12Resource*, ResourceStates>` | 资源状态映射 |
| `m_trackedResources` | `vector<ID3D12Resource*>` | 跟踪的资源列表 |
| `m_currentTopology` | `D3D12_PRIMITIVE_TOPOLOGY` | 当前拓扑类型 |
| `m_currentPipelineState` | `ID3D12PipelineState*` | 当前 PSO |
| `m_currentRootSignature` | `ID3D12RootSignature*` | 当前根签名 |
| `m_currentDescriptorHeap` | `ID3D12DescriptorHeap*` | 当前描述符堆 |
## 使用示例
```cpp
D3D12Device device;
device.Initialize(desc);
// Create command queue and list
CommandQueueDesc queueDesc;
queueDesc.type = CommandQueueType::Direct;
D3D12CommandQueue* cmdQueue = device.CreateCommandQueueImpl(queueDesc);
CommandListDesc listDesc;
listDesc.type = CommandQueueType::Direct;
D3D12CommandList* cmdList = device.CreateCommandListImpl(listDesc);
// Begin recording
cmdList->Reset();
cmdList->SetPipelineState(pipelineState);
cmdList->SetRenderTargets(1, &rtvHandle, &dsvHandle);
cmdList->SetViewports(1, &viewport);
cmdList->SetScissorRect(scissorRect);
cmdList->SetVertexBuffers(0, 1, &vbv);
cmdList->DrawIndexed(indexCount, 1, 0, 0, 0);
cmdList->Close();
// Execute
cmdQueue->ExecuteCommandListsInternal(1, &cmdList);
```
## 继承关系
```
RHICommandList (interface)
└── D3D12CommandList (implementation)
```
## 备注
- D3D12CommandList 内部维护资源状态映射,自动处理资源状态转换
- 使用 `TrackResource` 可以将自定义资源添加到状态跟踪系统
- Bundle 是一种优化手段,可以复用频繁执行的命令序列

View File

@@ -0,0 +1,113 @@
# D3D12CommandQueue
DirectX 12 命令队列的 D3D12 实现,封装了 `ID3D12CommandQueue`
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12CommandQueue.h>
```
## 继承关系
```
RHICommandQueue (interface)
└── D3D12CommandQueue (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12CommandQueue()`
默认构造函数。
#### `~D3D12CommandQueue() override`
析构函数,确保调用 `Shutdown()`
### 初始化与销毁
#### `bool Initialize(ID3D12Device* device, CommandQueueType type = CommandQueueType::Direct)`
初始化命令队列。
- `device`: D3D12 设备
- `type`: 命令队列类型
- 返回: 初始化是否成功
#### `void Shutdown() override`
关闭命令队列。
### 命令执行
#### `void ExecuteCommandLists(uint32_t count, void** lists)`
执行命令列表(接口实现)。
#### `void ExecuteCommandListsInternal(uint32_t count, ID3D12CommandList** lists)`
执行命令列表(内部实现,接受 D3D12 原生类型)。
### 同步操作
#### `void Signal(RHIFence* fence, uint64_t value)`
发送信号量到栅栏。
#### `void Wait(RHIFence* fence, uint64_t value)`
等待栅栏达到指定值。
#### `void WaitForIdle()`
等待命令队列空闲。
#### `uint64_t GetCompletedValue() override`
获取已完成信号值。
#### `void Signal(ID3D12Fence* fence, uint64_t value)`
发送信号(内部版本)。
#### `void Wait(ID3D12Fence* fence, uint64_t value)`
等待(内部版本)。
### 属性查询
#### `CommandQueueType GetType() const override`
获取命令队列类型。
#### `uint64_t GetTimestampFrequency() const override`
获取时间戳频率Hz
#### `ID3D12CommandQueue* GetCommandQueue() const`
获取底层 `ID3D12CommandQueue` 指针。
#### `void* GetNativeHandle() override`
返回原生句柄。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_commandQueue` | `ComPtr<ID3D12CommandQueue>` | D3D12 命令队列 |
| `m_type` | `CommandQueueType` | 命令队列类型 |
| `m_timestampFrequency` | `uint64_t` | 时间戳频率 |
## 使用示例
```cpp
D3D12CommandQueue cmdQueue;
cmdQueue.Initialize(device->GetDevice(), CommandQueueType::Direct);
// Execute command list
ID3D12CommandList* lists[] = { cmdList->GetCommandList() };
cmdQueue.ExecuteCommandListsInternal(1, lists);
// Sync with fence
D3D12Fence fence;
fence.Initialize(device->GetDevice());
cmdQueue.Signal(fence.GetFence(), 1);
fence.Wait(1);
// Wait for idle
cmdQueue.WaitForIdle();
```
## 备注
- 三种命令队列类型Direct图形/计算、Compute计算、Copy复制
- 时间戳频率用于将 GPU 时间戳转换为实际时间
- `WaitForIdle` 会阻塞 CPU 直到所有已提交命令完成

View File

@@ -0,0 +1,124 @@
# D3D12Common
D3D12 通用辅助函数集合,提供描述符大小、屏障创建、格式支持检查等功能。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12Common.h>
```
## 命名空间
`XCEngine::RHI`
## 描述符大小函数
#### `inline UINT GetDescriptorHandleIncrementSize(ID3D12Device* device, D3D12_DESCRIPTOR_HEAP_TYPE heapType)`
获取描述符增量大小。
#### `inline UINT GetRTVDescriptorSize(ID3D12Device* device)`
获取 RTV 描述符大小。
#### `inline UINT GetDSVDescriptorSize(ID3D12Device* device)`
获取 DSV 描述符大小。
#### `inline UINT GetCBV_SRV_UAVDescriptorSize(ID3D12Device* device)`
获取 CBV/SRV/UAV 描述符大小。
#### `inline UINT GetSamplerDescriptorSize(ID3D12Device* device)`
获取 Sampler 描述符大小。
## 屏障创建函数
#### `inline D3D12_RESOURCE_BARRIER CreateTransitionBarrier(...)`
创建资源状态转换屏障。
参数:
- `resource`: 目标资源
- `stateBefore`: 转换前状态
- `stateAfter`: 转换后状态
- `subresource`: 子资源索引(默认所有)
#### `inline D3D12_RESOURCE_BARRIER CreateUAVBarrier(ID3D12Resource* resource = nullptr)`
创建 UAV 屏障。
#### `inline D3D12_RESOURCE_BARRIER CreateAliasingBarrier(...)`
创建别名化屏障。
## 格式支持检查
#### `inline bool CheckFormatSupport(ID3D12Device* device, DXGI_FORMAT format, D3D12_FORMAT_SUPPORT1 support1, D3D12_FORMAT_SUPPORT2 support2 = D3D12_FORMAT_SUPPORT2_NONE)`
检查格式支持。
#### `inline bool IsRenderTargetFormatSupported(ID3D12Device* device, DXGI_FORMAT format)`
检查是否支持作为渲染目标。
#### `inline bool IsDepthStencilFormatSupported(ID3D12Device* device, DXGI_FORMAT format)`
检查是否支持作为深度模板。
#### `inline bool IsShaderResourceFormatSupported(ID3D12Device* device, DXGI_FORMAT format)`
检查 shader 是否可以读取该格式。
#### `inline bool IsTextureFormatSupported(ID3D12Device* device, DXGI_FORMAT format)`
检查是否支持作为纹理。
## 清除值创建
#### `inline D3D12_CLEAR_VALUE CreateRenderTargetClearValue(DXGI_FORMAT format, float r = 0.0f, float g = 0.0f, float b = 0.0f, float a = 1.0f)`
创建渲染目标清除值。
#### `inline D3D12_CLEAR_VALUE CreateDepthStencilClearValue(DXGI_FORMAT format, float depth = 1.0f, uint8_t stencil = 0)`
创建深度模板清除值。
## 视口和裁剪矩形
#### `inline D3D12_VIEWPORT CreateViewport(float width, float height, float topLeftX = 0.0f, float topLeftY = 0.0f, float minDepth = 0.0f, float maxDepth = 1.0f)`
创建视口。
#### `inline D3D12_RECT CreateScissorRect(int left, int top, int right, int bottom)`
创建裁剪矩形。
## 缓冲区视图
#### `inline D3D12_VERTEX_BUFFER_VIEW CreateVertexBufferView(...)`
创建顶点缓冲区视图。
#### `inline D3D12_INDEX_BUFFER_VIEW CreateIndexBufferView(...)`
创建索引缓冲区视图。
## 描述符句柄运算
#### `inline D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle(...)`
计算偏移后的 CPU 描述符句柄。
#### `inline D3D12_GPU_DESCRIPTOR_HANDLE GetGPUDescriptorHandle(...)`
计算偏移后的 GPU 描述符句柄。
## 使用示例
```cpp
// Check format support
if (!IsRenderTargetFormatSupported(device, DXGI_FORMAT_R8G8B8A8_UNORM)) {
// Fall back to supported format
}
// Create barriers
D3D12_RESOURCE_BARRIER barriers[2];
barriers[0] = CreateTransitionBarrier(
resource, D3D12_RESOURCE_STATE_RENDER_TARGET,
D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
barriers[1] = CreateUAVBarrier(uavResource);
// Set barriers
cmdList->ResourceBarrier(2, barriers);
// Create viewport
D3D12_VIEWPORT vp = CreateViewport(1920.0f, 1080.0f);
cmdList->RSSetViewports(1, &vp);
```
## 备注
- 所有函数为 inline可在头文件中使用
- 这些是高频使用的辅助函数,避免重复代码

View File

@@ -0,0 +1,47 @@
# D3D12ConstantBufferView
DirectX 12 常量缓冲区视图的 D3D12 实现。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12ConstantBufferView.h>
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12ConstantBufferView()`
默认构造函数。
#### `~D3D12ConstantBufferView()`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `void Initialize(ID3D12Device* device, ID3D12Resource* buffer, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc = nullptr)`
创建 CBV。
- `buffer`: 缓冲区资源
- `desc`: CBV 描述(可选,会自动设置 size 为 256 字节对齐)
#### `void Shutdown()`
释放 CBV。
### 属性
#### `D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle() const`
获取 CPU 描述符句柄。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_handle` | `D3D12_CPU_DESCRIPTOR_HANDLE` | CPU 描述符句柄 |
| `m_resource` | `ID3D12Resource*` | 关联的缓冲区资源 |
## 备注
- CBV 大小自动向上对齐到 256 字节
- 常量缓冲区应使用 UPLOAD 堆类型以便 CPU 更新
- 可以通过根签名直接绑定 CBV 而无需 CBV 描述符

View File

@@ -0,0 +1,52 @@
# D3D12DepthStencilView
DirectX 12 深度模板视图的 D3D12 实现。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12DepthStencilView.h>
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12DepthStencilView()`
默认构造函数。
#### `~D3D12DepthStencilView()`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `void Initialize(ID3D12Device* device, ID3D12Resource* resource, const D3D12_DEPTH_STENCIL_VIEW_DESC* desc = nullptr)`
创建 DSV。
#### `void InitializeAt(ID3D12Device* device, ID3D12Resource* resource, D3D12_CPU_DESCRIPTOR_HANDLE handle, const D3D12_DEPTH_STENCIL_VIEW_DESC* desc = nullptr)`
在指定位置创建 DSV。
#### `void Shutdown()`
释放 DSV。
### 属性
#### `D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle() const`
获取 CPU 描述符句柄。
### 静态辅助函数
#### `static D3D12_DEPTH_STENCIL_VIEW_DESC CreateDesc(Format format, D3D12_DSV_DIMENSION dimension = D3D12_DSV_DIMENSION_TEXTURE2D)`
创建 DSV 描述。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_handle` | `D3D12_CPU_DESCRIPTOR_HANDLE` | CPU 描述符句柄 |
| `m_resource` | `ID3D12Resource*` | 关联的资源 |
## 备注
- DSV 必须在 DSV 类型描述符堆中分配
- 支持只读 DSV通过描述符标志区分

View File

@@ -0,0 +1,114 @@
# D3D12DescriptorHeap
DirectX 12 描述符堆的 D3D12 实现,封装了 `ID3D12DescriptorHeap`
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12DescriptorHeap.h>
```
## 继承关系
```
RHIDescriptorPool (interface)
└── D3D12DescriptorHeap (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12DescriptorHeap()`
默认构造函数。
#### `~D3D12DescriptorHeap() override`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `bool Initialize(ID3D12Device* device, DescriptorHeapType type, uint32_t numDescriptors, bool shaderVisible = false)`
使用参数初始化。
- `device`: D3D12 设备
- `type`: 描述符堆类型
- `numDescriptors`: 描述符数量
- `shaderVisible`: 是否对 GPU 可见CBV_SRV_UAV 和 Sampler 堆需要)
- 返回: 初始化是否成功
#### `bool Initialize(const DescriptorPoolDesc& desc) override`
使用统一描述符初始化。
#### `void Shutdown() override`
释放描述符堆。
### 描述符句柄
#### `ID3D12DescriptorHeap* GetDescriptorHeap() const`
获取底层 `ID3D12DescriptorHeap` 指针。
#### `CPUDescriptorHandle GetCPUDescriptorHandle(uint32_t index)`
获取指定索引的 CPU 描述符句柄。
#### `GPUDescriptorHandle GetGPUDescriptorHandle(uint32_t index)`
获取指定索引的 GPU 描述符句柄。
#### `D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandleForHeapStart() const`
获取堆起始 CPU 句柄。
#### `D3D12_GPU_DESCRIPTOR_HANDLE GetGPUDescriptorHandleForHeapStart() const`
获取堆起始 GPU 句柄。
### 属性
#### `uint32_t GetDescriptorCount() const override`
获取描述符总数。
#### `DescriptorHeapType GetType() const override`
获取描述符堆类型。
#### `uint32_t GetDescriptorSize() const`
获取单个描述符大小(增量大小)。
#### `void* GetNativeHandle() override`
返回原生句柄。
### 静态辅助函数
#### `static D3D12_DESCRIPTOR_HEAP_DESC CreateDesc(DescriptorHeapType type, uint32_t numDescriptors, bool shaderVisible = false)`
创建 D3D12 描述符堆描述。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_descriptorHeap` | `ComPtr<ID3D12DescriptorHeap>` | D3D12 描述符堆 |
| `m_type` | `DescriptorHeapType` | 堆类型 |
| `m_numDescriptors` | `uint32_t` | 描述符数量 |
| `m_descriptorSize` | `uint32_t` | 增量大小 |
| `m_shaderVisible` | `bool` | 是否 shader visible |
## 使用示例
```cpp
// Create RTV heap
D3D12DescriptorHeap rtvHeap;
rtvHeap.Initialize(device->GetDevice(), DescriptorHeapType::RTV, 10, false);
// Create SRV/CBV/UAV heap
D3D12DescriptorHeap cbvHeap;
cbvHeap.Initialize(device->GetDevice(), DescriptorHeapType::CBV_SRV_UAV, 100, true);
// Get handle for creating views
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = rtvHeap.GetCPUDescriptorHandle(0);
// Create RTV
D3D12RenderTargetView rtv;
rtv.InitializeAt(device->GetDevice(), texture->GetResource(), rtvHandle, nullptr);
```
## 备注
- 四种描述符堆类型: CBV_SRV_UAV, Sampler, RTV, DSV
- RTV 和 DSV 堆通常不需要 shader visible
- CBV_SRV_UAV 和 Sampler 堆如需在 shader 中访问必须 shader visible
- 描述符堆创建后大小固定,不能调整

View File

@@ -0,0 +1,169 @@
# D3D12Device
DirectX 12 设备的 D3D12 实现,是引擎的 RHI 抽象层 `RHIDevice` 接口的具体实现。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12Device.h>
```
## 类概览
`D3D12Device` 封装了 DirectX 12 的 `ID3D12Device``IDXGIFactory4`,负责创建和管理所有 RHI 资源。
## 公共成员函数
### 初始化与销毁
#### `bool Initialize(const RHIDeviceDesc& desc)`
初始化 D3D12 设备,包括创建 DXGI Factory 和 D3D12 Device。
- `desc`: 设备描述符,包含调试层配置等
- 返回: 初始化是否成功
#### `void Shutdown()`
关闭并释放所有 D3D12 资源。
### 设备信息
#### `ID3D12Device* GetDevice() const`
获取底层 `ID3D12Device` 指针。
#### `IDXGIFactory4* GetFactory() const`
获取底层 `IDXGIFactory4` 指针。
#### `const AdapterInfo& GetAdapterInfo() const`
获取当前 GPU 适配器信息,包含:
- `description`: 适配器描述
- `dedicatedVideoMemory`: 专用显存
- `dedicatedSystemMemory`: 专用系统内存
- `sharedSystemMemory`: 共享系统内存
- `vendorId` / `deviceId`: 供应商和设备 ID
- `isSoftware`: 是否为软件适配器
#### `std::vector<AdapterInfo> EnumerateAdapters()`
枚举系统中所有可用的 GPU 适配器。
### 功能查询
#### `UINT GetDescriptorHandleIncrementSize(DescriptorHeapType type) const`
获取指定类型描述符堆的增量大小。
- `type`: 堆类型 (CBV_SRV_UAV, Sampler, RTV, DSV)
#### `bool CheckFeatureSupport(D3D12_FEATURE feature, void* featureSupportData, uint32_t featureSupportDataSize)`
查询设备支持的特定功能。
#### `const RHICapabilities& GetCapabilities() const`
获取设备功能支持信息。
#### `const RHIDeviceInfo& GetDeviceInfo() const`
获取设备详细信息。
### 设备状态
#### `bool IsDeviceRemoved() const`
检测设备是否被移除(通常因驱动崩溃)。
### 资源创建
#### `RHIBuffer* CreateBuffer(const BufferDesc& desc)` {#buffer}
创建 D3D12 缓冲区。
#### `RHITexture* CreateTexture(const TextureDesc& desc)` {#texture}
创建 D3D12 纹理。
#### `RHISwapChain* CreateSwapChain(const SwapChainDesc& desc)` {#swapchain}
创建 D3D12 交换链。
#### `RHICommandList* CreateCommandList(const CommandListDesc& desc)` {#cmdlist}
创建 D3D12 命令列表。
#### `RHICommandQueue* CreateCommandQueue(const CommandQueueDesc& desc)` {#cmdqueue}
创建 D3D12 命令队列。
#### `RHIShader* CompileShader(const ShaderCompileDesc& desc)` {#shader}
编译着色器。
#### `RHIPipelineState* CreatePipelineState(const PipelineStateDesc& desc)` {#pso}
创建管线状态对象。
#### `RHIFence* CreateFence(const FenceDesc& desc)` {#fence}
创建栅栏同步对象。
#### `RHISampler* CreateSampler(const SamplerDesc& desc)` {#sampler}
创建采样器。
### 内部实现创建
#### `D3D12CommandQueue* CreateCommandQueueImpl(const CommandQueueDesc& desc)`
创建 `D3D12CommandQueue` 实例。
#### `D3D12CommandList* CreateCommandListImpl(const CommandListDesc& desc)`
创建 `D3D12CommandList` 实例。
#### `D3D12CommandAllocator* CreateCommandAllocator(const CommandAllocatorDesc& desc)`
创建 `D3D12CommandAllocator`
#### `D3D12DescriptorHeap* CreateDescriptorHeap(const DescriptorHeapDesc& desc)`
创建 `D3D12DescriptorHeap`
#### `D3D12QueryHeap* CreateQueryHeap(const QueryHeapDesc& desc)`
创建 `D3D12QueryHeap`
#### `D3D12RootSignature* CreateRootSignature(const RootSignatureDesc& desc)`
创建 `D3D12RootSignature`
### 视图创建
#### `D3D12RenderTargetView* CreateRenderTargetView(D3D12Buffer* resource, const RenderTargetViewDesc& desc)`
创建渲染目标视图。
#### `D3D12DepthStencilView* CreateDepthStencilView(D3D12Buffer* resource, const DepthStencilViewDesc& desc)`
创建深度模板视图。
#### `D3D12ShaderResourceView* CreateShaderResourceView(D3D12Buffer* resource, const ShaderResourceViewDesc& desc)`
创建着色器资源视图。
#### `D3D12UnorderedAccessView* CreateUnorderedAccessView(D3D12Buffer* resource, const UnorderedAccessViewDesc& desc)`
创建无序访问视图。
#### `D3D12ConstantBufferView* CreateConstantBufferView(D3D12Buffer* resource, const ConstantBufferViewDesc& desc)`
创建常量缓冲区视图。
## 使用示例
```cpp
#include <XCEngine/RHI/D3D12/D3D12Device.h>
using namespace XCEngine::RHI;
D3D12Device device;
RHIDeviceDesc desc;
desc.enableDebugLayer = true;
if (device.Initialize(desc)) {
auto& caps = device.GetCapabilities();
auto& info = device.GetAdapterInfo();
// Create resources
BufferDesc vertexBufferDesc;
vertexBufferDesc.size = 1024;
vertexBufferDesc.type = BufferType::Vertex;
RHIBuffer* vb = device.CreateBuffer(vertexBufferDesc);
device.Shutdown();
}
```
## 继承关系
```
RHIDevice (interface)
└── D3D12Device (implementation)
```
## 备注
- D3D12Device 是引擎中最重要的 D3D12 对象,所有其他 D3D12 资源都依赖它创建
- 设备移除Device Removed通常由驱动超时或硬件问题导致
- 使用 `SetDeviceRemoved()` 可以模拟设备移除场景用于测试

View File

@@ -0,0 +1,154 @@
# D3D12Enum
D3D12 枚举值转换函数集合,提供 RHI 抽象枚举到 D3D12 原生枚举的转换。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12Enum.h>
```
## 命名空间
`XCEngine::RHI`
## 转换函数列表
### 填充模式和剔除模式
#### `inline D3D12_FILL_MODE ToD3D12(FillMode mode)`
`FillMode::Wireframe` -> `D3D12_FILL_MODE_WIREFRAME`
`FillMode::Solid` -> `D3D12_FILL_MODE_SOLID`
#### `inline D3D12_CULL_MODE ToD3D12(CullMode mode)`
`CullMode::None` -> `D3D12_CULL_MODE_NONE`
`CullMode::Front` -> `D3D12_CULL_MODE_FRONT`
`CullMode::Back` -> `D3D12_CULL_MODE_BACK`
### 深度模板
#### `inline D3D12_COMPARISON_FUNC ToD3D12(ComparisonFunc func)`
转换比较函数 (Never, Less, Equal, LessEqual, Greater, NotEqual, GreaterEqual, Always)
#### `inline D3D12_STENCIL_OP ToD3D12(StencilOp op)`
转换模板操作 (Keep, Zero, Replace, IncrSat, DecrSat, Invert, Incr, Decr)
### 混合
#### `inline D3D12_BLEND_OP ToD3D12(BlendOp op)`
转换混合操作 (Add, Subtract, ReverseSubtract, Min, Max)
#### `inline D3D12_BLEND ToD3D12(BlendFactor factor)`
转换混合因子 (Zero, One, SrcColor, InvSrcColor, SrcAlpha, InvSrcAlpha, SrcAlphaSat, BlendFactor, InvBlendFactor)
#### `inline D3D12_LOGIC_OP ToD3D12(LogicOp op)`
转换逻辑操作 (Clear, Set, Copy, CopyInverted, Noop, Invert, And, Nand, Or, Nor, Xor, Equiv, AndReverse, AndInverted, OrReverse, OrInverted)
### 纹理采样
#### `inline D3D12_FILTER ToD3D12(FilterMode mode)`
转换过滤器模式 (Point, Linear, Anisotropic, ComparisonPoint, ComparisonLinear, ComparisonAnisotropic)
#### `inline D3D12_TEXTURE_ADDRESS_MODE ToD3D12(TextureAddressMode mode)`
转换纹理寻址模式 (Wrap, Mirror, Clamp, Border, MirrorOnce)
#### `inline D3D12_STATIC_BORDER_COLOR ToD3D12(BorderColor color)`
转换边框颜色 (TransparentBlack, OpaqueBlack, OpaqueWhite)
### Shader 相关
#### `inline D3D12_SHADER_VISIBILITY ToD3D12(ShaderVisibility visibility)`
转换 Shader 可见性 (All, Vertex, Hull, Domain, Geometry, Pixel, Amplification, Mesh)
### 格式
#### `inline DXGI_FORMAT ToD3D12(Format format)`
转换纹理/缓冲区格式。
支持的格式映射:
- `Format::Unknown` -> `DXGI_FORMAT_UNKNOWN`
- `Format::R8_UNorm` -> `DXGI_FORMAT_R8_UNORM`
- `Format::R8G8_UNorm` -> `DXGI_FORMAT_R8G8_UNORM`
- `Format::R8G8B8A8_UNorm` -> `DXGI_FORMAT_R8G8B8A8_UNORM`
- `Format::R16G16B16A16_Float` -> `DXGI_FORMAT_R16G16B16A16_FLOAT`
- `Format::R32G32B32A32_Float` -> `DXGI_FORMAT_R32G32B32A32_FLOAT`
- `Format::R16_Float` -> `DXGI_FORMAT_R16_FLOAT`
- `Format::R32_Float` -> `DXGI_FORMAT_R32_FLOAT`
- `Format::D16_UNorm` -> `DXGI_FORMAT_D16_UNORM`
- `Format::D24_UNorm_S8_UInt` -> `DXGI_FORMAT_D24_UNORM_S8_UINT`
- `Format::D32_Float` -> `DXGI_FORMAT_D32_FLOAT`
- `Format::BC1-7_UNorm` -> 对应 BC 压缩格式
- `Format::R32G32B32A32_UInt` -> `DXGI_FORMAT_R32G32B32A32_UINT`
- `Format::R32_UInt` -> `DXGI_FORMAT_R32_UINT`
#### `inline DXGI_FORMAT ToDXGI(Format format)`
`ToD3D12(format)`DXGI 别名。
### 资源状态
#### `inline D3D12_RESOURCE_STATES ToD3D12(ResourceStates state)`
转换资源状态 (Common, VertexAndConstantBuffer, IndexBuffer, RenderTarget, UnorderedAccess, DepthWrite, DepthRead, NonPixelShaderResource, PixelShaderResource, CopySrc, CopyDst, Present, GenericRead)
### 堆类型
#### `inline D3D12_HEAP_TYPE ToD3D12(HeapType type)`
转换堆类型 (Default, Upload, Readback)
### 拓扑
#### `inline D3D12_PRIMITIVE_TOPOLOGY_TYPE ToD3D12(PrimitiveTopology topology)`
转换图元拓扑类型 (Point, Line, Triangle, Patch)
#### `inline D3D12_PRIMITIVE_TOPOLOGY ToD3D12Topology(PrimitiveTopology topology)`
转换详细图元拓扑 (PointList, LineList, LineStrip, TriangleList, TriangleStrip, PatchList 等)
### 描述符堆
#### `inline D3D12_DESCRIPTOR_HEAP_TYPE ToD3D12(DescriptorHeapType type)`
转换描述符堆类型 (CBV_SRV_UAV, Sampler, RTV, DSV)
### 查询
#### `inline D3D12_QUERY_TYPE ToD3D12(QueryType type)`
转换查询类型 (Occlusion, Timestamp, PipelineStatistics)
### 根参数
#### `inline D3D12_ROOT_PARAMETER_TYPE ToD3D12(RootParameterType type)`
转换根参数类型 (DescriptorTable, Constants, CBV, SRV, UAV)
### 纹理类型
#### `inline D3D12_RESOURCE_DIMENSION ToD3D12(TextureType type)`
转换纹理类型维度 (Texture1D, Texture2D, Texture3D)
### 命令列表
#### `inline D3D12_COMMAND_LIST_TYPE ToD3D12(CommandQueueType type)`
转换命令列表类型 (Direct, Compute, Copy)
## 使用示例
```cpp
// When creating PSO
D3D12_GRAPHICS_PIPELINE_STATE_DESC desc = {};
desc.FillMode = ToD3D12(fillMode);
desc.CullMode = ToD3D12(cullMode);
desc.DepthStencilState.DepthFunc = ToD3D12(depthFunc);
// When creating texture
D3D12_RESOURCE_DESC texDesc = {};
texDesc.Format = ToD3D12(textureFormat);
// When transitioning resource
D3D12_RESOURCE_BARRIER barrier = CreateTransitionBarrier(
resource,
ToD3D12(stateBefore),
ToD3D12(stateAfter));
```
## 备注
- 所有转换函数为 inline可在头文件中使用
- switch 语句确保编译期检查所有枚举值
- 未处理的枚举值返回合理的默认值

View File

@@ -0,0 +1,106 @@
# D3D12Fence
DirectX 12 栅栏同步对象的 D3D12 实现,封装了 `ID3D12Fence`
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12Fence.h>
```
## 继承关系
```
RHIFence (interface)
└── D3D12Fence (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12Fence()`
默认构造函数。
#### `~D3D12Fence() override`
析构函数,确保调用 `Shutdown()`
### 初始化与销毁
#### `bool Initialize(ID3D12Device* device, uint64_t initialValue = 0)`
初始化栅栏。
- `device`: D3D12 设备
- `initialValue`: 初始信号值
- 返回: 初始化是否成功
#### `void Shutdown() override`
关闭栅栏并释放事件句柄。
### 信号操作
#### `void Signal() override`
发送信号,将值增加 1。
#### `void Signal(uint64_t value) override`
发送信号,设置指定值。
#### `void Wait(uint64_t value) override`
等待栅栏达到指定值。
#### `uint64_t GetCompletedValue() const override`
获取当前完成值。
#### `bool IsSignaled() const override`
检查是否已达到信号值。
#### `void* GetEventHandle()`
获取事件句柄,用于自定义等待。
### 原生接口
#### `void* GetNativeHandle() override { return m_fence.Get(); }`
#### `ID3D12Fence* GetFence() const`
获取底层 `ID3D12Fence` 指针。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_fence` | `ComPtr<ID3D12Fence>` | D3D12 栅栏对象 |
| `m_eventHandle` | `void*` | 同步事件句柄 |
| `m_signalValue` | `uint64_t` | 最后信号值 |
## 使用示例
```cpp
D3D12Fence fence;
fence.Initialize(device->GetDevice());
// CPU-GPU 同步
cmdQueue->Signal(fence.GetFence(), 1);
fence.Wait(1);
// 多帧同步
uint64_t frameFenceValues[3] = {0, 0, 0};
int frameIndex = 0;
void RenderFrame() {
uint64_t fenceValue = frameIndex + 1;
cmdQueue->Signal(fence.GetFence(), fenceValue);
// Wait for this frame's previous render to complete
if (fence.GetCompletedValue() < frameFenceValues[frameIndex]) {
fence.Wait(frameFenceValues[frameIndex]);
}
frameFenceValues[frameIndex] = fenceValue;
frameIndex = (frameIndex + 1) % 3;
}
```
## 备注
- 栅栏用于 CPU-GPU 和 GPU-GPU 同步
- 事件句柄可用于 `WaitForSingleObject` 等 Win32 API
- 多帧缓冲时常用栅栏确保帧间资源安全

View File

@@ -0,0 +1,78 @@
# D3D12 后端概览
**命名空间**: `XCEngine::RHI`
**类型**: `module`
**描述**: DirectX 12 后端实现模块,提供对 DirectX 12 API 的完整封装。
## 概述
D3D12 后端是 XCEngine RHI 抽象层的 DirectX 12 实现。该模块封装了 DirectX 12 的所有核心功能,包括设备管理、资源创建、命令录制和执行、同步等。
## 模块内容
### 核心组件
| 组件 | 描述 |
|------|------|
| [D3D12Device](./d3d12-device.md) | DirectX 12 设备实现 |
| [D3D12CommandList](./d3d12-command-list.md) | 命令列表实现 |
### 资源类型
| 组件 | 描述 |
|------|------|
| [D3D12Buffer](./d3d12-buffer.md) | GPU 缓冲区实现 |
| [D3D12Texture](./d3d12-texture.md) | GPU 纹理实现 |
### 命令执行
| 组件 | 描述 |
|------|------|
| [D3D12CommandQueue](./d3d12-command-queue.md) | 命令队列实现 |
| [D3D12CommandAllocator](./d3d12-command-allocator.md) | 命令分配器 |
### 同步原语
| 组件 | 描述 |
|------|------|
| [D3D12Fence](./d3d12-fence.md) | 同步栅栏实现 |
| [D3D12SwapChain](./d3d12-swap-chain.md) | 交换链实现 |
### 渲染状态
| 组件 | 描述 |
|------|------|
| [D3D12Shader](./d3d12-shader.md) | 着色器实现 |
| [D3D12PipelineState](./d3d12-pipeline-state.md) | 管线状态对象 |
| [D3D12Sampler](./d3d12-sampler.md) | 采样器实现 |
| [D3D12RootSignature](./d3d12-root-signature.md) | 根签名实现 |
### 描述符
| 组件 | 描述 |
|------|------|
| [D3D12DescriptorHeap](./d3d12-descriptor-heap.md) | 描述符堆实现 |
| [D3D12RenderTargetView](./d3d12-render-target-view.md) | 渲染目标视图 |
| [D3D12DepthStencilView](./d3d12-depth-stencil-view.md) | 深度模板视图 |
| [D3D12ShaderResourceView](./d3d12-shader-resource-view.md) | 着色器资源视图 |
| [D3D12UnorderedAccessView](./d3d12-unordered-access-view.md) | 无序访问视图 |
| [D3D12ConstantBufferView](./d3d12-constant-buffer-view.md) | 常量缓冲视图 |
### 查询
| 组件 | 描述 |
|------|------|
| [D3D12QueryHeap](./d3d12-query-heap.md) | 查询堆实现 |
### 工具
| 组件 | 描述 |
|------|------|
| [D3D12Screenshot](./d3d12-screenshot.md) | 截图工具 |
## 相关文档
- [RHI 抽象层](../rhi/rhi-overview.md)
- [OpenGL 后端](../opengl/opengl-device.md)

View File

@@ -0,0 +1,123 @@
# D3D12PipelineState
DirectX 12 管线状态对象的 D3D12 实现,封装了 `ID3D12PipelineState`
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12PipelineState.h>
```
## 继承关系
```
RHIPipelineState (interface)
└── D3D12PipelineState (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12PipelineState()`
默认构造函数。
#### `~D3D12PipelineState() override`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `bool Initialize(ID3D12Device* device, const D3D12_GRAPHICS_PIPELINE_STATE_DESC& desc)`
使用 D3D12 PSO 描述初始化。
- `device`: D3D12 设备
- `desc`: 完整的图形管线状态描述
- 返回: 初始化是否成功
#### `void Shutdown() override`
释放 PSO 资源。
### 原生接口
#### `ID3D12PipelineState* GetPipelineState() const`
获取底层 `ID3D12PipelineState` 指针。
#### `void* GetNativeHandle() override`
返回原生句柄。
#### `PipelineType GetType() const override`
返回 `PipelineType::Graphics`
### 绑定
#### `void Bind() override`
绑定 PSO 到命令列表。
#### `void Unbind() override`
解绑 PSO。
### 静态辅助函数
#### `static D3D12_GRAPHICS_PIPELINE_STATE_DESC CreateDesc(...)`
创建完整的 PSO 描述。
参数:
- `ID3D12RootSignature* rootSignature`: 根签名
- `const D3D12_SHADER_BYTECODE& vs`: 顶点着色器
- `const D3D12_SHADER_BYTECODE& ps`: 像素着色器
- `const D3D12_SHADER_BYTECODE& gs`: 几何着色器(可选)
- `uint32_t inputElementCount`: 输入元素数量
- `const D3D12_INPUT_ELEMENT_DESC* inputElements`: 输入元素数组
#### `static D3D12_INPUT_ELEMENT_DESC CreateInputElement(...)`
创建输入元素描述,有两个重载:
-`alignedByteOffset` 参数
- 自动计算 `alignedByteOffset` 参数
参数:
- `semanticName`: 语义名称 (e.g., "POSITION", "TEXCOORD")
- `semanticIndex`: 语义索引
- `format`: 格式
- `inputSlot`: 输入槽
- `alignedByteOffset`: 对齐偏移(可选)
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_pipelineState` | `ComPtr<ID3D12PipelineState>` | D3D12 PSO 对象 |
## 使用示例
```cpp
// Define input layout
D3D12_INPUT_ELEMENT_DESC inputElements[] = {
D3D12PipelineState::CreateInputElement("POSITION", 0, Format::R32G32B32A32_Float, 0),
D3D12PipelineState::CreateInputElement("TEXCOORD", 0, Format::R32G32_Float, 1),
};
// Create PSO description
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
psoDesc.pRootSignature = rootSignature->GetRootSignature();
psoDesc.VS = vertexShader.GetD3D12Bytecode();
psoDesc.PS = pixelShader.GetD3D12Bytecode();
psoDesc.InputLayout = { inputElements, 2 };
psoDesc.RasterizerState = ...;
psoDesc.BlendState = ...;
psoDesc.DepthStencilState = ...;
psoDesc.SampleMask = UINT_MAX;
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
psoDesc.NumRenderTargets = 1;
psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
psoDesc.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
psoDesc.SampleDesc.Count = 1;
D3D12PipelineState pso;
pso.Initialize(device->GetDevice(), psoDesc);
pso.Bind();
```
## 备注
- PSO 一旦创建不可修改,只能重新创建
- PSO 创建开销大,应缓存复用
- `ID3D12PipelineState` 是不可变对象,切换开销比 OpenGL 小

View File

@@ -0,0 +1,82 @@
# D3D12QueryHeap
DirectX 12 查询堆的 D3D12 实现,封装了 `ID3D12QueryHeap`
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12QueryHeap.h>
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12QueryHeap()`
默认构造函数。
#### `~D3D12QueryHeap()`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `bool Initialize(ID3D12Device* device, QueryType type, uint32_t count)`
初始化查询堆。
- `device`: D3D12 设备
- `type`: 查询类型
- `count`: 查询数量
- 返回: 初始化是否成功
#### `void Shutdown()`
释放查询堆。
### 属性
#### `ID3D12QueryHeap* GetQueryHeap() const`
获取底层 `ID3D12QueryHeap` 指针。
#### `void* GetNativeHandle() const`
返回原生句柄。
#### `QueryType GetType() const`
获取查询类型。
#### `uint32_t GetCount() const`
获取查询数量。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_queryHeap` | `ComPtr<ID3D12QueryHeap>` | D3D12 查询堆 |
| `m_type` | `QueryType` | 查询类型 |
| `m_count` | `uint32_t` | 查询数量 |
## 使用示例
```cpp
// Create query heap for occlusion
D3D12QueryHeap queryHeap;
queryHeap.Initialize(device->GetDevice(), QueryType::Occlusion, 2);
// Create readback buffer for results
D3D12Buffer readbackBuffer;
readbackBuffer.Initialize(device->GetDevice(), sizeof(uint64_t) * 2,
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_HEAP_TYPE_READBACK);
// In render pass
cmdList->BeginQuery(queryHeap.GetQueryHeap(), QueryType::Occlusion, 0);
// Draw bounding box
cmdList->Draw(8);
cmdList->EndQuery(queryHeap.GetQueryHeap(), QueryType::Occlusion, 0);
// Resolve to readback buffer
cmdList->ResolveQueryData(queryHeap.GetQueryHeap(), QueryType::Occlusion, 0, 1,
readbackBuffer.GetResource(), 0);
```
## 备注
- 三种查询类型: Occlusion遮挡、Timestamp时间戳、PipelineStatistics管线统计
- 查询数据需要通过 resolve 操作复制到可读缓冲区
- 时间戳查询需要命令队列支持时间戳功能

View File

@@ -0,0 +1,68 @@
# D3D12RenderTargetView
DirectX 12 渲染目标视图的 D3D12 实现。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12RenderTargetView.h>
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12RenderTargetView()`
默认构造函数。
#### `~D3D12RenderTargetView()`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `void Initialize(ID3D12Device* device, ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc = nullptr)`
在描述符堆中分配描述符并创建 RTV。
- `device`: D3D12 设备
- `resource`: 资源对象
- `desc`: RTV 描述(可选,自动推断)
#### `void InitializeAt(ID3D12Device* device, ID3D12Resource* resource, D3D12_CPU_DESCRIPTOR_HANDLE handle, const D3D12_RENDER_TARGET_VIEW_DESC* desc = nullptr)`
在指定描述符句柄位置创建 RTV。
- `handle`: 预分配的描述符句柄
#### `void Shutdown()`
释放 RTV不释放资源
### 属性
#### `D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle() const`
获取 CPU 描述符句柄。
### 静态辅助函数
#### `static D3D12_RENDER_TARGET_VIEW_DESC CreateDesc(Format format, D3D12_RTV_DIMENSION dimension = D3D12_RTV_DIMENSION_TEXTURE2D)`
创建 RTV 描述。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_handle` | `D3D12_CPU_DESCRIPTOR_HANDLE` | CPU 描述符句柄 |
| `m_resource` | `ID3D12Resource*` | 关联的资源 |
## 使用示例
```cpp
D3D12RenderTargetView rtv;
rtv.Initialize(device->GetDevice(), texture->GetResource());
// Or at specific handle
D3D12_CPU_DESCRIPTOR_HANDLE handle = rtvHeap.GetCPUDescriptorHandle(0);
D3D12RenderTargetView rtv2;
rtv2.InitializeAt(device->GetDevice(), texture2->GetResource(), handle);
```
## 备注
- RTV 不拥有底层资源Shutdown 不会释放资源
- RTV 必须在 RTV 类型描述符堆中分配

View File

@@ -0,0 +1,132 @@
# D3D12RootSignature
DirectX 12 根签名的 D3D12 实现,封装了 `ID3D12RootSignature`
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12RootSignature.h>
```
## 命名空间
`XCEngine::RHI` (不继承 RHI 抽象接口)
## 公共成员函数
### 构造函数与析构函数
#### `D3D12RootSignature()`
默认构造函数。
#### `~D3D12RootSignature()`
析构函数,确保调用 `Shutdown()`
### 生命周期
#### `bool Initialize(ID3D12Device* device, const D3D12_ROOT_SIGNATURE_DESC& desc)`
初始化根签名。
- `device`: D3D12 设备
- `desc`: 根签名描述
- 返回: 初始化是否成功
#### `void Shutdown()`
释放根签名。
### 原生接口
#### `ID3D12RootSignature* GetRootSignature() const`
获取底层 `ID3D12RootSignature` 指针。
#### `void* GetNativeHandle() const`
返回原生句柄。
#### `uint32_t GetParameterCount() const`
获取根参数数量。
### 静态辅助函数
#### `static D3D12_ROOT_SIGNATURE_DESC CreateDesc(...)`
创建根签名描述。
参数:
- `D3D12_ROOT_PARAMETER* parameters`: 根参数数组
- `uint32_t parameterCount`: 参数数量
- `D3D12_STATIC_SAMPLER_DESC* samplers`: 静态采样器数组
- `uint32_t samplerCount`: 静态采样器数量
- `D3D12_ROOT_SIGNATURE_FLAGS flags`: 标志
#### `static D3D12_ROOT_PARAMETER CreateCBV(uint32_t shaderRegister, ShaderVisibility visibility = ShaderVisibility::All, uint32_t registerSpace = 0)`
创建常量缓冲区视图根参数。
#### `static D3D12_ROOT_PARAMETER CreateSRV(uint32_t shaderRegister, ShaderVisibility visibility = ShaderVisibility::All, uint32_t registerSpace = 0)`
创建着色器资源视图根参数。
#### `static D3D12_ROOT_PARAMETER CreateUAV(uint32_t shaderRegister, ShaderVisibility visibility = ShaderVisibility::All, uint32_t registerSpace = 0)`
创建无序访问视图根参数。
#### `static D3D12_ROOT_PARAMETER Create32BitConstants(uint32_t shaderRegister, uint32_t num32BitValues, ShaderVisibility visibility = ShaderVisibility::All, uint32_t registerSpace = 0)`
创建 32 位常量根参数。
#### `static D3D12_ROOT_PARAMETER CreateDescriptorTable(uint32_t numRanges, const D3D12_DESCRIPTOR_RANGE* ranges, ShaderVisibility visibility = ShaderVisibility::All)`
创建描述符表根参数。
#### `static D3D12_STATIC_SAMPLER_DESC CreateStaticSampler(...)`
创建静态采样器描述。
#### `static D3D12_SAMPLER_DESC CreateSamplerDesc(FilterMode filter, TextureAddressMode address, float maxLOD = D3D12_FLOAT32_MAX)`
创建采样器描述。
#### `static D3D12_DESCRIPTOR_RANGE CreateDescriptorRange(...)`
创建描述符范围。
参数:
- `type`: 描述符类型 (CBV, SRV, UAV, Sampler)
- `baseShaderRegister`: 基寄存器编号
- `numDescriptors`: 描述符数量
- `registerSpace`: 寄存器空间
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_rootSignature` | `ComPtr<ID3D12RootSignature>` | D3D12 根签名 |
| `m_parameterCount` | `uint32_t` | 参数数量 |
## 使用示例
```cpp
// Create root parameters
D3D12_ROOT_PARAMETER params[3];
// Parameter 0: CBV
params[0] = D3D12RootSignature::CreateCBV(0);
// Parameter 1: 32-bit constants (e.g., 4x4 matrix = 16 floats)
params[1] = D3D12RootSignature::Create32BitConstants(0, 16);
// Parameter 2: Descriptor table
D3D12_DESCRIPTOR_RANGE ranges[1];
ranges[0] = D3D12RootSignature::CreateDescriptorRange(
D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 0, 10);
params[2] = D3D12RootSignature::CreateDescriptorTable(1, ranges);
// Create static samplers
D3D12_SAMPLER_DESC sampDesc = D3D12RootSignature::CreateSamplerDesc(
FilterMode::Linear, TextureAddressMode::Wrap);
D3D12_STATIC_SAMPLER_DESC staticSamp = D3D12RootSignature::CreateStaticSampler(0, sampDesc);
// Create root signature
D3D12_ROOT_SIGNATURE_DESC rsDesc = D3D12RootSignature::CreateDesc(
params, 3, &staticSamp, 1);
D3D12RootSignature rootSig;
rootSig.Initialize(device->GetDevice(), rsDesc);
```
## 备注
- 根签名定义 GPU 能访问的资源布局
- 根参数有三种类型: 描述符表、常量、描述符
- 描述符表使用描述符范围引用描述符堆中的描述符
- 静态采样器嵌入根签名,无需描述符堆
- 根签名需要与 PSO 匹配

View File

@@ -0,0 +1,64 @@
# D3D12Sampler
DirectX 12 采样器的 D3D12 实现。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12Sampler.h>
```
## 继承关系
```
RHISampler (interface)
└── D3D12Sampler (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12Sampler()`
默认构造函数。
#### `~D3D12Sampler() override`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `bool Initialize(ID3D12Device* device, const D3D12_SAMPLER_DESC& desc)`
初始化采样器。
- `device`: D3D12 设备
- `desc`: D3D12 采样器描述
- 返回: 初始化是否成功
#### `void Shutdown() override`
释放采样器。
### 描述
#### `D3D12_SAMPLER_DESC GetDesc() const`
获取采样器描述。
### 接口实现
#### `void* GetNativeHandle() override`
返回 `nullptr`D3D12 采样器通过描述符堆管理)。
#### `unsigned int GetID() override`
返回 0。
#### `void Bind(unsigned int unit) override / Unbind(unsigned int unit) override`
绑定/解绑(空实现)。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_desc` | `D3D12_SAMPLER_DESC` | 采样器描述 |
## 备注
- D3D12 采样器通常放在根签名或采样器描述符堆中
- 静态采样器在根签名中声明,无需描述符堆

View File

@@ -0,0 +1,50 @@
# D3D12Screenshot
D3D12 截图工具类,提供屏幕截图捕获功能。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12Screenshot.h>
```
## 命名空间
`XCEngine::RHI`
## 公共静态成员函数
#### `static bool Capture(ID3D12Device* device, ID3D12CommandQueue* commandQueue, ID3D12Resource* renderTarget, const char* filename, uint32_t width, uint32_t height)`
捕获渲染目标内容并保存为图片。
- `device`: D3D12 设备
- `commandQueue`: 命令队列
- `renderTarget`: 渲染目标资源
- `filename`: 输出文件名
- `width` / `height`: 截图尺寸
- 返回: 捕获是否成功
## 内部静态成员函数
#### `static bool CopyToReadbackAndSave(...)`
内部实现:复制到回读缓冲区并保存。
## 使用示例
```cpp
// Capture back buffer
D3D12Texture* backBuffer = swapChain->GetBackBuffer(
swapChain->GetCurrentBackBufferIndex());
D3D12Screenshot::Capture(
device->GetDevice(),
cmdQueue->GetCommandQueue(),
backBuffer->GetResource(),
"screenshot.png",
1920, 1080);
```
## 备注
- 截图自动复制到 READBACK 堆然后保存
- 支持 PNG 等常见图片格式
- 可能在内部创建临时资源

View File

@@ -0,0 +1,53 @@
# D3D12ShaderResourceView
DirectX 12 着色器资源视图的 D3D12 实现。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12ShaderResourceView.h>
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12ShaderResourceView()`
默认构造函数。
#### `~D3D12ShaderResourceView()`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `void Initialize(ID3D12Device* device, ID3D12Resource* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc = nullptr)`
创建 SRV。
#### `void InitializeAt(ID3D12Device* device, ID3D12Resource* resource, D3D12_CPU_DESCRIPTOR_HANDLE handle, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc = nullptr)`
在指定位置创建 SRV。
#### `void Shutdown()`
释放 SRV。
### 属性
#### `D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle() const`
获取 CPU 描述符句柄。
### 静态辅助函数
#### `static D3D12_SHADER_RESOURCE_VIEW_DESC CreateDesc(Format format, D3D12_SRV_DIMENSION dimension = D3D12_SRV_DIMENSION_TEXTURE2D, uint32_t mipLevels = 1)`
创建 SRV 描述。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_handle` | `D3D12_CPU_DESCRIPTOR_HANDLE` | CPU 描述符句柄 |
| `m_resource` | `ID3D12Resource*` | 关联的资源 |
## 备注
- SRV 用于在 shader 中读取资源
- SRV 必须在 CBV_SRV_UAV 类型描述符堆中分配
- 如果需要在 shader 中访问,必须创建 shader visible 的描述符堆

View File

@@ -0,0 +1,108 @@
# D3D12Shader
DirectX 12 着色器的 D3D12 实现,封装了 `ID3DBlob` 编译结果。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12Shader.h>
```
## 继承关系
```
RHIShader (interface)
└── D3D12Shader (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12Shader()`
默认构造函数。
#### `~D3D12Shader() override`
析构函数,确保调用 `Shutdown()`
### 编译
#### `bool CompileFromFile(const wchar_t* filePath, const char* entryPoint, const char* target) override`
从文件编译着色器。
- `filePath`: HLSL 文件路径
- `entryPoint`: 入口点函数名 (e.g., "VS", "PS")
- `target`: 着色器目标 (e.g., "vs_5_1", "ps_5_1", "cs_5_1")
- 返回: 编译是否成功
#### `bool Compile(const void* sourceData, size_t sourceSize, const char* entryPoint, const char* target) override`
从内存编译着色器。
- `sourceData`: 着色器源代码
- `sourceSize`: 代码大小
- `entryPoint`: 入口点
- `target`: 目标
- 返回: 编译是否成功
#### `void Shutdown() override`
释放着色器编译结果。
### 着色器信息
#### `const D3D12_SHADER_BYTECODE GetD3D12Bytecode() const`
获取 D3D12 着色器字节码结构。
#### `const void* GetBytecode() const`
获取字节码指针。
#### `size_t GetBytecodeSize() const`
获取字节码大小。
#### `ShaderType GetType() const override`
获取着色器类型。
#### `const InputLayoutDesc& GetInputLayout() const`
获取输入布局描述。
### 接口实现
#### `void* GetNativeHandle() override`
返回字节码指针。
#### `bool IsValid() const override`
检查着色器是否有效。
#### `void Bind() override / Unbind() override`
绑定/解绑(空实现)。
#### `void SetInt/SetFloat/SetVec3/SetVec4/SetMat4(...)`
设置着色器变量(空实现,实际通过根签名绑定)。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_bytecode` | `ComPtr<ID3DBlob>` | 编译成功的字节码 |
| `m_error` | `ComPtr<ID3DBlob>` | 编译错误信息 |
| `m_type` | `ShaderType` | 着色器类型 |
| `m_inputLayout` | `InputLayoutDesc` | 输入布局 |
## 使用示例
```cpp
D3D12Shader vertexShader;
if (vertexShader.CompileFromFile(L"shaders/DefaultVS.hlsl", "main", "vs_5_1")) {
auto bytecode = vertexShader.GetD3D12Bytecode();
// Use in PSO description
}
D3D12Shader pixelShader;
pixelShader.CompileFromFile(L"shaders/DefaultPS.hlsl", "main", "ps_5_1");
D3D12Shader computeShader;
computeShader.CompileFromFile(L"shaders/CopyCS.hlsl", "main", "cs_5_1");
```
## 备注
- 编译错误信息存储在 `m_error` 中,可输出到日志
- 字节码用于创建 Pipeline State Object
- 着色器目标格式: `{type}_{major}_{minor}`, e.g., `vs_5_1`, `ps_6_0`

View File

@@ -0,0 +1,136 @@
# D3D12SwapChain
DirectX 12 交换链的 D3D12 实现,封装了 `IDXGISwapChain3`
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12SwapChain.h>
```
## 继承关系
```
RHISwapChain (interface)
└── D3D12SwapChain (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12SwapChain()`
默认构造函数。
#### `~D3D12SwapChain() override`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `bool Initialize(IDXGIFactory4* factory, ID3D12CommandQueue* commandQueue, HWND windowHandle, uint32_t width, uint32_t height, uint32_t bufferCount = 2)`
创建新的交换链。
- `factory`: DXGI Factory
- `commandQueue`: 命令队列
- `windowHandle`: 窗口句柄
- `width` / `height`: 交换链尺寸
- `bufferCount`: 后台缓冲区数量(默认 2
- 返回: 初始化是否成功
#### `bool Initialize(IDXGISwapChain* swapChain, uint32_t width, uint32_t height)`
从现有 `IDXGISwapChain` 初始化。
- `swapChain`: 已存在的交换链
- `width` / `height`: 尺寸
- 返回: 初始化是否成功
#### `void Shutdown() override`
释放交换链资源。
### 交换链操作
#### `uint32_t GetCurrentBackBufferIndex() const override`
获取当前后台缓冲区索引。
#### `RHITexture* GetCurrentBackBuffer() override`
获取当前后台缓冲区纹理。
#### `D3D12Texture* GetBackBuffer(uint32_t index) const`
获取指定索引的后台缓冲区。
#### `void Present(uint32_t syncInterval = 1, uint32_t flags = 0) override`
呈现(显示)内容。
- `syncInterval`: 垂直同步间隔 (0=立即, 1-4=等待)
- `flags`: 附加标志
#### `void Resize(uint32_t width, uint32_t height) override`
调整交换链尺寸。
### 显示模式
#### `void SetFullscreen(bool fullscreen) override`
切换全屏模式。
#### `bool IsFullscreen() const override`
检查是否处于全屏模式。
### 事件处理
#### `bool ShouldClose() const override`
检查是否应该关闭(全屏时按 Alt+Enter
#### `void SetShouldClose(bool shouldClose)`
设置关闭标志。
#### `void PollEvents() override`
轮询窗口事件。
### 原生接口
#### `void* GetNativeHandle() override`
获取原生句柄。
#### `IDXGISwapChain3* GetSwapChain() const`
获取底层 `IDXGISwapChain3` 指针。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_swapChain` | `ComPtr<IDXGISwapChain3>` | DXGI 交换链 |
| `m_commandQueue` | `ComPtr<ID3D12CommandQueue>` | 命令队列引用 |
| `m_windowHandle` | `HWND` | 窗口句柄 |
| `m_width` | `uint32_t` | 宽度 |
| `m_height` | `uint32_t` | 高度 |
| `m_bufferCount` | `uint32_t` | 缓冲区数量 |
| `m_backBuffers` | `vector<D3D12Texture>` | 后台缓冲区纹理 |
## 使用示例
```cpp
D3D12SwapChain swapChain;
swapChain.Initialize(
device->GetFactory(),
cmdQueue->GetCommandQueue(),
hwnd, 1920, 1080, 2);
// Render loop
while (!swapChain.ShouldClose()) {
swapChain.PollEvents();
auto backBuffer = swapChain.GetCurrentBackBuffer();
// Transition to render target state
// Render...
// Transition to present state
swapChain.Present(1, 0);
}
// Resize
swapChain.Resize(3840, 2160);
```
## 备注
- `syncInterval = 0`: 立即呈现,可能产生撕裂
- `syncInterval = 1`: 等待垂直同步(推荐)
- 全屏模式切换需要处理窗口消息
- 窗口尺寸改变后必须调用 `Resize`

View File

@@ -0,0 +1,169 @@
# D3D12Texture
DirectX 12 纹理的 D3D12 实现,封装了 `ID3D12Resource` (texture 类型)。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12Texture.h>
```
## 继承关系
```
RHITexture (interface)
└── D3D12Texture (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12Texture()`
默认构造函数。
#### `~D3D12Texture() override`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `bool Initialize(ID3D12Device* device, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES initialState = D3D12_RESOURCE_STATE_COMMON)`
使用资源描述创建纹理。
- `device`: D3D12 设备
- `desc`: D3D12 资源描述
- `initialState`: 初始资源状态
- 返回: 初始化是否成功
#### `bool InitializeFromExisting(ID3D12Resource* resource)`
从现有 `ID3D12Resource` 初始化。
#### `bool InitializeFromData(ID3D12Device* device, ID3D12GraphicsCommandList* commandList, const void* pixelData, uint32_t width, uint32_t height, DXGI_FORMAT format)`
创建纹理并从像素数据初始化。
- `device`: D3D12 设备
- `commandList`: 命令列表
- `pixelData`: 像素数据指针
- `width` / `height`: 纹理尺寸
- `format`: 像素格式
- 返回: 初始化是否成功
#### `bool InitializeDepthStencil(ID3D12Device* device, uint32_t width, uint32_t height, DXGI_FORMAT format = DXGI_FORMAT_D24_UNORM_S8_UINT)`
创建深度模板纹理。
- `device`: D3D12 设备
- `width` / `height`: 纹理尺寸
- `format`: 深度格式 (D16, D24S8, D32F)
- 返回: 初始化是否成功
#### `void Shutdown() override`
释放纹理资源。
### 资源信息
#### `ID3D12Resource* GetResource() const`
获取底层 `ID3D12Resource` 指针。
#### `D3D12_RESOURCE_DESC GetDesc() const`
获取资源描述。
#### `uint32_t GetWidth() const override`
获取纹理宽度。
#### `uint32_t GetHeight() const override`
获取纹理高度。
#### `uint32_t GetDepth() const override`
获取纹理深度3D 纹理)或数组大小。
#### `uint32_t GetMipLevels() const override`
获取 Mipmap 级别数量。
#### `uint32_t GetArraySize() const`
获取数组大小。
#### `uint64_t GetGPUAddress() const`
获取 GPU 虚拟地址。
#### `size_t GetSize() const`
获取纹理大小(字节估算)。
### 状态管理
#### `void* GetNativeHandle() override { return m_resource.Get(); }`
返回原生句柄。
#### `ResourceStates GetState() const override`
获取当前资源状态。
#### `void SetState(ResourceStates state) override`
设置资源状态。
### 接口实现
#### `Format GetFormat() const override`
获取纹理格式。
#### `TextureType GetTextureType() const override`
获取纹理类型(当前固定返回 `TextureType::Texture2D`)。
#### `const std::string& GetName() const override`
获取对象名称。
#### `void SetName(const std::string& name) override`
设置对象名称。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_resource` | `ComPtr<ID3D12Resource>` | D3D12 纹理资源 |
| `m_state` | `ResourceStates` | 当前资源状态 |
| `m_name` | `std::string` | 对象名称 |
## 使用示例
### 创建 2D 纹理
```cpp
D3D12Texture texture;
D3D12_RESOURCE_DESC texDesc = {};
texDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
texDesc.Width = 1024;
texDesc.Height = 1024;
texDesc.MipLevels = 1;
texDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
texDesc.SampleDesc.Count = 1;
texDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
texture.Initialize(device->GetDevice(), texDesc);
```
### 创建深度模板纹理
```cpp
D3D12Texture depthTexture;
depthTexture.InitializeDepthStencil(
device->GetDevice(),
1920, 1080,
DXGI_FORMAT_D24_UNORM_S8_UINT);
```
### 创建并初始化纹理数据
```cpp
D3D12Texture texture;
std::vector<uint8_t> pixels(width * height * 4);
FillPixelData(pixels.data(), width, height);
texture.InitializeFromData(
device->GetDevice(),
cmdList->GetCommandList(),
pixels.data(),
width, height,
DXGI_FORMAT_R8G8B8A8_UNORM);
```
## 备注
- 纹理通常创建在 `D3D12_HEAP_TYPE_DEFAULT` 堆上
- 需要上传数据时,先创建 UPLOAD 堆缓冲区,再通过命令列表复制
- 深度纹理需要设置 `D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL`
- 渲染目标纹理需要设置 `D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET`

View File

@@ -0,0 +1,74 @@
# D3D12Types
D3D12 类型转换和辅助函数集合,提供 RHI 抽象类型到 D3D12 类型的转换。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12Types.h>
```
## 命名空间
`XCEngine::RHI`
## 转换函数
### Viewport 和 Rect
#### `inline D3D12_VIEWPORT ToD3D12(const Viewport& vp)`
`Viewport` 转换为 `D3D12_VIEWPORT`
#### `inline D3D12_RECT ToD3D12(const Rect& rect)`
`Rect` 转换为 `D3D12_RECT`
### ClearValue
#### `inline D3D12_CLEAR_VALUE ToD3D12(const ClearValue& clearValue, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE)`
`ClearValue` 转换为 `D3D12_CLEAR_VALUE`(颜色清除值)。
#### `inline D3D12_CLEAR_VALUE ToD3D12DepthStencil(const ClearValue& clearValue, DXGI_FORMAT format)`
`ClearValue` 转换为深度模板清除值。
### 资源描述
#### `inline D3D12_RESOURCE_DESC ToD3D12(const TextureDesc& desc)`
`TextureDesc` 转换为 `D3D12_RESOURCE_DESC`
#### `inline D3D12_RESOURCE_DESC ToD3D12(const BufferDesc& desc)`
`BufferDesc` 转换为 `D3D12_RESOURCE_DESC`
#### `inline D3D12_DESCRIPTOR_HEAP_DESC ToD3D12(const DescriptorHeapDesc& desc)`
`DescriptorHeapDesc` 转换为 `D3D12_DESCRIPTOR_HEAP_DESC`
#### `inline D3D12_COMMAND_QUEUE_DESC ToD3D12(const CommandQueueDesc& desc)`
`CommandQueueDesc` 转换为 `D3D12_COMMAND_QUEUE_DESC`
### 堆属性
#### `inline D3D12_HEAP_PROPERTIES ToD3D12HeapProperties(D3D12_HEAP_TYPE heapType, UINT nodeMask = 0)`
创建 D3D12 堆属性结构。
## 使用示例
```cpp
Viewport vp;
vp.topLeftX = 0; vp.topLeftY = 0;
vp.width = 1920; vp.height = 1080;
vp.minDepth = 0.0f; vp.maxDepth = 1.0f;
D3D12_VIEWPORT d3dVp = ToD3D12(vp);
TextureDesc texDesc;
texDesc.width = 1920;
texDesc.height = 1080;
texDesc.format = Format::R8G8B8A8_UNorm;
// ... set other fields
D3D12_RESOURCE_DESC d3d12Desc = ToD3D12(texDesc);
```
## 备注
- 所有转换函数为 inline可在头文件中使用
- 转换自动处理类型映射和默认值设置

View File

@@ -0,0 +1,45 @@
# D3D12UnorderedAccessView
DirectX 12 无序访问视图的 D3D12 实现。
## 头文件
```cpp
#include <XCEngine/RHI/D3D12/D3D12UnorderedAccessView.h>
```
## 公共成员函数
### 构造函数与析构函数
#### `D3D12UnorderedAccessView()`
默认构造函数。
#### `~D3D12UnorderedAccessView()`
析构函数,确保调用 `Shutdown()`
### 初始化
#### `void Initialize(ID3D12Device* device, ID3D12Resource* resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc = nullptr)`
创建 UAV。
#### `void Shutdown()`
释放 UAV。
### 属性
#### `D3D12_CPU_DESCRIPTOR_HANDLE GetCPUDescriptorHandle() const`
获取 CPU 描述符句柄。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_handle` | `D3D12_CPU_DESCRIPTOR_HANDLE` | CPU 描述符句柄 |
| `m_resource` | `ID3D12Resource*` | 关联的资源 |
## 备注
- UAV 用于 compute shader 中的读写访问
- UAV 需要 barrier 来同步读写
- UAV 必须在 CBV_SRV_UAV 类型描述符堆中分配

View File

@@ -0,0 +1,135 @@
# OpenGLBuffer
OpenGL 缓冲区的实现,封装 OpenGL buffer object。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLBuffer.h>
```
## 继承关系
```
RHIBuffer (interface)
└── OpenGLBuffer (implementation)
```
## OpenGLBufferType 枚举
| 值 | 描述 |
|----|------|
| `Vertex` | 顶点缓冲区 |
| `Index` | 索引缓冲区 |
| `Uniform` | Uniform 缓冲区 (UBO) |
| `CopyRead` | 复制源缓冲区 |
| `CopyWrite` | 复制目标缓冲区 |
| `AtomicCounter` | 原子计数器缓冲区 |
| `DispatchIndirect` | 间接计算调用缓冲区 |
| `DrawIndirect` | 间接绘制缓冲区 |
| `ShaderBindingTable` | 光线追踪 Shader 绑定表 |
## 公共成员函数
### 构造函数与析构函数
#### `OpenGLBuffer()`
#### `~OpenGLBuffer() override`
### 初始化
#### `bool Initialize(OpenGLBufferType type, size_t size, const void* data = nullptr, bool dynamic = false)`
通用初始化。
- `type`: 缓冲区类型
- `size`: 大小(字节)
- `data`: 初始数据(可选)
- `dynamic`: 是否动态更新
#### `bool InitializeVertexBuffer(const void* data, size_t size)`
初始化顶点缓冲区。
#### `bool InitializeIndexBuffer(const void* data, size_t size)`
初始化索引缓冲区。
#### `void Shutdown() override`
### 绑定操作
#### `void Bind() const`
绑定缓冲区到当前 target。
#### `void Unbind() const`
解除绑定。
#### `void BindBase(unsigned int target, unsigned int index) const`
绑定到指定的 binding point用于 UBO、SSBO 等)。
### 数据操作
#### `void* Map() override`
映射缓冲区到 CPU。
#### `void Unmap() override`
解除映射。
#### `void SetData(const void* data, size_t size, size_t offset = 0) override`
更新缓冲区数据。
### 属性
#### `unsigned int GetID() const`
获取 OpenGL buffer ID。
#### `uint64_t GetSize() const override`
获取缓冲区大小。
#### `OpenGLBufferType GetType() const`
获取缓冲区类型。
#### `bool IsDynamic() const`
是否动态缓冲区。
#### `BufferType GetBufferType() const override / void SetBufferType(BufferType type) override`
#### `uint32_t GetStride() const override / void SetStride(uint32_t stride) override`
#### `void* GetNativeHandle() override`
返回 `reinterpret_cast<void*>(static_cast<uintptr_t>(m_buffer))`
#### `ResourceStates GetState() const override`
返回 `ResourceStates::Common`OpenGL 无显式状态)
#### `const std::string& GetName() const override / void SetName(...) override`
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_buffer` | `unsigned int` | GL buffer ID |
| `m_size` | `size_t` | 大小 |
| `m_isIndexBuffer` | `bool` | 是否索引缓冲区 |
| `m_dynamic` | `bool` | 是否动态 |
| `m_type` | `OpenGLBufferType` | 缓冲区类型 |
| `m_bufferType` | `BufferType` | RHI 缓冲区类型 |
| `m_stride` | `uint32_t` | 顶点步长 |
| `m_name` | `std::string` | 名称 |
## 使用示例
```cpp
OpenGLBuffer vb;
float vertices[] = { ... };
vb.InitializeVertexBuffer(vertices, sizeof(vertices));
vb.SetBufferType(BufferType::Vertex);
vb.SetStride(sizeof(float) * 5);
OpenGLBuffer ib;
uint16_t indices[] = { 0, 1, 2, ... };
ib.InitializeIndexBuffer(indices, sizeof(indices));
// Bind and draw
vb.Bind();
ib.Bind();
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, 0);
```

View File

@@ -0,0 +1,308 @@
# OpenGLCommandList
OpenGL 命令列表实现。OpenGL 是立即模式 API此类提供命令录制和批量提交的能力。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLCommandList.h>
```
## 继承关系
```
RHICommandList (interface)
└── OpenGLCommandList (implementation)
```
## 枚举
### PrimitiveType
| 值 | OpenGL 常量 |
|----|-------------|
| `Points` | `GL_POINTS` |
| `Lines` | `GL_LINES` |
| `LineStrip` | `GL_LINE_STRIP` |
| `Triangles` | `GL_TRIANGLES` |
| `TriangleStrip` | `GL_TRIANGLE_STRIP` |
| `TriangleFan` | `GL_TRIANGLE_FAN` |
| `LineListAdj` | `GL_LINES_ADJACENCY` |
| `TriangleListAdj` | `GL_TRIANGLES_ADJACENCY` |
| `Patch` | `GL_PATCHES` |
### ClearFlag
| 值 | 描述 |
|----|------|
| `Color` | 清除颜色缓冲区 |
| `Depth` | 清除深度缓冲区 |
| `Stencil` | 清除模板缓冲区 |
支持 `|` 操作符合并。
## 公共成员函数
### 生命周期
#### `void Shutdown() override`
#### `void Reset() override`
重置命令列表。
#### `void Close() override`
关闭命令列表。
### 清除操作
#### `void Clear(float r, float g, float b, float a, unsigned int buffers)`
清除指定缓冲区。
#### `void ClearColor(float r, float g, float b, float a)`
#### `void ClearDepth(float depth)`
#### `void ClearStencil(int stencil)`
#### `void ClearDepthStencil(float depth, int stencil)`
### RHI 接口实现
#### `void SetPipelineState(void* pipelineState) override`
#### `void SetVertexBuffer(uint32_t slot, void* buffer, uint64_t offset, uint32_t stride) override`
#### `void SetVertexBuffers(uint32_t startSlot, uint32_t count, ...) override`
#### `void SetIndexBuffer(void* buffer, uint64_t offset, Format format) override`
#### `void TransitionBarrier(void* resource, ...) override`
OpenGL 实现为空(无显式状态管理)。
#### `void SetPrimitiveTopology(PrimitiveTopology topology) override`
#### `void SetViewport(const Viewport& viewport) override`
#### `void SetViewports(uint32_t count, const Viewport* viewports) override`
#### `void SetScissorRect(const Rect& rect) override`
#### `void SetScissorRects(uint32_t count, const Rect* rects) override`
#### `void SetRenderTargets(uint32_t count, void** renderTargets, void* depthStencil) override`
#### `void SetDepthStencilState(const DepthStencilState& state) override`
#### `void SetStencilRef(uint8_t ref) override`
#### `void SetBlendState(const BlendState& state) override`
#### `void SetBlendFactor(const float factor[4]) override`
#### `void ClearRenderTarget(void* renderTarget, const float color[4]) override`
#### `void ClearDepthStencil(void* depthStencil, float depth, uint8_t stencil) override`
#### `void Draw(uint32_t vertexCount, uint32_t instanceCount, uint32_t startVertex, uint32_t startInstance) override`
#### `void DrawIndexed(uint32_t indexCount, uint32_t instanceCount, uint32_t startIndex, int32_t baseVertex, uint32_t startInstance) override`
#### `void Dispatch(uint32_t x, uint32_t y, uint32_t z) override`
#### `void CopyResource(void* dst, void* src) override`
### OpenGL 特有方法
#### `void SetVertexBuffer(unsigned int buffer, size_t offset, size_t stride)`
直接设置顶点缓冲区OpenGL 逃逸)。
#### `void SetVertexBuffers(unsigned int startSlot, unsigned int count, const unsigned int* buffers, const size_t* offsets, const size_t* strides)`
#### `void SetIndexBuffer(unsigned int buffer, unsigned int type)`
#### `void SetIndexBuffer(unsigned int buffer, unsigned int type, size_t offset)`
#### `void BindVertexArray(unsigned int vao)`
#### `void BindVertexArray(unsigned int vao, unsigned int indexBuffer, unsigned int indexType)`
#### `void UseShader(unsigned int program)`
### 视口与裁剪
#### `void SetViewport(int x, int y, int width, int height)`
#### `void SetViewport(float x, float y, float width, float height, float minDepth, float maxDepth)`
#### `void SetViewports(unsigned int count, const float* viewports)`
#### `void SetScissor(int x, int y, int width, int height)`
#### `void SetScissorRects(unsigned int count, const int* rects)`
#### `void EnableScissorTest(bool enable)`
### 深度测试
#### `void EnableDepthTest(bool enable)`
#### `void EnableDepthWrite(bool enable)`
#### `void SetDepthFunc(unsigned int func)`
### 模板测试
#### `void EnableStencilTest(bool enable)`
#### `void SetStencilFunc(unsigned int func, int ref, unsigned int mask)`
#### `void SetStencilOp(unsigned int fail, unsigned int zfail, unsigned int zpass)`
### 混合
#### `void EnableBlending(bool enable)`
#### `void SetBlendFunc(unsigned int src, unsigned int dst)`
#### `void SetBlendFuncSeparate(unsigned int srcRGB, unsigned int dstRGB, unsigned int srcAlpha, unsigned int dstAlpha)`
#### `void SetBlendEquation(unsigned int mode)`
#### `void SetBlendColor(float r, float g, float b, float a)`
### 光栅化
#### `void EnableCulling(bool enable)`
#### `void SetCullFace(unsigned int face)`
#### `void SetFrontFace(unsigned int face)`
#### `void SetPolygonMode(unsigned int mode)`
#### `void SetPolygonOffset(float factor, float units)`
#### `void SetPrimitiveType(PrimitiveType type)`
### 绘制
#### `void Draw(PrimitiveType type, unsigned int vertexCount, unsigned int startVertex)`
#### `void DrawInstanced(PrimitiveType type, unsigned int vertexCount, unsigned int instanceCount, unsigned int startVertex, unsigned int startInstance)`
#### `void DrawIndexed(PrimitiveType type, unsigned int indexCount, unsigned int startIndex, int baseVertex)`
#### `void DrawIndexedInstanced(PrimitiveType type, unsigned int indexCount, unsigned int instanceCount, unsigned int startIndex, int baseVertex, unsigned int startInstance)`
#### `void DrawIndirect(...)`
#### `void DrawIndexedIndirect(...)`
#### `void MultiDrawArrays(PrimitiveType type, const int* first, const int* count, unsigned int drawCount)`
#### `void MultiDrawElements(...)`
### 计算着色器
#### `void DispatchIndirect(unsigned int buffer, size_t offset)`
#### `void DispatchCompute(unsigned int x, unsigned int y, unsigned int z, unsigned int groupX, unsigned int groupY, unsigned int groupZ)`
### 内存屏障
#### `void MemoryBarrier(unsigned int barriers)`
#### `void TextureBarrier()`
### 纹理绑定
#### `void BindTexture(unsigned int target, unsigned int unit, unsigned int texture)`
#### `void BindTextures(unsigned int first, unsigned int count, const unsigned int* textures)`
#### `void BindSampler(unsigned int unit, unsigned int sampler)`
#### `void BindSamplers(unsigned int first, unsigned int count, const unsigned int* samplers)`
#### `void BindImageTexture(...)`
### 缓冲区绑定
#### `void BindBufferBase(unsigned int target, unsigned int index, unsigned int buffer)`
#### `void BindBufferRange(unsigned int target, unsigned int index, unsigned int buffer, size_t offset, size_t size)`
### OpenGL 状态
#### `void Enable(unsigned int cap)`
#### `void Disable(unsigned int cap)`
#### `void Enablei(unsigned int cap, unsigned int index)`
#### `void Disablei(unsigned int cap, unsigned int index)`
### Uniform 设置
#### `void SetUniform1i(int location, int v)`
#### `void SetUniform1f(int location, float v)`
#### `void SetUniform2f(int location, float x, float y)`
#### `void SetUniform3f(int location, float x, float y, float z)`
#### `void SetUniform4f(int location, float x, float y, float z, float w)`
#### `void SetUniform1fv(int location, int count, const float* v)`
#### `void SetUniform2fv/3fv/4fv`
#### `void SetUniformMatrix4fv(int location, int count, bool transpose, const float* v)`
### Shader 程序
#### `void UseProgram(unsigned int program)`
#### `void BindFragDataLocation(unsigned int program, unsigned int colorNumber, const char* name)`
#### `void BindFragDataLocationIndexed(...)`
### 查询
#### `void BeginQuery(unsigned int target, unsigned int id)`
#### `void EndQuery(unsigned int target)`
#### `void GetQueryObjectiv/GetQueryObjectuiv`
### Framebuffer 操作
#### `void ReadPixels(int x, int y, int width, int height, unsigned int format, unsigned int type, void* data)`
#### `void BlitFramebuffer(...)`
#### `void CopyImageSubData(...)`
#### `void InvalidateFramebuffer(unsigned int target, unsigned int count, const unsigned int* attachments)`
#### `void InvalidateSubFramebuffer(...)`
### 调试
#### `void PushDebugGroup(unsigned int source, unsigned int id, int length, const char* message)`
#### `void PopDebugGroup()`
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_primitiveType` | `unsigned int` | 当前图元类型 |
| `m_currentVAO` | `unsigned int` | 当前 VAO |
| `m_currentProgram` | `unsigned int` | 当前 program |
## 备注
- OpenGL 是立即模式 API`OpenGLCommandList` 主要用于状态批处理
- `Reset()``Close()` 是可选的,可直接调用 GL 命令

View File

@@ -0,0 +1,63 @@
# OpenGLCommandQueue
OpenGL 命令队列实现。OpenGL 是立即模式 API此类主要提供 RHI 接口兼容。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLCommandQueue.h>
```
## 继承关系
```
RHICommandQueue (interface)
└── OpenGLCommandQueue (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `OpenGLCommandQueue()`
#### `~OpenGLCommandQueue() override`
### 生命周期
#### `void Shutdown() override`
### 命令执行
#### `void ExecuteCommandLists(uint32_t count, void** lists) override`
执行命令列表OpenGL 下为 no-op直接调用 GL 命令)。
### 同步
#### `void Signal(RHIFence* fence, uint64_t value) override`
发送信号。
#### `void Wait(RHIFence* fence, uint64_t value) override`
等待栅栏。
#### `uint64_t GetCompletedValue() override`
#### `void WaitForIdle() override`
等待空闲(调用 `glFinish`)。
### 属性
#### `CommandQueueType GetType() const override`
返回 `CommandQueueType::Direct`
#### `uint64_t GetTimestampFrequency() const override`
返回 0。
#### `void* GetNativeHandle() override`
返回 `nullptr`
## 备注
- OpenGL 没有显式的命令队列,所有命令立即执行
- `ExecuteCommandLists` 在 OpenGL 后端为空操作
- `Signal`/`Wait` 仍然工作,使用 GLsync/fence 对象实现

View File

@@ -0,0 +1,105 @@
# OpenGLDepthStencilView
OpenGL 深度模板视图实现。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLDepthStencilView.h>
```
## 枚举
### DepthStencilFormat
| 值 | OpenGL 内部格式 |
|----|----------------|
| `D16_UNORM` | `GL_DEPTH_COMPONENT16` |
| `D24_UNORM_S8_UINT` | `GL_DEPTH24_STENCIL8` |
| `D32_FLOAT` | `GL_DEPTH_COMPONENT32F` |
| `D32_FLOAT_S8X24_UINT` | `GL_DEPTH32F_STENCIL8` |
### DepthStencilType
| 值 | 描述 |
|----|------|
| `Texture2D` | 2D 纹理 |
| `Texture2DArray` | 2D 纹理数组 |
| `TextureCube` | 立方体贴图 |
## OpenGLDepthStencilViewDesc
```cpp
struct OpenGLDepthStencilViewDesc {
DepthStencilType type = DepthStencilType::Texture2D;
int mipLevel = 0;
int baseArraySlice = 0;
int arraySize = 1;
int layer = 0;
};
```
## 公共成员函数
#### `OpenGLDepthStencilView()`
#### `~OpenGLDepthStencilView()`
#### `bool Initialize(unsigned int texture, const OpenGLDepthStencilViewDesc& desc)`
#### `bool Initialize(unsigned int texture, int mipLevel = 0)`
#### `bool InitializeCubemap(unsigned int cubemap, int face, int mipLevel = 0)`
#### `void Shutdown()`
#### `void Bind()`
#### `void Unbind()`
#### `void ClearDepth(float depth)`
#### `void ClearStencil(uint8_t stencil)`
#### `void ClearDepthStencil(float depth, uint8_t stencil)`
#### `unsigned int GetFramebuffer() const`
#### `unsigned int GetTexture() const`
#### `int GetMipLevel() const`
#### `int GetWidth() const`
#### `int GetHeight() const`
#### `static void BindFramebuffer(unsigned int framebuffer)`
#### `static void UnbindFramebuffer()`
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_texture` | `unsigned int` | GL texture ID |
| `m_framebuffer` | `unsigned int` | GL framebuffer ID |
| `m_mipLevel` | `int` | Mip 级别 |
| `m_width/height` | `int` | 尺寸 |
| `m_type` | `DepthStencilType` | 类型 |
| `m_format` | `DepthStencilFormat` | 格式 |
## 使用示例
```cpp
OpenGLDepthStencilView dsv;
dsv.Initialize(depthTexture.GetID());
dsv.Bind();
dsv.ClearDepthStencil(1.0f, 0);
dsv.Unbind();
// Combined with RTV
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTex, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthTex, 0);
```

View File

@@ -0,0 +1,109 @@
# OpenGLDevice
OpenGL 设备的实现,基于 GLFW 和现代 OpenGL。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLDevice.h>
```
## 继承关系
```
RHIDevice (interface)
└── OpenGLDevice (implementation)
```
## 公共成员函数
### 初始化与销毁
#### `bool Initialize(const RHIDeviceDesc& desc) override`
初始化 OpenGL 上下文和设备。
#### `void Shutdown() override`
关闭设备,销毁窗口(如果拥有)。
#### `bool CreateRenderWindow(int width, int height, const char* title, bool enableDebug = false)`
创建渲染窗口并初始化 OpenGL 上下文。
#### `bool InitializeWithExistingWindow(GLFWwindow* window)`
使用已有的 GLFW 窗口初始化。
### 窗口操作
#### `GLFWwindow* GetWindow() const`
获取 GLFW 窗口指针。
#### `void SwapBuffers()`
交换前后缓冲区。
#### `bool PollEvents()`
轮询窗口事件。
#### `void SetShouldClose(bool shouldClose)`
设置关闭标志。
#### `bool ShouldClose() const`
检查是否应该关闭。
### 资源创建
#### `RHIBuffer* CreateBuffer(const BufferDesc& desc) override`
#### `RHITexture* CreateTexture(const TextureDesc& desc) override`
#### `RHISwapChain* CreateSwapChain(const SwapChainDesc& desc) override`
#### `RHICommandList* CreateCommandList(const CommandListDesc& desc) override`
#### `RHICommandQueue* CreateCommandQueue(const CommandQueueDesc& desc) override`
#### `RHIShader* CompileShader(const ShaderCompileDesc& desc) override`
#### `RHIPipelineState* CreatePipelineState(const PipelineStateDesc& desc) override`
#### `RHIFence* CreateFence(const FenceDesc& desc) override`
#### `RHISampler* CreateSampler(const SamplerDesc& desc) override`
### 设备信息
#### `const RHICapabilities& GetCapabilities() const override`
获取 OpenGL 功能支持信息。
#### `const RHIDeviceInfo& GetDeviceInfo() const override`
获取设备详细信息。
#### `void* GetNativeDevice() override`
返回窗口指针。
#### `void* GetNativeHandle() const`
返回窗口指针。
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_window` | `GLFWwindow*` | GLFW 窗口 |
| `m_deviceInfo` | `RHIDeviceInfo` | 设备信息 |
| `m_capabilities` | `RHICapabilities` | 功能支持 |
| `m_initialized` | `bool` | 是否已初始化 |
| `m_ownsWindow` | `bool` | 是否拥有窗口 |
## 使用示例
```cpp
OpenGLDevice device;
device.CreateRenderWindow(1920, 1080, "XCEngine", true);
RHIShader* shader = device.CompileShader(shaderDesc);
RHIPipelineState* pso = device.CreatePipelineState(psoDesc);
while (!device.ShouldClose()) {
device.PollEvents();
// Render...
device.SwapBuffers();
}
```

View File

@@ -0,0 +1,99 @@
# OpenGLFence
OpenGL 栅栏同步实现,使用 `GLsync` (Fence objects)。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLFence.h>
```
## FenceStatus 枚举
| 值 | 描述 |
|----|------|
| `Signaled` | 栅栏已发出信号 |
| `Unsignaled` | 栅栏未发出信号 |
| `Error` | 错误状态 |
## 继承关系
```
RHIFence (interface)
└── OpenGLFence (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `OpenGLFence()`
#### `~OpenGLFence() override`
### 初始化
#### `bool Initialize(bool signaled = false)`
初始化栅栏。
- `signaled`: 是否初始为已发出信号状态
#### `void Shutdown() override`
### 信号操作
#### `void Signal() override`
发送信号。
#### `void Signal(uint64_t value) override`
发送信号(值递增)。
#### `void Wait(uint64_t value) override`
等待栅栏达到指定值。
#### `void Reset()`
重置栅栏。
### 状态查询
#### `bool IsSignaled() const override`
检查是否已发出信号。
#### `FenceStatus GetStatus() const`
获取栅栏状态。
#### `uint64_t GetCompletedValue() const override`
获取已完成值。
#### `uint64_t GetCurrentValue() const`
获取当前值。
### 原生接口
#### `void* GetNativeHandle() override { return m_sync; }`
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_sync` | `void*` | GLsync 对象 |
| `m_fenceValue` | `uint64_t` | 栅栏值 |
| `m_completedValue` | `uint64_t` | 已完成值 |
| `m_signaled` | `bool` | 是否已发出信号 |
## 使用示例
```cpp
OpenGLFence fence;
fence.Initialize();
// Insert fence after draw commands
glFlush();
GLsync sync = glFenceSync(GL_SYNC_GPU_commands_COMPLETE, 0);
glClientWaitSync(sync, GL_SYNC_FLUSH_COMMANDS_BIT, timeout);
// Or use class
glFlush();
fence.Signal();
fence.Wait(1);
```

View File

@@ -0,0 +1,87 @@
# OpenGL Backend Overview
OpenGL RHI 后端实现,基于 GLFW 和现代 OpenGL (Core Profile)。
## 头文件
所有 OpenGL 后端头文件位于 `engine/include/XCEngine/RHI/OpenGL/`
## 架构说明
OpenGL 是**立即模式** API与 D3D12 的命令列表模式有本质区别:
- 无显式的命令列表录制和提交
- 状态通过 OpenGL 状态机管理
- `OpenGLCommandList` 主要用于状态批处理和 RHI 接口兼容
- 交换链使用 GLFW 窗口管理
## 后端组件
| 类 | 文件 | 描述 |
|----|------|------|
| `OpenGLDevice` | `OpenGLDevice.h` | 主设备,管理窗口和 OpenGL 上下文 |
| `OpenGLBuffer` | `OpenGLBuffer.h` | GPU 缓冲区VBO/UBO/SSBO |
| `OpenGLTexture` | `OpenGLTexture.h` | 纹理对象1D/2D/3D/Cube |
| `OpenGLCommandList` | `OpenGLCommandList.h` | 命令列表(状态批处理) |
| `OpenGLCommandQueue` | `OpenGLCommandQueue.h` | 命令队列RHI 兼容层) |
| `OpenGLSwapChain` | `OpenGLSwapChain.h` | 交换链GLFW 窗口) |
| `OpenGLFence` | `OpenGLFence.h` | 栅栏同步GLsync |
| `OpenGLShader` | `OpenGLShader.h` | Shader Program |
| `OpenGLPipelineState` | `OpenGLPipelineState.h` | 管线状态 |
| `OpenGLSampler` | `OpenGLSampler.h` | 采样器对象 |
| `OpenGLVertexArray` | `OpenGLVertexArray.h` | 顶点数组对象 (VAO) |
| `OpenGLRenderTargetView` | `OpenGLRenderTargetView.h` | 渲染目标 (FBO) |
| `OpenGLDepthStencilView` | `OpenGLDepthStencilView.h` | 深度模板 (FBO) |
## 初始化流程
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLDevice.h>
using namespace XCEngine::RHI;
OpenGLDevice device;
device.CreateRenderWindow(1920, 1080, "XCEngine", true);
// Create resources
OpenGLShader shader;
shader.CompileFromFile("shaders/Default.vert", "shaders/Default.frag");
OpenGLBuffer vb;
vb.InitializeVertexBuffer(vertices, sizeof(vertices));
OpenGLTexture texture;
texture.LoadFromFile("textures/diffuse.png");
// Render loop
while (!device.ShouldClose()) {
device.PollEvents();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader.Use();
vb.Bind();
texture.Bind(0);
glDrawArrays(GL_TRIANGLES, 0, vertexCount);
device.SwapBuffers();
}
```
## 与 D3D12 的差异
| 方面 | D3D12 | OpenGL |
|------|-------|--------|
| 模式 | 命令列表录制 | 立即模式 |
| 状态管理 | 显式资源状态 | OpenGL 状态机 |
| 描述符 | 描述符堆 + 句柄 | 绑定点 |
| 管线状态 | PSO不可变 | 可变状态 |
| 内存管理 | 显式显存管理 | 驱动自动管理 |
| 多线程 | 需要 Bundle | 上下文共享 |
## 扩展模块
- **GLFW**: 窗口管理和输入
- **GLSL**: 着色器语言 (Core Profile)
- **stb_image**: 纹理文件加载

View File

@@ -0,0 +1,229 @@
# OpenGLPipelineState
OpenGL 管线状态对象实现,封装多种 OpenGL 状态。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLPipelineState.h>
```
## 继承关系
```
RHIPipelineState (interface)
└── OpenGLPipelineState (implementation)
```
## 枚举
### OpenGLPrimitiveTopology
| 值 | 描述 |
|----|------|
| `Points` | 点 |
| `Lines` | 线 |
| `LineStrip` | 线带 |
| `Triangles` | 三角形 |
| `TriangleStrip` | 三角形带 |
### OpenGLBlendOp
| 值 | OpenGL 常量 |
|----|-------------|
| `Add` | `GL_FUNC_ADD` |
| `Subtract` | `GL_FUNC_SUBTRACT` |
| `ReverseSubtract` | `GL_FUNC_REVERSE_SUBTRACT` |
| `Min` | `GL_MIN` |
| `Max` | `GL_MAX` |
### CullFace / FrontFace / PolygonMode
```cpp
enum class CullFace { Front, Back, FrontAndBack };
enum class FrontFace { Clockwise, CounterClockwise };
enum class PolygonMode { Point, Line, Fill };
```
## 状态结构体
### OpenGLDepthStencilState
```cpp
struct OpenGLDepthStencilState {
bool depthTestEnable = true;
bool depthWriteEnable = true;
ComparisonFunc depthFunc = ComparisonFunc::Less;
bool stencilEnable = false;
uint8_t stencilReadMask = 0xFF;
uint8_t stencilWriteMask = 0xFF;
int stencilRef = 0;
ComparisonFunc stencilFunc = ComparisonFunc::Always;
StencilOp stencilFailOp = StencilOp::Keep;
StencilOp stencilDepthFailOp = StencilOp::Keep;
StencilOp stencilDepthPassOp = StencilOp::Keep;
};
```
### OpenGLBlendState
```cpp
struct OpenGLBlendState {
bool blendEnable = false;
BlendFactor srcBlend = BlendFactor::SrcAlpha;
BlendFactor dstBlend = BlendFactor::InvSrcAlpha;
BlendFactor srcBlendAlpha = BlendFactor::One;
BlendFactor dstBlendAlpha = BlendFactor::Zero;
BlendOp blendOp = BlendOp::Add;
BlendOp blendOpAlpha = BlendOp::Add;
uint8_t colorWriteMask = 0xF;
float blendFactor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
};
```
### OpenGLRasterizerState
```cpp
struct OpenGLRasterizerState {
bool cullFaceEnable = true;
CullFace cullFace = CullFace::Back;
FrontFace frontFace = FrontFace::CounterClockwise;
PolygonMode polygonMode = PolygonMode::Fill;
float polygonOffsetFactor = 0.0f;
float polygonOffsetUnits = 0.0f;
bool depthClipEnable = true;
bool scissorTestEnable = false;
bool multisampleEnable = false;
bool sampleAlphaToCoverageEnable = false;
};
```
### ViewportState / ScissorState / LogicalOperation
```cpp
struct ViewportState {
float x = 0.0f, y = 0.0f;
float width = 0.0f, height = 0.0f;
float minDepth = 0.0f, maxDepth = 1.0f;
};
struct ScissorState {
bool enable = false;
int x = 0, y = 0, width = 0, height = 0;
};
struct LogicalOperation {
bool enable = false;
uint32_t operation = 0;
};
```
## 公共成员函数
### 生命周期
#### `OpenGLPipelineState()`
#### `~OpenGLPipelineState() override`
#### `void Shutdown() override`
### 绑定
#### `void Bind() override`
应用所有状态。
#### `void Unbind() override`
#### `void* GetNativeHandle() override`
#### `PipelineType GetType() const override { return PipelineType::Graphics; }`
### 状态设置
#### `void SetDepthStencilState(const OpenGLDepthStencilState& state)`
#### `void SetBlendState(const OpenGLBlendState& state)`
#### `void SetRasterizerState(const OpenGLRasterizerState& state)`
#### `void SetViewport(const ViewportState& state)`
#### `void SetScissor(const ScissorState& state)`
#### `void SetLogicalOperation(const LogicalOperation& state)`
### 状态应用
#### `void Apply()`
应用所有状态。
#### `void ApplyDepthStencil()`
#### `void ApplyBlend()`
#### `void ApplyRasterizer()`
#### `void ApplyViewport()`
#### `void ApplyScissor()`
### 清除
#### `void SetClearColor(float r, float g, float b, float a)`
#### `void Clear(unsigned int buffers)`
### Shader 附加
#### `void AttachShader(unsigned int program)`
#### `void DetachShader()`
### 属性获取
#### `const OpenGLDepthStencilState& GetDepthStencilState() const`
#### `const OpenGLBlendState& GetBlendState() const`
#### `const OpenGLRasterizerState& GetRasterizerState() const`
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_depthStencilState` | `OpenGLDepthStencilState` | 深度模板状态 |
| `m_blendState` | `OpenGLBlendState` | 混合状态 |
| `m_rasterizerState` | `OpenGLRasterizerState` | 光栅化状态 |
| `m_viewportState` | `ViewportState` | 视口状态 |
| `m_scissorState` | `ScissorState` | 裁剪状态 |
| `m_logicalOperation` | `LogicalOperation` | 逻辑操作 |
| `m_clearColor` | `float[4]` | 清除颜色 |
| `m_program` | `unsigned int` | GL program |
| `m_programAttached` | `bool` | program 是否附加 |
## 使用示例
```cpp
OpenGLPipelineState pso;
OpenGLDepthStencilState ds;
ds.depthTestEnable = true;
ds.depthWriteEnable = true;
ds.depthFunc = ComparisonFunc::Less;
pso.SetDepthStencilState(ds);
OpenGLBlendState blend;
blend.blendEnable = true;
blend.srcBlend = BlendFactor::SrcAlpha;
blend.dstBlend = BlendFactor::InvSrcAlpha;
pso.SetBlendState(blend);
OpenGLRasterizerState raster;
raster.cullFaceEnable = true;
raster.cullFace = CullFace::Back;
pso.SetRasterizerState(raster);
pso.AttachShader(shaderProgram);
pso.Bind();
```

View File

@@ -0,0 +1,106 @@
# OpenGLRenderTargetView
OpenGL 渲染目标视图实现,使用 framebuffer object (FBO)。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLRenderTargetView.h>
```
## 枚举
### RenderTargetType
| 值 | 描述 |
|----|------|
| `Texture2D` | 2D 纹理 |
| `Texture2DArray` | 2D 纹理数组 |
| `Texture3D` | 3D 纹理 |
| `TextureCube` | 立方体贴图 |
| `TextureCubeArray` | 立方体贴图数组 |
## OpenGLRenderTargetViewDesc
```cpp
struct OpenGLRenderTargetViewDesc {
RenderTargetType type = RenderTargetType::Texture2D;
int mipLevel = 0;
int baseArraySlice = 0;
int arraySize = 1;
int layer = 0;
uint32_t format = 0;
};
```
## 公共成员函数
#### `OpenGLRenderTargetView()`
#### `~OpenGLRenderTargetView()`
#### `bool Initialize(unsigned int texture, const OpenGLRenderTargetViewDesc& desc)`
#### `bool Initialize(unsigned int texture, int mipLevel = 0)`
#### `bool InitializeCubemap(unsigned int cubemap, int face, int mipLevel = 0)`
#### `void Shutdown()`
#### `void Bind(unsigned int slot = 0)`
#### `void Bind(unsigned int count, const unsigned int* framebuffers, const int* drawBuffers)`
#### `void Unbind()`
#### `void Clear(float r, float g, float b, float a)`
#### `void Clear(float r, float g, float b, float a, float depth, uint8_t stencil)`
#### `unsigned int GetFramebuffer() const`
#### `unsigned int GetTexture() const`
#### `int GetMipLevel() const`
#### `int GetWidth() const`
#### `int GetHeight() const`
#### `static void BindFramebuffer(unsigned int framebuffer)`
#### `static void UnbindFramebuffer()`
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_texture` | `unsigned int` | GL texture ID |
| `m_framebuffer` | `unsigned int` | GL framebuffer ID |
| `m_mipLevel` | `int` | Mip 级别 |
| `m_width/height` | `int` | 尺寸 |
| `m_type` | `RenderTargetType` | 类型 |
| `m_framebuffers` | `vector<unsigned int>` | 额外 framebuffer 列表 |
## 使用示例
```cpp
// Create framebuffer with color attachment
OpenGLRenderTargetView rtv;
rtv.Initialize(texture.GetID());
rtv.Bind();
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 3);
rtv.Unbind();
// MRT
OpenGLRenderTargetView rtvs[2];
rtvs[0].Initialize(texture0.GetID());
rtvs[1].Initialize(texture1.GetID());
unsigned int fbs[] = { rtvs[0].GetFramebuffer(), rtvs[1].GetFramebuffer() };
int draws[] = { 0, 1 };
rtvs[0].Bind(2, fbs, draws);
glClear(GL_COLOR_BUFFER_BIT);
```

View File

@@ -0,0 +1,102 @@
# OpenGLSampler
OpenGL 采样器实现。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLSampler.h>
```
## 继承关系
```
RHISampler (interface)
└── OpenGLSampler (implementation)
```
## 枚举
### SamplerWrapMode
| 值 | OpenGL 常量 |
|----|-------------|
| `Repeat` | `GL_REPEAT` |
| `MirroredRepeat` | `GL_MIRRORED_REPEAT` |
| `ClampToEdge` | `GL_CLAMP_TO_EDGE` |
| `ClampToBorder` | `GL_CLAMP_TO_BORDER` |
### SamplerFilter
| 值 | OpenGL 常量 |
|----|-------------|
| `Nearest` | `GL_NEAREST` |
| `Linear` | `GL_LINEAR` |
| `NearestMipmapNearest` | `GL_NEAREST_MIPMAP_NEAREST` |
| `LinearMipmapNearest` | `GL_LINEAR_MIPMAP_NEAREST` |
| `NearestMipmapLinear` | `GL_NEAREST_MIPMAP_LINEAR` |
| `LinearMipmapLinear` | `GL_LINEAR_MIPMAP_LINEAR` |
### SamplerCompareMode
| 值 | OpenGL 常量 |
|----|-------------|
| `None` | `GL_NONE` |
| `CompareToRef` | `GL_COMPARE_REF_TO_TEXTURE` |
## OpenGLSamplerDesc
```cpp
struct OpenGLSamplerDesc {
SamplerFilter minFilter = SamplerFilter::LinearMipmapLinear;
SamplerFilter magFilter = SamplerFilter::Linear;
SamplerWrapMode wrapS = SamplerWrapMode::Repeat;
SamplerWrapMode wrapT = SamplerWrapMode::Repeat;
SamplerWrapMode wrapR = SamplerWrapMode::Repeat;
SamplerCompareMode compareMode = SamplerCompareMode::None;
int compareFunc = 0;
float maxAnisotropy = 1.0f;
float minLod = -1000.0f;
float maxLod = 1000.0f;
};
```
## 公共成员函数
#### `OpenGLSampler()`
#### `~OpenGLSampler() override`
#### `bool Initialize(const OpenGLSamplerDesc& desc)`
#### `void Shutdown() override`
#### `void Bind(unsigned int unit) override`
#### `void Unbind(unsigned int unit) override`
#### `unsigned int GetID() const`
#### `void* GetNativeHandle() override`
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_sampler` | `unsigned int` | GL sampler ID |
| `m_desc` | `OpenGLSamplerDesc` | 采样器描述 |
## 使用示例
```cpp
OpenGLSampler sampler;
OpenGLSamplerDesc desc;
desc.minFilter = SamplerFilter::LinearMipmapLinear;
desc.magFilter = SamplerFilter::Linear;
desc.wrapS = desc.wrapT = SamplerWrapMode::Repeat;
desc.maxAnisotropy = 16.0f;
sampler.Initialize(desc);
sampler.Bind(0);
glBindTextureUnit(0, texture.GetID());
```

View File

@@ -0,0 +1,151 @@
# OpenGLShader
OpenGL 着色器实现,封装 shader program。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLShader.h>
```
## 继承关系
```
RHIShader (interface)
└── OpenGLShader (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `OpenGLShader()`
#### `~OpenGLShader() override`
### RHI 接口实现
#### `bool CompileFromFile(const wchar_t* filePath, const char* entryPoint, const char* target) override`
从文件编译(适配 RHI 接口,`target` 被忽略)。
#### `bool Compile(const void* sourceData, size_t sourceSize, const char* entryPoint, const char* target) override`
从内存编译。
#### `void Shutdown() override`
### OpenGL 特有编译方法
#### `bool CompileFromFile(const char* vertexPath, const char* fragmentPath)`
编译顶点+片元着色器。
#### `bool CompileFromFile(const char* vertexPath, const char* fragmentPath, const char* geometryPath)`
编译 VS + GS + FS。
#### `bool Compile(const char* vertexSource, const char* fragmentSource)`
从源码编译 VS + FS。
#### `bool Compile(const char* vertexSource, const char* fragmentSource, const char* geometrySource)`
#### `bool CompileCompute(const char* computeSource)`
编译计算着色器。
#### `bool Compile(const char* source, ShaderType type)`
按类型编译单个着色器。
### 绑定
#### `void Use() const`
使用此 program。
#### `void Bind() override { Use(); }`
#### `void Unbind() override`
### Uniform 设置
#### `void SetInt(const char* name, int value) override`
#### `void SetIntArray(const char* name, const int* values, unsigned int count)`
#### `void SetFloat(const char* name, float value) override`
#### `void SetFloatArray(const char* name, const float* values, unsigned int count)`
#### `void SetVec3(const char* name, float x, float y, float z) override`
#### `void SetVec3(const char* name, const float* values)`
#### `void SetVec4(const char* name, float x, float y, float z, float w) override`
#### `void SetVec4(const char* name, const float* values)`
#### `void SetMat2(const char* name, const float* value)`
#### `void SetMat3(const char* name, const float* value)`
#### `void SetMat4(const char* name, const float* value) override`
#### `void SetMat4Array(const char* name, const float* values, unsigned int count)`
### 属性
#### `int GetUniformLocation(const char* name) const`
获取 uniform location。
#### `unsigned int GetID() const`
获取 GL program ID。
#### `void* GetNativeHandle() override`
#### `bool IsValid() const override`
检查 program 是否有效。
#### `ShaderType GetType() const override`
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_program` | `unsigned int` | GL program ID |
| `m_type` | `ShaderType` | 着色器类型 |
## 私有方法
#### `bool CheckCompileErrors(unsigned int shader, const char* type)`
检查单个 shader 编译错误。
#### `bool CheckLinkErrors(unsigned int program)`
检查 program 链接错误。
## 使用示例
```cpp
// Simple shader
OpenGLShader shader;
shader.Compile(R"(
#version 450 core
layout(location=0) in vec3 aPos;
void main() { gl_Position = vec4(aPos, 1.0); }
)",
R"(
#version 450 core
out vec4 FragColor;
void main() { FragColor = vec4(1.0); }
)",
"vs", "fs");
shader.Use();
shader.SetMat4("u_model", glm::value_ptr(model));
shader.SetVec3("u_color", 1.0f, 0.0f, 0.0f);
shader.SetInt("u_texture", 0);
// From files
OpenGLShader shader2;
shader2.CompileFromFile("shaders/Default.vert", "shaders/Default.frag");
```
## 备注
- 使用 GLSL 450 core profile
- 编译/链接错误通过日志输出
- `GetUniformLocation` 返回 -1 表示 uniform 不存在

View File

@@ -0,0 +1,138 @@
# OpenGLSwapChain
OpenGL 交换链实现,基于 GLFW 窗口和双缓冲。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLSwapChain.h>
```
## 枚举
### PresentMode
| 值 | 描述 |
|----|------|
| `Immediate` | 立即呈现,无垂直同步 |
| `VSync` | 等待垂直同步 |
| `Mailbox` | 邮箱模式(渲染时不阻塞) |
| `Fifo` | 标准 FIFO 队列(默认) |
### SurfaceFormat
| 值 | 描述 |
|----|------|
| `RGBA8` | 8-bit RGBA |
| `RGBA16F` | 16-bit float RGBA |
| `RGBA32F` | 32-bit float RGBA |
| `BGRA8` | BGRA 格式 |
## 继承关系
```
RHISwapChain (interface)
└── OpenGLSwapChain (implementation)
```
## 公共成员函数
### 构造函数与析构函数
#### `OpenGLSwapChain()`
#### `~OpenGLSwapChain() override`
### 初始化
#### `bool Initialize(GLFWwindow* window, bool vsync = true)`
初始化交换链。
#### `bool Initialize(GLFWwindow* window, int width, int height, PresentMode mode = PresentMode::VSync)`
#### `void Shutdown() override`
### 呈现操作
#### `void Present(uint32_t syncInterval = 1, uint32_t flags = 0) override`
呈现帧。
- `syncInterval`: 垂直同步间隔
#### `void SwapBuffers()`
直接交换缓冲区。
### 尺寸管理
#### `void Resize(uint32_t width, uint32_t height) override`
#### `void SetFramebufferSize(int width, int height)`
### 垂直同步
#### `void SetVSync(bool enabled)`
设置垂直同步。
#### `bool IsVSync() const`
检查是否启用垂直同步。
### 全屏
#### `void SetFullscreen(bool fullscreen) override`
#### `bool IsFullscreen() const override`
### 窗口事件
#### `bool ShouldClose() const override`
#### `void SetShouldClose(bool shouldClose) override`
#### `void PollEvents() override`
### 缓冲区查询
#### `uint32_t GetCurrentBackBufferIndex() const override`
返回 0OpenGL 单缓冲区索引)。
#### `RHITexture* GetCurrentBackBuffer() override`
返回 `nullptr`OpenGL 使用默认 framebuffer
### 属性
#### `int GetWidth() const`
#### `int GetHeight() const`
#### `int GetFramebufferWidth() const`
#### `int GetFramebufferHeight() const`
#### `GLFWwindow* GetWindow() const`
#### `void* GetNativeHandle() override`
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_window` | `GLFWwindow*` | GLFW 窗口 |
| `m_width/height` | `int` | 窗口尺寸 |
| `m_framebufferWidth/height` | `int` | 帧缓冲尺寸 (DPI aware) |
| `m_vsync` | `bool` | 是否垂直同步 |
| `m_presentMode` | `PresentMode` | 呈现模式 |
## 使用示例
```cpp
OpenGLSwapChain swapChain;
swapChain.Initialize(window, true);
while (!swapChain.ShouldClose()) {
swapChain.PollEvents();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Render...
swapChain.Present(1);
}
```

View File

@@ -0,0 +1,149 @@
# OpenGLTexture
OpenGL 纹理的实现,封装 OpenGL texture object。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLTexture.h>
```
## 继承关系
```
RHITexture (interface)
└── OpenGLTexture (implementation)
```
## 枚举
### OpenGLTextureType
| 值 | 描述 |
|----|------|
| `Texture1D` | 1D 纹理 |
| `Texture2D` | 2D 纹理 |
| `Texture2DArray` | 2D 纹理数组 |
| `Texture3D` | 3D 纹理 |
| `TextureCube` | 立方体贴图 |
| `TextureCubeArray` | 立方体贴图数组 |
### OpenGLFormat / OpenGLInternalFormat
| OpenGLFormat | OpenGLInternalFormat | 描述 |
|--------------|---------------------|------|
| `R8` | `1` | 单通道 8-bit |
| `RG8` | `2` | 双通道 8-bit |
| `RGBA8` | `4` | 四通道 8-bit |
| `RGBA16F` | `11` | 四通道 16-bit float |
| `RGBA32F` | `16` | 四通道 32-bit float |
| `Depth24Stencil8` | `38` | 24-bit depth + 8-bit stencil |
| `Depth32F` | `31` | 32-bit float depth |
| `CompressedDXT1` | `21` | DXT1 压缩 |
| `CompressedDXT5` | `22` | DXT5 压缩 |
## 公共成员函数
### 构造函数与析构函数
#### `OpenGLTexture()`
#### `~OpenGLTexture() override`
### 初始化
#### `bool Initialize(OpenGLTextureType type, int width, int height, int depth, int mipLevels, OpenGLFormat format, const void* data = nullptr)`
通用初始化。
#### `bool Initialize2D(int width, int height, int channels, const void* data, bool generateMipmap = true)`
便捷的 2D 纹理初始化。
- `channels`: 通道数 (1-4)
#### `bool InitializeCubeMap(int size, int mipLevels, OpenGLFormat format, const void* data = nullptr)`
初始化立方体贴图。
#### `bool LoadFromFile(const char* path, bool flipVertical = true)`
从图片文件加载纹理(需要 stb_image
#### `void Shutdown() override`
### 绑定操作
#### `void Bind(int slot = 0) const`
绑定纹理到纹理单元。
#### `void Unbind() const`
#### `void BindImage(int slot, bool read, bool write) const`
绑定为 image texture用于 compute shader
### 纹理操作
#### `void GenerateMipmap()`
生成 Mipmap。
#### `void SetFiltering(int minFilter, int magFilter)`
设置过滤模式。
#### `void SetWrapping(int wrapS, int wrapT, int wrapR = -1)`
设置纹理环绕模式。
### 属性
#### `unsigned int GetID() const`
获取 OpenGL texture ID。
#### `OpenGLTextureType GetOpenGLType() const`
获取纹理类型。
#### `uint32_t GetWidth() const override`
#### `uint32_t GetHeight() const override`
#### `uint32_t GetDepth() const override`
#### `uint32_t GetMipLevels() const override`
#### `TextureType GetTextureType() const override`
转换为 RHI TextureType。
#### `void* GetNativeHandle() override`
#### `Format GetFormat() const override / void SetFormat(Format format)`
#### `const std::string& GetName() const override / void SetName(...)`
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_texture` | `unsigned int` | GL texture ID |
| `m_type` | `OpenGLTextureType` | 纹理类型 |
| `m_width/height/depth` | `int` | 尺寸 |
| `m_mipLevels` | `int` | Mipmap 级别 |
| `m_channels` | `int` | 通道数 |
| `m_format` | `Format` | RHI 格式 |
| `m_name` | `std::string` | 名称 |
## 使用示例
```cpp
// Load from file
OpenGLTexture diffuse;
diffuse.LoadFromFile("textures/diffuse.png");
// Create from data
OpenGLTexture texture;
unsigned char pixels[] = { ... };
texture.Initialize2D(512, 512, 4, pixels);
texture.SetFiltering(GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR);
texture.SetWrapping(GL_REPEAT, GL_REPEAT);
texture.GenerateMipmap();
// Bind
texture.Bind(0);
glBindTextureUnit(0, texture.GetID());
// Compute image binding
texture.BindImage(0, true, false);
```

View File

@@ -0,0 +1,88 @@
# OpenGLVertexArray
OpenGL 顶点数组对象 (VAO) 封装。
## 头文件
```cpp
#include <XCEngine/RHI/OpenGL/OpenGLVertexArray.h>
```
## VertexAttribute
```cpp
struct VertexAttribute {
unsigned int index; // 属性索引 (layout location)
int count; // 组件数量 (1-4)
unsigned int type; // GL 类型 (GL_FLOAT, etc.)
bool normalized; // 是否归一化
size_t stride; // 顶点步长
size_t offset; // 属性偏移
};
```
## 公共成员函数
#### `OpenGLVertexArray()`
#### `~OpenGLVertexArray()`
#### `bool Initialize()`
#### `void AddVertexBuffer(unsigned int buffer, const VertexAttribute& attribute)`
#### `void SetIndexBuffer(unsigned int buffer, unsigned int type)`
#### `void Shutdown()`
#### `void Bind() const`
#### `void Unbind() const`
#### `unsigned int GetID() const`
#### `unsigned int GetIndexBuffer() const`
#### `unsigned int GetIndexCount() const`
## 内部成员
| 成员 | 类型 | 描述 |
|------|------|------|
| `m_vao` | `unsigned int` | GL VAO ID |
| `m_indexBuffer` | `unsigned int` | 索引缓冲区 |
| `m_indexCount` | `unsigned int` | 索引数量 |
| `m_vertexBufferCount` | `int` | 顶点缓冲区数量 |
## 使用示例
```cpp
OpenGLVertexArray vao;
vao.Initialize();
// Position attribute
VertexAttribute pos;
pos.index = 0;
pos.count = 3;
pos.type = GL_FLOAT;
pos.normalized = false;
pos.stride = sizeof(Vertex);
pos.offset = 0;
vao.AddVertexBuffer(vb.GetID(), pos);
// UV attribute
VertexAttribute uv;
uv.index = 1;
uv.count = 2;
uv.type = GL_FLOAT;
uv.normalized = false;
uv.stride = sizeof(Vertex);
uv.offset = sizeof(float) * 3;
vao.AddVertexBuffer(vb.GetID(), uv);
// Index buffer
vao.SetIndexBuffer(ib.GetID(), GL_UNSIGNED_SHORT);
vao.Bind();
glDrawElements(GL_TRIANGLES, vao.GetIndexCount(), GL_UNSIGNED_SHORT, 0);
```

109
docs/api/rhi/rhi-buffer.md Normal file
View File

@@ -0,0 +1,109 @@
# RHIBuffer
**命名空间**: `XCEngine::RHI`
**类型**: `class` (abstract)
**描述**: GPU 缓冲区资源抽象接口,用于管理顶点缓冲、索引缓冲、常量缓冲等 GPU 内存资源。
## 概述
`RHIBuffer` 封装了 GPU 缓冲区的创建、数据上传、状态管理等操作。支持多种缓冲区类型,包括顶点缓冲、索引缓冲、常量缓冲等。
## 公共方法
### 生命周期
| 方法 | 描述 |
|------|------|
| `virtual void Shutdown()` | 释放缓冲区资源 |
### 数据操作
| 方法 | 描述 |
|------|------|
| `virtual void* Map()` | 映射缓冲区内存到 CPU 可访问 |
| `virtual void Unmap()` | 取消内存映射 |
| `virtual void SetData(const void* data, size_t size, size_t offset = 0)` | 设置缓冲区数据 |
### 属性访问
| 方法 | 描述 |
|------|------|
| `virtual uint64_t GetSize() const` | 获取缓冲区大小(字节) |
| `virtual BufferType GetBufferType() const` | 获取缓冲区类型 |
| `virtual void SetBufferType(BufferType type)` | 设置缓冲区类型 |
| `virtual uint32_t GetStride() const` | 获取单个元素的字节大小 |
| `virtual void SetStride(uint32_t stride)` | 设置元素字节大小 |
### 状态管理
| 方法 | 描述 |
|------|------|
| `virtual ResourceStates GetState() const` | 获取当前资源状态 |
| `virtual void SetState(ResourceStates state)` | 设置资源状态 |
### 其他
| 方法 | 描述 |
|------|------|
| `virtual void* GetNativeHandle()` | 获取原生 API 句柄 |
| `virtual const std::string& GetName() const` | 获取缓冲区名称 |
| `virtual void SetName(const std::string& name)` | 设置缓冲区名称(用于调试) |
## 缓冲区类型 (BufferType)
| 枚举值 | 描述 |
|--------|------|
| `BufferType::Vertex` | 顶点缓冲 |
| `BufferType::Index` | 索引缓冲 |
| `BufferType::Constant` | 常量缓冲 (Constant Buffer) |
| `BufferType::ReadBack` | 回读缓冲(用于 CPU 读取 GPU 数据) |
| `BufferType::Indirect` | 间接执行缓冲 |
| `BufferType::RaytracingAccelerationStructure` | 光线追踪加速结构 |
| `BufferType::ShaderBindingTable` | 光线追踪着色器绑定表 |
## 资源状态 (ResourceStates)
| 状态 | 描述 |
|------|------|
| `Common` | 默认状态 |
| `VertexAndConstantBuffer` | 顶点/常量缓冲 |
| `IndexBuffer` | 索引缓冲 |
| `RenderTarget` | 渲染目标 |
| `UnorderedAccess` | 无序访问 |
| `DepthWrite` | 深度写入 |
| `DepthRead` | 深度读取 |
| `CopySrc` | 复制源 |
| `CopyDst` | 复制目标 |
| `Present` | 呈现状态 |
## 使用示例
```cpp
// 创建设备后创建顶点缓冲
BufferDesc desc;
desc.size = sizeof(Vertex) * vertexCount;
desc.stride = sizeof(Vertex);
desc.bufferType = (uint32_t)BufferType::Vertex;
desc.flags = 0;
RHIBuffer* vertexBuffer = device->CreateBuffer(desc);
// 上传顶点数据
void* mapped = vertexBuffer->Map();
memcpy(mapped, vertexData, desc.size);
vertexBuffer->Unmap();
// 设置资源状态为顶点缓冲
vertexBuffer->SetState(ResourceStates::VertexAndConstantBuffer);
// 使用完毕后关闭
vertexBuffer->Shutdown();
```
## 相关文档
- [RHIDevice](./rhi-device.md) - 创建设备
- [RHITexture](./rhi-texture.md) - 纹理资源
- [RHICommandList](./rhi-command-list.md) - 命令列表

View File

@@ -0,0 +1,88 @@
# RHICapabilities
**命名空间**: `XCEngine::RHI`
**类型**: `struct`
**描述**: GPU 设备能力结构体,描述了当前图形设备支持的各种功能和限制。
## 概述
`RHICapabilities` 存储了设备的能力信息,包括对各种图形特性的支持情况和资源尺寸限制。
## 公共成员
### 特性支持
| 成员 | 类型 | 描述 |
|------|------|------|
| `bSupportsRayTracing` | `bool` | 支持光线追踪 |
| `bSupportsMeshShaders` | `bool` | 支持 Mesh 着色器 |
| `bSupportsExplicitMultiThreading` | `bool` | 支持显式多线程 |
| `bSupportsGeometryShaders` | `bool` | 支持几何着色器 |
| `bSupportsTessellation` | `bool` | 支持曲面细分 |
| `bSupportsComputeShaders` | `bool` | 支持计算着色器 |
| `bSupportsDepthBoundsTest` | `bool` | 支持深度范围测试 |
| `bSupportsAlphaToCoverage` | `bool` | 支持 Alpha 到覆盖 |
| `bSupportsIndependentBlend` | `bool` | 支持独立混合 |
| `bSupportsLogicOps` | `bool` | 支持逻辑操作 |
| `bSupportsMultiViewport` | `bool` | 支持多视口 |
| `bSupportsConservativeRasterization` | `bool` | 支持保守光栅化 |
| `bSupportsProgrammableSamplePositions` | `bool` | 支持可编程采样位置 |
### 资源限制
| 成员 | 类型 | 描述 |
|------|------|------|
| `maxTexture2DSize` | `uint32_t` | 最大 2D 纹理尺寸 |
| `maxTexture3DSize` | `uint32_t` | 最大 3D 纹理尺寸 |
| `maxTextureCubeSize` | `uint32_t` | 最大立方体贴图尺寸 |
| `maxRenderTargets` | `uint32_t` | 最大渲染目标数量 |
| `maxViewports` | `uint32_t` | 最大视口数量 |
| `maxVertexAttribs` | `uint32_t` | 最大顶点属性数量 |
| `maxConstantBufferSize` | `uint32_t` | 最大常量缓冲大小 |
| `maxAnisotropy` | `uint32_t` | 最大各向异性级别 |
| `maxColorAttachments` | `uint32_t` | 最大颜色附件数量 |
### 线/点渲染
| 成员 | 类型 | 描述 |
|------|------|------|
| `minSmoothedLineWidth` | `float` | 最小平滑线宽 |
| `maxSmoothedLineWidth` | `float` | 最大平滑线宽 |
| `minPointSize` | `float` | 最小点大小 |
| `maxPointSize` | `float` | 最大点大小 |
| `maxPointSizeAA` | `float` | 抗锯齿最大点大小 |
| `maxLineWidth` | `float` | 最大线宽 |
| `maxLineWidthAA` | `float` | 抗锯齿最大线宽 |
### 版本信息
| 成员 | 类型 | 描述 |
|------|------|------|
| `majorVersion` | `int` | 主版本号 |
| `minorVersion` | `int` | 次版本号 |
| `shaderModel` | `std::string` | 着色器模型版本 |
## 使用示例
```cpp
// 获取设备能力
const RHICapabilities& caps = device->GetCapabilities();
// 检查功能支持
if (caps.bSupportsRayTracing) {
// 启用光线追踪功能
}
if (caps.bSupportsComputeShaders) {
// 启用计算着色器功能
}
// 使用资源限制
uint32_t textureSize = std::min(requestedSize, caps.maxTexture2DSize);
```
## 相关文档
- [RHIDevice](./rhi-device.md) - 设备对象

Some files were not shown because too many files have changed in this diff Show More