From 9bad996ecf42193f7cece300cba54db4d4eed35d Mon Sep 17 00:00:00 2001 From: ssdfasd <2156608475@qq.com> Date: Wed, 18 Mar 2026 17:49:22 +0800 Subject: [PATCH] refactor: reorganize docs into plan/ and add skills/ --- docs/api/containers/container-array.md | 116 +++++ docs/api/containers/container-hashmap.md | 137 ++++++ docs/api/containers/container-overview.md | 55 +++ docs/api/containers/container-string.md | 132 +++++ docs/api/core/core-event.md | 77 +++ docs/api/core/core-filewriter.md | 75 +++ docs/api/core/core-overview.md | 94 ++++ docs/api/core/core-refcounted.md | 50 ++ docs/api/core/core-smartptr.md | 54 +++ docs/api/core/core-types.md | 49 ++ docs/api/debug/debug-consolelogsink.md | 52 ++ docs/api/debug/debug-filelogsink.md | 47 ++ docs/api/debug/debug-ilogsink.md | 47 ++ docs/api/debug/debug-logcategory.md | 46 ++ docs/api/debug/debug-logentry.md | 48 ++ docs/api/debug/debug-logger.md | 108 +++++ docs/api/debug/debug-loglevel.md | 40 ++ docs/api/debug/debug-overview.md | 83 ++++ docs/api/debug/debug-profiler.md | 117 +++++ docs/api/index.md | 94 ++++ docs/api/math/math-aabb.md | 67 +++ docs/api/math/math-bounds.md | 61 +++ docs/api/math/math-box.md | 63 +++ docs/api/math/math-color.md | 72 +++ docs/api/math/math-frustum.md | 61 +++ docs/api/math/math-h.md | 51 ++ docs/api/math/math-matrix3.md | 69 +++ docs/api/math/math-matrix4.md | 101 ++++ docs/api/math/math-overview.md | 100 ++++ docs/api/math/math-plane.md | 66 +++ docs/api/math/math-quaternion.md | 86 ++++ docs/api/math/math-ray.md | 58 +++ docs/api/math/math-rect.md | 137 ++++++ docs/api/math/math-sphere.md | 47 ++ docs/api/math/math-transform.md | 67 +++ docs/api/math/math-vector2.md | 68 +++ docs/api/math/math-vector3.md | 84 ++++ docs/api/math/math-vector4.md | 62 +++ docs/api/memory/memory-allocator.md | 74 +++ docs/api/memory/memory-linear-allocator.md | 82 ++++ docs/api/memory/memory-manager.md | 99 ++++ docs/api/memory/memory-overview.md | 72 +++ docs/api/memory/memory-pool-allocator.md | 75 +++ docs/api/memory/memory-proxy-allocator.md | 71 +++ docs/api/resources/resources-asyncloader.md | 99 ++++ docs/api/resources/resources-audioclip.md | 131 +++++ .../resources/resources-dependencygraph.md | 110 +++++ docs/api/resources/resources-filesystem.md | 118 +++++ docs/api/resources/resources-iloader.md | 112 +++++ .../api/resources/resources-importsettings.md | 164 +++++++ docs/api/resources/resources-iresource.md | 79 +++ docs/api/resources/resources-material.md | 146 ++++++ docs/api/resources/resources-mesh.md | 148 ++++++ docs/api/resources/resources-overview.md | 82 ++++ docs/api/resources/resources-resourcecache.md | 98 ++++ .../api/resources/resources-resourcehandle.md | 100 ++++ .../resources/resources-resourcemanager.md | 166 +++++++ docs/api/resources/resources-resourcetypes.md | 101 ++++ docs/api/resources/resources-shader.md | 149 ++++++ docs/api/resources/resources-texture.md | 152 ++++++ docs/api/rhi/d3d12/d3d12-buffer.md | 178 +++++++ docs/api/rhi/d3d12/d3d12-command-allocator.md | 80 +++ docs/api/rhi/d3d12/d3d12-command-list.md | 269 ++++++++++ docs/api/rhi/d3d12/d3d12-command-queue.md | 113 +++++ docs/api/rhi/d3d12/d3d12-common.md | 124 +++++ .../rhi/d3d12/d3d12-constant-buffer-view.md | 47 ++ .../api/rhi/d3d12/d3d12-depth-stencil-view.md | 52 ++ docs/api/rhi/d3d12/d3d12-descriptor-heap.md | 114 +++++ docs/api/rhi/d3d12/d3d12-device.md | 169 +++++++ docs/api/rhi/d3d12/d3d12-enum.md | 154 ++++++ docs/api/rhi/d3d12/d3d12-fence.md | 106 ++++ docs/api/rhi/d3d12/d3d12-overview.md | 78 +++ docs/api/rhi/d3d12/d3d12-pipeline-state.md | 123 +++++ docs/api/rhi/d3d12/d3d12-query-heap.md | 82 ++++ .../api/rhi/d3d12/d3d12-render-target-view.md | 68 +++ docs/api/rhi/d3d12/d3d12-root-signature.md | 132 +++++ docs/api/rhi/d3d12/d3d12-sampler.md | 64 +++ docs/api/rhi/d3d12/d3d12-screenshot.md | 50 ++ .../rhi/d3d12/d3d12-shader-resource-view.md | 53 ++ docs/api/rhi/d3d12/d3d12-shader.md | 108 +++++ docs/api/rhi/d3d12/d3d12-swap-chain.md | 136 ++++++ docs/api/rhi/d3d12/d3d12-texture.md | 169 +++++++ docs/api/rhi/d3d12/d3d12-types.md | 74 +++ .../rhi/d3d12/d3d12-unordered-access-view.md | 45 ++ docs/api/rhi/opengl/opengl-buffer.md | 135 ++++++ docs/api/rhi/opengl/opengl-command-list.md | 308 ++++++++++++ docs/api/rhi/opengl/opengl-command-queue.md | 63 +++ .../rhi/opengl/opengl-depth-stencil-view.md | 105 ++++ docs/api/rhi/opengl/opengl-device.md | 109 +++++ docs/api/rhi/opengl/opengl-fence.md | 99 ++++ docs/api/rhi/opengl/opengl-overview.md | 87 ++++ docs/api/rhi/opengl/opengl-pipeline-state.md | 229 +++++++++ .../rhi/opengl/opengl-render-target-view.md | 106 ++++ docs/api/rhi/opengl/opengl-sampler.md | 102 ++++ docs/api/rhi/opengl/opengl-shader.md | 151 ++++++ docs/api/rhi/opengl/opengl-swap-chain.md | 138 ++++++ docs/api/rhi/opengl/opengl-texture.md | 149 ++++++ docs/api/rhi/opengl/opengl-vertex-array.md | 88 ++++ docs/api/rhi/rhi-buffer.md | 109 +++++ docs/api/rhi/rhi-capabilities.md | 88 ++++ docs/api/rhi/rhi-command-list.md | 179 +++++++ docs/api/rhi/rhi-command-queue.md | 82 ++++ docs/api/rhi/rhi-descriptor-pool.md | 51 ++ docs/api/rhi/rhi-device.md | 89 ++++ docs/api/rhi/rhi-enums.md | 458 ++++++++++++++++++ docs/api/rhi/rhi-factory.md | 46 ++ docs/api/rhi/rhi-fence.md | 68 +++ docs/api/rhi/rhi-overview.md | 122 +++++ docs/api/rhi/rhi-pipeline-layout.md | 40 ++ docs/api/rhi/rhi-pipeline-state.md | 47 ++ docs/api/rhi/rhi-sampler.md | 101 ++++ docs/api/rhi/rhi-shader.md | 115 +++++ docs/api/rhi/rhi-swap-chain.md | 94 ++++ docs/api/rhi/rhi-texture.md | 102 ++++ docs/api/rhi/rhi-types.md | 394 +++++++++++++++ docs/api/threading/threading-lambdatask.md | 53 ++ docs/api/threading/threading-mutex.md | 51 ++ docs/api/threading/threading-overview.md | 74 +++ docs/api/threading/threading-readwritelock.md | 53 ++ docs/api/threading/threading-spinlock.md | 46 ++ docs/api/threading/threading-task-group.md | 86 ++++ docs/api/threading/threading-task-system.md | 110 +++++ docs/api/threading/threading-task.md | 96 ++++ .../threading/threading-tasksystemconfig.md | 33 ++ docs/api/threading/threading-thread.md | 77 +++ docs/{ => plan}/D3D12后端测试设计.md | 0 docs/{ => plan}/OpenGL后端测试设计.md | 0 docs/{ => plan}/OpenGL测试实施计划.md | 0 docs/{ => plan}/RHI抽象层设计与实现.md | 0 docs/{ => plan}/TESTING.md | 0 docs/{ => plan}/Unity SRP API参考文档.md | 0 docs/{ => plan}/XCEngine渲染引擎架构设计.md | 0 docs/{ => plan}/XCGameEngine架构设计.md | 0 docs/{ => plan}/仿Unity RHI架构设计.md | 0 .../DXR_Volumetric_Rendering_Research_Report.md | 0 .../开题报告和任务书/任务书-王子文.docx | Bin .../开题报告和任务书/完整开题报告.md | 0 .../开题报告和任务书/开题报告-王子文.doc | 0 docs/{ => plan}/旧版题目/开题报告-王子文.doc | 0 docs/{ => plan}/旧版题目/开题报告-王子文.md | 0 docs/{ => plan}/深入方向规划.md | 0 skills/doc-api-manager/SKILL.md | 341 +++++++++++++ skills/doc-blueprint-manager/SKILL.md | 332 +++++++++++++ 143 files changed, 13263 insertions(+) create mode 100644 docs/api/containers/container-array.md create mode 100644 docs/api/containers/container-hashmap.md create mode 100644 docs/api/containers/container-overview.md create mode 100644 docs/api/containers/container-string.md create mode 100644 docs/api/core/core-event.md create mode 100644 docs/api/core/core-filewriter.md create mode 100644 docs/api/core/core-overview.md create mode 100644 docs/api/core/core-refcounted.md create mode 100644 docs/api/core/core-smartptr.md create mode 100644 docs/api/core/core-types.md create mode 100644 docs/api/debug/debug-consolelogsink.md create mode 100644 docs/api/debug/debug-filelogsink.md create mode 100644 docs/api/debug/debug-ilogsink.md create mode 100644 docs/api/debug/debug-logcategory.md create mode 100644 docs/api/debug/debug-logentry.md create mode 100644 docs/api/debug/debug-logger.md create mode 100644 docs/api/debug/debug-loglevel.md create mode 100644 docs/api/debug/debug-overview.md create mode 100644 docs/api/debug/debug-profiler.md create mode 100644 docs/api/index.md create mode 100644 docs/api/math/math-aabb.md create mode 100644 docs/api/math/math-bounds.md create mode 100644 docs/api/math/math-box.md create mode 100644 docs/api/math/math-color.md create mode 100644 docs/api/math/math-frustum.md create mode 100644 docs/api/math/math-h.md create mode 100644 docs/api/math/math-matrix3.md create mode 100644 docs/api/math/math-matrix4.md create mode 100644 docs/api/math/math-overview.md create mode 100644 docs/api/math/math-plane.md create mode 100644 docs/api/math/math-quaternion.md create mode 100644 docs/api/math/math-ray.md create mode 100644 docs/api/math/math-rect.md create mode 100644 docs/api/math/math-sphere.md create mode 100644 docs/api/math/math-transform.md create mode 100644 docs/api/math/math-vector2.md create mode 100644 docs/api/math/math-vector3.md create mode 100644 docs/api/math/math-vector4.md create mode 100644 docs/api/memory/memory-allocator.md create mode 100644 docs/api/memory/memory-linear-allocator.md create mode 100644 docs/api/memory/memory-manager.md create mode 100644 docs/api/memory/memory-overview.md create mode 100644 docs/api/memory/memory-pool-allocator.md create mode 100644 docs/api/memory/memory-proxy-allocator.md create mode 100644 docs/api/resources/resources-asyncloader.md create mode 100644 docs/api/resources/resources-audioclip.md create mode 100644 docs/api/resources/resources-dependencygraph.md create mode 100644 docs/api/resources/resources-filesystem.md create mode 100644 docs/api/resources/resources-iloader.md create mode 100644 docs/api/resources/resources-importsettings.md create mode 100644 docs/api/resources/resources-iresource.md create mode 100644 docs/api/resources/resources-material.md create mode 100644 docs/api/resources/resources-mesh.md create mode 100644 docs/api/resources/resources-overview.md create mode 100644 docs/api/resources/resources-resourcecache.md create mode 100644 docs/api/resources/resources-resourcehandle.md create mode 100644 docs/api/resources/resources-resourcemanager.md create mode 100644 docs/api/resources/resources-resourcetypes.md create mode 100644 docs/api/resources/resources-shader.md create mode 100644 docs/api/resources/resources-texture.md create mode 100644 docs/api/rhi/d3d12/d3d12-buffer.md create mode 100644 docs/api/rhi/d3d12/d3d12-command-allocator.md create mode 100644 docs/api/rhi/d3d12/d3d12-command-list.md create mode 100644 docs/api/rhi/d3d12/d3d12-command-queue.md create mode 100644 docs/api/rhi/d3d12/d3d12-common.md create mode 100644 docs/api/rhi/d3d12/d3d12-constant-buffer-view.md create mode 100644 docs/api/rhi/d3d12/d3d12-depth-stencil-view.md create mode 100644 docs/api/rhi/d3d12/d3d12-descriptor-heap.md create mode 100644 docs/api/rhi/d3d12/d3d12-device.md create mode 100644 docs/api/rhi/d3d12/d3d12-enum.md create mode 100644 docs/api/rhi/d3d12/d3d12-fence.md create mode 100644 docs/api/rhi/d3d12/d3d12-overview.md create mode 100644 docs/api/rhi/d3d12/d3d12-pipeline-state.md create mode 100644 docs/api/rhi/d3d12/d3d12-query-heap.md create mode 100644 docs/api/rhi/d3d12/d3d12-render-target-view.md create mode 100644 docs/api/rhi/d3d12/d3d12-root-signature.md create mode 100644 docs/api/rhi/d3d12/d3d12-sampler.md create mode 100644 docs/api/rhi/d3d12/d3d12-screenshot.md create mode 100644 docs/api/rhi/d3d12/d3d12-shader-resource-view.md create mode 100644 docs/api/rhi/d3d12/d3d12-shader.md create mode 100644 docs/api/rhi/d3d12/d3d12-swap-chain.md create mode 100644 docs/api/rhi/d3d12/d3d12-texture.md create mode 100644 docs/api/rhi/d3d12/d3d12-types.md create mode 100644 docs/api/rhi/d3d12/d3d12-unordered-access-view.md create mode 100644 docs/api/rhi/opengl/opengl-buffer.md create mode 100644 docs/api/rhi/opengl/opengl-command-list.md create mode 100644 docs/api/rhi/opengl/opengl-command-queue.md create mode 100644 docs/api/rhi/opengl/opengl-depth-stencil-view.md create mode 100644 docs/api/rhi/opengl/opengl-device.md create mode 100644 docs/api/rhi/opengl/opengl-fence.md create mode 100644 docs/api/rhi/opengl/opengl-overview.md create mode 100644 docs/api/rhi/opengl/opengl-pipeline-state.md create mode 100644 docs/api/rhi/opengl/opengl-render-target-view.md create mode 100644 docs/api/rhi/opengl/opengl-sampler.md create mode 100644 docs/api/rhi/opengl/opengl-shader.md create mode 100644 docs/api/rhi/opengl/opengl-swap-chain.md create mode 100644 docs/api/rhi/opengl/opengl-texture.md create mode 100644 docs/api/rhi/opengl/opengl-vertex-array.md create mode 100644 docs/api/rhi/rhi-buffer.md create mode 100644 docs/api/rhi/rhi-capabilities.md create mode 100644 docs/api/rhi/rhi-command-list.md create mode 100644 docs/api/rhi/rhi-command-queue.md create mode 100644 docs/api/rhi/rhi-descriptor-pool.md create mode 100644 docs/api/rhi/rhi-device.md create mode 100644 docs/api/rhi/rhi-enums.md create mode 100644 docs/api/rhi/rhi-factory.md create mode 100644 docs/api/rhi/rhi-fence.md create mode 100644 docs/api/rhi/rhi-overview.md create mode 100644 docs/api/rhi/rhi-pipeline-layout.md create mode 100644 docs/api/rhi/rhi-pipeline-state.md create mode 100644 docs/api/rhi/rhi-sampler.md create mode 100644 docs/api/rhi/rhi-shader.md create mode 100644 docs/api/rhi/rhi-swap-chain.md create mode 100644 docs/api/rhi/rhi-texture.md create mode 100644 docs/api/rhi/rhi-types.md create mode 100644 docs/api/threading/threading-lambdatask.md create mode 100644 docs/api/threading/threading-mutex.md create mode 100644 docs/api/threading/threading-overview.md create mode 100644 docs/api/threading/threading-readwritelock.md create mode 100644 docs/api/threading/threading-spinlock.md create mode 100644 docs/api/threading/threading-task-group.md create mode 100644 docs/api/threading/threading-task-system.md create mode 100644 docs/api/threading/threading-task.md create mode 100644 docs/api/threading/threading-tasksystemconfig.md create mode 100644 docs/api/threading/threading-thread.md rename docs/{ => plan}/D3D12后端测试设计.md (100%) rename docs/{ => plan}/OpenGL后端测试设计.md (100%) rename docs/{ => plan}/OpenGL测试实施计划.md (100%) rename docs/{ => plan}/RHI抽象层设计与实现.md (100%) rename docs/{ => plan}/TESTING.md (100%) rename docs/{ => plan}/Unity SRP API参考文档.md (100%) rename docs/{ => plan}/XCEngine渲染引擎架构设计.md (100%) rename docs/{ => plan}/XCGameEngine架构设计.md (100%) rename docs/{ => plan}/仿Unity RHI架构设计.md (100%) rename docs/{ => plan}/开题报告和任务书/DXR_Volumetric_Rendering_Research_Report.md (100%) rename docs/{ => plan}/开题报告和任务书/任务书-王子文.docx (100%) rename docs/{ => plan}/开题报告和任务书/完整开题报告.md (100%) rename docs/{ => plan}/开题报告和任务书/开题报告-王子文.doc (100%) rename docs/{ => plan}/旧版题目/开题报告-王子文.doc (100%) rename docs/{ => plan}/旧版题目/开题报告-王子文.md (100%) rename docs/{ => plan}/深入方向规划.md (100%) create mode 100644 skills/doc-api-manager/SKILL.md create mode 100644 skills/doc-blueprint-manager/SKILL.md diff --git a/docs/api/containers/container-array.md b/docs/api/containers/container-array.md new file mode 100644 index 00000000..f7065635 --- /dev/null +++ b/docs/api/containers/container-array.md @@ -0,0 +1,116 @@ +# Array + +**命名空间**: `XCEngine::Containers` + +**类型**: `class` (template) + +**描述**: 模板动态数组容器,提供自动扩容的数组实现。 + +## 概述 + +`Array` 是一个模板动态数组容器,提供了类似 `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 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 + +// 基本用法 +Containers::Array arr; +arr.PushBack(1); +arr.PushBack(2); +arr.PushBack(3); + +// 使用 initializer_list +Containers::Array 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) - 内存分配器 diff --git a/docs/api/containers/container-hashmap.md b/docs/api/containers/container-hashmap.md new file mode 100644 index 00000000..424620f4 --- /dev/null +++ b/docs/api/containers/container-hashmap.md @@ -0,0 +1,137 @@ +# HashMap + +**命名空间**: `XCEngine::Containers` + +**类型**: `class` (template) + +**描述**: 模板哈希表容器,提供键值对存储和快速查找。 + +## 概述 + +`HashMap` 是一个模板哈希表容器,实现了分离链接法的哈希表,支持键值对的插入、查找和删除操作。 + +## 公共类型 + +### Pair + +| 成员 | 类型 | 描述 | +|------|------|------| +| `first` | `Key` | 键 | +| `second` | `Value` | 值 | + +### 迭代器 + +| 别名 | 类型 | 描述 | +|------|------|------| +| `Iterator` | `typename Array::Iterator` | 迭代器类型 | +| `ConstIterator` | `typename Array::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 + +// 基本用法 +Containers::HashMap 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) - 内存分配器 diff --git a/docs/api/containers/container-overview.md b/docs/api/containers/container-overview.md new file mode 100644 index 00000000..ab5ba066 --- /dev/null +++ b/docs/api/containers/container-overview.md @@ -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 + +// 使用 Array +Containers::Array arr; +arr.PushBack(1); +arr.PushBack(2); +arr.PushBack(3); + +// 使用 String +Containers::String str; +str = "Hello, "; +str += "World!"; + +// 使用 HashMap +Containers::HashMap map; +map.Insert("key1", 100); +map.Insert("key2", 200); +int* value = map.Find("key1"); +``` + +## 相关文档 + +- [Memory 模块](../memory/memory-overview.md) - 内存分配器接口 diff --git a/docs/api/containers/container-string.md b/docs/api/containers/container-string.md new file mode 100644 index 00000000..949abe72 --- /dev/null +++ b/docs/api/containers/container-string.md @@ -0,0 +1,132 @@ +# String + +**命名空间**: `XCEngine::Containers` + +**类型**: `class` + +**描述**: 动态字符串类,提供 UTF-8 编码的字符串操作。 + +## 概述 + +`String` 是一个自定义动态字符串类,提供常见的字符串操作功能,支持拷贝构造、移动构造和多种字符串操作方法。 + +## 类型别名 + +| 别名 | 类型 | 描述 | +|------|------|------| +| `SizeType` | `size_t` | 大小类型 | + +## 常量 + +| 常量 | 值 | 描述 | +|------|-----|------| +| `static constexpr SizeType npos` | `static_cast(-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 { + size_t operator()(const XCEngine::Containers::String& str) const noexcept; + }; +} +``` + +## 使用示例 + +```cpp +#include + +// 基本用法 +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) - 哈希表 diff --git a/docs/api/core/core-event.md b/docs/api/core/core-event.md new file mode 100644 index 00000000..4997f7bc --- /dev/null +++ b/docs/api/core/core-event.md @@ -0,0 +1,77 @@ +# Event + +**命名空间**: `XCEngine::Core` + +**类型**: `class` (template) + +**描述**: 事件系统模板类,提供类型安全的多订阅者事件/委托系统。 + +## 概述 + +`Event` 是一个类型安全的事件发布-订阅系统。它支持多个回调订阅、退订和线程安全的调用。非常适合用于游戏引擎中的事件驱动通信。 + +## 模板参数 + +| 参数 | 描述 | +|------|------| +| `Args...` | 事件回调的参数类型 | + +## 类型别名 + +| 别名 | 类型 | 描述 | +|------|------|------| +| `Callback` | `std::function` | 回调函数类型 | +| `Listener` | `std::pair` | 监听器条目 | +| `Iterator` | `std::vector::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 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 模块总览 diff --git a/docs/api/core/core-filewriter.md b/docs/api/core/core-filewriter.md new file mode 100644 index 00000000..628055d3 --- /dev/null +++ b/docs/api/core/core-filewriter.md @@ -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 + +// 方式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) - 文件日志输出 diff --git a/docs/api/core/core-overview.md b/docs/api/core/core-overview.md new file mode 100644 index 00000000..6977936a --- /dev/null +++ b/docs/api/core/core-overview.md @@ -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 +using Ref = std::shared_ptr; + +template +using UniqueRef = std::unique_ptr; + +template +Ref MakeRef(Args&&... args); + +template +UniqueRef MakeUnique(Args&&... args); +``` + +## 使用示例 + +```cpp +#include + +// 使用类型别名 +Core::uint32 value = 100; +Core::byte data[4]; + +// 使用智能指针 +auto ref = MakeRef(); +auto unique = MakeUnique(); + +// 使用事件系统 +Event 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) - 内存管理 diff --git a/docs/api/core/core-refcounted.md b/docs/api/core/core-refcounted.md new file mode 100644 index 00000000..17012ab1 --- /dev/null +++ b/docs/api/core/core-refcounted.md @@ -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) - 智能指针 diff --git a/docs/api/core/core-smartptr.md b/docs/api/core/core-smartptr.md new file mode 100644 index 00000000..e06efca1 --- /dev/null +++ b/docs/api/core/core-smartptr.md @@ -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` | `std::shared_ptr` | 共享引用智能指针 | +| `Core::UniqueRef` | `std::unique_ptr` | 独占所有权的智能指针 | + +## 工厂函数 + +| 函数 | 返回值 | 描述 | +|------|--------|------| +| `Core::MakeRef(Args&&... args)` | `Ref` | 创建共享指针 | +| `Core::MakeUnique(Args&&... args)` | `UniqueRef` | 创建独占指针 | + +## 使用示例 + +```cpp +#include + +// 使用 Ref(共享指针) +Core::Ref ref = Core::MakeRef(arg1, arg2); + +// 使用 UniqueRef(独占指针) +Core::UniqueRef unique = Core::MakeUnique(); + +// 传递所有权 +Core::Ref ref2 = ref; // 引用计数 +1 + +// 检查有效性 +if (ref) { + ref->DoSomething(); +} + +// 自定义删除器 +Core::UniqueRef + file(fopen("test.txt", "r"), &fclose); +``` + +## 相关文档 + +- [RefCounted](./core-refcounted.md) - 引用计数基类 +- [Types](./core-types.md) - 类型别名 diff --git a/docs/api/core/core-types.md b/docs/api/core/core-types.md new file mode 100644 index 00000000..864c23c0 --- /dev/null +++ b/docs/api/core/core-types.md @@ -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 + +// 使用类型别名 +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) - 引用计数基类 diff --git a/docs/api/debug/debug-consolelogsink.md b/docs/api/debug/debug-consolelogsink.md new file mode 100644 index 00000000..f78f1138 --- /dev/null +++ b/docs/api/debug/debug-consolelogsink.md @@ -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(); +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) - 文件输出 diff --git a/docs/api/debug/debug-filelogsink.md b/docs/api/debug/debug-filelogsink.md new file mode 100644 index 00000000..c7566966 --- /dev/null +++ b/docs/api/debug/debug-filelogsink.md @@ -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("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) - 文件写入工具 diff --git a/docs/api/debug/debug-ilogsink.md b/docs/api/debug/debug-ilogsink.md new file mode 100644 index 00000000..f2b35229 --- /dev/null +++ b/docs/api/debug/debug-ilogsink.md @@ -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()); +``` + +## 相关文档 + +- [Logger](./debug-logger.md) - 日志记录器 +- [ConsoleLogSink](./debug-consolelogsink.md) - 控制台输出 +- [FileLogSink](./debug-filelogsink.md) - 文件输出 diff --git a/docs/api/debug/debug-logcategory.md b/docs/api/debug/debug-logcategory.md new file mode 100644 index 00000000..aa5ee886 --- /dev/null +++ b/docs/api/debug/debug-logcategory.md @@ -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) - 日志记录器 diff --git a/docs/api/debug/debug-logentry.md b/docs/api/debug/debug-logentry.md new file mode 100644 index 00000000..a8834b8c --- /dev/null +++ b/docs/api/debug/debug-logentry.md @@ -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) - 日志记录器 diff --git a/docs/api/debug/debug-logger.md b/docs/api/debug/debug-logger.md new file mode 100644 index 00000000..0224a852 --- /dev/null +++ b/docs/api/debug/debug-logger.md @@ -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 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 + +// 初始化 +Logger::Get().Initialize(); +Logger::Get().AddSink(std::make_unique()); +Logger::Get().AddSink(std::make_unique("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) - 日志级别枚举 diff --git a/docs/api/debug/debug-loglevel.md b/docs/api/debug/debug-loglevel.md new file mode 100644 index 00000000..84b844c5 --- /dev/null +++ b/docs/api/debug/debug-loglevel.md @@ -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) - 日志记录器 diff --git a/docs/api/debug/debug-overview.md b/docs/api/debug/debug-overview.md new file mode 100644 index 00000000..3bf23e15 --- /dev/null +++ b/docs/api/debug/debug-overview.md @@ -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 + +// 初始化日志系统 +Logger::Get().Initialize(); +Logger::Get().AddSink(std::make_unique()); +Logger::Get().AddSink(std::make_unique("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) - 性能分析器 diff --git a/docs/api/debug/debug-profiler.md b/docs/api/debug/debug-profiler.md new file mode 100644 index 00000000..34bac893 --- /dev/null +++ b/docs/api/debug/debug-profiler.md @@ -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) - 日志记录器 diff --git a/docs/api/index.md b/docs/api/index.md new file mode 100644 index 00000000..a6e448cc --- /dev/null +++ b/docs/api/index.md @@ -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 +#include + +// 创建 D3D12 设备 +RHI::RHIDevice* device = RHI::RHIFactory::CreateRHIDevice(RHI::RHIType::D3D12); + +// 初始化 +RHI::RHIDeviceDesc desc; +desc.windowHandle = hwnd; +device->Initialize(desc); +``` + +### 使用资源管理器 + +```cpp +#include + +// 加载纹理 +auto texture = Resources::ResourceManager::Get().Load("textures/player.png"); + +// 加载网格 +auto mesh = Resources::ResourceManager::Get().Load("models/player.fbx"); +``` + +### 日志记录 + +```cpp +#include + +// 记录日志 +XE_LOG(Debug::LogCategory::Rendering, Debug::LogLevel::Info, "Render started"); +``` + +### 数学运算 + +```cpp +#include + +// 创建变换矩阵 +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) diff --git a/docs/api/math/math-aabb.md b/docs/api/math/math-aabb.md new file mode 100644 index 00000000..b93c00ec --- /dev/null +++ b/docs/api/math/math-aabb.md @@ -0,0 +1,67 @@ +# AABB / OBB + +轴对齐包围盒 (AABB) 和有向包围盒 (OBB)。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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)) { ... } +``` diff --git a/docs/api/math/math-bounds.md b/docs/api/math/math-bounds.md new file mode 100644 index 00000000..530ab804 --- /dev/null +++ b/docs/api/math/math-bounds.md @@ -0,0 +1,61 @@ +# Bounds + +轴对齐包围盒 (AABB),中心-范围表示。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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); +``` diff --git a/docs/api/math/math-box.md b/docs/api/math/math-box.md new file mode 100644 index 00000000..8eb7748c --- /dev/null +++ b/docs/api/math/math-box.md @@ -0,0 +1,63 @@ +# Box + +带变换的有向包围盒 (OBB) 结构体。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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); +} +``` diff --git a/docs/api/math/math-color.md b/docs/api/math/math-color.md new file mode 100644 index 00000000..983513a3 --- /dev/null +++ b/docs/api/math/math-color.md @@ -0,0 +1,72 @@ +# Color + +颜色结构体,支持 RGBA 浮点分量。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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(); +``` diff --git a/docs/api/math/math-frustum.md b/docs/api/math/math-frustum.md new file mode 100644 index 00000000..e261e57e --- /dev/null +++ b/docs/api/math/math-frustum.md @@ -0,0 +1,61 @@ +# Frustum + +视锥体,用于视锥剔除。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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); +} +``` diff --git a/docs/api/math/math-h.md b/docs/api/math/math-h.md new file mode 100644 index 00000000..2a7a232b --- /dev/null +++ b/docs/api/math/math-h.md @@ -0,0 +1,51 @@ +# Math - 数学常量 + +数学库全局常量和辅助函数。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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 相等 +} + +// 三角函数(来自 ) +float sinVal = std::sin(angle); +float cosVal = std::cos(angle); +``` diff --git a/docs/api/math/math-matrix3.md b/docs/api/math/math-matrix3.md new file mode 100644 index 00000000..669e5a3d --- /dev/null +++ b/docs/api/math/math-matrix3.md @@ -0,0 +1,69 @@ +# Matrix3 / Matrix3x3 + +3x3 矩阵结构体,用于表示 3D 旋转和缩放变换。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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); +``` diff --git a/docs/api/math/math-matrix4.md b/docs/api/math/math-matrix4.md new file mode 100644 index 00000000..750e32e2 --- /dev/null +++ b/docs/api/math/math-matrix4.md @@ -0,0 +1,101 @@ +# Matrix4 / Matrix4x4 + +4x4 矩阵结构体,用于表示完整的 3D 变换(平移、旋转、缩放)、视图和投影变换。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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); +``` diff --git a/docs/api/math/math-overview.md b/docs/api/math/math-overview.md new file mode 100644 index 00000000..e01f87f5 --- /dev/null +++ b/docs/api/math/math-overview.md @@ -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 +#include +#include +#include + +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(); +``` diff --git a/docs/api/math/math-plane.md b/docs/api/math/math-plane.md new file mode 100644 index 00000000..da1a90b6 --- /dev/null +++ b/docs/api/math/math-plane.md @@ -0,0 +1,66 @@ +# Plane + +3D 平面结构体,由法线和距离表示。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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)) { ... } +``` diff --git a/docs/api/math/math-quaternion.md b/docs/api/math/math-quaternion.md new file mode 100644 index 00000000..182c5a1a --- /dev/null +++ b/docs/api/math/math-quaternion.md @@ -0,0 +1,86 @@ +# Quaternion + +四元数结构体,用于表示 3D 旋转,避免欧拉角的万向锁问题。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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); +``` diff --git a/docs/api/math/math-ray.md b/docs/api/math/math-ray.md new file mode 100644 index 00000000..93f42f47 --- /dev/null +++ b/docs/api/math/math-ray.md @@ -0,0 +1,58 @@ +# Ray + +3D 射线结构体,用于光线投射和拾取。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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); +} +``` diff --git a/docs/api/math/math-rect.md b/docs/api/math/math-rect.md new file mode 100644 index 00000000..38ca88e2 --- /dev/null +++ b/docs/api/math/math-rect.md @@ -0,0 +1,137 @@ +# Rect / RectInt / Viewport + +2D 矩形和视口结构体。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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 +``` diff --git a/docs/api/math/math-sphere.md b/docs/api/math/math-sphere.md new file mode 100644 index 00000000..7438bcf9 --- /dev/null +++ b/docs/api/math/math-sphere.md @@ -0,0 +1,47 @@ +# Sphere + +3D 球体结构体。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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)) { ... } +``` diff --git a/docs/api/math/math-transform.md b/docs/api/math/math-transform.md new file mode 100644 index 00000000..db5262bb --- /dev/null +++ b/docs/api/math/math-transform.md @@ -0,0 +1,67 @@ +# Transform + +3D 变换结构体,包含位置、旋转和缩放,用于层次化变换。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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); +``` diff --git a/docs/api/math/math-vector2.md b/docs/api/math/math-vector2.md new file mode 100644 index 00000000..fbff215c --- /dev/null +++ b/docs/api/math/math-vector2.md @@ -0,0 +1,68 @@ +# Vector2 + +2D 向量结构体,用于表示 2D 空间中的点、方向或颜色。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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); +``` diff --git a/docs/api/math/math-vector3.md b/docs/api/math/math-vector3.md new file mode 100644 index 00000000..4e714d0f --- /dev/null +++ b/docs/api/math/math-vector3.md @@ -0,0 +1,84 @@ +# Vector3 + +3D 向量结构体,用于表示 3D 空间中的点、方向、颜色或法线。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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); +``` diff --git a/docs/api/math/math-vector4.md b/docs/api/math/math-vector4.md new file mode 100644 index 00000000..97b2b74c --- /dev/null +++ b/docs/api/math/math-vector4.md @@ -0,0 +1,62 @@ +# Vector4 + +4D 向量结构体,用于表示齐次坐标、颜色 (RGBA) 或 SIMD 操作。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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(); +``` diff --git a/docs/api/memory/memory-allocator.md b/docs/api/memory/memory-allocator.md new file mode 100644 index 00000000..2315db0b --- /dev/null +++ b/docs/api/memory/memory-allocator.md @@ -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 + +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) - 内存池分配器 diff --git a/docs/api/memory/memory-linear-allocator.md b/docs/api/memory/memory-linear-allocator.md new file mode 100644 index 00000000..ccc1d8dc --- /dev/null +++ b/docs/api/memory/memory-linear-allocator.md @@ -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(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) - 代理分配器 diff --git a/docs/api/memory/memory-manager.md b/docs/api/memory/memory-manager.md new file mode 100644 index 00000000..aaa4999b --- /dev/null +++ b/docs/api/memory/memory-manager.md @@ -0,0 +1,99 @@ +# MemoryManager + +**命名空间**: `XCEngine::Memory` + +**类型**: `class` (singleton) + +**描述**: 全局内存管理器单例,提供系统分配器和各种专用分配器的创建。 + +## 概述 + +`MemoryManager` 是 XCEngine 内存管理系统的核心单例。它负责维护系统分配器,提供分配器工厂方法,并支持内存泄漏检测和报告。 + +## 单例访问 + +| 方法 | 描述 | +|------|------| +| `static MemoryManager& Get()` | 获取单例实例 | + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `void Initialize()` | 初始化内存管理器 | +| `void Shutdown()` | 关闭内存管理器 | + +### 系统分配器 + +| 方法 | 描述 | +|------|------| +| `IAllocator* GetSystemAllocator()` | 获取系统默认分配器 | + +### 分配器创建 + +| 方法 | 描述 | +|------|------| +| `std::unique_ptr CreateLinearAllocator(size_t size)` | 创建线性分配器 | +| `std::unique_ptr CreatePoolAllocator(size_t blockSize, size_t count)` | 创建内存池分配器 | +| `std::unique_ptr 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) - 代理分配器 diff --git a/docs/api/memory/memory-overview.md b/docs/api/memory/memory-overview.md new file mode 100644 index 00000000..520f36e3 --- /dev/null +++ b/docs/api/memory/memory-overview.md @@ -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 + +// 获取系统分配器 +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) - 使用分配器的容器 diff --git a/docs/api/memory/memory-pool-allocator.md b/docs/api/memory/memory-pool-allocator.md new file mode 100644 index 00000000..b3c84004 --- /dev/null +++ b/docs/api/memory/memory-pool-allocator.md @@ -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) - 代理分配器 diff --git a/docs/api/memory/memory-proxy-allocator.md b/docs/api/memory/memory-proxy-allocator.md new file mode 100644 index 00000000..30ab1bab --- /dev/null +++ b/docs/api/memory/memory-proxy-allocator.md @@ -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) - 内存管理器 diff --git a/docs/api/resources/resources-asyncloader.md b/docs/api/resources/resources-asyncloader.md new file mode 100644 index 00000000..2f66c585 --- /dev/null +++ b/docs/api/resources/resources-asyncloader.md @@ -0,0 +1,99 @@ +# AsyncLoader + +**命名空间**: `XCEngine::Resources` + +**类型**: `class` (singleton) + +**描述**: 异步资源加载器单例,负责多线程后台资源加载和完成回调调度。 + +## 概述 + +`AsyncLoader` 是 XCEngine 的后台异步加载系统。它使用独立工作线程从磁盘加载资源,并在加载完成后通过回调通知调用者。它维护待处理队列和完成队列,通过双缓冲机制实现无锁的线程安全操作。 + +## 单例访问 + +| 方法 | 描述 | +|------|------| +| `static AsyncLoader& Get()` | 获取单例实例 | + +## LoadRequest 结构体 + +异步加载请求结构体。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `path` | `Containers::String` | 资源路径 | +| `type` | `ResourceType` | 资源类型 | +| `callback` | `std::function` | 加载完成回调函数 | +| `settings` | `ImportSettings*` | 导入设置(可为 nullptr) | +| `requestId` | `Core::uint64` | 请求唯一标识符 | + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `void Initialize(Core::uint32 workerThreadCount = 2)` | 初始化异步加载器,创建工作线程 | +| `void Shutdown()` | 关闭异步加载器,等待所有挂起任务完成 | + +### 提交请求 + +| 方法 | 描述 | +|------|------| +| `void Submit(const Containers::String& path, ResourceType type, std::function callback)` | 提交异步加载请求 | +| `void Submit(const Containers::String& path, ResourceType type, ImportSettings* settings, std::function 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 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(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) - 资源加载器接口 diff --git a/docs/api/resources/resources-audioclip.md b/docs/api/resources/resources-audioclip.md new file mode 100644 index 00000000..700ce893 --- /dev/null +++ b/docs/api/resources/resources-audioclip.md @@ -0,0 +1,131 @@ +# AudioClip + +**命名空间**: `XCEngine::Resources` + +**类型**: `class` + +**描述**: 音频片段资源类,管理音频样本数据、格式信息和播放参数。 + +## 概述 + +`AudioClip` 是 XCEngine 中的音频资源类,继承自 `IResource`。它管理音频的原始样本数据、采样率、通道数、位深度、时长、格式类型和播放参数。 + +## 头文件 + +```cpp +#include +``` + +## 枚举类型 + +### 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& data)` | 设置音频数据 | +| `const Containers::Array& 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 sfx = ResourceManager::Get().Load("sounds/explosion.wav"); +ResourceHandle music = ResourceManager::Get().Load("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) - 资源管理器 diff --git a/docs/api/resources/resources-dependencygraph.md b/docs/api/resources/resources-dependencygraph.md new file mode 100644 index 00000000..f9141ba8 --- /dev/null +++ b/docs/api/resources/resources-dependencygraph.md @@ -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 GetDependencies(ResourceGUID guid) const` | 获取指定资源的直接依赖列表 | +| `Containers::Array GetDependents(ResourceGUID guid) const` | 获取依赖指定资源的所有资源列表 | +| `Containers::Array GetAllDependencies(ResourceGUID guid) const` | 获取所有递归依赖(包括传递依赖) | + +### 引用计数 + +| 方法 | 描述 | +|------|------| +| `void IncrementRefCount(ResourceGUID guid)` | 增加引用计数 | +| `void DecrementRefCount(ResourceGUID guid)` | 减少引用计数 | +| `Core::uint32 GetRefCount(ResourceGUID guid) const` | 获取引用计数 | + +### 循环检测 + +| 方法 | 描述 | +|------|------| +| `bool HasCircularDependency(ResourceGUID guid, Containers::Array& outCycle) const` | 检测是否存在循环依赖 | + +### 排序与卸载 + +| 方法 | 描述 | +|------|------| +| `Containers::Array TopologicalSort() const` | 拓扑排序(按依赖顺序) | +| `bool Unload(ResourceGUID guid)` | 安全卸载(考虑依赖关系) | + +### 清理 + +| 方法 | 描述 | +|------|------| +| `void Clear()` | 清空所有节点和依赖关系 | + +## DependencyNode 结构体 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `guid` | `ResourceGUID` | 资源全局唯一标识符 | +| `type` | `ResourceType` | 资源类型 | +| `dependencies` | `Containers::Array` | 此资源依赖的其他资源 | +| `dependents` | `Containers::Array` | 依赖此资源的其他资源 | +| `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 cycle; +if (graph.HasCircularDependency(guid, cycle)) { + printf("Circular dependency detected!"); +} + +// 引用计数 +graph.IncrementRefCount(guid); +graph.DecrementRefCount(guid); +``` + +## 相关文档 + +- [ResourceManager](./resources-resourcemanager.md) - 资源管理器 +- [ResourceHandle](./resources-resourcehandle.md) - 资源句柄 diff --git a/docs/api/resources/resources-filesystem.md b/docs/api/resources/resources-filesystem.md new file mode 100644 index 00000000..02f6ef79 --- /dev/null +++ b/docs/api/resources/resources-filesystem.md @@ -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 ReadResource(const Containers::String& relativePath)` | 读取资源文件内容(字节数组) | + +### 资源信息 + +| 方法 | 描述 | +|------|------| +| `bool GetResourceInfo(const Containers::String& relativePath, ResourceInfo& outInfo)` | 获取资源信息 | +| `void EnumerateResources(const Containers::String& pattern, Containers::Array& outResources)` | 枚举匹配的资源 | + +## 使用示例 + +```cpp +#include + +// 初始化资源文件系统 +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 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) - 资源加载器 diff --git a/docs/api/resources/resources-iloader.md b/docs/api/resources/resources-iloader.md new file mode 100644 index 00000000..068fbd21 --- /dev/null +++ b/docs/api/resources/resources-iloader.md @@ -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 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 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 + GetDependencies(const Containers::String& path) const override { + return {}; // 纹理通常无依赖 + } +}; + +// 注册加载器 +ResourceManager::Get().RegisterLoader(new TextureLoader()); +``` + +## 相关文档 + +- [ResourceManager](./resources-resourcemanager.md) - 资源管理器 +- [AsyncLoader](./resources-asyncloader.md) - 异步加载器 diff --git a/docs/api/resources/resources-importsettings.md b/docs/api/resources/resources-importsettings.md new file mode 100644 index 00000000..904833e6 --- /dev/null +++ b/docs/api/resources/resources-importsettings.md @@ -0,0 +1,164 @@ +# ImportSettings + +**命名空间**: `XCEngine::Resources` + +**类型**: `class` (abstract) + +**描述**: 资源导入设置抽象基类,定义资源导入时的配置选项接口。 + +## 概述 + +`ImportSettings` 是所有资源导入设置的抽象基类。它提供了克隆和 JSON 序列化接口,允许不同资源类型定义各自的导入选项。引擎内置了两个具体实现:`TextureImportSettings` 和 `MeshImportSettings`。 + +## 公共方法 + +| 方法 | 描述 | +|------|------| +| `virtual Core::UniqueRef 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 +#include + +// 纹理导入设置 +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 tex = ResourceManager::Get().Load("tex.png", &texSettings); +ResourceHandle mesh = ResourceManager::Get().Load("model.fbx", &meshSettings); +``` + +## 相关文档 + +- [IResourceLoader](./resources-iloader.md) - 资源加载器 +- [ResourceManager](./resources-resourcemanager.md) - 资源管理器 diff --git a/docs/api/resources/resources-iresource.md b/docs/api/resources/resources-iresource.md new file mode 100644 index 00000000..c78d93dd --- /dev/null +++ b/docs/api/resources/resources-iresource.md @@ -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) - 资源类型定义 diff --git a/docs/api/resources/resources-material.md b/docs/api/resources/resources-material.md new file mode 100644 index 00000000..e28bb612 --- /dev/null +++ b/docs/api/resources/resources-material.md @@ -0,0 +1,146 @@ +# Material + +**命名空间**: `XCEngine::Resources` + +**类型**: `class` + +**描述**: 材质资源类,管理渲染所需的着色器和属性参数。 + +## 概述 + +`Material` 是 XCEngine 中的材质资源类,继承自 `IResource`。它管理材质关联的着色器和各种属性参数(浮点数、向量、纹理等),并支持将属性数据打包到常量缓冲区。 + +## 头文件 + +```cpp +#include +``` + +## 枚举类型 + +### 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* 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)` | 设置纹理属性 | + +### 属性获取 + +| 方法 | 描述 | +|------|------| +| `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 GetTexture(const Containers::String& name) const` | 获取纹理属性 | + +### 常量缓冲区 + +| 方法 | 描述 | +|------|------| +| `const Containers::Array& GetConstantBufferData() const` | 获取常量缓冲区数据 | +| `void UpdateConstantBuffer()` | 更新常量缓冲区数据 | + +### 属性管理 + +| 方法 | 描述 | +|------|------| +| `bool HasProperty(const Containers::String& name) const` | 检查属性是否存在 | +| `void RemoveProperty(const Containers::String& name)` | 移除属性 | +| `void ClearAllProperties()` | 清空所有属性 | + +## 使用示例 + +```cpp +// 加载材质 +ResourceHandle mat = ResourceManager::Get().Load("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) - 纹理资源 diff --git a/docs/api/resources/resources-mesh.md b/docs/api/resources/resources-mesh.md new file mode 100644 index 00000000..da9a7e4b --- /dev/null +++ b/docs/api/resources/resources-mesh.md @@ -0,0 +1,148 @@ +# Mesh + +**命名空间**: `XCEngine::Resources` + +**类型**: `class` + +**描述**: 网格资源类,管理 3D 模型的顶点数据、索引数据和网格分段信息。 + +## 概述 + +`Mesh` 是 XCEngine 中的网格资源类,继承自 `IResource`。它管理网格的顶点数据(位置、法线、UV、切线、颜色、骨骼权重等)、索引数据和网格分段(submesh)。 + +## 头文件 + +```cpp +#include +``` + +## 枚举类型 + +### 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& GetSections() const` | 获取所有分段 | + +## 使用示例 + +```cpp +// 加载网格 +ResourceHandle mesh = ResourceManager::Get().Load("models/player.fbx"); + +// 手动设置顶点数据 +struct Vertex { + float position[3]; + float normal[3]; + float uv[2]; +}; + +Containers::Array vertices; +vertices.Resize(vertexCount); +// ... 填充顶点数据 ... + +mesh->SetVertexData( + vertices.Data(), + vertices.Size() * sizeof(Vertex), + vertexCount, + sizeof(Vertex), + VertexAttribute::Position | VertexAttribute::Normal | VertexAttribute::UV0 +); + +// 设置索引数据 +Containers::Array 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) - 资源管理器 diff --git a/docs/api/resources/resources-overview.md b/docs/api/resources/resources-overview.md new file mode 100644 index 00000000..8dbd4a44 --- /dev/null +++ b/docs/api/resources/resources-overview.md @@ -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 + +// 初始化资源管理器 +ResourceManager::Get().Initialize(); +ResourceManager::Get().SetResourceRoot("resources/"); + +// 同步加载资源 +ResourceHandle tex = ResourceManager::Get().Load("textures/player.png"); +ResourceHandle mesh = ResourceManager::Get().Load("models/player.fbx"); +ResourceHandle mat = ResourceManager::Get().Load("materials/player.mat"); + +// 异步加载 +ResourceManager::Get().LoadAsync("textures/terrain.png", + [](ResourceHandle tex) { + // 加载完成回调 + }); + +// 释放资源 +tex.Reset(); +mesh.Reset(); +``` + +## 相关文档 + +- [RHI 模块](../rhi/rhi-overview.md) - GPU 资源创建 diff --git a/docs/api/resources/resources-resourcecache.md b/docs/api/resources/resources-resourcecache.md new file mode 100644 index 00000000..fd15fa24 --- /dev/null +++ b/docs/api/resources/resources-resourcecache.md @@ -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 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) - 资源基类 diff --git a/docs/api/resources/resources-resourcehandle.md b/docs/api/resources/resources-resourcehandle.md new file mode 100644 index 00000000..7e23ae23 --- /dev/null +++ b/docs/api/resources/resources-resourcehandle.md @@ -0,0 +1,100 @@ +# ResourceHandle + +**命名空间**: `XCEngine::Resources` + +**类型**: `class` (template) + +**描述**: 模板资源句柄类,提供资源的引用计数式安全访问,自动管理资源的加载和释放。 + +## 概述 + +`ResourceHandle` 是一个模板句柄类,用于安全地持有对资源的引用。它通过 `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 tex = ResourceManager::Get().Load("textures/player.png"); + +// 检查有效性 +if (tex.IsValid()) { + // 安全访问资源 + uint32_t width = tex->GetWidth(); +} + +// 拷贝句柄(引用计数 +1) +ResourceHandle tex2 = tex; + +// 移动句柄 +ResourceHandle tex3 = std::move(tex2); + +// 句柄离开作用域时自动释放(引用计数 -1) +tex.Reset(); // 手动释放 +``` + +## 相关文档 + +- [IResource](./resources-iresource.md) - 资源基类 +- [ResourceManager](./resources-resourcemanager.md) - 资源管理器 +- [ResourceCache](./resources-resourcecache.md) - 资源缓存 diff --git a/docs/api/resources/resources-resourcemanager.md b/docs/api/resources/resources-resourcemanager.md new file mode 100644 index 00000000..e024c85d --- /dev/null +++ b/docs/api/resources/resources-resourcemanager.md @@ -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 Load(const Containers::String& path, ImportSettings* settings = nullptr)` | 同步加载资源(模板方法) | + +### 异步加载 + +| 方法 | 描述 | +|------|------| +| `void LoadAsync(const Containers::String& path, ResourceType type, std::function callback)` | 异步加载资源 | +| `void LoadAsync(const Containers::String& path, ResourceType type, ImportSettings* settings, std::function callback)` | 带设置的异步加载 | + +### 批量加载 + +| 方法 | 描述 | +|------|------| +| `void LoadGroup(const Containers::Array& paths, std::function)> 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 GetResourcePaths() const` | 获取所有已加载资源的路径列表 | +| `void UnloadGroup(const Containers::Array& 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 tex = ResourceManager::Get().Load("textures/player.png"); +ResourceHandle mesh = ResourceManager::Get().Load("models/player.fbx"); + +// 异步加载 +ResourceManager::Get().LoadAsync("textures/terrain.png", + [](LoadResult result) { + if (result.success) { + ResourceHandle tex(result.resource); + // 使用纹理... + } + }); + +// 批量加载 +Containers::Array paths = {"a.png", "b.png", "c.png"}; +ResourceManager::Get().LoadGroup(paths, + [](ResourceHandle 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) - 异步加载器 diff --git a/docs/api/resources/resources-resourcetypes.md b/docs/api/resources/resources-resourcetypes.md new file mode 100644 index 00000000..fb6e53c5 --- /dev/null +++ b/docs/api/resources/resources-resourcetypes.md @@ -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 cache; +cache[texGuid] = texture; +``` + +## 相关文档 + +- [IResource](./resources-iresource.md) - 资源基类 +- [ResourceManager](./resources-resourcemanager.md) - 资源管理器 diff --git a/docs/api/resources/resources-shader.md b/docs/api/resources/resources-shader.md new file mode 100644 index 00000000..22f5b2fc --- /dev/null +++ b/docs/api/resources/resources-shader.md @@ -0,0 +1,149 @@ +# Shader + +**命名空间**: `XCEngine::Resources` + +**类型**: `class` + +**描述**: 着色器资源类,管理着色器源码、编译后的二进制和 uniform/attribute 信息。 + +## 概述 + +`Shader` 是 XCEngine 中的着色器资源类,继承自 `IResource`。它管理着色器源码、编译后的二进制数据、着色器类型、语言类型、uniform 列表和 attribute 列表,并持有对应的 RHI 着色器资源指针。 + +## 头文件 + +```cpp +#include +``` + +## 枚举类型 + +### 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& binary)` | 设置编译后二进制 | +| `const Containers::Array& GetCompiledBinary() const` | 获取编译后二进制 | + +### Uniform 和 Attribute + +| 方法 | 描述 | +|------|------| +| `void AddUniform(const ShaderUniform& uniform)` | 添加 Uniform 描述 | +| `const Containers::Array& GetUniforms() const` | 获取 Uniform 列表 | +| `void AddAttribute(const ShaderAttribute& attribute)` | 添加 Attribute 描述 | +| `const Containers::Array& GetAttributes() const` | 获取 Attribute 列表 | + +### RHI 资源 + +| 方法 | 描述 | +|------|------| +| `class IRHIShader* GetRHIResource() const` | 获取 RHI 着色器资源 | +| `void SetRHIResource(class IRHIShader* resource)` | 设置 RHI 着色器资源 | + +## 使用示例 + +```cpp +// 加载着色器 +ResourceHandle vs = ResourceManager::Get().Load("shaders/vertex.glsl"); +ResourceHandle fs = ResourceManager::Get().Load("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) - 材质资源 diff --git a/docs/api/resources/resources-texture.md b/docs/api/resources/resources-texture.md new file mode 100644 index 00000000..90e56fdb --- /dev/null +++ b/docs/api/resources/resources-texture.md @@ -0,0 +1,152 @@ +# Texture + +**命名空间**: `XCEngine::Resources` + +**类型**: `class` + +**描述**: 纹理资源类,管理 2D/3D 纹理和立方体贴图的像素数据。 + +## 概述 + +`Texture` 是 XCEngine 中的纹理资源类,继承自 `IResource`。它管理纹理的尺寸、格式、像素数据,并支持 mipmap 生成等功能。 + +## 头文件 + +```cpp +#include +``` + +## 枚举类型 + +### 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 tex = ResourceManager::Get().Load("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 纹理接口 diff --git a/docs/api/rhi/d3d12/d3d12-buffer.md b/docs/api/rhi/d3d12/d3d12-buffer.md new file mode 100644 index 00000000..f0990259 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-buffer.md @@ -0,0 +1,178 @@ +# D3D12Buffer + +DirectX 12 缓冲区的 D3D12 实现,封装了 `ID3D12Resource` (buffer 类型)。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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` | 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 回读数据的堆 +- 创建后立即使用需注意资源状态转换 diff --git a/docs/api/rhi/d3d12/d3d12-command-allocator.md b/docs/api/rhi/d3d12/d3d12-command-allocator.md new file mode 100644 index 00000000..52bed1a8 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-command-allocator.md @@ -0,0 +1,80 @@ +# D3D12CommandAllocator + +DirectX 12 命令分配器的 D3D12 实现,封装了 `ID3D12CommandAllocator`。 + +## 头文件 + +```cpp +#include +``` + +## 公共成员函数 + +### 构造函数与析构函数 + +#### `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` | 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 完成所有关联命令后才能重置 +- 每个帧通常有独立的命令分配器以支持帧间并行 +- 命令分配器创建开销小,可以频繁创建销毁 diff --git a/docs/api/rhi/d3d12/d3d12-command-list.md b/docs/api/rhi/d3d12/d3d12-command-list.md new file mode 100644 index 00000000..82e8774d --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-command-list.md @@ -0,0 +1,269 @@ +# D3D12CommandList + +DirectX 12 图形命令列表的 D3D12 实现,封装了 `ID3D12GraphicsCommandList`。 + +## 头文件 + +```cpp +#include +``` + +## 类概览 + +`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` | D3D12 命令列表 | +| `m_type` | `CommandQueueType` | 命令队列类型 | +| `m_resourceStateMap` | `unordered_map` | 资源状态映射 | +| `m_trackedResources` | `vector` | 跟踪的资源列表 | +| `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 是一种优化手段,可以复用频繁执行的命令序列 diff --git a/docs/api/rhi/d3d12/d3d12-command-queue.md b/docs/api/rhi/d3d12/d3d12-command-queue.md new file mode 100644 index 00000000..cde95f61 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-command-queue.md @@ -0,0 +1,113 @@ +# D3D12CommandQueue + +DirectX 12 命令队列的 D3D12 实现,封装了 `ID3D12CommandQueue`。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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` | 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 直到所有已提交命令完成 diff --git a/docs/api/rhi/d3d12/d3d12-common.md b/docs/api/rhi/d3d12/d3d12-common.md new file mode 100644 index 00000000..fa8ac3f5 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-common.md @@ -0,0 +1,124 @@ +# D3D12Common + +D3D12 通用辅助函数集合,提供描述符大小、屏障创建、格式支持检查等功能。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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,可在头文件中使用 +- 这些是高频使用的辅助函数,避免重复代码 diff --git a/docs/api/rhi/d3d12/d3d12-constant-buffer-view.md b/docs/api/rhi/d3d12/d3d12-constant-buffer-view.md new file mode 100644 index 00000000..36571bd4 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-constant-buffer-view.md @@ -0,0 +1,47 @@ +# D3D12ConstantBufferView + +DirectX 12 常量缓冲区视图的 D3D12 实现。 + +## 头文件 + +```cpp +#include +``` + +## 公共成员函数 + +### 构造函数与析构函数 + +#### `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 描述符 diff --git a/docs/api/rhi/d3d12/d3d12-depth-stencil-view.md b/docs/api/rhi/d3d12/d3d12-depth-stencil-view.md new file mode 100644 index 00000000..beb3678d --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-depth-stencil-view.md @@ -0,0 +1,52 @@ +# D3D12DepthStencilView + +DirectX 12 深度模板视图的 D3D12 实现。 + +## 头文件 + +```cpp +#include +``` + +## 公共成员函数 + +### 构造函数与析构函数 + +#### `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(通过描述符标志区分) diff --git a/docs/api/rhi/d3d12/d3d12-descriptor-heap.md b/docs/api/rhi/d3d12/d3d12-descriptor-heap.md new file mode 100644 index 00000000..4e4e5831 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-descriptor-heap.md @@ -0,0 +1,114 @@ +# D3D12DescriptorHeap + +DirectX 12 描述符堆的 D3D12 实现,封装了 `ID3D12DescriptorHeap`。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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` | 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 +- 描述符堆创建后大小固定,不能调整 diff --git a/docs/api/rhi/d3d12/d3d12-device.md b/docs/api/rhi/d3d12/d3d12-device.md new file mode 100644 index 00000000..9441a58f --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-device.md @@ -0,0 +1,169 @@ +# D3D12Device + +DirectX 12 设备的 D3D12 实现,是引擎的 RHI 抽象层 `RHIDevice` 接口的具体实现。 + +## 头文件 + +```cpp +#include +``` + +## 类概览 + +`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 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 + +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()` 可以模拟设备移除场景用于测试 diff --git a/docs/api/rhi/d3d12/d3d12-enum.md b/docs/api/rhi/d3d12/d3d12-enum.md new file mode 100644 index 00000000..65cfe06d --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-enum.md @@ -0,0 +1,154 @@ +# D3D12Enum + +D3D12 枚举值转换函数集合,提供 RHI 抽象枚举到 D3D12 原生枚举的转换。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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 语句确保编译期检查所有枚举值 +- 未处理的枚举值返回合理的默认值 diff --git a/docs/api/rhi/d3d12/d3d12-fence.md b/docs/api/rhi/d3d12/d3d12-fence.md new file mode 100644 index 00000000..bd5ff532 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-fence.md @@ -0,0 +1,106 @@ +# D3D12Fence + +DirectX 12 栅栏同步对象的 D3D12 实现,封装了 `ID3D12Fence`。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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` | 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 +- 多帧缓冲时常用栅栏确保帧间资源安全 diff --git a/docs/api/rhi/d3d12/d3d12-overview.md b/docs/api/rhi/d3d12/d3d12-overview.md new file mode 100644 index 00000000..8dfe2ef0 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-overview.md @@ -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) diff --git a/docs/api/rhi/d3d12/d3d12-pipeline-state.md b/docs/api/rhi/d3d12/d3d12-pipeline-state.md new file mode 100644 index 00000000..74d503c2 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-pipeline-state.md @@ -0,0 +1,123 @@ +# D3D12PipelineState + +DirectX 12 管线状态对象的 D3D12 实现,封装了 `ID3D12PipelineState`。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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` | 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 小 diff --git a/docs/api/rhi/d3d12/d3d12-query-heap.md b/docs/api/rhi/d3d12/d3d12-query-heap.md new file mode 100644 index 00000000..b3710f61 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-query-heap.md @@ -0,0 +1,82 @@ +# D3D12QueryHeap + +DirectX 12 查询堆的 D3D12 实现,封装了 `ID3D12QueryHeap`。 + +## 头文件 + +```cpp +#include +``` + +## 公共成员函数 + +### 构造函数与析构函数 + +#### `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` | 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 操作复制到可读缓冲区 +- 时间戳查询需要命令队列支持时间戳功能 diff --git a/docs/api/rhi/d3d12/d3d12-render-target-view.md b/docs/api/rhi/d3d12/d3d12-render-target-view.md new file mode 100644 index 00000000..0fa91d8b --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-render-target-view.md @@ -0,0 +1,68 @@ +# D3D12RenderTargetView + +DirectX 12 渲染目标视图的 D3D12 实现。 + +## 头文件 + +```cpp +#include +``` + +## 公共成员函数 + +### 构造函数与析构函数 + +#### `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 类型描述符堆中分配 diff --git a/docs/api/rhi/d3d12/d3d12-root-signature.md b/docs/api/rhi/d3d12/d3d12-root-signature.md new file mode 100644 index 00000000..31779ed7 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-root-signature.md @@ -0,0 +1,132 @@ +# D3D12RootSignature + +DirectX 12 根签名的 D3D12 实现,封装了 `ID3D12RootSignature`。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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` | 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 匹配 diff --git a/docs/api/rhi/d3d12/d3d12-sampler.md b/docs/api/rhi/d3d12/d3d12-sampler.md new file mode 100644 index 00000000..a24c3af9 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-sampler.md @@ -0,0 +1,64 @@ +# D3D12Sampler + +DirectX 12 采样器的 D3D12 实现。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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 采样器通常放在根签名或采样器描述符堆中 +- 静态采样器在根签名中声明,无需描述符堆 diff --git a/docs/api/rhi/d3d12/d3d12-screenshot.md b/docs/api/rhi/d3d12/d3d12-screenshot.md new file mode 100644 index 00000000..1ad5ce80 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-screenshot.md @@ -0,0 +1,50 @@ +# D3D12Screenshot + +D3D12 截图工具类,提供屏幕截图捕获功能。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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 等常见图片格式 +- 可能在内部创建临时资源 diff --git a/docs/api/rhi/d3d12/d3d12-shader-resource-view.md b/docs/api/rhi/d3d12/d3d12-shader-resource-view.md new file mode 100644 index 00000000..75e7fec9 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-shader-resource-view.md @@ -0,0 +1,53 @@ +# D3D12ShaderResourceView + +DirectX 12 着色器资源视图的 D3D12 实现。 + +## 头文件 + +```cpp +#include +``` + +## 公共成员函数 + +### 构造函数与析构函数 + +#### `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 的描述符堆 diff --git a/docs/api/rhi/d3d12/d3d12-shader.md b/docs/api/rhi/d3d12/d3d12-shader.md new file mode 100644 index 00000000..0e31696f --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-shader.md @@ -0,0 +1,108 @@ +# D3D12Shader + +DirectX 12 着色器的 D3D12 实现,封装了 `ID3DBlob` 编译结果。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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` | 编译成功的字节码 | +| `m_error` | `ComPtr` | 编译错误信息 | +| `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` diff --git a/docs/api/rhi/d3d12/d3d12-swap-chain.md b/docs/api/rhi/d3d12/d3d12-swap-chain.md new file mode 100644 index 00000000..c5eb253b --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-swap-chain.md @@ -0,0 +1,136 @@ +# D3D12SwapChain + +DirectX 12 交换链的 D3D12 实现,封装了 `IDXGISwapChain3`。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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` | DXGI 交换链 | +| `m_commandQueue` | `ComPtr` | 命令队列引用 | +| `m_windowHandle` | `HWND` | 窗口句柄 | +| `m_width` | `uint32_t` | 宽度 | +| `m_height` | `uint32_t` | 高度 | +| `m_bufferCount` | `uint32_t` | 缓冲区数量 | +| `m_backBuffers` | `vector` | 后台缓冲区纹理 | + +## 使用示例 + +```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` diff --git a/docs/api/rhi/d3d12/d3d12-texture.md b/docs/api/rhi/d3d12/d3d12-texture.md new file mode 100644 index 00000000..3f1d6f06 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-texture.md @@ -0,0 +1,169 @@ +# D3D12Texture + +DirectX 12 纹理的 D3D12 实现,封装了 `ID3D12Resource` (texture 类型)。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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` | 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 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` diff --git a/docs/api/rhi/d3d12/d3d12-types.md b/docs/api/rhi/d3d12/d3d12-types.md new file mode 100644 index 00000000..9f7852ce --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-types.md @@ -0,0 +1,74 @@ +# D3D12Types + +D3D12 类型转换和辅助函数集合,提供 RHI 抽象类型到 D3D12 类型的转换。 + +## 头文件 + +```cpp +#include +``` + +## 命名空间 + +`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,可在头文件中使用 +- 转换自动处理类型映射和默认值设置 diff --git a/docs/api/rhi/d3d12/d3d12-unordered-access-view.md b/docs/api/rhi/d3d12/d3d12-unordered-access-view.md new file mode 100644 index 00000000..53074ff4 --- /dev/null +++ b/docs/api/rhi/d3d12/d3d12-unordered-access-view.md @@ -0,0 +1,45 @@ +# D3D12UnorderedAccessView + +DirectX 12 无序访问视图的 D3D12 实现。 + +## 头文件 + +```cpp +#include +``` + +## 公共成员函数 + +### 构造函数与析构函数 + +#### `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 类型描述符堆中分配 diff --git a/docs/api/rhi/opengl/opengl-buffer.md b/docs/api/rhi/opengl/opengl-buffer.md new file mode 100644 index 00000000..546e4fd4 --- /dev/null +++ b/docs/api/rhi/opengl/opengl-buffer.md @@ -0,0 +1,135 @@ +# OpenGLBuffer + +OpenGL 缓冲区的实现,封装 OpenGL buffer object。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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(static_cast(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); +``` diff --git a/docs/api/rhi/opengl/opengl-command-list.md b/docs/api/rhi/opengl/opengl-command-list.md new file mode 100644 index 00000000..9c89ff2f --- /dev/null +++ b/docs/api/rhi/opengl/opengl-command-list.md @@ -0,0 +1,308 @@ +# OpenGLCommandList + +OpenGL 命令列表实现。OpenGL 是立即模式 API,此类提供命令录制和批量提交的能力。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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 命令 diff --git a/docs/api/rhi/opengl/opengl-command-queue.md b/docs/api/rhi/opengl/opengl-command-queue.md new file mode 100644 index 00000000..29548aa8 --- /dev/null +++ b/docs/api/rhi/opengl/opengl-command-queue.md @@ -0,0 +1,63 @@ +# OpenGLCommandQueue + +OpenGL 命令队列实现。OpenGL 是立即模式 API,此类主要提供 RHI 接口兼容。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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 对象实现 diff --git a/docs/api/rhi/opengl/opengl-depth-stencil-view.md b/docs/api/rhi/opengl/opengl-depth-stencil-view.md new file mode 100644 index 00000000..4a6af4c6 --- /dev/null +++ b/docs/api/rhi/opengl/opengl-depth-stencil-view.md @@ -0,0 +1,105 @@ +# OpenGLDepthStencilView + +OpenGL 深度模板视图实现。 + +## 头文件 + +```cpp +#include +``` + +## 枚举 + +### 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); +``` diff --git a/docs/api/rhi/opengl/opengl-device.md b/docs/api/rhi/opengl/opengl-device.md new file mode 100644 index 00000000..96e5d73c --- /dev/null +++ b/docs/api/rhi/opengl/opengl-device.md @@ -0,0 +1,109 @@ +# OpenGLDevice + +OpenGL 设备的实现,基于 GLFW 和现代 OpenGL。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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(); +} +``` diff --git a/docs/api/rhi/opengl/opengl-fence.md b/docs/api/rhi/opengl/opengl-fence.md new file mode 100644 index 00000000..19306b97 --- /dev/null +++ b/docs/api/rhi/opengl/opengl-fence.md @@ -0,0 +1,99 @@ +# OpenGLFence + +OpenGL 栅栏同步实现,使用 `GLsync` (Fence objects)。 + +## 头文件 + +```cpp +#include +``` + +## 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); +``` diff --git a/docs/api/rhi/opengl/opengl-overview.md b/docs/api/rhi/opengl/opengl-overview.md new file mode 100644 index 00000000..7dc4ecfc --- /dev/null +++ b/docs/api/rhi/opengl/opengl-overview.md @@ -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 + +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**: 纹理文件加载 diff --git a/docs/api/rhi/opengl/opengl-pipeline-state.md b/docs/api/rhi/opengl/opengl-pipeline-state.md new file mode 100644 index 00000000..72f07947 --- /dev/null +++ b/docs/api/rhi/opengl/opengl-pipeline-state.md @@ -0,0 +1,229 @@ +# OpenGLPipelineState + +OpenGL 管线状态对象实现,封装多种 OpenGL 状态。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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(); +``` diff --git a/docs/api/rhi/opengl/opengl-render-target-view.md b/docs/api/rhi/opengl/opengl-render-target-view.md new file mode 100644 index 00000000..9739f3b5 --- /dev/null +++ b/docs/api/rhi/opengl/opengl-render-target-view.md @@ -0,0 +1,106 @@ +# OpenGLRenderTargetView + +OpenGL 渲染目标视图实现,使用 framebuffer object (FBO)。 + +## 头文件 + +```cpp +#include +``` + +## 枚举 + +### 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` | 额外 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); +``` diff --git a/docs/api/rhi/opengl/opengl-sampler.md b/docs/api/rhi/opengl/opengl-sampler.md new file mode 100644 index 00000000..8026ccca --- /dev/null +++ b/docs/api/rhi/opengl/opengl-sampler.md @@ -0,0 +1,102 @@ +# OpenGLSampler + +OpenGL 采样器实现。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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()); +``` diff --git a/docs/api/rhi/opengl/opengl-shader.md b/docs/api/rhi/opengl/opengl-shader.md new file mode 100644 index 00000000..b0ebe130 --- /dev/null +++ b/docs/api/rhi/opengl/opengl-shader.md @@ -0,0 +1,151 @@ +# OpenGLShader + +OpenGL 着色器实现,封装 shader program。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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 不存在 diff --git a/docs/api/rhi/opengl/opengl-swap-chain.md b/docs/api/rhi/opengl/opengl-swap-chain.md new file mode 100644 index 00000000..50848a9f --- /dev/null +++ b/docs/api/rhi/opengl/opengl-swap-chain.md @@ -0,0 +1,138 @@ +# OpenGLSwapChain + +OpenGL 交换链实现,基于 GLFW 窗口和双缓冲。 + +## 头文件 + +```cpp +#include +``` + +## 枚举 + +### 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` +返回 0(OpenGL 单缓冲区索引)。 + +#### `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); +} +``` diff --git a/docs/api/rhi/opengl/opengl-texture.md b/docs/api/rhi/opengl/opengl-texture.md new file mode 100644 index 00000000..0a517bba --- /dev/null +++ b/docs/api/rhi/opengl/opengl-texture.md @@ -0,0 +1,149 @@ +# OpenGLTexture + +OpenGL 纹理的实现,封装 OpenGL texture object。 + +## 头文件 + +```cpp +#include +``` + +## 继承关系 + +``` +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); +``` diff --git a/docs/api/rhi/opengl/opengl-vertex-array.md b/docs/api/rhi/opengl/opengl-vertex-array.md new file mode 100644 index 00000000..22e255ae --- /dev/null +++ b/docs/api/rhi/opengl/opengl-vertex-array.md @@ -0,0 +1,88 @@ +# OpenGLVertexArray + +OpenGL 顶点数组对象 (VAO) 封装。 + +## 头文件 + +```cpp +#include +``` + +## 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); +``` diff --git a/docs/api/rhi/rhi-buffer.md b/docs/api/rhi/rhi-buffer.md new file mode 100644 index 00000000..b0b0a7c9 --- /dev/null +++ b/docs/api/rhi/rhi-buffer.md @@ -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) - 命令列表 diff --git a/docs/api/rhi/rhi-capabilities.md b/docs/api/rhi/rhi-capabilities.md new file mode 100644 index 00000000..c450b5c2 --- /dev/null +++ b/docs/api/rhi/rhi-capabilities.md @@ -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) - 设备对象 diff --git a/docs/api/rhi/rhi-command-list.md b/docs/api/rhi/rhi-command-list.md new file mode 100644 index 00000000..bc3d1528 --- /dev/null +++ b/docs/api/rhi/rhi-command-list.md @@ -0,0 +1,179 @@ +# RHICommandList + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` (abstract) + +**描述**: GPU 命令列表抽象接口,用于录制和执行 GPU 命令。 + +## 概述 + +`RHICommandList` 封装了 GPU 命令的录制和执行。每个后端实现需要提供命令列表的创建、重置、命令录制和关闭等功能。 + +## 公共类型 + +### DepthStencilState + +深度模板状态结构体。 + +```cpp +struct DepthStencilState { + bool depthEnable = true; // 启用深度测试 + bool depthWriteMask = true; // 深度写入掩码 + ComparisonFunc depthFunc; // 深度比较函数 + bool stencilEnable = false; // 启用模板测试 + uint8_t stencilReadMask = 0xFF; // 模板读取掩码 + uint8_t stencilWriteMask = 0xFF; // 模板写入掩码 + struct StencilOpDesc { // 模板操作描述 + StencilOp stencilFailOp; // 模板失败操作 + StencilOp stencilDepthFailOp; // 深度失败操作 + StencilOp stencilPassOp; // 通过操作 + ComparisonFunc stencilFunc; // 模板比较函数 + }; + StencilOpDesc frontFace; // 前面模板状态 + StencilOpDesc backFace; // 背面模板状态 +}; +``` + +### BlendState + +混合状态结构体。 + +```cpp +struct BlendState { + bool alphaToCoverageEnable = false; // Alpha 到覆盖 + bool independentBlendEnable = false; // 独立混合 + struct RenderTarget { // 渲染目标混合 + bool blendEnable; // 启用混合 + BlendFactor srcBlend; // 源混合因子 + BlendFactor dstBlend; // 目标混合因子 + BlendOp blendOp; // 混合操作 + BlendFactor srcBlendAlpha; // Alpha 源混合 + BlendFactor dstBlendAlpha; // Alpha 目标混合 + BlendOp blendOpAlpha; // Alpha 混合操作 + uint8_t renderTargetWriteMask; // 颜色写入掩码 + }; + RenderTarget renderTargets[8]; // 每个 RT 的混合状态 + float blendFactor[4]; // 全局混合因子 +}; +``` + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual void Shutdown()` | 释放命令列表资源 | + +### 命令录制控制 + +| 方法 | 描述 | +|------|------| +| `virtual void Reset()` | 重置命令列表,开始新的录制 | +| `virtual void Close()` | 关闭命令列表,结束录制 | + +### 资源状态转换 + +| 方法 | 描述 | +|------|------| +| `virtual void TransitionBarrier(void* resource, ResourceStates stateBefore, ResourceStates stateAfter)` | 资源状态转换屏障 | + +### 渲染状态设置 + +| 方法 | 描述 | +|------|------| +| `virtual void SetPipelineState(void* pso)` | 设置管线状态对象 | +| `virtual void SetPrimitiveTopology(PrimitiveTopology topology)` | 设置图元拓扑 | +| `virtual void SetViewport(const Viewport& viewport)` | 设置视口 | +| `virtual void SetViewports(uint32_t count, const Viewport* viewports)` | 设置多个视口 | +| `virtual void SetScissorRect(const Rect& rect)` | 设置裁剪矩形 | +| `virtual void SetScissorRects(uint32_t count, const Rect* rects)` | 设置多个裁剪矩形 | +| `virtual void SetRenderTargets(uint32_t count, void** renderTargets, void* depthStencil = nullptr)` | 设置渲染目标 | + +### 深度/混合状态 + +| 方法 | 描述 | +|------|------| +| `virtual void SetDepthStencilState(const DepthStencilState& state)` | 设置深度模板状态 | +| `virtual void SetStencilRef(uint8_t ref)` | 设置模板参考值 | +| `virtual void SetBlendState(const BlendState& state)` | 设置混合状态 | +| `virtual void SetBlendFactor(const float factor[4])` | 设置混合因子 | + +### 顶点/索引缓冲 + +| 方法 | 描述 | +|------|------| +| `virtual void SetVertexBuffer(uint32_t slot, void* buffer, uint64_t offset, uint32_t stride)` | 设置顶点缓冲 | +| `virtual void SetVertexBuffers(uint32_t startSlot, uint32_t count, const uint64_t* buffers, const uint64_t* offsets, const uint32_t* strides)` | 设置多个顶点缓冲 | +| `virtual void SetIndexBuffer(void* buffer, uint64_t offset, Format format)` | 设置索引缓冲 | + +### 绘制命令 + +| 方法 | 描述 | +|------|------| +| `virtual void Draw(uint32_t vertexCount, uint32_t instanceCount = 1, uint32_t startVertex = 0, uint32_t startInstance = 0)` | 绘制调用 | +| `virtual void DrawIndexed(uint32_t indexCount, uint32_t instanceCount = 1, uint32_t startIndex = 0, int32_t baseVertex = 0, uint32_t startInstance = 0)` | 索引绘制调用 | + +### 清除命令 + +| 方法 | 描述 | +|------|------| +| `virtual void Clear(float r, float g, float b, float a, uint32_t buffers)` | 清除缓冲 | +| `virtual void ClearRenderTarget(void* renderTarget, const float color[4])` | 清除渲染目标 | +| `virtual void ClearDepthStencil(void* depthStencil, float depth, uint8_t stencil)` | 清除深度模板 | + +### 资源复制 + +| 方法 | 描述 | +|------|------| +| `virtual void CopyResource(void* dst, void* src)` | 复制资源 | + +### 计算着色器 + +| 方法 | 描述 | +|------|------| +| `virtual void Dispatch(uint32_t x, uint32_t y, uint32_t z)` | 分发计算着色器 | + +## 图元拓扑类型 (PrimitiveTopology) + +| 枚举值 | 描述 | +|--------|------| +| `PointList` | 点列表 | +| `LineList` | 线段列表 | +| `LineStrip` | 线段条带 | +| `TriangleList` | 三角形列表 | +| `TriangleStrip` | 三角形条带 | +| `PatchList` | 补丁列表(曲面细分) | + +## 使用示例 + +```cpp +// 重置命令列表 +commandList->Reset(); + +// 设置渲染状态 +commandList->SetPipelineState(pipelineState); +commandList->SetPrimitiveTopology(PrimitiveTopology::TriangleList); +commandList->SetViewport(viewport); +commandList->SetRenderTargets(1, &renderTarget, depthStencil); + +// 设置顶点缓冲 +commandList->SetVertexBuffer(0, vertexBuffer->GetNativeHandle(), 0, sizeof(Vertex)); +commandList->SetIndexBuffer(indexBuffer->GetNativeHandle(), 0, Format::R32_UInt); + +// 绘制 +commandList->DrawIndexed(indexCount, 1, 0, 0, 0); + +// 关闭命令列表 +commandList->Close(); + +// 提交到命令队列执行 +commandQueue->ExecuteCommandLists(1, (void**)&commandList); +``` + +## 相关文档 + +- [RHICommandQueue](./rhi-command-queue.md) - 命令队列 +- [RHIPipelineState](./rhi-pipeline-state.md) - 管线状态 +- [RHIDevice](./rhi-device.md) - 创建设备 diff --git a/docs/api/rhi/rhi-command-queue.md b/docs/api/rhi/rhi-command-queue.md new file mode 100644 index 00000000..6aa3f488 --- /dev/null +++ b/docs/api/rhi/rhi-command-queue.md @@ -0,0 +1,82 @@ +# RHICommandQueue + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` (abstract) + +**描述**: GPU 命令队列抽象接口,负责提交和执行命令列表,以及 GPU/CPU 同步。 + +## 概述 + +`RHICommandQueue` 封装了 GPU 命令队列的操作,包括命令列表提交、同步栅栏操作、GPU 空闲等待等功能。 + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual void Shutdown()` | 关闭命令队列 | + +### 命令执行 + +| 方法 | 描述 | +|------|------| +| `virtual void ExecuteCommandLists(uint32_t count, void** lists)` | 执行命令列表 | +| `virtual void Signal(RHIFence* fence, uint64_t value)` | 信号通知栅栏 | +| `virtual void Wait(RHIFence* fence, uint64_t value)` | 等待栅栏 | +| `virtual uint64_t GetCompletedValue()` | 获取已完成的值 | +| `virtual void WaitForIdle()` | 等待队列空闲 | + +### 属性访问 + +| 方法 | 描述 | +|------|------| +| `virtual CommandQueueType GetType() const` | 获取队列类型 | +| `virtual uint64_t GetTimestampFrequency() const` | 获取时间戳频率 | + +### 其他 + +| 方法 | 描述 | +|------|------| +| `virtual void* GetNativeHandle()` | 获取原生 API 句柄 | + +## 命令队列类型 (CommandQueueType) + +| 枚举值 | 描述 | +|--------|------| +| `Direct` | 直接队列,用于图形和计算命令 | +| `Compute` | 计算队列,专门用于计算着色器 | +| `Copy` | 复制队列,专门用于资源复制 | + +## 使用示例 + +```cpp +// 创建命令队列 +CommandQueueDesc queueDesc; +queueDesc.queueType = (uint32_t)CommandQueueType::Direct; +RHICommandQueue* commandQueue = device->CreateCommandQueue(queueDesc); + +// 创建同步栅栏 +FenceDesc fenceDesc; +fenceDesc.initialValue = 0; +RHIFence* fence = device->CreateFence(fenceDesc); + +// 提交命令列表执行 +commandQueue->ExecuteCommandLists(1, (void**)&commandList); + +// 信号通知栅栏 +commandQueue->Signal(fence, 1); + +// CPU 等待 GPU 完成 +fence->Wait(1); + +// 或者让 CPU 等待队列空闲 +commandQueue->WaitForIdle(); +``` + +## 相关文档 + +- [RHICommandList](./rhi-command-list.md) - 命令列表 +- [RHIFence](./rhi-fence.md) - 同步栅栏 +- [RHIDevice](./rhi-device.md) - 创建设备 diff --git a/docs/api/rhi/rhi-descriptor-pool.md b/docs/api/rhi/rhi-descriptor-pool.md new file mode 100644 index 00000000..ac0aa1f6 --- /dev/null +++ b/docs/api/rhi/rhi-descriptor-pool.md @@ -0,0 +1,51 @@ +# RHIDescriptorPool + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` (abstract) + +**描述**: GPU 描述符堆池抽象接口,用于管理 GPU 描述符的分配和回收。 + +## 概述 + +`RHIDescriptorPool` 封装了描述符堆(Descriptor Heap)的操作。描述符堆用于存储各种 GPU 描述符,如常量缓冲视图(CBV)、着色器资源视图(SRV)、无序访问视图(UAV)和采样器等。 + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual bool Initialize(const DescriptorPoolDesc& desc)` | 初始化描述符池 | +| `virtual void Shutdown()` | 释放描述符池资源 | + +### 属性访问 + +| 方法 | 描述 | +|------|------| +| `virtual void* GetNativeHandle()` | 获取原生 API 句柄 | +| `virtual uint32_t GetDescriptorCount() const` | 获取描述符数量 | +| `virtual DescriptorHeapType GetType() const` | 获取堆类型 | + +## 描述符池描述 (DescriptorPoolDesc) + +| 成员 | 类型 | 描述 | +|------|------|------| +| `device` | `void*` | 关联的设备指针 | +| `type` | `DescriptorHeapType` | 堆类型 | +| `descriptorCount` | `uint32_t` | 描述符数量 | +| `shaderVisible` | `bool` | 是否对着色器可见 | + +## 描述符堆类型 (DescriptorHeapType) + +| 枚举值 | 描述 | +|--------|------| +| `CBV_SRV_UAV` | 常量缓冲/着色器资源/无序访问视图 | +| `Sampler` | 采样器 | +| `RTV` | 渲染目标视图 | +| `DSV` | 深度模板视图 | + +## 相关文档 + +- [RHIDevice](./rhi-device.md) - 创建设备 +- [RHICapabilities](./rhi-capabilities.md) - 设备能力 diff --git a/docs/api/rhi/rhi-device.md b/docs/api/rhi/rhi-device.md new file mode 100644 index 00000000..82548d50 --- /dev/null +++ b/docs/api/rhi/rhi-device.md @@ -0,0 +1,89 @@ +# RHIDevice + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` (abstract) + +**描述**: RHI 渲染设备抽象接口,代表一个图形设备实例。 + +## 概述 + +`RHIDevice` 是 RHI 模块的核心接口之一,负责创建和管理所有 GPU 资源。每个 RHI 后端(D3D12、OpenGL 等)都需要实现此接口。 + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual bool Initialize(const RHIDeviceDesc& desc)` | 初始化设备 | +| `virtual void Shutdown()` | 关闭设备,释放所有资源 | + +### 资源创建 + +| 方法 | 描述 | +|------|------| +| `virtual RHIBuffer* CreateBuffer(const BufferDesc& desc)` | 创建 GPU 缓冲区 | +| `virtual RHITexture* CreateTexture(const TextureDesc& desc)` | 创建 GPU 纹理 | +| `virtual RHISwapChain* CreateSwapChain(const SwapChainDesc& desc)` | 创建交换链 | +| `virtual RHICommandList* CreateCommandList(const CommandListDesc& desc)` | 创建命令列表 | +| `virtual RHICommandQueue* CreateCommandQueue(const CommandQueueDesc& desc)` | 创建命令队列 | +| `virtual RHIShader* CompileShader(const ShaderCompileDesc& desc)` | 编译着色器 | +| `virtual RHIPipelineState* CreatePipelineState(const PipelineStateDesc& desc)` | 创建管线状态对象 | +| `virtual RHIFence* CreateFence(const FenceDesc& desc)` | 创建同步栅栏 | +| `virtual RHISampler* CreateSampler(const SamplerDesc& desc)` | 创建采样器 | + +### 设备信息 + +| 方法 | 描述 | +|------|------| +| `virtual const RHICapabilities& GetCapabilities() const` | 获取设备能力 | +| `virtual const RHIDeviceInfo& GetDeviceInfo() const` | 获取设备信息 | +| `virtual void* GetNativeDevice() = 0` | 获取原生设备指针 | + +## 使用示例 + +```cpp +// 创建 D3D12 设备 +RHI::RHIDevice* device = RHI::RHIFactory::CreateRHIDevice(RHI::RHIType::D3D12); + +// 配置设备描述 +RHI::RHIDeviceDesc desc; +desc.windowHandle = hwnd; +desc.width = 1280; +desc.height = 720; +desc.appName = L"MyApp"; +desc.enableDebugLayer = true; + +// 初始化设备 +if (device->Initialize(desc)) { + // 获取设备能力 + const RHI::RHICapabilities& caps = device->GetCapabilities(); + if (caps.bSupportsRayTracing) { + // 设备支持光线追踪 + } + + // 获取设备信息 + const RHI::RHIDeviceInfo& info = device->GetDeviceInfo(); + printf("GPU: %ls\n", info.description.c_str()); + + // 创建资源 + RHI::BufferDesc bufferDesc; + bufferDesc.size = 1024; + bufferDesc.bufferType = (uint32_t)RHI::BufferType::Vertex; + RHI::RHIBuffer* buffer = device->CreateBuffer(bufferDesc); + + // ... 使用设备 ... + + // 关闭设备 + device->Shutdown(); +} + +delete device; +``` + +## 相关文档 + +- [RHIFactory](./rhi-factory.md) - 设备工厂 +- [RHICapabilities](./rhi-capabilities.md) - 设备能力 +- [RHITypes](./rhi-types.md) - 设备描述结构体 diff --git a/docs/api/rhi/rhi-enums.md b/docs/api/rhi/rhi-enums.md new file mode 100644 index 00000000..e3a85486 --- /dev/null +++ b/docs/api/rhi/rhi-enums.md @@ -0,0 +1,458 @@ +# RHIEnums + +**命名空间**: `XCEngine::RHI` + +**类型**: `enums` + +**描述**: RHI 模块中使用的所有枚举类型汇总。 + +## 概述 + +本文档汇总了 RHI 模块中定义的所有枚举类型。这些枚举定义了图形 API 的各种选项和状态。 + +--- + +## ShaderType + +着色器类型枚举。 + +| 值 | 描述 | +|----|------| +| `ShaderType::Vertex` | 顶点着色器 | +| `ShaderType::Fragment` | 片元着色器 | +| `ShaderType::Geometry` | 几何着色器 | +| `ShaderType::Compute` | 计算着色器 | +| `ShaderType::TessControl` | 曲面细分控制 | +| `ShaderType::TessEvaluation` | 曲面细分评估 | +| `ShaderType::Hull` | Hull 着色器 (D3D) | +| `ShaderType::Domain` | Domain 着色器 (D3D) | +| `ShaderType::Amplification` | 放大着色器 (D3D12.9+) | +| `ShaderType::Mesh` | Mesh 着色器 (D3D12.9+) | +| `ShaderType::Library` | 着色器库 | + +--- + +## CullMode + +背面剔除模式枚举。 + +| 值 | 描述 | +|----|------| +| `CullMode::None` | 不剔除 | +| `CullMode::Front` | 剔除正面 | +| `CullMode::Back` | 剔除背面(默认) | + +--- + +## FillMode + +填充模式枚举。 + +| 值 | 描述 | +|----|------| +| `FillMode::Wireframe` | 线框模式 | +| `FillMode::Solid` | 实体模式(默认) | + +--- + +## BlendOp + +混合操作枚举。 + +| 值 | 描述 | +|----|------| +| `BlendOp::Add` | 加法 | +| `BlendOp::Subtract` | 减法 | +| `BlendOp::ReverseSubtract` | 反向减法 | +| `BlendOp::Min` | 最小值 | +| `BlendOp::Max` | 最大值 | + +--- + +## BlendFactor + +混合因子枚举。 + +| 值 | 描述 | +|----|------| +| `BlendFactor::Zero` | 0 | +| `BlendFactor::One` | 1 | +| `BlendFactor::SrcColor` | 源颜色 | +| `BlendFactor::InvSrcColor` | 1 - 源颜色 | +| `BlendFactor::SrcAlpha` | 源 Alpha | +| `BlendFactor::InvSrcAlpha` | 1 - 源 Alpha | +| `BlendFactor::DstAlpha` | 目标 Alpha | +| `BlendFactor::InvDstAlpha` | 1 - 目标 Alpha | +| `BlendFactor::DstColor` | 目标颜色 | +| `BlendFactor::InvDstColor` | 1 - 目标颜色 | +| `BlendFactor::SrcAlphaSat` | 饱和(源 Alpha, 1 - 目标 Alpha) | +| `BlendFactor::BlendFactor` | 混合因子 | +| `BlendFactor::InvBlendFactor` | 1 - 混合因子 | +| `BlendFactor::Src1Color` | 第二个源颜色 | +| `BlendFactor::InvSrc1Color` | 1 - 第二个源颜色 | +| `BlendFactor::Src1Alpha` | 第二个源 Alpha | +| `BlendFactor::InvSrc1Alpha` | 1 - 第二个源 Alpha | + +--- + +## ComparisonFunc + +比较函数枚举。 + +| 值 | 描述 | +|----|------| +| `ComparisonFunc::Never` | 从不通过 | +| `ComparisonFunc::Less` | 小于通过 | +| `ComparisonFunc::Equal` | 等于通过 | +| `ComparisonFunc::LessEqual` | 小于等于通过 | +| `ComparisonFunc::Greater` | 大于通过 | +| `ComparisonFunc::NotEqual` | 不等于通过 | +| `ComparisonFunc::GreaterEqual` | 大于等于通过 | +| `ComparisonFunc::Always` | 总是通过 | + +--- + +## StencilOp + +模板操作枚举。 + +| 值 | 描述 | +|----|------| +| `StencilOp::Keep` | 保持当前值 | +| `StencilOp::Zero` | 设置为 0 | +| `StencilOp::Replace` | 替换为参考值 | +| `StencilOp::IncrSat` | 增加并饱和 | +| `StencilOp::DecrSat` | 减少并饱和 | +| `StencilOp::Invert` | 位反转 | +| `StencilOp::Incr` | 增加并回绕 | +| `StencilOp::Decr` | 减少并回绕 | + +--- + +## TextureType + +纹理类型枚举。 + +| 值 | 描述 | +|----|------| +| `TextureType::Texture1D` | 1D 纹理 | +| `TextureType::Texture2D` | 2D 纹理 | +| `TextureType::Texture2DArray` | 2D 纹理数组 | +| `TextureType::Texture3D` | 3D 纹理 | +| `TextureType::TextureCube` | 立方体贴图 | +| `TextureType::TextureCubeArray` | 立方体贴图数组 | + +--- + +## BufferType + +缓冲区类型枚举。 + +| 值 | 描述 | +|----|------| +| `BufferType::Vertex` | 顶点缓冲 | +| `BufferType::Index` | 索引缓冲 | +| `BufferType::Constant` | 常量缓冲 | +| `BufferType::ReadBack` | 回读缓冲 | +| `BufferType::Indirect` | 间接缓冲 | +| `BufferType::RaytracingAccelerationStructure` | 光追加速结构 | +| `BufferType::ShaderBindingTable` | 着色器绑定表 | + +--- + +## DescriptorType + +描述符类型枚举。 + +| 值 | 描述 | +|----|------| +| `DescriptorType::CBV` | 常量缓冲视图 | +| `DescriptorType::SRV` | 着色器资源视图 | +| `DescriptorType::UAV` | 无序访问视图 | +| `DescriptorType::Sampler` | 采样器 | +| `DescriptorType::RTV` | 渲染目标视图 | +| `DescriptorType::DSV` | 深度模板视图 | + +--- + +## PipelineType + +管线类型枚举。 + +| 值 | 描述 | +|----|------| +| `PipelineType::Graphics` | 图形管线 | +| `PipelineType::Compute` | 计算管线 | +| `PipelineType::Raytracing` | 光线追踪管线 | + +--- + +## CommandQueueType + +命令队列类型枚举。 + +| 值 | 描述 | +|----|------| +| `CommandQueueType::Direct` | 直接队列 | +| `CommandQueueType::Compute` | 计算队列 | +| `CommandQueueType::Copy` | 复制队列 | + +--- + +## LoadAction + +加载操作枚举。 + +| 值 | 描述 | +|----|------| +| `LoadAction::Undefined` | 未定义 | +| `LoadAction::Load` | 加载现有内容 | +| `LoadAction::Clear` | 清除为默认值 | + +--- + +## StoreAction + +存储操作枚举。 + +| 值 | 描述 | +|----|------| +| `StoreAction::Undefined` | 未定义 | +| `StoreAction::Store` | 存储 | +| `StoreAction::Resolve` | 解析 | +| `StoreAction::StoreAndResolve` | 存储并解析 | +| `StoreAction::Discard` | 丢弃 | + +--- + +## PresentFlags + +呈现标志枚举。 + +| 值 | 描述 | +|----|------| +| `PresentFlags::None` | 无特殊标志 | +| `PresentFlags::AllowTearing` | 允许垂直同步撕裂 | +| `PresentFlags::StrictlyTimedFrame` | 严格帧时序 | +| `PresentFlags::AllowDisplayLatencyWaitableObject` | 显示延迟等待对象 | + +--- + +## FilterMode + +采样器过滤模式枚举。 + +| 值 | 描述 | +|----|------| +| `FilterMode::Point` | 点采样 | +| `FilterMode::Linear` | 双线性插值 | +| `FilterMode::Anisotropic` | 各向异性过滤 | +| `FilterMode::ComparisonPoint` | 比较点采样 | +| `FilterMode::ComparisonLinear` | 比较双线性 | +| `FilterMode::ComparisonAnisotropic` | 比较各向异性 | +| `FilterMode::MinimumPoint` | 最小值点采样 | +| `FilterMode::MinimumLinear` | 最小值线性 | +| `FilterMode::MinimumAnisotropic` | 最小值各向异性 | +| `FilterMode::MaximumPoint` | 最大值点采样 | +| `FilterMode::MaximumLinear` | 最大值线性 | +| `FilterMode::MaximumAnisotropic` | 最大值各向异性 | + +--- + +## TextureAddressMode + +纹理寻址模式枚举。 + +| 值 | 描述 | +|----|------| +| `TextureAddressMode::Wrap` | 重复寻址 | +| `TextureAddressMode::Mirror` | 镜像寻址 | +| `TextureAddressMode::Clamp` | 钳制寻址 | +| `TextureAddressMode::Border` | 边框颜色 | +| `TextureAddressMode::MirrorOnce` | 单次镜像 | + +--- + +## BorderColor + +边框颜色枚举。 + +| 值 | 描述 | +|----|------| +| `BorderColor::TransparentBlack` | 透明黑色 (0,0,0,0) | +| `BorderColor::OpaqueBlack` | 不透明黑色 (0,0,0,1) | +| `BorderColor::OpaqueWhite` | 不透明白色 (1,1,1,1) | + +--- + +## LogicOp + +逻辑操作枚举。 + +| 值 | 描述 | +|----|------| +| `LogicOp::Clear` | 清零 | +| `LogicOp::Set` | 置一 | +| `LogicOp::Copy` | 复制 | +| `LogicOp::CopyInverted` | 复制取反 | +| `LogicOp::Noop` | 无操作 | +| `LogicOp::Invert` | 取反 | +| `LogicOp::And` | 与 | +| `LogicOp::Nand` | 与非 | +| `LogicOp::Or` | 或 | +| `LogicOp::Nor` | 或非 | +| `LogicOp::Xor` | 异或 | +| `LogicOp::Equiv` | 同或 | +| `LogicOp::AndReverse` | 反向与 | +| `LogicOp::AndInverted` | 与反 | +| `LogicOp::OrReverse` | 反向或 | +| `LogicOp::OrInverted` | 或反 | + +--- + +## ColorWriteMask + +颜色写入掩码枚举,支持位运算组合。 + +| 值 | 描述 | +|----|------| +| `ColorWriteMask::Red` | 红色通道 (1) | +| `ColorWriteMask::Green` | 绿色通道 (2) | +| `ColorWriteMask::Blue` | 蓝色通道 (4) | +| `ColorWriteMask::Alpha` | Alpha 通道 (8) | +| `ColorWriteMask::All` | 所有通道 (15) | + +支持 `operator|` 进行组合,如 `ColorWriteMask::Red | ColorWriteMask::Green`。 + +--- + +## ShaderVisibility + +着色器可见性枚举。 + +| 值 | 描述 | +|----|------| +| `ShaderVisibility::All` | 所有着色器阶段 | +| `ShaderVisibility::Vertex` | 顶点着色器 | +| `ShaderVisibility::Hull` | Hull 着色器 | +| `ShaderVisibility::Domain` | Domain 着色器 | +| `ShaderVisibility::Geometry` | 几何着色器 | +| `ShaderVisibility::Pixel` | 像素着色器 | +| `ShaderVisibility::Amplification` | 放大着色器 | +| `ShaderVisibility::Mesh` | Mesh 着色器 | + +--- + +## RootParameterType + +根参数类型枚举。 + +| 值 | 描述 | +|----|------| +| `RootParameterType::DescriptorTable` | 描述符表 | +| `RootParameterType::Constants` | 内联常量 | +| `RootParameterType::CBV` | 常量缓冲视图 | +| `RootParameterType::SRV` | 着色器资源视图 | +| `RootParameterType::UAV` | 无序访问视图 | + +--- + +## DescriptorHeapType + +描述符堆类型枚举。 + +| 值 | 描述 | +|----|------| +| `DescriptorHeapType::CBV_SRV_UAV` | 常量缓冲/着色器资源/无序访问视图 | +| `DescriptorHeapType::Sampler` | 采样器 | +| `DescriptorHeapType::RTV` | 渲染目标视图 | +| `DescriptorHeapType::DSV` | 深度模板视图 | + +--- + +## QueryType + +查询类型枚举。 + +| 值 | 描述 | +|----|------| +| `QueryType::Occlusion` | 遮挡查询 | +| `QueryType::Timestamp` | 时间戳查询 | +| `QueryType::PipelineStatistics` | 管线统计查询 | + +--- + +## Format + +纹理/缓冲区格式枚举。 + +| 值 | 描述 | +|----|------| +| `Format::Unknown` | 未知 | +| `Format::R8_UNorm` | 单通道 8 位归一化 | +| `Format::R8G8_UNorm` | 双通道 8 位归一化 | +| `Format::R8G8B8A8_UNorm` | 四通道 8 位归一化 | +| `Format::R16G16B16A16_Float` | 四通道 16 位浮点 | +| `Format::R32G32B32A32_Float` | 四通道 32 位浮点 | +| `Format::R16_Float` | 单通道 16 位浮点 | +| `Format::R32_Float` | 单通道 32 位浮点 | +| `Format::D16_UNorm` | 16 位深度 | +| `Format::D24_UNorm_S8_UInt` | 24 位深度 + 8 位模板 | +| `Format::D32_Float` | 32 位深度 | +| `Format::BC1_UNorm` | BC1 压缩 (DXT1) | +| `Format::BC2_UNorm` | BC2 压缩 (DXT3) | +| `Format::BC3_UNorm` | BC3 压缩 (DXT5) | +| `Format::BC4_UNorm` | BC4 压缩 (ATI1N) | +| `Format::BC5_UNorm` | BC5 压缩 (ATI2N) | +| `Format::BC6H_UF16` | BC6H 有符号浮点压缩 | +| `Format::BC7_UNorm` | BC7 高质量压缩 | +| `Format::R32_UInt` | 单通道 32 位无符号整数 | +| `Format::R32G32B32A32_UInt` | 四通道 32 位无符号整数 | + +--- + +## ResourceStates + +资源状态枚举。 + +| 值 | 描述 | +|----|------| +| `ResourceStates::Common` | 通用状态 | +| `ResourceStates::VertexAndConstantBuffer` | 顶点/常量缓冲 | +| `ResourceStates::IndexBuffer` | 索引缓冲 | +| `ResourceStates::RenderTarget` | 渲染目标 | +| `ResourceStates::UnorderedAccess` | 无序访问 | +| `ResourceStates::DepthWrite` | 深度写入 | +| `ResourceStates::DepthRead` | 深度读取 | +| `ResourceStates::NonPixelShaderResource` | 非像素着色器资源 | +| `ResourceStates::PixelShaderResource` | 像素着色器资源 | +| `ResourceStates::CopySrc` | 复制源 | +| `ResourceStates::CopyDst` | 复制目标 | +| `ResourceStates::Present` | 呈现 | +| `ResourceStates::GenericRead` | 通用读取 | + +--- + +## HeapType + +内存堆类型枚举。 + +| 值 | 描述 | +|----|------| +| `HeapType::Default` | 默认堆(GPU 直接访问) | +| `HeapType::Upload` | 上传堆(CPU 可写,GPU 可读) | +| `HeapType::Readback` | 回读堆(CPU 可读) | +| `HeapType::Custom` | 自定义堆 | + +--- + +## RHIType + +RHI 后端类型枚举。 + +| 值 | 描述 | +|----|------| +| `RHIType::D3D12` | DirectX 12 | +| `RHIType::OpenGL` | OpenGL | +| `RHIType::Vulkan` | Vulkan(预留) | +| `RHIType::Metal` | Metal(预留) | diff --git a/docs/api/rhi/rhi-factory.md b/docs/api/rhi/rhi-factory.md new file mode 100644 index 00000000..40f3b5b2 --- /dev/null +++ b/docs/api/rhi/rhi-factory.md @@ -0,0 +1,46 @@ +# RHIFactory + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` + +**描述**: RHI 设备工厂,用于创建不同图形 API 后端的渲染设备。 + +## 概述 + +`RHIFactory` 是静态工厂类,提供统一的接口来创建不同后端的 `RHIDevice` 实例。通过 `RHIType` 枚举指定要创建的后端类型。 + +## 公共方法 + +| 方法 | 描述 | +|------|------| +| `static RHIDevice* CreateRHIDevice(RHIType type)` | 根据类型创建 RHI 设备 | +| `static RHIDevice* CreateRHIDevice(const std::string& typeName)` | 根据类型名称字符串创建设备 | + +## 类型映射 + +| RHIType | typeName 参数值 | +|----------|-----------------| +| `RHIType::D3D12` | `"D3D12"` | +| `RHIType::OpenGL` | `"OpenGL"` | +| `RHIType::Vulkan` | `"Vulkan"` | +| `RHIType::Metal` | `"Metal"` | + +## 使用示例 + +```cpp +// 方法1:使用枚举创建 +RHIDevice* d3d12Device = RHIFactory::CreateRHIDevice(RHIType::D3D12); + +// 方法2:使用字符串创建 +RHIDevice* glDevice = RHIFactory::CreateRHIDevice("OpenGL"); + +// 方法3:根据配置选择 +std::string backend = "D3D12"; // 可以从配置文件读取 +RHIDevice* device = RHIFactory::CreateRHIDevice(backend); +``` + +## 相关文档 + +- [RHIDevice](./rhi-device.md) - 渲染设备 +- [RHIEnums](./rhi-enums.md) - RHIType 枚举定义 diff --git a/docs/api/rhi/rhi-fence.md b/docs/api/rhi/rhi-fence.md new file mode 100644 index 00000000..7a982a6d --- /dev/null +++ b/docs/api/rhi/rhi-fence.md @@ -0,0 +1,68 @@ +# RHIFence + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` (abstract) + +**描述**: GPU 同步栅栏抽象接口,用于 GPU/CPU 同步和跨队列同步。 + +## 概述 + +`RHIFence` 封装了 GPU 栅栏操作,提供了一种可靠的方式来同步 CPU 和 GPU 之间的执行,以及不同命令队列之间的同步。 + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual void Shutdown()` | 释放栅栏资源 | + +### 同步操作 + +| 方法 | 描述 | +|------|------| +| `virtual void Signal()` | 信号通知(值为 1) | +| `virtual void Signal(uint64_t value)` | 信号通知(指定值) | +| `virtual void Wait(uint64_t value)` | 等待指定值 | +| `virtual uint64_t GetCompletedValue() const` | 获取已完成的值 | +| `virtual bool IsSignaled() const` | 检查是否已信号通知 | + +### 其他 + +| 方法 | 描述 | +|------|------| +| `virtual void* GetNativeHandle()` | 获取原生 API 句柄 | + +## 使用示例 + +```cpp +// 创建栅栏 +FenceDesc desc; +desc.initialValue = 0; +RHIFence* fence = device->CreateFence(desc); + +// CPU 等待 GPU 完成工作 +commandQueue->Signal(fence, 1); +fence->Wait(1); + +// 或者使用 GetCompletedValue 轮询 +commandQueue->Signal(fence, 100); +while (fence->GetCompletedValue() < 100) { + // CPU 可以做其他工作 + DoOtherWork(); +} + +// 检查栅栏状态 +if (fence->IsSignaled()) { + // GPU 工作已完成 +} + +// 重置和复用 +fence->Signal(0); +``` + +## 相关文档 + +- [RHICommandQueue](./rhi-command-queue.md) - 命令队列 +- [RHIDevice](./rhi-device.md) - 创建设备 diff --git a/docs/api/rhi/rhi-overview.md b/docs/api/rhi/rhi-overview.md new file mode 100644 index 00000000..6ebf566b --- /dev/null +++ b/docs/api/rhi/rhi-overview.md @@ -0,0 +1,122 @@ +# RHI (Render Hardware Interface) + +**命名空间**: `XCEngine::RHI` + +**类型**: `module` + +**描述**: RHI 抽象层是 XCEngine 的核心渲染硬件接口模块,提供了对底层图形 API(D3D12、OpenGL 等)的统一抽象。 + +## 概述 + +RHI(Render Hardware Interface)模块是 XCEngine 图形引擎的核心抽象层。它通过定义一组统一的接口和类型,封装了不同图形 API 的差异,使上层代码可以在不关心具体实现的情况下进行渲染。 + +### 架构设计 + +``` +┌─────────────────────────────────────────────┐ +│ 上层渲染代码 │ +│ (Renderer, Scene, Materials, etc.) │ +└─────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────┐ +│ RHI 抽象接口层 │ +│ RHIDevice, RHICommandList, RHIBuffer, ... │ +└─────────────────────────────────────────────┘ + │ + ┌───────────┴───────────┐ + ▼ ▼ +┌─────────────────────┐ ┌─────────────────────┐ +│ D3D12 后端 │ │ OpenGL 后端 │ +│ D3D12Device, ... │ │ OpenGLDevice, ... │ +└─────────────────────┘ └─────────────────────┘ +``` + +### 核心组件 + +| 组件 | 描述 | +|------|------| +| `RHIDevice` | 渲染设备抽象,代表一个图形设备实例 | +| `RHIFactory` | RHI 设备工厂,用于创建不同后端的设备 | +| `RHIBuffer` | GPU 缓冲区资源抽象(顶点缓冲、索引缓冲、常量缓冲等) | +| `RHITexture` | GPU 纹理资源抽象 | +| `RHICommandList` | GPU 命令列表抽象 | +| `RHICommandQueue` | GPU 命令队列抽象 | +| `RHISwapChain` | 交换链抽象,用于窗口渲染 | +| `RHIFence` | GPU 同步栅栏抽象 | +| `RHIShader` | 着色器资源抽象 | +| `RHIPipelineState` | 渲染管线状态抽象 | +| `RHISampler` | 纹理采样器抽象 | + +### 设备创建流程 + +```cpp +// 1. 使用工厂创建设备 +RHIDevice* device = RHIFactory::CreateRHIDevice(RHIType::D3D12); + +// 2. 初始化设备 +RHIDeviceDesc desc; +desc.windowHandle = hwnd; +desc.width = 1280; +desc.height = 720; +desc.appName = L"MyApp"; +device->Initialize(desc); + +// 3. 获取设备能力 +const RHICapabilities& caps = device->GetCapabilities(); + +// 4. 创建资源 +RHIBuffer* vertexBuffer = device->CreateBuffer(bufferDesc); +RHITexture* texture = device->CreateTexture(textureDesc); + +// 5. 使用完毕后关闭设备 +device->Shutdown(); +delete device; +``` + +### 支持的后端 + +| 后端 | 枚举值 | 状态 | +|------|--------|------| +| DirectX 12 | `RHIType::D3D12` | ✅ 已实现 | +| OpenGL | `RHIType::OpenGL` | ✅ 已实现 | +| Vulkan | `RHIType::Vulkan` | 🔜 预留 | +| Metal | `RHIType::Metal` | 🔜 预留 | + +## 模块内容 + +### 核心接口 + +- [RHIDevice](./rhi-device.md) - 渲染设备 +- [RHIFactory](./rhi-factory.md) - 设备工厂 + +### 资源类型 + +- [RHIBuffer](./rhi-buffer.md) - GPU 缓冲区 +- [RHITexture](./rhi-texture.md) - GPU 纹理 + +### 命令执行 + +- [RHICommandList](./rhi-command-list.md) - 命令列表 +- [RHICommandQueue](./rhi-command-queue.md) - 命令队列 +- [RHISwapChain](./rhi-swap-chain.md) - 交换链 +- [RHIFence](./rhi-fence.md) - 同步栅栏 + +### 渲染状态 + +- [RHIShader](./rhi-shader.md) - 着色器 +- [RHIPipelineState](./rhi-pipeline-state.md) - 管线状态 +- [RHISampler](./rhi-sampler.md) - 采样器 +- [RHIDescriptorPool](./rhi-descriptor-pool.md) - 描述符池 +- [RHIPipelineLayout](./rhi-pipeline-layout.md) - 管线布局 +- [RHICapabilities](./rhi-capabilities.md) - 设备能力 + +### 类型定义 + +- [RHIEnums](./rhi-enums.md) - 枚举类型汇总 +- [RHITypes](./rhi-types.md) - 结构体类型汇总 + +## 相关文档 + +- [D3D12 后端](./d3d12/d3d12-overview.md) +- [OpenGL 后端](./opengl/opengl-overview.md) diff --git a/docs/api/rhi/rhi-pipeline-layout.md b/docs/api/rhi/rhi-pipeline-layout.md new file mode 100644 index 00000000..14fcd8c1 --- /dev/null +++ b/docs/api/rhi/rhi-pipeline-layout.md @@ -0,0 +1,40 @@ +# RHIPipelineLayout + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` (abstract) + +**描述**: GPU 渲染管线布局抽象接口,用于定义着色器资源的绑定布局。 + +## 概述 + +`RHIPipelineLayout` 封装了管线布局(Root Signature)的创建和管理。管线布局定义了着色器程序期望的资源布局,包括常量缓冲、纹理和采样器的绑定位置。 + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual bool Initialize(const RHIPipelineLayoutDesc& desc)` | 初始化管线布局 | +| `virtual void Shutdown()` | 释放管线布局资源 | + +### 其他 + +| 方法 | 描述 | +|------|------| +| `virtual void* GetNativeHandle()` | 获取原生 API 句柄 | + +## 管线布局描述 (RHIPipelineLayoutDesc) + +| 成员 | 类型 | 描述 | +|------|------|------| +| `constantBufferCount` | `uint32_t` | 常量缓冲数量 | +| `textureCount` | `uint32_t` | 纹理数量 | +| `samplerCount` | `uint32_t` | 采样器数量 | +| `uavCount` | `uint32_t` | UAV 数量 | + +## 相关文档 + +- [RHIDevice](./rhi-device.md) - 创建设备 +- [RHIPipelineState](./rhi-pipeline-state.md) - 管线状态 diff --git a/docs/api/rhi/rhi-pipeline-state.md b/docs/api/rhi/rhi-pipeline-state.md new file mode 100644 index 00000000..9bc4f74d --- /dev/null +++ b/docs/api/rhi/rhi-pipeline-state.md @@ -0,0 +1,47 @@ +# RHIPipelineState + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` (abstract) + +**描述**: GPU 渲染管线状态抽象接口,封装了渲染管线的各种固定功能配置。 + +## 概述 + +`RHIPipelineState` 封装了渲染管线状态的创建和管理。管线状态对象(PIPSO)存储了 GPU 管线的不可变配置,包括着色器、混合状态、深度模板状态、光栅化状态等。 + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual void Shutdown()` | 释放管线状态对象 | + +### 绑定/解绑 + +| 方法 | 描述 | +|------|------| +| `virtual void Bind()` | 绑定管线状态到管线 | +| `virtual void Unbind()` | 解绑管线状态 | + +### 属性访问 + +| 方法 | 描述 | +|------|------| +| `virtual void* GetNativeHandle()` | 获取原生 API 句柄 | +| `virtual PipelineType GetType() const` | 获取管线类型 | + +## 管线类型 (PipelineType) + +| 枚举值 | 描述 | +|--------|------| +| `Graphics` | 图形渲染管线 | +| `Compute` | 计算管线 | +| `Raytracing` | 光线追踪管线 | + +## 相关文档 + +- [RHIDevice](./rhi-device.md) - 创建设备 +- [RHIShader](./rhi-shader.md) - 着色器 +- [RHICommandList](./rhi-command-list.md) - 命令列表 diff --git a/docs/api/rhi/rhi-sampler.md b/docs/api/rhi/rhi-sampler.md new file mode 100644 index 00000000..76f9dcdc --- /dev/null +++ b/docs/api/rhi/rhi-sampler.md @@ -0,0 +1,101 @@ +# RHISampler + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` (abstract) + +**描述**: GPU 纹理采样器抽象接口,用于配置纹理过滤和寻址模式。 + +## 概述 + +`RHISampler` 封装了纹理采样器的配置,包括过滤模式、寻址模式、各向异性、mipmap 等设置。 + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual void Shutdown()` | 释放采样器资源 | + +### 绑定/解绑 + +| 方法 | 描述 | +|------|------| +| `virtual void Bind(unsigned int unit)` | 绑定采样器到纹理单元 | +| `virtual void Unbind(unsigned int unit)` | 解绑采样器 | + +### 属性访问 + +| 方法 | 描述 | +|------|------| +| `virtual void* GetNativeHandle()` | 获取原生 API 句柄 | +| `virtual unsigned int GetID()` | 获取采样器 ID | + +## 采样器描述 (SamplerDesc) + +| 成员 | 类型 | 描述 | +|------|------|------| +| `filter` | `uint32_t` | 过滤模式 | +| `addressU` | `uint32_t` | U 轴寻址模式 | +| `addressV` | `uint32_t` | V 轴寻址模式 | +| `addressW` | `uint32_t` | W 轴寻址模式 | +| `mipLodBias` | `float` | Mipmap 级别偏移 | +| `maxAnisotropy` | `uint32_t` | 最大各向异性级别 | +| `comparisonFunc` | `uint32_t` | 比较函数 | +| `borderColorR` | `float` | 边框颜色 R | +| `borderColorG` | `float` | 边框颜色 G | +| `borderColorB` | `float` | 边框颜色 B | +| `borderColorA` | `float` | 边框颜色 A | +| `minLod` | `float` | 最小 Mipmap 级别 | +| `maxLod` | `float` | 最大 Mipmap 级别 | + +## 过滤模式 (FilterMode) + +| 枚举值 | 描述 | +|--------|------| +| `Point` | 点采样 | +| `Linear` | 双线性插值 | +| `Anisotropic` | 各向异性过滤 | +| `ComparisonPoint` | 带比较的点采样 | +| `ComparisonLinear` | 带比较的双线性插值 | +| `ComparisonAnisotropic` | 带比较的各向异性 | + +## 寻址模式 (TextureAddressMode) + +| 枚举值 | 描述 | +|--------|------| +| `Wrap` | 重复寻址 | +| `Mirror` | 镜像寻址 | +| `Clamp` | 钳制寻址 | +| `Border` | 边框颜色寻址 | +| `MirrorOnce` | 单次镜像 | + +## 使用示例 + +```cpp +// 创建采样器 +SamplerDesc samplerDesc; +samplerDesc.filter = (uint32_t)FilterMode::Anisotropic; +samplerDesc.addressU = (uint32_t)TextureAddressMode::Wrap; +samplerDesc.addressV = (uint32_t)TextureAddressMode::Wrap; +samplerDesc.addressW = (uint32_t)TextureAddressMode::Wrap; +samplerDesc.maxAnisotropy = 16; +samplerDesc.minLod = 0; +samplerDesc.maxLod = FLT_MAX; +samplerDesc.mipLodBias = 0; +samplerDesc.comparisonFunc = (uint32_t)ComparisonFunc::Never; + +RHISampler* sampler = device->CreateSampler(samplerDesc); + +// 绑定到纹理单元 0 +sampler->Bind(0); + +// 解绑 +sampler->Unbind(0); +``` + +## 相关文档 + +- [RHITexture](./rhi-texture.md) - 纹理资源 +- [RHIDevice](./rhi-device.md) - 创建设备 diff --git a/docs/api/rhi/rhi-shader.md b/docs/api/rhi/rhi-shader.md new file mode 100644 index 00000000..fe49823e --- /dev/null +++ b/docs/api/rhi/rhi-shader.md @@ -0,0 +1,115 @@ +# RHIShader + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` (abstract) + +**描述**: GPU 着色器资源抽象接口,用于管理着色器代码的编译和绑定。 + +## 概述 + +`RHIShader` 封装了着色器的编译、参数设置和绑定操作。着色器是 GPU 可编程管线的核心组件。 + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual void Shutdown()` | 释放着色器资源 | + +### 编译 + +| 方法 | 描述 | +|------|------| +| `virtual bool CompileFromFile(const wchar_t* filePath, const char* entryPoint, const char* target)` | 从文件编译着色器 | +| `virtual bool Compile(const void* sourceData, size_t sourceSize, const char* entryPoint, const char* target)` | 从内存编译着色器 | + +### 属性访问 + +| 方法 | 描述 | +|------|------| +| `virtual ShaderType GetType() const` | 获取着色器类型 | +| `virtual bool IsValid() const` | 检查着色器是否有效 | + +### 绑定/解绑 + +| 方法 | 描述 | +|------|------| +| `virtual void Bind()` | 绑定着色器到管线 | +| `virtual void Unbind()` | 解绑着色器 | + +### Uniform 设置 + +| 方法 | 描述 | +|------|------| +| `virtual void SetInt(const char* name, int value)` | 设置整数 uniform | +| `virtual void SetFloat(const char* name, float value)` | 设置浮点 uniform | +| `virtual void SetVec3(const char* name, float x, float y, float z)` | 设置三维向量 uniform | +| `virtual void SetVec4(const char* name, float x, float y, float z, float w)` | 设置四维向量 uniform | +| `virtual void SetMat4(const char* name, const float* value)` | 设置 4x4 矩阵 uniform | + +### 其他 + +| 方法 | 描述 | +|------|------| +| `virtual void* GetNativeHandle()` | 获取原生 API 句柄 | + +## 着色器类型 (ShaderType) + +| 枚举值 | 描述 | +|--------|------| +| `Vertex` | 顶点着色器 | +| `Fragment` | 片元着色器 | +| `Geometry` | 几何着色器 | +| `Compute` | 计算着色器 | +| `TessControl` | 曲面细分控制着色器 | +| `TessEvaluation` | 曲面细分评估着色器 | +| `Hull` | Hull 着色器 (D3D) | +| `Domain` | Domain 着色器 (D3D) | +| `Amplification` | 放大着色器 (D3D12.9+) | +| `Mesh` | Mesh 着色器 (D3D12.9+) | +| `Library` | 着色器库 | + +## 编译目标格式 + +| API | 目标格式 | +|-----|----------| +| D3D11 | `vs_5_0`, `ps_5_0`, `gs_5_0`, `cs_5_0` | +| D3D12 | `vs_6_0`, `ps_6_0`, `gs_6_0`, `cs_6_0`, `ds_6_0`, `hs_6_0` | +| OpenGL | `GLSL` (GLSL 源码) | + +## 使用示例 + +```cpp +// 编译顶点着色器 +RHIShader* vs = device->CompileShader({}); +vs->CompileFromFile(L"shaders/vertex.hlsl", "main", "vs_6_0"); + +// 编译片元着色器 +RHIShader* ps = device->CompileShader({}); +ps->CompileFromFile(L"shaders/fragment.hlsl", "main", "ps_6_0"); + +// 设置 uniform +vs->SetMat4("modelMatrix", modelMatrix); +vs->SetMat4("viewMatrix", viewMatrix); +vs->SetMat4("projectionMatrix", projectionMatrix); + +ps->SetVec3("lightDir", 0.5f, 0.8f, 0.3f); +ps->SetFloat("roughness", 0.5f); +ps->SetInt("albedoMap", 0); + +// 绑定着色器 +vs->Bind(); +ps->Bind(); + +// 使用完毕后关闭 +vs->Shutdown(); +ps->Shutdown(); +``` + +## 相关文档 + +- [RHIDevice](./rhi-device.md) - 创建设备 +- [RHIPipelineState](./rhi-pipeline-state.md) - 管线状态 +- [RHICommandList](./rhi-command-list.md) - 命令列表 diff --git a/docs/api/rhi/rhi-swap-chain.md b/docs/api/rhi/rhi-swap-chain.md new file mode 100644 index 00000000..7b6f7318 --- /dev/null +++ b/docs/api/rhi/rhi-swap-chain.md @@ -0,0 +1,94 @@ +# RHISwapChain + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` (abstract) + +**描述**: GPU 交换链抽象接口,用于管理窗口渲染和帧缓冲区切换。 + +## 概述 + +`RHISwapChain` 封装了帧缓冲区交换链的操作,包括获取当前后台缓冲、呈现渲染结果、窗口调整等功能。 + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual void Shutdown()` | 关闭交换链 | + +### 交换链操作 + +| 方法 | 描述 | +|------|------| +| `virtual uint32_t GetCurrentBackBufferIndex() const` | 获取当前后台缓冲索引 | +| `virtual RHITexture* GetCurrentBackBuffer()` | 获取当前后台缓冲纹理 | +| `virtual void Present(uint32_t syncInterval = 1, uint32_t flags = 0)` | 呈现渲染结果 | +| `virtual void Resize(uint32_t width, uint32_t height)` | 调整交换链大小 | + +### 全屏模式 + +| 方法 | 描述 | +|------|------| +| `virtual void SetFullscreen(bool fullscreen)` | 设置全屏模式 | +| `virtual bool IsFullscreen() const` | 检查是否全屏 | + +### 窗口事件 + +| 方法 | 描述 | +|------|------| +| `virtual bool ShouldClose() const` | 检查是否应该关闭 | +| `virtual void SetShouldClose(bool shouldClose)` | 设置关闭标志 | +| `virtual void PollEvents()` | 处理窗口事件 | + +### 其他 + +| 方法 | 描述 | +|------|------| +| `virtual void* GetNativeHandle()` | 获取原生 API 句柄 | + +## 相关文档 + +```cpp +// 创建交换链 +SwapChainDesc swapChainDesc; +swapChainDesc.width = 1280; +swapChainDesc.height = 720; +swapChainDesc.bufferCount = 2; +swapChainDesc.format = (uint32_t)Format::R8G8B8A8_UNorm; +swapChainDesc.refreshRate = 60; +swapChainDesc.sampleCount = 1; +swapChainDesc.sampleQuality = 0; +swapChainDesc.swapEffect = 0; +swapChainDesc.flags = 0; + +RHISwapChain* swapChain = device->CreateSwapChain(swapChainDesc); + +// 渲染循环 +while (!swapChain->ShouldClose()) { + swapChain->PollEvents(); + + // 获取当前后台缓冲 + RHITexture* backBuffer = swapChain->GetCurrentBackBuffer(); + + // 录制渲染命令 + commandList->Reset(); + commandList->SetRenderTargets(1, &backBuffer, nullptr); + commandList->ClearRenderTarget(backBuffer, clearColor); + // ... 更多渲染命令 ... + commandList->Close(); + + // 执行并呈现 + commandQueue->ExecuteCommandLists(1, (void**)&commandList); + swapChain->Present(1, 0); +} + +swapChain->Shutdown(); +``` + +## 相关文档 + +- [RHITexture](./rhi-texture.md) - 纹理资源 +- [RHICommandQueue](./rhi-command-queue.md) - 命令队列 +- [RHIDevice](./rhi-device.md) - 创建设备 diff --git a/docs/api/rhi/rhi-texture.md b/docs/api/rhi/rhi-texture.md new file mode 100644 index 00000000..4f8ca8a9 --- /dev/null +++ b/docs/api/rhi/rhi-texture.md @@ -0,0 +1,102 @@ +# RHITexture + +**命名空间**: `XCEngine::RHI` + +**类型**: `class` (abstract) + +**描述**: GPU 纹理资源抽象接口,用于管理 1D、2D、3D 纹理和立方体贴图等 GPU 资源。 + +## 概述 + +`RHITexture` 封装了 GPU 纹理的创建、状态管理和属性访问。纹理是 GPU 渲染中最常用的资源类型之一。 + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual void Shutdown()` | 释放纹理资源 | + +### 属性访问 + +| 方法 | 描述 | +|------|------| +| `virtual uint32_t GetWidth() const` | 获取纹理宽度(像素) | +| `virtual uint32_t GetHeight() const` | 获取纹理高度(像素) | +| `virtual uint32_t GetDepth() const` | 获取纹理深度(3D 纹理) | +| `virtual uint32_t GetMipLevels() const` | 获取 Mipmap 级别数 | +| `virtual Format GetFormat() const` | 获取纹理格式 | +| `virtual TextureType GetTextureType() const` | 获取纹理类型 | + +### 状态管理 + +| 方法 | 描述 | +|------|------| +| `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)` | 设置纹理名称(用于调试) | + +## 纹理类型 (TextureType) + +| 枚举值 | 描述 | +|--------|------| +| `TextureType::Texture1D` | 1D 纹理 | +| `TextureType::Texture2D` | 2D 纹理 | +| `TextureType::Texture2DArray` | 2D 纹理数组 | +| `TextureType::Texture3D` | 3D 纹理(体积纹理) | +| `TextureType::TextureCube` | 立方体贴图 | +| `TextureType::TextureCubeArray` | 立方体贴图数组 | + +## 纹理格式 (Format) + +| 格式 | 描述 | +|------|------| +| `Format::Unknown` | 未知格式 | +| `Format::R8_UNorm` | 单通道 8 位归一化 | +| `Format::R8G8_UNorm` | 双通道 8 位归一化 | +| `Format::R8G8B8A8_UNorm` | 四通道 8 位归一化 | +| `Format::R16G16B16A16_Float` | 四通道 16 位浮点 | +| `Format::R32G32B32A32_Float` | 四通道 32 位浮点 | +| `Format::D32_Float` | 32 位深度 | +| `Format::D24_UNorm_S8_UInt` | 24 位深度 + 8 位模板 | +| `Format::BC1_UNorm` | 压缩格式 (DXT1) | +| `Format::BC7_UNorm` | 压缩格式 | + +## 使用示例 + +```cpp +// 创建 2D 纹理 +TextureDesc desc; +desc.width = 1024; +desc.height = 1024; +desc.depth = 1; +desc.mipLevels = 1; +desc.arraySize = 1; +desc.format = (uint32_t)Format::R8G8B8A8_UNorm; +desc.textureType = (uint32_t)TextureType::Texture2D; +desc.sampleCount = 1; +desc.sampleQuality = 0; +desc.flags = 0; + +RHITexture* texture = device->CreateTexture(desc); + +// 设置资源状态 +texture->SetState(ResourceStates::PixelShaderResource); + +// 使用完毕后关闭 +texture->Shutdown(); +``` + +## 相关文档 + +- [RHIDevice](./rhi-device.md) - 创建设备 +- [RHIBuffer](./rhi-buffer.md) - 缓冲区资源 +- [RHISampler](./rhi-sampler.md) - 纹理采样器 diff --git a/docs/api/rhi/rhi-types.md b/docs/api/rhi/rhi-types.md new file mode 100644 index 00000000..c39c8b4f --- /dev/null +++ b/docs/api/rhi/rhi-types.md @@ -0,0 +1,394 @@ +# RHITypes + +**命名空间**: `XCEngine::RHI` + +**类型**: `structs` + +**描述**: RHI 模块中使用的所有结构体类型汇总。 + +## 概述 + +本文档汇总了 RHI 模块中定义的所有结构体类型。这些结构体用于配置各种资源的创建和渲染状态。 + +--- + +## Viewport + +视口结构体。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `topLeftX` | `float` | 视口左上角 X 坐标 | +| `topLeftY` | `float` | 视口左上角 Y 坐标 | +| `width` | `float` | 视口宽度 | +| `height` | `float` | 视口高度 | +| `minDepth` | `float` | 最小深度值 | +| `maxDepth` | `float` | 最大深度值 | + +--- + +## Rect + +裁剪矩形结构体。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `left` | `int32_t` | 矩形左边界 | +| `top` | `int32_t` | 矩形上边界 | +| `right` | `int32_t` | 矩形右边界 | +| `bottom` | `int32_t` | 矩形下边界 | + +--- + +## Color + +颜色结构体。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `r` | `float` | 红色分量 (0-1) | +| `g` | `float` | 绿色分量 (0-1) | +| `b` | `float` | 蓝色分量 (0-1) | +| `a` | `float` | Alpha 分量 (0-1) | + +--- + +## ClearValue + +清除值结构体。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `color` | `Color` | 清除颜色 | +| `depth` | `float` | 清除深度值 | +| `stencil` | `uint8_t` | 清除模板值 | + +--- + +## ShaderCompileMacro + +着色器编译宏定义。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `name` | `std::wstring` | 宏名称 | +| `definition` | `std::wstring` | 宏定义值 | + +--- + +## ShaderCompileDesc + +着色器编译描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `entryPoint` | `std::wstring` | 入口点函数名 | +| `profile` | `std::wstring` | 着色器配置文件 | +| `fileName` | `std::wstring` | 源文件名 | +| `macros` | `std::vector` | 编译宏列表 | + +--- + +## InputElementDesc + +输入布局元素描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `semanticName` | `std::string` | 语义名称 (如 POSITION, TEXCOORD) | +| `semanticIndex` | `uint32_t` | 语义索引 | +| `format` | `uint32_t` | 数据格式 | +| `inputSlot` | `uint32_t` | 输入槽 | +| `alignedByteOffset` | `uint32_t` | 对齐字节偏移 | +| `inputSlotClass` | `uint32_t` | 输入槽类别 | +| `instanceDataStepRate` | `uint32_t` | 实例数据步进率 | + +--- + +## InputLayoutDesc + +输入布局描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `elements` | `std::vector` | 输入元素列表 | + +--- + +## VertexBufferBinding + +顶点缓冲绑定描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `bufferLocation` | `uint64_t` | GPU 虚拟地址 | +| `sizeInBytes` | `uint32_t` | 缓冲区大小(字节) | +| `strideInBytes` | `uint32_t` | 单个顶点字节大小 | + +--- + +## TextureCopyLocation + +纹理复制位置描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `plSubresourceIndex` | `uint64_t` | 子资源索引 | +| `pResource` | `void*` | 资源指针 | + +--- + +## TextureDesc + +纹理描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `width` | `uint32_t` | 纹理宽度 | +| `height` | `uint32_t` | 纹理高度 | +| `depth` | `uint32_t` | 纹理深度 | +| `mipLevels` | `uint32_t` | Mipmap 级别数 | +| `arraySize` | `uint32_t` | 数组大小 | +| `format` | `uint32_t` | 纹理格式 | +| `textureType` | `uint32_t` | 纹理类型 | +| `sampleCount` | `uint32_t` | 采样数量 | +| `sampleQuality` | `uint32_t` | 采样质量 | +| `flags` | `uint64_t` | 纹理标志 | + +--- + +## BufferDesc + +缓冲区描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `size` | `uint64_t` | 缓冲区大小(字节) | +| `stride` | `uint32_t` | 元素字节大小 | +| `bufferType` | `uint32_t` | 缓冲区类型 | +| `flags` | `uint64_t` | 缓冲区标志 | + +--- + +## RenderTargetDesc + +渲染目标描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `width` | `uint32_t` | 宽度 | +| `height` | `uint32_t` | 高度 | +| `format` | `uint32_t` | 格式 | +| `sampleCount` | `uint32_t` | 采样数量 | +| `sampleQuality` | `uint32_t` | 采样质量 | + +--- + +## DepthStencilDesc + +深度模板描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `width` | `uint32_t` | 宽度 | +| `height` | `uint32_t` | 高度 | +| `format` | `uint32_t` | 格式 | +| `sampleCount` | `uint32_t` | 采样数量 | +| `sampleQuality` | `uint32_t` | 采样质量 | +| `depthEnable` | `bool` | 是否启用深度测试 | +| `stencilEnable` | `bool` | 是否启用模板测试 | + +--- + +## DescriptorHeapDesc + +描述符堆描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `descriptorCount` | `uint32_t` | 描述符数量 | +| `heapType` | `uint32_t` | 堆类型 | +| `flags` | `uint32_t` | 堆标志 | +| `nodeMask` | `uint32_t` | 节点掩码 | + +--- + +## CommandQueueDesc + +命令队列描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `queueType` | `uint32_t` | 队列类型 | +| `priority` | `uint32_t` | 优先级 | +| `nodeMask` | `uint32_t` | 节点掩码 | +| `flags` | `uint64_t` | 队列标志 | + +--- + +## CommandListDesc + +命令列表描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `commandListType` | `uint32_t` | 命令列表类型 | +| `nodeMask` | `uint32_t` | 节点掩码 | + +--- + +## FenceDesc + +栅栏描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `initialValue` | `uint64_t` | 初始值 | +| `flags` | `uint32_t` | 栅栏标志 | + +--- + +## SamplerDesc + +采样器描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `filter` | `uint32_t` | 过滤模式 | +| `addressU` | `uint32_t` | U 轴寻址模式 | +| `addressV` | `uint32_t` | V 轴寻址模式 | +| `addressW` | `uint32_t` | W 轴寻址模式 | +| `mipLodBias` | `float` | Mipmap 级别偏移 | +| `maxAnisotropy` | `uint32_t` | 最大各向异性 | +| `comparisonFunc` | `uint32_t` | 比较函数 | +| `borderColorR` | `float` | 边框颜色 R | +| `borderColorG` | `float` | 边框颜色 G | +| `borderColorB` | `float` | 边框颜色 B | +| `borderColorA` | `float` | 边框颜色 A | +| `minLod` | `float` | 最小 LOD | +| `maxLod` | `float` | 最大 LOD | + +--- + +## SwapChainDesc + +交换链描述。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `width` | `uint32_t` | 宽度 | +| `height` | `uint32_t` | 高度 | +| `bufferCount` | `uint32_t` | 缓冲数量 | +| `format` | `uint32_t` | 格式 | +| `refreshRate` | `uint32_t` | 刷新率 | +| `sampleCount` | `uint32_t` | 采样数量 | +| `sampleQuality` | `uint32_t` | 采样质量 | +| `swapEffect` | `uint32_t` | 交换效果 | +| `flags` | `uint32_t` | 交换链标志 | + +--- + +## RHIDeviceDesc + +设备描述。 + +| 成员 | 类型 | 描述 | 默认值 | +|------|------|------|--------| +| `enableDebugLayer` | `bool` | 启用调试层 | `false` | +| `enableGPUValidation` | `bool` | 启用 GPU 验证 | `false` | +| `adapterIndex` | `uint32_t` | 适配器索引 | `0` | +| `windowHandle` | `void*` | 窗口句柄 | `nullptr` | +| `width` | `uint32_t` | 窗口宽度 | `1280` | +| `height` | `uint32_t` | 窗口高度 | `720` | +| `appName` | `std::wstring` | 应用程序名称 | `L"XCEngine"` | + +--- + +## RHIDeviceInfo + +设备信息结构体。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `description` | `std::wstring` | 设备描述 | +| `vendor` | `std::wstring` | 供应商 | +| `renderer` | `std::wstring` | 渲染器 | +| `version` | `std::wstring` | 驱动版本 | +| `majorVersion` | `uint32_t` | 主版本 | +| `minorVersion` | `uint32_t` | 次版本 | +| `dedicatedVideoMemory` | `uint64_t` | 专用显存 | +| `dedicatedSystemMemory` | `uint64_t` | 专用系统内存 | +| `sharedSystemMemory` | `uint64_t` | 共享系统内存 | +| `vendorId` | `uint32_t` | 供应商 ID | +| `deviceId` | `uint32_t` | 设备 ID | +| `isSoftware` | `bool` | 是否软件设备 | + +--- + +## RHIRenderPassDesc + +渲染通道描述。 + +```cpp +struct RHIRenderPassDesc { + struct ColorAttachment { + void* texture = nullptr; + uint32_t loadAction = 0; + uint32_t storeAction = 0; + float clearColor[4] = {0.0f, 0.0f, 0.0f, 1.0f}; + }; + ColorAttachment colorAttachments[8]; + uint32_t colorAttachmentCount = 0; + struct DepthStencilAttachment { + void* texture = nullptr; + uint32_t loadAction = 0; + uint32_t storeAction = 0; + float clearDepth = 1.0f; + uint8_t clearStencil = 0; + } depthStencilAttachment; + bool hasDepthStencil = false; +}; +``` + +--- + +## DescriptorHandle + +描述符句柄。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `ptr` | `uint64_t` | 句柄指针 | + +--- + +## GPUDescriptorHandle + +GPU 描述符句柄。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `ptr` | `uint64_t` | GPU 句柄指针 | + +--- + +## CPUDescriptorHandle + +CPU 描述符句柄。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `ptr` | `uint64_t` | CPU 句柄指针 | + +--- + +## SubresourceRange + +子资源范围。 + +| 成员 | 类型 | 描述 | +|------|------|------| +| `baseMipLevel` | `uint32_t` | 基础 Mip 级别 | +| `mipLevels` | `uint32_t` | Mip 级别数 | +| `baseArraySlice` | `uint32_t` | 基础数组切片 | +| `arraySize` | `uint32_t` | 数组大小 | diff --git a/docs/api/threading/threading-lambdatask.md b/docs/api/threading/threading-lambdatask.md new file mode 100644 index 00000000..2ccbcf96 --- /dev/null +++ b/docs/api/threading/threading-lambdatask.md @@ -0,0 +1,53 @@ +# LambdaTask + +**命名空间**: `XCEngine::Threading` + +**类型**: `class` (template) + +**描述**: Lambda 任务封装模板类,允许使用 lambda 表达式创建任务,无需继承 ITask。 + +## 概述 + +`LambdaTask` 是一个模板封装类,将任意可调用对象(lambda、函数指针、std::function)包装为 `ITask`。这大大简化了简短任务的创建。 + +## 模板参数 + +| 参数 | 描述 | +|------|------| +| `Func` | 可调用对象类型 | + +## 构造方法 + +| 方法 | 描述 | +|------|------| +| `explicit LambdaTask(Func&& func, TaskPriority priority = TaskPriority::Normal)` | 构造 Lambda 任务 | + +## 使用示例 + +```cpp +// 使用 lambda 创建任务 +TaskSystem::Get().Submit( + std::make_unique>>( + []() { + printf("Hello from task!\n"); + }, + TaskPriority::Normal + ) +); + +// 或者直接使用 Submit 的便捷重载 +TaskSystem::Get().Submit([]() { + printf("Direct lambda task!\n"); +}); + +// 带依赖的任务 +TaskSystem::Get().Submit>([]() { + // 任务内容 +}, TaskPriority::High); +``` + +## 相关文档 + +- [ITask](./threading-task.md) - 任务基类 +- [TaskGroup](./threading-task-group.md) - 任务组 +- [TaskSystem](./threading-task-system.md) - 任务系统 diff --git a/docs/api/threading/threading-mutex.md b/docs/api/threading/threading-mutex.md new file mode 100644 index 00000000..713417cc --- /dev/null +++ b/docs/api/threading/threading-mutex.md @@ -0,0 +1,51 @@ +# Mutex + +**命名空间**: `XCEngine::Threading` + +**类型**: `class` + +**描述**: 互斥锁封装类,基于 `std::mutex` 实现,提供线程安全的互斥访问。 + +## 概述 + +`Mutex` 是对 `std::mutex` 的简单封装,提供了标准的 Lock/Unlock/TryLock 接口。它是 XCEngine 中最基础的同步原语,适用于保护共享数据的访问。 + +## 公共方法 + +| 方法 | 描述 | +|------|------| +| `void Lock()` | 获取锁(阻塞) | +| `void Unlock()` | 释放锁 | +| `bool TryLock()` | 尝试获取锁(非阻塞,成功返回 true) | + +## STL 兼容方法 + +支持 `lock()`、`unlock()`、`try_lock()` 以兼容 STL 的 lockable 概念。 + +## 使用示例 + +```cpp +Threading::Mutex mtx; +int sharedData = 0; + +// 线程安全地修改共享数据 +void SafeIncrement() { + mtx.Lock(); + ++sharedData; + mtx.Unlock(); +} + +// 或使用 TryLock +void SafeTryIncrement() { + if (mtx.TryLock()) { + ++sharedData; + mtx.Unlock(); + } +} +``` + +## 相关文档 + +- [SpinLock](./threading-spinlock.md) - 自旋锁 +- [ReadWriteLock](./threading-readwritelock.md) - 读写锁 +- [TaskSystem](./threading-task-system.md) - 任务系统 diff --git a/docs/api/threading/threading-overview.md b/docs/api/threading/threading-overview.md new file mode 100644 index 00000000..b922687a --- /dev/null +++ b/docs/api/threading/threading-overview.md @@ -0,0 +1,74 @@ +# Threading 模块概览 + +**命名空间**: `XCEngine::Threading` + +**类型**: `module` + +**描述**: XCEngine 的线程和并发模块,提供多线程编程所需的同步原语和任务系统。 + +## 概述 + +Threading 模块提供了一套完整的多线程编程工具,包括线程封装、同步原语和并行任务系统。 + +## 模块内容 + +### 同步原语 + +| 组件 | 文件 | 描述 | +|------|------|------| +| [Mutex](./threading-mutex.md) | `Mutex.h` | 互斥锁 | +| [SpinLock](./threading-spinlock.md) | `SpinLock.h` | 自旋锁 | +| [ReadWriteLock](./threading-readwritelock.md) | `ReadWriteLock.h` | 读写锁 | + +### 线程 + +| 组件 | 文件 | 描述 | +|------|------|------| +| [Thread](./threading-thread.md) | `Thread.h` | 线程封装类 | + +### 任务系统 + +| 组件 | 文件 | 描述 | +|------|------|------| +| [ITask](./threading-task.md) | `Task.h` | 任务基类 | +| [LambdaTask](./threading-lambdatask.md) | `LambdaTask.h` | Lambda 任务封装模板 | +| [TaskGroup](./threading-task-group.md) | `TaskGroup.h` | 任务组 | +| [TaskSystem](./threading-task-system.md) | `TaskSystem.h` | 并行任务调度系统 | +| [TaskSystemConfig](./threading-tasksystemconfig.md) | `TaskSystemConfig.h` | 任务系统配置 | + +## 同步原语对比 + +| 原语 | 适用场景 | 特点 | +|------|----------|------| +| `Mutex` | 一般互斥 | 可重入性差,开销适中 | +| `SpinLock` | 短临界区 | 无系统调用,开销低 | +| `ReadWriteLock` | 读多写少 | 读写分离,提高并发 | + +## 任务系统使用示例 + +```cpp +#include + +// 初始化任务系统 +TaskSystemConfig config; +config.workerThreadCount = 4; +TaskSystem::Get().Initialize(config); + +// 提交并行任务 +TaskSystem::Get().Submit([]() { + // 执行工作 +}); + +// 使用任务组 +TaskGroup* group = TaskSystem::Get().CreateTaskGroup(); +group->AddTask([]() { /* 任务1 */ }); +group->AddTask([]() { /* 任务2 */ }); +group->Wait(); + +// 销毁任务组 +TaskSystem::Get().DestroyTaskGroup(group); +``` + +## 相关文档 + +- [Memory 模块](../memory/memory-overview.md) - 内存分配器 diff --git a/docs/api/threading/threading-readwritelock.md b/docs/api/threading/threading-readwritelock.md new file mode 100644 index 00000000..efdac37f --- /dev/null +++ b/docs/api/threading/threading-readwritelock.md @@ -0,0 +1,53 @@ +# ReadWriteLock + +**命名空间**: `XCEngine::Threading` + +**类型**: `class` + +**描述**: 读写锁实现,支持多个并发读取或单一写入,提高读多写少场景的并发性能。 + +## 概述 + +`ReadWriteLock` 实现了一个经典的读写锁。它允许多个线程同时持有读锁,但在有写锁时,所有读锁都必须释放,写锁为独占访问。这对于读操作远多于写操作的共享数据非常有效。 + +## 公共方法 + +### 读锁 + +| 方法 | 描述 | +|------|------| +| `void ReadLock()` | 获取读锁(可重入,支持多个并发读者) | +| `void ReadUnlock()` | 释放读锁 | + +### 写锁 + +| 方法 | 描述 | +|------|------| +| `void WriteLock()` | 获取写锁(独占,阻塞所有读者和写者) | +| `void WriteUnlock()` | 释放写锁 | + +## 使用示例 + +```cpp +Threading::ReadWriteLock rwLock; +Containers::HashMap sharedMap; + +// 读操作(多个线程可同时读) +void ReadData(const String& key) { + rwLock.ReadLock(); + int* value = sharedMap.Find(key); + rwLock.ReadUnlock(); +} + +// 写操作(独占) +void WriteData(const String& key, int value) { + rwLock.WriteLock(); + sharedMap.Insert(key, value); + rwLock.WriteUnlock(); +} +``` + +## 相关文档 + +- [Mutex](./threading-mutex.md) - 互斥锁 +- [SpinLock](./threading-spinlock.md) - 自旋锁 diff --git a/docs/api/threading/threading-spinlock.md b/docs/api/threading/threading-spinlock.md new file mode 100644 index 00000000..0e60e429 --- /dev/null +++ b/docs/api/threading/threading-spinlock.md @@ -0,0 +1,46 @@ +# SpinLock + +**命名空间**: `XCEngine::Threading` + +**类型**: `class` + +**描述**: 自旋锁封装类,使用原子操作实现,适用于保护极短的临界区。 + +## 概述 + +`SpinLock` 是一个轻量级的自旋锁实现,使用 `std::atomic_flag` 的 test-and-set 操作。它在获取锁失败时不断轮询,不会导致线程切换,非常适合保护非常短的临界区(如简单的计数器递增)。 + +## 公共方法 + +| 方法 | 描述 | +|------|------| +| `void Lock()` | 获取锁(忙等待) | +| `void Unlock()` | 释放锁 | +| `bool TryLock()` | 尝试获取锁(非阻塞) | + +## 使用示例 + +```cpp +Threading::SpinLock spinLock; +int counter = 0; + +// 保护极短的临界区 +void FastIncrement() { + spinLock.Lock(); + ++counter; // 单一操作,无需切换到内核 + spinLock.Unlock(); +} + +// TryLock 用法 +void SafeIncrement() { + if (spinLock.TryLock()) { + ++counter; + spinLock.Unlock(); + } +} +``` + +## 相关文档 + +- [Mutex](./threading-mutex.md) - 互斥锁 +- [ReadWriteLock](./threading-readwritelock.md) - 读写锁 diff --git a/docs/api/threading/threading-task-group.md b/docs/api/threading/threading-task-group.md new file mode 100644 index 00000000..51abe816 --- /dev/null +++ b/docs/api/threading/threading-task-group.md @@ -0,0 +1,86 @@ +# TaskGroup + +**命名空间**: `XCEngine::Threading` + +**类型**: `class` + +**描述**: 任务组管理类,用于组织多个任务并支持批量等待、进度跟踪和依赖管理。 + +## 概述 + +`TaskGroup` 提供了一种批量管理任务的机制。它允许添加多个任务、设置任务依赖关系、等待所有任务完成,并提供进度回调功能。 + +## 公共方法 + +### 构造/析构 + +| 方法 | 描述 | +|------|------| +| `TaskGroup()` | 默认构造函数 | +| `~TaskGroup()` | 析构函数 | + +### 任务添加 + +| 方法 | 描述 | +|------|------| +| `uint64_t AddTask(std::unique_ptr task)` | 添加任务对象 | +| `uint64_t AddTask(Callback&& func, TaskPriority priority = TaskPriority::Normal)` | 添加 lambda 任务 | + +### 依赖管理 + +| 方法 | 描述 | +|------|------| +| `void AddDependency(uint64_t taskId, uint64_t dependsOn)` | 添加任务依赖关系 | + +### 等待 + +| 方法 | 描述 | +|------|------| +| `void Wait()` | 阻塞等待所有任务完成 | +| `bool WaitFor(std::chrono::milliseconds timeout)` | 超时等待 | + +### 回调和状态 + +| 方法 | 描述 | +|------|------| +| `void SetCompleteCallback(Callback&& callback)` | 设置完成回调 | +| `bool IsComplete() const` | 检查所有任务是否完成 | +| `float GetProgress() const` | 获取完成进度(0.0f ~ 1.0f) | +| `void Cancel()` | 取消所有任务 | + +## 使用示例 + +```cpp +TaskGroup* group = TaskSystem::Get().CreateTaskGroup(); + +// 添加多个任务 +uint64_t task1 = group->AddTask([]() { /* 任务1 */ }); +uint64_t task2 = group->AddTask([]() { /* 任务2 */ }); + +// 设置依赖:task3 等待 task1 完成 +uint64_t task3 = group->AddTask([]() { /* 任务3 */ }); +group->AddDependency(task3, task1); + +// 设置完成回调 +group->SetCompleteCallback([]() { + printf("All tasks completed!\n"); +}); + +// 等待完成 +group->Wait(); + +// 或者超时等待 +if (group->WaitFor(std::chrono::seconds(5))) { + printf("Completed within 5 seconds\n"); +} else { + printf("Timeout, some tasks did not complete\n"); +} + +// 销毁 +TaskSystem::Get().DestroyTaskGroup(group); +``` + +## 相关文档 + +- [ITask](./threading-task.md) - 任务基类 +- [TaskSystem](./threading-task-system.md) - 任务系统 diff --git a/docs/api/threading/threading-task-system.md b/docs/api/threading/threading-task-system.md new file mode 100644 index 00000000..33053714 --- /dev/null +++ b/docs/api/threading/threading-task-system.md @@ -0,0 +1,110 @@ +# TaskSystem + +**命名空间**: `XCEngine::Threading` + +**类型**: `class` (singleton) + +**描述**: 并行任务调度系统单例,提供工作窃取式任务队列和并行 for 循环。 + +## 概述 + +`TaskSystem` 是 XCEngine 的核心并行任务调度系统。它创建多个工作线程,使用优先级队列和工作窃取算法调度任务。它还提供 `ParallelFor` 方法用于数据级并行,以及主线程任务队列。 + +## 单例访问 + +| 方法 | 描述 | +|------|------| +| `static TaskSystem& Get()` | 获取单例实例 | + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `void Initialize(const TaskSystemConfig& config)` | 初始化任务系统 | +| `void Shutdown()` | 关闭任务系统 | + +### 任务提交 + +| 方法 | 描述 | +|------|------| +| `uint64_t Submit(std::unique_ptr task)` | 提交任务对象 | +| `uint64_t Submit(std::function&& func, TaskPriority priority = TaskPriority::Normal)` | 提交 lambda 任务 | + +### 任务组 + +| 方法 | 描述 | +|------|------| +| `TaskGroup* CreateTaskGroup()` | 创建任务组 | +| `void DestroyTaskGroup(TaskGroup* group)` | 销毁任务组 | + +### 等待 + +| 方法 | 描述 | +|------|------| +| `void Wait(uint64_t taskId)` | 等待指定任务完成 | + +### 信息 + +| 方法 | 描述 | +|------|------| +| `uint32_t GetWorkerThreadCount() const` | 获取工作线程数量 | + +### 并行 for + +| 方法 | 描述 | +|------|------| +| `template void ParallelFor(int32_t start, int32_t end, Func&& func)` | 并行执行 for 循环 | + +### 主线程 + +| 方法 | 描述 | +|------|------| +| `void RunOnMainThread(std::function&& func)` | 将任务提交到主线程执行 | +| `void Update()` | 在主线程中处理主线程队列 | + +## 使用示例 + +```cpp +// 初始化(4 个工作线程) +TaskSystemConfig config; +config.workerThreadCount = 4; +TaskSystem::Get().Initialize(config); + +// 提交任务 +TaskSystem::Get().Submit([]() { + printf("Task 1 running\n"); +}); + +TaskSystem::Get().Submit([]() { + printf("Task 2 running\n"); +}, TaskPriority::High); + +// 并行 for +TaskSystem::Get().ParallelFor(0, 1000, [](int32_t i) { + // 每个 i 独立处理 + process(i); +}); + +// 主线程任务 +TaskSystem::Get().RunOnMainThread([]() { + // 更新 UI 或其他主线程操作 +}); + +// 主循环中调用 Update +while (running) { + TaskSystem::Get().Update(); // 处理主线程任务 + // 其他渲染... +} + +// 关闭 +TaskSystem::Get().Shutdown(); +``` + +## 相关文档 + +- [ITask](./threading-task.md) - 任务基类 +- [LambdaTask](./threading-lambdatask.md) - Lambda 任务 +- [TaskGroup](./threading-task-group.md) - 任务组 +- [TaskSystemConfig](./threading-tasksystemconfig.md) - 配置 diff --git a/docs/api/threading/threading-task.md b/docs/api/threading/threading-task.md new file mode 100644 index 00000000..cf69f5d5 --- /dev/null +++ b/docs/api/threading/threading-task.md @@ -0,0 +1,96 @@ +# ITask / Task + +**命名空间**: `XCEngine::Threading` + +**类型**: `class` (abstract) / `enum` + +**描述**: 任务基类抽象接口和任务状态/优先级枚举定义。 + +## 概述 + +`ITask` 是任务系统的核心抽象基类。用户需要继承此类并实现 `Execute()` 方法来定义具体的任务逻辑。任务系统通过引用计数自动管理任务生命周期。 + +## TaskPriority 枚举 + +任务优先级枚举(数值越小优先级越高)。 + +| 值 | 描述 | +|----|------| +| `Critical` | 关键优先级(0) | +| `High` | 高优先级(1) | +| `Normal` | 普通优先级(2) | +| `Low` | 低优先级(3) | +| `Idle` | 空闲优先级(4) | + +## TaskStatus 枚举 + +任务状态枚举。 + +| 值 | 描述 | +|----|------| +| `Pending` | 等待中 | +| `Scheduled` | 已调度 | +| `Running` | 运行中 | +| `Completed` | 已完成 | +| `Failed` | 失败 | +| `Canceled` | 已取消 | + +## ITask 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `virtual void Execute() = 0` | 任务执行逻辑(纯虚) | +| `virtual void OnComplete() {}` | 任务完成回调(可重写) | +| `virtual void OnCancel() {}` | 任务取消回调(可重写) | + +### 属性 + +| 方法 | 描述 | +|------|------| +| `TaskPriority GetPriority() const` | 获取优先级 | +| `TaskStatus GetStatus() const` | 获取状态 | +| `uint64_t GetId() const` | 获取任务 ID | +| `void SetId(uint64_t id)` | 设置任务 ID | +| `void SetPriority(TaskPriority priority)` | 设置优先级 | +| `void SetStatus(TaskStatus status)` | 设置状态 | + +### 引用计数 + +| 方法 | 描述 | +|------|------| +| `void AddRef()` | 增加引用计数 | +| `void Release()` | 减少引用计数(自动 delete 引用归零时) | + +## 使用示例 + +```cpp +class MyTask : public ITask { +public: + explicit MyTask(int data) : m_data(data) {} + + void Execute() override { + // 执行任务逻辑 + printf("Task executed with data: %d\n", m_data); + } + + void OnComplete() override { + // 任务完成后的清理 + } + +private: + int m_data; +}; + +// 使用 +auto task = new MyTask(42); +task->SetPriority(TaskPriority::High); +TaskSystem::Get().Submit(std::unique_ptr(task)); +``` + +## 相关文档 + +- [LambdaTask](./threading-lambdatask.md) - Lambda 任务封装 +- [TaskGroup](./threading-task-group.md) - 任务组 +- [TaskSystem](./threading-task-system.md) - 任务系统 diff --git a/docs/api/threading/threading-tasksystemconfig.md b/docs/api/threading/threading-tasksystemconfig.md new file mode 100644 index 00000000..555f0d4f --- /dev/null +++ b/docs/api/threading/threading-tasksystemconfig.md @@ -0,0 +1,33 @@ +# TaskSystemConfig + +**命名空间**: `XCEngine::Threading` + +**类型**: `struct` + +**描述**: 任务系统配置结构体。 + +## 结构体成员 + +| 成员 | 类型 | 描述 | 默认值 | +|------|------|------|--------| +| `workerThreadCount` | `uint32_t` | 工作线程数量(0=自动检测) | 0 | +| `enableTaskProfiling` | `bool` | 启用任务性能分析 | true | +| `stealTasks` | `bool` | 启用工作窃取 | true | +| `maxTaskQueueSize` | `uint32_t` | 最大任务队列大小 | 1024 | +| `threadStackSize` | `uint32_t` | 线程栈大小(0=默认) | 0 | + +## 使用示例 + +```cpp +TaskSystemConfig config; +config.workerThreadCount = std::thread::hardware_concurrency(); +config.enableTaskProfiling = true; +config.stealTasks = true; +config.maxTaskQueueSize = 2048; + +TaskSystem::Get().Initialize(config); +``` + +## 相关文档 + +- [TaskSystem](./threading-task-system.md) - 任务系统 diff --git a/docs/api/threading/threading-thread.md b/docs/api/threading/threading-thread.md new file mode 100644 index 00000000..c7a6d2b0 --- /dev/null +++ b/docs/api/threading/threading-thread.md @@ -0,0 +1,77 @@ +# Thread + +**命名空间**: `XCEngine::Threading` + +**类型**: `class` + +**头文件**: `XCEngine/Threading/Thread.h` + +**描述**: 线程封装类,提供跨平台线程创建和管理功能。 + +## 概述 + +`Thread` 类封装了 `std::thread`,提供统一的线程管理接口,包括启动、加入、分离等操作。 + +## 公共类型 + +| 类型 | 描述 | +|------|------| +| `using Id = uint64_t` | 线程唯一标识符类型 | + +## 公共方法 + +### 生命周期 + +| 方法 | 描述 | +|------|------| +| `Thread()` | 默认构造函数 | +| `~Thread()` | 析构函数 | + +### 线程控制 + +| 方法 | 描述 | +|------|------| +| `template void Start(Func&& func, const Containers::String& name = "Thread")` | 启动线程,执行传入的函数 | +| `void Join()` | 等待线程结束 | +| `void Detach()` | 分离线程,使其独立运行 | + +### 属性访问 + +| 方法 | 描述 | +|------|------| +| `Id GetId() const` | 获取线程 ID | +| `const Containers::String& GetName() const` | 获取线程名称 | + +### 静态方法 + +| 方法 | 描述 | +|------|------| +| `static Id GetCurrentId()` | 获取当前线程 ID | +| `static void Sleep(uint32_t milliseconds)` | 线程休眠指定毫秒数 | +| `static void Yield()` | 让出当前线程的时间片 | + +## 使用示例 + +```cpp +#include + +// 创建并启动线程 +Thread thread; +thread.Start([]() { + // 线程工作 + printf("Worker thread running\n"); +}, "WorkerThread"); + +// 等待线程结束 +thread.Join(); + +// 使用静态方法 +Thread::Sleep(1000); // 休眠1秒 +Thread::Yield(); // 让出时间片 +auto currentId = Thread::GetCurrentId(); +``` + +## 相关文档 + +- [Mutex](./threading-mutex.md) - 互斥锁 +- [TaskSystem](./threading-task-system.md) - 任务调度系统 diff --git a/docs/D3D12后端测试设计.md b/docs/plan/D3D12后端测试设计.md similarity index 100% rename from docs/D3D12后端测试设计.md rename to docs/plan/D3D12后端测试设计.md diff --git a/docs/OpenGL后端测试设计.md b/docs/plan/OpenGL后端测试设计.md similarity index 100% rename from docs/OpenGL后端测试设计.md rename to docs/plan/OpenGL后端测试设计.md diff --git a/docs/OpenGL测试实施计划.md b/docs/plan/OpenGL测试实施计划.md similarity index 100% rename from docs/OpenGL测试实施计划.md rename to docs/plan/OpenGL测试实施计划.md diff --git a/docs/RHI抽象层设计与实现.md b/docs/plan/RHI抽象层设计与实现.md similarity index 100% rename from docs/RHI抽象层设计与实现.md rename to docs/plan/RHI抽象层设计与实现.md diff --git a/docs/TESTING.md b/docs/plan/TESTING.md similarity index 100% rename from docs/TESTING.md rename to docs/plan/TESTING.md diff --git a/docs/Unity SRP API参考文档.md b/docs/plan/Unity SRP API参考文档.md similarity index 100% rename from docs/Unity SRP API参考文档.md rename to docs/plan/Unity SRP API参考文档.md diff --git a/docs/XCEngine渲染引擎架构设计.md b/docs/plan/XCEngine渲染引擎架构设计.md similarity index 100% rename from docs/XCEngine渲染引擎架构设计.md rename to docs/plan/XCEngine渲染引擎架构设计.md diff --git a/docs/XCGameEngine架构设计.md b/docs/plan/XCGameEngine架构设计.md similarity index 100% rename from docs/XCGameEngine架构设计.md rename to docs/plan/XCGameEngine架构设计.md diff --git a/docs/仿Unity RHI架构设计.md b/docs/plan/仿Unity RHI架构设计.md similarity index 100% rename from docs/仿Unity RHI架构设计.md rename to docs/plan/仿Unity RHI架构设计.md diff --git a/docs/开题报告和任务书/DXR_Volumetric_Rendering_Research_Report.md b/docs/plan/开题报告和任务书/DXR_Volumetric_Rendering_Research_Report.md similarity index 100% rename from docs/开题报告和任务书/DXR_Volumetric_Rendering_Research_Report.md rename to docs/plan/开题报告和任务书/DXR_Volumetric_Rendering_Research_Report.md diff --git a/docs/开题报告和任务书/任务书-王子文.docx b/docs/plan/开题报告和任务书/任务书-王子文.docx similarity index 100% rename from docs/开题报告和任务书/任务书-王子文.docx rename to docs/plan/开题报告和任务书/任务书-王子文.docx diff --git a/docs/开题报告和任务书/完整开题报告.md b/docs/plan/开题报告和任务书/完整开题报告.md similarity index 100% rename from docs/开题报告和任务书/完整开题报告.md rename to docs/plan/开题报告和任务书/完整开题报告.md diff --git a/docs/开题报告和任务书/开题报告-王子文.doc b/docs/plan/开题报告和任务书/开题报告-王子文.doc similarity index 100% rename from docs/开题报告和任务书/开题报告-王子文.doc rename to docs/plan/开题报告和任务书/开题报告-王子文.doc diff --git a/docs/旧版题目/开题报告-王子文.doc b/docs/plan/旧版题目/开题报告-王子文.doc similarity index 100% rename from docs/旧版题目/开题报告-王子文.doc rename to docs/plan/旧版题目/开题报告-王子文.doc diff --git a/docs/旧版题目/开题报告-王子文.md b/docs/plan/旧版题目/开题报告-王子文.md similarity index 100% rename from docs/旧版题目/开题报告-王子文.md rename to docs/plan/旧版题目/开题报告-王子文.md diff --git a/docs/深入方向规划.md b/docs/plan/深入方向规划.md similarity index 100% rename from docs/深入方向规划.md rename to docs/plan/深入方向规划.md diff --git a/skills/doc-api-manager/SKILL.md b/skills/doc-api-manager/SKILL.md new file mode 100644 index 00000000..01f29130 --- /dev/null +++ b/skills/doc-api-manager/SKILL.md @@ -0,0 +1,341 @@ +# XCEngine API 文档编写与校验 Skill + +## 用途 + +根据 XCEngine C++ 引擎源码生成符合规范的 API 文档,并进行格式校验和查漏补缺。 + +--- + +## 文档层次结构规范 + +### 文件命名 + +文档文件统一命名为 `{module-name}.md`,按子系统组织目录结构: + +``` +docs/api/ +├── index.md # 总索引 +├── math/ # 数学库 +├── containers/ # 容器 +├── memory/ # 内存管理 +├── threading/ # 线程与任务 +├── debug/ # 调试与日志 +├── core/ # 核心基础 +├── rhi/ # RHI 抽象层 +│ ├── d3d12/ # D3D12 后端 +│ └── opengl/ # OpenGL 后端 +└── resources/ # 资源管理 +``` + +### 文档模板 + +```markdown +# {类/结构体名称} + +**命名空间**: `{namespace}` + +**类型**: `{type}` (`class` / `struct` / `class` (abstract) / `class` (template) / `class` (singleton) / `enum` / `struct`) + +**描述**: {一句话功能描述} + +## 概述 + +{模块功能详细介绍,包括设计目的和使用场景} + +## {类型别名/子类型 1}(可选章节) + +{子类型详细说明} + +## 公共方法 + +### {方法分组 1} + +| 方法 | 描述 | +|------|------| +| `{signature}` | {描述} | + +### {方法分组 2} + +| 方法 | 描述 | +|------|------| +| `{signature}` | {描述} | + +## 公共成员(struct/enum 时) + +| 成员 | 类型 | 描述 | +|------|------|------| +| `{name}` | `{type}` | {description} | + +## 枚举值(enum 时) + +| 值 | 描述 | +|----|------| +| `{EnumValue}` | {description} | + +## 使用示例 + +```cpp +{代码示例} +``` + +## 相关文档 + +- [{文档名}](./{filename}.md) - {简短描述} +``` + +--- + +## 必需字段规范 + +### 元信息(必须) + +- `**命名空间**`: C++ 命名空间,如 `XCEngine::Math`、`XCEngine::RHI` +- `**类型**`: `class`、`struct`、`enum`、`class` (abstract)、`class` (template)、`class` (singleton) +- `**描述**`: 一句话功能描述 + +### 必需章节 + +1. **概述** - 模块功能介绍(设计目的、使用场景) +2. **公共方法** - 所有 public 方法按逻辑分组列出 +3. **使用示例** - 完整可运行的代码示例 +4. **相关文档** - @see 交叉引用 + +### 可选章节(按需添加) + +- **类型别名/子类型** - 嵌套类型、结构体成员、枚举值 +- **构造/析构** +- **运算符重载** +- **静态方法** +- **私有成员说明** + +--- + +## 校验规则 + +### 1. 格式校验 + +- [ ] 文档有且只有一个 `#` 一级标题 +- [ ] 元信息完整:`命名空间`、`类型`、`描述` +- [ ] 每个方法有清晰的分组标题 +- [ ] 代码块使用 ``` 包裹,语言标识正确(`cpp`、`json`) +- [ ] 表格格式正确:`|header|`,有分隔行 `|------|------|` + +### 2. 引用校验 + +- [ ] `@see` / `- [xxx](./xxx.md)` 引用的文件存在 +- [ ] 引用路径使用相对路径 +- [ ] 不存在循环引用 + +### 3. 内容校验 + +- [ ] 所有 public 方法都已列出 +- [ ] 方法签名与源码一致 +- [ ] 返回值类型正确 +- [ ] 默认参数值标注清楚 +- [ ] 示例代码可编译运行 +- [ ] 命名空间与源码一致 + +--- + +## 生成流程 + +1. **扫描源码**:分析 `engine/include/XCEngine/` 目录下的头文件 +2. **识别 API**:查找 `class`、`struct`、`enum`、`namespace` +3. **提取信息**:从源码中提取方法签名、成员变量、枚举值、文档注释 +4. **生成文档**:按照上述模板生成 Markdown 文件 +5. **校验输出**:运行校验规则,检查格式和引用 +6. **输出报告**:列出生成的文档和发现的问题 + +--- + +## 各子系统文档清单 + +### Math 模块 + +- [x] math-overview.md +- [x] math-h.md (常量) +- [x] math-vector2.md +- [x] math-vector3.md +- [x] math-vector4.md +- [x] math-matrix3.md +- [x] math-matrix4.md +- [x] math-quaternion.md +- [x] math-transform.md +- [x] math-color.md +- [x] math-plane.md +- [x] math-sphere.md +- [x] math-box.md +- [x] math-bounds.md +- [x] math-aabb.md +- [x] math-frustum.md +- [x] math-ray.md +- [x] math-rect.md + +### Containers 模块 + +- [x] container-overview.md +- [x] container-array.md +- [x] container-string.md +- [x] container-hashmap.md + +### Memory 模块 + +- [x] memory-overview.md +- [x] memory-allocator.md +- [x] memory-linear-allocator.md +- [x] memory-pool-allocator.md +- [x] memory-proxy-allocator.md +- [x] memory-manager.md + +### Threading 模块 + +- [x] threading-overview.md +- [x] threading-thread.md +- [x] threading-mutex.md +- [x] threading-spinlock.md +- [x] threading-readwritelock.md +- [x] threading-task.md +- [x] threading-lambdatask.md +- [x] threading-task-group.md +- [x] threading-task-system.md +- [x] threading-tasksystemconfig.md + +### Debug 模块 + +- [x] debug-overview.md +- [x] debug-logger.md +- [x] debug-ilogsink.md +- [x] debug-consolelogsink.md +- [x] debug-filelogsink.md +- [x] debug-loglevel.md +- [x] debug-logcategory.md +- [x] debug-logentry.md +- [x] debug-profiler.md + +### Core 模块 + +- [x] core-overview.md +- [x] core-types.md +- [x] core-smartptr.md +- [x] core-refcounted.md +- [x] core-event.md +- [x] core-filewriter.md + +### RHI 模块(抽象层) + +- [x] rhi-overview.md +- [x] rhi-device.md +- [x] rhi-factory.md +- [x] rhi-buffer.md +- [x] rhi-texture.md +- [x] rhi-shader.md +- [x] rhi-command-list.md +- [x] rhi-command-queue.md +- [x] rhi-swap-chain.md +- [x] rhi-fence.md +- [x] rhi-pipeline-state.md +- [x] rhi-sampler.md +- [x] rhi-pipeline-layout.md +- [x] rhi-descriptor-pool.md +- [x] rhi-capabilities.md +- [x] rhi-types.md +- [x] rhi-enums.md + +### RHI D3D12 后端 + +- [x] d3d12-overview.md +- [x] d3d12-device.md +- [x] d3d12-buffer.md +- [x] d3d12-texture.md +- [x] d3d12-command-list.md +- [x] d3d12-command-queue.md +- [x] d3d12-swap-chain.md +- [x] d3d12-fence.md +- [x] d3d12-shader.md +- [x] d3d12-pipeline-state.md +- [x] d3d12-sampler.md +- [x] d3d12-root-signature.md +- [x] d3d12-descriptor-heap.md +- [x] d3d12-render-target-view.md +- [x] d3d12-depth-stencil-view.md +- [x] d3d12-shader-resource-view.md +- [x] d3d12-unordered-access-view.md +- [x] d3d12-constant-buffer-view.md +- [x] d3d12-command-allocator.md +- [x] d3d12-query-heap.md +- [x] d3d12-screenshot.md +- [x] d3d12-types.md +- [x] d3d12-enums.md +- [x] d3d12-common.md + +### RHI OpenGL 后端 + +- [x] opengl-overview.md +- [x] opengl-device.md +- [x] opengl-buffer.md +- [x] opengl-texture.md +- [x] opengl-command-list.md +- [x] opengl-command-queue.md +- [x] opengl-swap-chain.md +- [x] opengl-fence.md +- [x] opengl-shader.md +- [x] opengl-pipeline-state.md +- [x] opengl-sampler.md +- [x] opengl-vertex-array.md +- [x] opengl-render-target-view.md +- [x] opengl-depth-stencil-view.md + +### Resources 模块 + +- [x] resources-overview.md +- [x] resources-iresource.md +- [x] resources-resourcehandle.md +- [x] resources-iloader.md +- [x] resources-resourcemanager.md +- [x] resources-resourcecache.md +- [x] resources-asyncloader.md +- [x] resources-dependencygraph.md +- [x] resources-filesystem.md +- [x] resources-resourcetypes.md +- [x] resources-importsettings.md + +--- + +## 输出格式 + +```json +{ + "generated": [ + { + "file": "docs/api/math/math-vector3.md", + "status": "created", + "classes": 1, + "methods": 15 + } + ], + "issues": [ + { + "file": "docs/api/rhi/rhi-overview.md", + "type": "broken_reference", + "message": "../rhi/d3d12/d3d12-device.md 引用了不存在的文件,应为 ../rhi/d3d12/d3d12-overview.md" + } + ] +} +``` + +--- + +## 使用示例 + +用户输入: +``` +完善 docs/api 文档,检查并修复错误 +``` + +AI 执行: +1. 扫描 `engine/include/XCEngine/` 源码目录 +2. 识别所有头文件中的 class/struct/enum +3. 对比现有文档,找出缺失文件和错误引用 +4. 生成或修复 Markdown 文档 +5. 运行校验检查格式和引用 +6. 输出生成报告和问题列表 diff --git a/skills/doc-blueprint-manager/SKILL.md b/skills/doc-blueprint-manager/SKILL.md new file mode 100644 index 00000000..e80d50fb --- /dev/null +++ b/skills/doc-blueprint-manager/SKILL.md @@ -0,0 +1,332 @@ +# 蓝图文档生成与校验 Skill + +## 用途 + +根据项目源码生成符合 XCSDD 规范的蓝图文档(系统架构设计文档),并校验 YAML 结构和依赖关系。 + +--- + +## 蓝图文档结构规范 + +### 文件命名 + +蓝图文档统一命名为 `blueprint.md`,放在 `docs/` 目录下。 + +### 文档整体结构 + +```markdown +# {系统名称} 蓝图示例 + +--- + +# SYSTEM_META + +```yaml +name: {系统名称} +version: {版本号} +type: {系统类型} +description: "{系统描述}" +target_runtime: {目标运行时} +``` + +--- + +# SYSTEM_STRUCTURE + +```yaml +root: {根模块} + +subsystems: + - name: {子系统名} + responsibilities: + - "{职责1}" + - "{职责2}" + provides: [{提供的接口1}, {提供的接口2}] + depends_on: [{依赖的子系统}] + boundary: + inputs: [{输入}] + outputs: [{输出}] + +modules: + - name: {模块名} + parent_subsystem: {所属子系统} + responsibility: "{模块职责}" + public_api: + - fn: {函数名} + params: + - name: {参数名} + type: {参数类型} + returns: type: {返回类型} +``` + +--- + +# EVOLUTION_MODE + +```yaml +mode: {build|evolve|maintain} +description: "{模式描述}" +context: | + {详细上下文说明} +``` + +--- + +# REQUIREMENTS + +```yaml +- id: {REQ-ID} + title: {需求标题} + description: "{需求描述}" + source: {user|constraint} + type: {functional|non-functional} + acceptance_criteria: + - "{验收标准1}" + priority: {P0|P1|P2} +``` + +--- + +# MVS_DEFINITION + +```yaml +mvs_solutions: + - id: {MVS-ID} + name: {最小可行方案名称} + goal: "{目标描述}" + + verification_criteria: + - "{验证标准1}" + + scope: + - subsystem: {子系统名} + components: [{组件名}] + + code_structure: + - file: {文件名} + purpose: "{文件用途}" + contains: + - "{包含的功能}" + standalone: {true|false} + + integration_plan: + - step: "{集成步骤1}" + + status: {pending|in_progress|completed} +``` + +--- + +# DATA_MODELS + +```yaml +- name: {模型名} + description: "{模型描述}" + fields: + - name: {字段名} + type: {类型} + default: {默认值} + constraints: {required|optional} +``` + +--- + +# EVOLUTION_PLAN + +```yaml +fix_plan: + - issue_id: {BUG-ID} + description: "..." + root_cause: "..." + minimal_change: + - file: {文件路径} + verification: ... + +refactor_plan: + - target: "{重构目标}" + constraints: [...] + steps: [...] + +feature_plan: + - feature_id: {FEAT-ID} + name: "{功能名称}" + addition: "..." + integration_point: ... + steps: [...] +``` + +--- + +## YAML 结构规范 + +### SYSTEM_META(必需) + +| 字段 | 类型 | 必填 | 描述 | +|------|------|------|------| +| name | string | 是 | 系统名称 | +| version | string | 是 | 版本号,格式 x.y.z | +| type | string | 是 | 系统类型(game-engine、web-framework、api-service 等) | +| description | string | 是 | 系统一句话描述 | +| target_runtime | string | 否 | 目标运行时环境 | + +### SYSTEM_STRUCTURE(必需) + +#### subsystems 数组 + +| 字段 | 类型 | 必填 | 描述 | +|------|------|------|------| +| name | string | 是 | 子系统名称,唯一标识 | +| responsibilities | string[] | 是 | 职责列表,至少 1 项 | +| provides | string[] | 是 | 提供的接口列表 | +| depends_on | string[] | 是 | 依赖的子系统 | +| boundary | object | 否 | 边界定义 | +| boundary.inputs | string[] | 否 | 输入项 | +| boundary.outputs | string[] | 否 | 输出项 | + +#### modules 数组 + +| 字段 | 类型 | 必填 | 描述 | +|------|------|------|------| +| name | string | 是 | 模块名称,唯一标识 | +| parent_subsystem | string | 是 | 所属子系统名称 | +| responsibility | string | 是 | 模块职责描述 | +| public_api | object[] | 是 | 公共 API 列表 | +| public_api[].fn | string | 是 | 函数名 | +| public_api[].params | object[] | 是 | 参数列表 | +| public_api[].params[].name | string | 是 | 参数名 | +| public_api[].params[].type | string | 是 | 参数类型 | +| public_api[].returns | object | 否 | 返回值 | +| public_api[].returns.type | string | 是(当有 returns 时) | 返回类型 | + +### EVOLUTION_MODE(必需) + +| 字段 | 类型 | 必填 | 描述 | +|------|------|------|------| +| mode | enum | 是 | `build`(从零构建)、`evolve`(演进迭代)、`maintain`(维护修复) | +| description | string | 是 | 模式描述 | +| context | string | 是 | 详细上下文,多行字符串 | + +### REQUIREMENTS(可选) + +| 字段 | 类型 | 必填 | 描述 | +|------|------|------|------| +| id | string | 是 | 需求 ID,格式 REQ-XXX | +| title | string | 是 | 需求标题 | +| description | string | 是 | 需求描述 | +| source | enum | 是 | `user`(用户需求)、`constraint`(约束条件) | +| type | enum | 是 | `functional`(功能性)、`non-functional`(非功能性) | +| acceptance_criteria | string[] | 是 | 验收标准,至少 1 项 | +| priority | enum | 是 | `P0`(关键)、`P1`(重要)、`P2`(次要) | + +### MVS_DEFINITION(可选) + +| 字段 | 类型 | 必填 | 描述 | +|------|------|------|------| +| id | string | 是 | MVS ID,格式 MVS-XXX | +| name | string | 是 | 最小可行方案名称 | +| goal | string | 是 | 目标描述 | +| verification_criteria | string[] | 是 | 验证标准 | +| scope | object[] | 是 | 涉及范围 | +| code_structure | object[] | 是 | 代码结构 | +| integration_plan | string[] | 是 | 集成计划 | +| status | enum | 是 | `pending`、`in_progress`、`completed` | + +--- + +## 校验规则 + +### 1. YAML 语法校验 + +- [ ] YAML 代码块可正常解析 +- [ ] 无缩进错误 +- [ ] 无重复键 +- [ ] 数组格式正确 + +### 2. 结构校验 + +- [ ] `SYSTEM_META` 存在且字段完整 +- [ ] `SYSTEM_STRUCTURE` 存在且包含 `subsystems` +- [ ] `EVOLUTION_MODE` 存在且 mode 有效 +- [ ] 所有 `subsystems` 有唯一 name +- [ ] 所有 `modules` 有唯一 name 且 parent_subsystem 有效 + +### 3. 依赖关系校验 + +- [ ] `subsystems[].depends_on` 引用的子系统存在 +- [ ] `modules[].parent_subsystem` 引用的子系统存在 +- [ ] 无循环依赖(A → B → A) +- [ ] 每个子系统的 `provides` 接口被其他子系统 `depends_on` + +### 4. 数据一致性校验 + +- [ ] 所有 `public_api[].params[].type` 使用标准类型 +- [ ] `REQUIREMENTS[].id` 格式正确(REQ-XXX) +- [ ] `MVS_DEFINITION[].id` 格式正确(MVS-XXX) +- [ ] `MVS_DEFINITION[].status` 值有效 + +--- + +## 生成流程 + +1. **分析源码**:扫描 `src/` 目录下的代码文件 +2. **识别子系统**:根据目录结构或模块注释识别子系统 +3. **提取接口**:从代码中提取 public API(函数签名、参数、返回值) +4. **识别依赖**:分析 `import`/`require` 语句确定模块依赖 +5. **生成 SYSTEM_STRUCTURE**:构建 subsystems 和 modules +6. **生成 REQUIREMENTS**:从 TODO、BUG 注释中提取需求 +7. **生成 MVS_DEFINITION**:为关键功能生成最小可行方案 +8. **校验输出**:运行所有校验规则 +9. **输出报告**:列出生成内容和问题 + +--- + +## 输出格式 + +```json +{ + "generated": { + "meta": { + "name": "系统名称", + "subsystems": 8, + "modules": 15, + "requirements": 10, + "mvs_solutions": 3 + } + }, + "issues": [ + { + "section": "SYSTEM_STRUCTURE", + "type": "missing_dependency", + "message": "子系统 'Physics' 依赖 'Rendering',但该子系统不存在" + }, + { + "section": "SYSTEM_STRUCTURE", + "type": "circular_dependency", + "message": "发现循环依赖: Core → Rendering → Core" + } + ], + "warnings": [ + { + "section": "REQUIREMENTS", + "message": "REQ-005 的 acceptance_criteria 为空" + } + ] +} +``` + +--- + +## 使用示例 + +用户输入: +``` +为这个项目生成蓝图文档 +``` + +AI 执行: +1. 扫描源码目录分析代码结构 +2. 识别子系统(Core、Rendering、Physics、Scripting 等) +3. 提取模块和 public API +4. 生成 `blueprint.md` 文件 +5. 运行校验检查 YAML 结构和依赖 +6. 输出生成报告和问题列表