From d33798f895463cee9be807972cb8c09cc87db054 Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Fri, 11 Nov 2022 22:51:31 +0800 Subject: [PATCH] [develop] update native pipeline (#13270) --- cocos/rendering/custom/define.ts | 2 +- exports/custom-pipeline.ts | 2 + native/CMakeLists.txt | 1 + native/cocos/base/Ptr.h | 20 +- .../cocos/renderer/frame-graph/DevicePass.cpp | 8 +- .../renderer/frame-graph/ImmutableState.cpp | 4 +- native/cocos/renderer/gfx-base/GFXBarrier.cpp | 421 ++++++++++------ native/cocos/renderer/gfx-base/GFXBarrier.h | 6 +- .../cocos/renderer/gfx-base/GFXDef-common.h | 2 +- native/cocos/renderer/gfx-vulkan/VKDevice.cpp | 2 + .../renderer/pipeline/InstancedBuffer.cpp | 4 +- .../cocos/renderer/pipeline/InstancedBuffer.h | 2 +- .../cocos/renderer/pipeline/LODModelsUtil.cpp | 6 +- .../cocos/renderer/pipeline/LODModelsUtil.h | 2 +- .../pipeline/custom/FGDispatcherGraphs.h | 292 ++++++++--- .../pipeline/custom/FGDispatcherTypes.cpp | 30 +- .../pipeline/custom/FGDispatcherTypes.h | 84 +++- .../pipeline/custom/FrameGraphDispatcher.cpp | 458 +++++++++++------- .../pipeline/custom/NativeExecutor.cpp | 272 ++++++++--- .../pipeline/custom/NativePipelineFwd.h | 12 +- .../pipeline/custom/NativePipelineTypes.cpp | 79 ++- .../pipeline/custom/NativePipelineTypes.h | 189 ++++---- .../pipeline/custom/NativeRenderQueue.cpp | 123 +++++ .../pipeline/custom/NativeResourceGraph.cpp | 17 + native/cocos/renderer/pipeline/custom/Set.h | 4 +- 25 files changed, 1381 insertions(+), 661 deletions(-) create mode 100644 native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index 9d399df34f..c16e4f3f92 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -815,7 +815,7 @@ export function buildNativeDeferredPipeline (camera: Camera, ppl: Pipeline) { ppl.addRenderTarget('Emissive', Format.RGBA16F, width, height, ResourceResidency.MANAGED); ppl.addDepthStencil('DepthStencil', Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); // Lighting - ppl.addRenderTexture('Color', Format.RGBA8, width, height, camera.window); + ppl.addRenderTexture('Color', Format.BGRA8, width, height, camera.window); } if (!lightingInfo) { lightingInfo = new LightingInfo(); diff --git a/exports/custom-pipeline.ts b/exports/custom-pipeline.ts index 98b864e66f..ba060b05a5 100644 --- a/exports/custom-pipeline.ts +++ b/exports/custom-pipeline.ts @@ -1,6 +1,8 @@ import { legacyCC } from '../cocos/core/global-exports'; import * as rendering from '../cocos/rendering/custom'; +import { LayoutGraphData } from '../cocos/rendering/custom/layout-graph'; legacyCC.rendering = rendering; +legacyCC.rendering.defaultLayoutGraph = new LayoutGraphData(); export { rendering }; diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index c1a1f5d328..c8de1530c4 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -1327,6 +1327,7 @@ cocos_source_files( cocos/renderer/pipeline/custom/NativePipelineTypes.cpp cocos/renderer/pipeline/custom/NativePipelineTypes.h cocos/renderer/pipeline/custom/NativeRenderGraph.cpp + cocos/renderer/pipeline/custom/NativeRenderQueue.cpp cocos/renderer/pipeline/custom/RenderCommonFwd.h cocos/renderer/pipeline/custom/RenderCommonJsb.cpp cocos/renderer/pipeline/custom/RenderCommonJsb.h diff --git a/native/cocos/base/Ptr.h b/native/cocos/base/Ptr.h index d3742c3c38..a5ba6a9f79 100644 --- a/native/cocos/base/Ptr.h +++ b/native/cocos/base/Ptr.h @@ -1,8 +1,8 @@ /**************************************************************************** Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - + http://www.cocos.com - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated engine source code (the "Software"), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license @@ -10,10 +10,10 @@ not use Cocos Creator software for developing other software or tools that's used for developing games. You are not granted to publish, distribute, sublicense, and/or sell copies of Cocos Creator. - + The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -78,6 +78,7 @@ #pragma once #include +#include "cocos/base/std/hash/hash_fwd.hpp" namespace cc { @@ -213,3 +214,14 @@ protected: }; } // namespace cc + +namespace ccstd { + +template +struct hash> { + hash_t operator()(const cc::IntrusivePtr &val) const noexcept { + return hash{}(val.get()); + } +}; + +} // namespace ccstd diff --git a/native/cocos/renderer/frame-graph/DevicePass.cpp b/native/cocos/renderer/frame-graph/DevicePass.cpp index 3ccbafdb30..d45f5d2247 100644 --- a/native/cocos/renderer/frame-graph/DevicePass.cpp +++ b/native/cocos/renderer/frame-graph/DevicePass.cpp @@ -163,10 +163,10 @@ void DevicePass::passDependency(gfx::RenderPassInfo &rpInfo) { nullptr, bufferBarriers.data() + lastBufferIndex, buffers.data() + lastBufferIndex, - static_cast(buffers.size() - lastBufferIndex + 1), + static_cast(buffers.size() - lastBufferIndex), textureBarriers.data() + lastTextureIndex, textures.data() + lastTextureIndex, - static_cast(textures.size() - lastTextureIndex + 1)}); + static_cast(textures.size() - lastTextureIndex)}); for (const auto &rearBarrier : _barriers[barrierID].get().rearBarriers) { const auto &res = getBarrier(rearBarrier, &_resourceTable); @@ -198,10 +198,10 @@ void DevicePass::passDependency(gfx::RenderPassInfo &rpInfo) { nullptr, bufferBarriers.data() + lastBufferIndex, buffers.data() + lastBufferIndex, - static_cast(buffers.size() - lastBufferIndex + 1), + static_cast(buffers.size() - lastBufferIndex), textureBarriers.data() + lastTextureIndex, textures.data() + lastTextureIndex, - static_cast(textures.size() - lastTextureIndex + 1)}); + static_cast(textures.size() - lastTextureIndex)}); } } } diff --git a/native/cocos/renderer/frame-graph/ImmutableState.cpp b/native/cocos/renderer/frame-graph/ImmutableState.cpp index 11a61f321d..8b2906cb44 100644 --- a/native/cocos/renderer/frame-graph/ImmutableState.cpp +++ b/native/cocos/renderer/frame-graph/ImmutableState.cpp @@ -44,11 +44,11 @@ using gfx::TextureUsage; namespace { AccessFlags getAccessFlags(BufferUsage usage, MemoryUsage memUsage, const AccessStatus& status) noexcept { - return gfx::getAccessFlags(usage, memUsage, status.visibility, status.access, status.passType); + return gfx::getAccessFlags(usage, memUsage, status.access, status.visibility); } AccessFlags getAccessFlags(TextureUsage usage, const AccessStatus& status) noexcept { - return gfx::getAccessFlags(usage, status.visibility, status.access, status.passType); + return gfx::getAccessFlags(usage, status.access, status.visibility); } } // namespace diff --git a/native/cocos/renderer/gfx-base/GFXBarrier.cpp b/native/cocos/renderer/gfx-base/GFXBarrier.cpp index 780b83baab..eb5e133bfb 100644 --- a/native/cocos/renderer/gfx-base/GFXBarrier.cpp +++ b/native/cocos/renderer/gfx-base/GFXBarrier.cpp @@ -1,4 +1,5 @@ #include "GFXBarrier.h" +#include #include namespace cc { @@ -14,41 +15,96 @@ enum class ResourceType : uint32_t { }; enum class CommonUsage : uint32_t { - NONE = 0, - COPY_SRC = 1 << 0, - COPY_DST = 1 << 1, - ROM = 1 << 2, // sampled or UNIFORM - STORAGE = 1 << 3, - IB_OR_CA = 1 << 4, - VB_OR_DS = 1 << 5, - INDIRECT_OR_INPUT = 1 << 6, + NONE = 1 << 0, + COPY_SRC = 1 << 1, + COPY_DST = 1 << 2, + ROM = 1 << 3, // sampled or UNIFORM + STORAGE = 1 << 4, + IB_OR_CA = 1 << 5, + VB_OR_DS = 1 << 6, + INDIRECT_OR_INPUT = 1 << 7, }; CC_ENUM_BITWISE_OPERATORS(CommonUsage); +constexpr CommonUsage textureUsageToCommonUsage(TextureUsage usage) { + CommonUsage res{0}; + if (hasFlag(usage, TextureUsage::NONE)) { + res |= CommonUsage::NONE; + } + if (hasFlag(usage, TextureUsage::TRANSFER_SRC)) { + res |= CommonUsage::COPY_SRC; + } + if (hasFlag(usage, TextureUsage::TRANSFER_DST)) { + res |= CommonUsage::COPY_DST; + } + if (hasFlag(usage, TextureUsage::SAMPLED)) { + res |= CommonUsage::ROM; + } + if (hasFlag(usage, TextureUsage::STORAGE)) { + res |= CommonUsage::STORAGE; + } + if (hasFlag(usage, TextureUsage::COLOR_ATTACHMENT)) { + res |= CommonUsage::IB_OR_CA; + } + if (hasFlag(usage, TextureUsage::DEPTH_STENCIL_ATTACHMENT)) { + res |= CommonUsage::VB_OR_DS; + } + if (hasFlag(usage, TextureUsage::INPUT_ATTACHMENT)) { + res |= CommonUsage::INDIRECT_OR_INPUT; + } + return res; +} + +constexpr CommonUsage bufferUsageToCommonUsage(BufferUsage usage) { + CommonUsage res{0}; + if (hasFlag(usage, BufferUsage::NONE)) { + res |= CommonUsage::NONE; + } + if (hasFlag(usage, BufferUsage::TRANSFER_SRC)) { + res |= CommonUsage::COPY_SRC; + } + if (hasFlag(usage, BufferUsage::TRANSFER_DST)) { + res |= CommonUsage::COPY_DST; + } + if (hasFlag(usage, BufferUsage::UNIFORM)) { + res |= CommonUsage::ROM; + } + if (hasFlag(usage, BufferUsage::STORAGE)) { + res |= CommonUsage::STORAGE; + } + if (hasFlag(usage, BufferUsage::INDEX)) { + res |= CommonUsage::IB_OR_CA; + } + if (hasFlag(usage, BufferUsage::VERTEX)) { + res |= CommonUsage::VB_OR_DS; + } + if (hasFlag(usage, BufferUsage::INDIRECT)) { + res |= CommonUsage::INDIRECT_OR_INPUT; + } + return res; +} + struct AccessElem { uint32_t mask{0xFFFFFFFF}; uint32_t key{0xFFFFFFFF}; AccessFlags access{AccessFlags::NONE}; }; -// 23 and above :reserved -// 21 ~ 22: MemoryAccess -// 19 ~ 20: MemoryUsage -// 13 ~ 18: PassType -// 11 ~ 12: ResourceType -// 9 ~ 10: ShaderStageFlags -// 0 ~ 8: CommonUsage -constexpr uint32_t IGNORE_MEMACCESS = 0b0011111111111111111111; -constexpr uint32_t IGNORE_MEMUSAGE = 0b1100111111111111111111; -constexpr uint32_t IGNORE_PASSTYPE = 0b1111000000111111111111; -constexpr uint32_t IGNORE_RESTYPE = 0b1111111111001111111111; -constexpr uint32_t IGNORE_SHADERSTAGE = 0b1111111111110011111111; -constexpr uint32_t IGNORE_CMNUSAGE = 0b1111111111111100000000; +// 20 and above :reserved +// 18 ~ 19: MemoryAccess +// 16 ~ 17: MemoryUsage +// 14 ~ 15: ResourceType +// 8 ~ 13: ShaderStageFlags +// 0 ~ 7: CommonUsage +constexpr uint32_t IGNORE_MEMACCESS = 0b00111111111111111111; +constexpr uint32_t IGNORE_MEMUSAGE = 0b11001111111111111111; +constexpr uint32_t IGNORE_RESTYPE = 0b11110011111111111111; +constexpr uint32_t IGNORE_SHADERSTAGE = 0b11111100000011111111; +constexpr uint32_t IGNORE_CMNUSAGE = 0b11111111111100000000; constexpr uint32_t IGNORE_NONE = 0xFFFFFFFF; constexpr uint32_t CARE_MEMACCESS = ~IGNORE_MEMACCESS; constexpr uint32_t CARE_MEMUSAGE = ~IGNORE_MEMUSAGE; -constexpr uint32_t CARE_PASSTYPE = ~IGNORE_PASSTYPE; constexpr uint32_t CARE_RESTYPE = ~IGNORE_RESTYPE; constexpr uint32_t CARE_SHADERSTAGE = ~IGNORE_SHADERSTAGE; constexpr uint32_t CARE_CMNUSAGE = ~IGNORE_CMNUSAGE; @@ -56,20 +112,19 @@ constexpr uint32_t CARE_NONE = ~IGNORE_NONE; #define OPERABLE(val) static_cast::type>(val) -constexpr auto ACCESS_READ = OPERABLE(MemoryAccess::READ_ONLY) << 20; -constexpr auto ACCESS_WRITE = OPERABLE(MemoryAccess::WRITE_ONLY) << 20; -constexpr auto MEM_DEVICE = OPERABLE(MemoryUsage::DEVICE) << 18; -constexpr auto MEM_HOST = OPERABLE(MemoryUsage::HOST) << 18; -constexpr auto PASS_RASTER = 1 << (OPERABLE(PassType::RASTER) + 12); -constexpr auto PASS_COMPUTE = 1 << (OPERABLE(PassType::COMPUTE) + 12); -constexpr auto PASS_COPY = 1 << (OPERABLE(PassType::COPY) + 12); -constexpr auto PASS_MOVE = 1 << (OPERABLE(PassType::MOVE) + 12); -constexpr auto PASS_RAYTRACE = 1 << (OPERABLE(PassType::RAYTRACE) + 12); -constexpr auto PASS_PRESENT = 1 << (OPERABLE(PassType::PRESENT) + 12); -constexpr auto RES_BUFFER = 1 << (OPERABLE(ResourceType::BUFFER) + 10); -constexpr auto RES_TEXTURE = 1 << (OPERABLE(ResourceType::TEXTURE) + 10); +constexpr auto ACCESS_WRITE = OPERABLE(MemoryAccess::WRITE_ONLY) << 18; +constexpr auto ACCESS_READ = OPERABLE(MemoryAccess::READ_ONLY) << 18; +constexpr auto MEM_HOST = OPERABLE(MemoryUsage::HOST) << 16; +constexpr auto MEM_DEVICE = OPERABLE(MemoryUsage::DEVICE) << 16; +constexpr auto RES_TEXTURE = OPERABLE(ResourceType::TEXTURE) << 14; +constexpr auto RES_BUFFER = OPERABLE(ResourceType::BUFFER) << 14; +constexpr auto SHADERSTAGE_COMP = 1 << 13; +constexpr auto SHADERSTAGE_FRAG = 1 << 12; +constexpr auto SHADERSTAGE_GEOM = 1 << 11; +constexpr auto SHADERSTAGE_EVAL = 1 << 10; +constexpr auto SHADERSTAGE_CTRL = 1 << 9; constexpr auto SHADERSTAGE_VERT = 1 << 8; -constexpr auto SHADERSTAGE_FRAG = 1 << 9; +constexpr auto CMN_NONE = OPERABLE(CommonUsage::NONE); constexpr auto CMN_COPY_SRC = OPERABLE(CommonUsage::COPY_SRC); constexpr auto CMN_COPY_DST = OPERABLE(CommonUsage::COPY_DST); constexpr auto CMN_ROM = OPERABLE(CommonUsage::ROM); @@ -87,104 +142,104 @@ constexpr std::array ACCESS_MAP = {{ 0x0, AccessFlags::NONE}, - {IGNORE_PASSTYPE & IGNORE_SHADERSTAGE, - ACCESS_READ | MEM_DEVICE | RES_BUFFER | CMN_INDIRECT_OR_INPUT, + {CARE_RESTYPE | CARE_CMNUSAGE, + RES_BUFFER | CMN_INDIRECT_OR_INPUT, AccessFlags::INDIRECT_BUFFER}, - {IGNORE_SHADERSTAGE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_BUFFER | CMN_IB_OR_CA, + {CARE_RESTYPE | CARE_CMNUSAGE, + RES_BUFFER | CMN_IB_OR_CA, AccessFlags::INDEX_BUFFER}, // buffer usage indicates what it is, so shader stage ignored. - {IGNORE_SHADERSTAGE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_BUFFER | CMN_VB_OR_DS, + {CARE_RESTYPE | CARE_CMNUSAGE, + ACCESS_READ | RES_BUFFER | CMN_VB_OR_DS, AccessFlags::VERTEX_BUFFER}, // ditto - {IGNORE_NONE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_BUFFER | SHADERSTAGE_VERT | CMN_ROM, + {IGNORE_MEMUSAGE, + ACCESS_READ | RES_BUFFER | SHADERSTAGE_VERT | CMN_ROM, AccessFlags::VERTEX_SHADER_READ_UNIFORM_BUFFER}, - {IGNORE_NONE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_VERT | CMN_ROM, + {IGNORE_MEMUSAGE, + ACCESS_READ | RES_TEXTURE | SHADERSTAGE_VERT | CMN_ROM, AccessFlags::VERTEX_SHADER_READ_TEXTURE}, - {IGNORE_RESTYPE & IGNORE_CMNUSAGE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | SHADERSTAGE_VERT, + {IGNORE_MEMUSAGE & IGNORE_RESTYPE, + ACCESS_READ | SHADERSTAGE_VERT | CMN_STORAGE, AccessFlags::VERTEX_SHADER_READ_OTHER}, - {IGNORE_NONE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_BUFFER | SHADERSTAGE_FRAG | CMN_ROM, + {IGNORE_MEMUSAGE, + ACCESS_READ | RES_BUFFER | SHADERSTAGE_FRAG | CMN_ROM, AccessFlags::FRAGMENT_SHADER_READ_UNIFORM_BUFFER}, - {IGNORE_NONE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_ROM, + {IGNORE_MEMUSAGE, + ACCESS_READ | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_ROM, AccessFlags::FRAGMENT_SHADER_READ_TEXTURE}, - {IGNORE_NONE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_IB_OR_CA | CMN_INDIRECT_OR_INPUT, + {IGNORE_MEMUSAGE, + ACCESS_READ | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_IB_OR_CA | CMN_INDIRECT_OR_INPUT, AccessFlags::FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT}, - {IGNORE_NONE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_VB_OR_DS | CMN_INDIRECT_OR_INPUT, + {IGNORE_MEMUSAGE, + ACCESS_READ | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_VB_OR_DS | CMN_INDIRECT_OR_INPUT, AccessFlags::FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT}, - {IGNORE_NONE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | SHADERSTAGE_FRAG, + {IGNORE_MEMUSAGE & IGNORE_RESTYPE, + ACCESS_READ | SHADERSTAGE_FRAG | CMN_STORAGE, AccessFlags::FRAGMENT_SHADER_READ_OTHER}, - {IGNORE_NONE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_IB_OR_CA, - AccessFlags::COLOR_ATTACHMENT_READ}, + //{IGNORE_MEMUSAGE, + // ACCESS_READ | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_IB_OR_CA, + // AccessFlags::COLOR_ATTACHMENT_READ}, - {IGNORE_NONE, - ACCESS_READ | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_VB_OR_DS, - AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ}, + //{IGNORE_MEMUSAGE, + // ACCESS_READ | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_VB_OR_DS, + // AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ}, - {IGNORE_PASSTYPE & IGNORE_SHADERSTAGE, - ACCESS_READ | MEM_DEVICE | RES_BUFFER | CMN_ROM, + {IGNORE_MEMUSAGE, + ACCESS_READ | RES_BUFFER | SHADERSTAGE_COMP | CMN_ROM, AccessFlags::COMPUTE_SHADER_READ_UNIFORM_BUFFER}, - {IGNORE_PASSTYPE & IGNORE_SHADERSTAGE, - ACCESS_READ | MEM_DEVICE | RES_TEXTURE | CMN_ROM, + {IGNORE_MEMUSAGE, + ACCESS_READ | RES_TEXTURE | SHADERSTAGE_COMP | CMN_ROM, AccessFlags::COMPUTE_SHADER_READ_TEXTURE}, - {CARE_MEMACCESS | CARE_MEMUSAGE, - ACCESS_READ | MEM_DEVICE, + {CARE_MEMACCESS | CARE_SHADERSTAGE | CARE_CMNUSAGE, + ACCESS_READ | SHADERSTAGE_COMP | CMN_STORAGE, AccessFlags::COMPUTE_SHADER_READ_OTHER}, - {CARE_MEMACCESS | CARE_MEMUSAGE | CARE_PASSTYPE, - ACCESS_READ | MEM_DEVICE | PASS_COMPUTE, + {CARE_MEMACCESS | CARE_CMNUSAGE, + ACCESS_READ | CMN_COPY_SRC, AccessFlags::TRANSFER_READ}, {CARE_MEMACCESS | CARE_MEMUSAGE, ACCESS_READ | MEM_HOST, AccessFlags::HOST_READ}, - {CARE_MEMACCESS | CARE_MEMUSAGE | CARE_PASSTYPE, - ACCESS_READ | MEM_DEVICE | PASS_PRESENT, + {CARE_CMNUSAGE | CARE_RESTYPE, + RES_TEXTURE | CMN_NONE, AccessFlags::PRESENT}, - {IGNORE_RESTYPE & IGNORE_CMNUSAGE, - ACCESS_WRITE | MEM_DEVICE | PASS_RASTER | SHADERSTAGE_VERT, + {CARE_MEMACCESS | CARE_SHADERSTAGE | CARE_CMNUSAGE, + ACCESS_WRITE | SHADERSTAGE_VERT | CMN_STORAGE, AccessFlags::VERTEX_SHADER_WRITE}, - {IGNORE_RESTYPE & IGNORE_CMNUSAGE, - ACCESS_WRITE | MEM_DEVICE | PASS_RASTER | SHADERSTAGE_FRAG, + {CARE_MEMACCESS | CARE_SHADERSTAGE | CARE_CMNUSAGE, + ACCESS_WRITE | SHADERSTAGE_FRAG | CMN_STORAGE, AccessFlags::FRAGMENT_SHADER_WRITE}, - {IGNORE_NONE, - ACCESS_WRITE | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_IB_OR_CA, + {IGNORE_MEMUSAGE, + ACCESS_WRITE | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_IB_OR_CA, AccessFlags::COLOR_ATTACHMENT_WRITE}, {IGNORE_NONE, - ACCESS_WRITE | MEM_DEVICE | PASS_RASTER | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_VB_OR_DS, + ACCESS_WRITE | MEM_DEVICE | RES_TEXTURE | SHADERSTAGE_FRAG | CMN_VB_OR_DS, AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE}, - {CARE_MEMACCESS | CARE_MEMUSAGE, - ACCESS_WRITE | MEM_DEVICE, + {CARE_MEMACCESS | CARE_SHADERSTAGE | CARE_CMNUSAGE, + ACCESS_WRITE | SHADERSTAGE_COMP | CMN_STORAGE, AccessFlags::COMPUTE_SHADER_WRITE}, - {CARE_MEMACCESS | CARE_MEMUSAGE | CARE_PASSTYPE, - ACCESS_WRITE | MEM_DEVICE | PASS_COPY, + {CARE_MEMACCESS | CARE_CMNUSAGE, + ACCESS_WRITE | CMN_COPY_DST, AccessFlags::TRANSFER_WRITE}, {CARE_MEMACCESS | CARE_MEMUSAGE, @@ -192,80 +247,109 @@ constexpr std::array ACCESS_MAP = {{ AccessFlags::HOST_WRITE}, }}; -} // namespace - -AccessFlags getAccessFlags( - BufferUsage usage, MemoryUsage memUsage, - ShaderStageFlags visibility, - MemoryAccessBit access, - PassType passType) noexcept { - uint32_t info = 0xFFFFFFFF; - info &= (OPERABLE(access) << 20 | IGNORE_MEMACCESS); - info &= (OPERABLE(memUsage) << 18 | IGNORE_MEMUSAGE); - info &= (1 << (OPERABLE(passType) + 12) | IGNORE_PASSTYPE); - info &= (1 << (OPERABLE(ResourceType::BUFFER) + 10) | IGNORE_RESTYPE); - switch (visibility) { - case ShaderStageFlags::NONE: - info &= IGNORE_SHADERSTAGE; - break; - case ShaderStageFlags::VERTEX: - info &= ((1 << 8) | IGNORE_SHADERSTAGE); - break; - case ShaderStageFlags::FRAGMENT: - info &= ((1 << 9) | IGNORE_SHADERSTAGE); - break; - default: - info |= ((0b11 << 8) | IGNORE_SHADERSTAGE); +constexpr bool validateAccess(ResourceType type, CommonUsage usage, MemoryAccess access, ShaderStageFlags visibility) { + bool res = true; + if (type == ResourceType::BUFFER) { + uint32_t conflicts[] = { + hasFlag(usage, CommonUsage::ROM) && hasFlag(access, MemoryAccess::WRITE_ONLY), // uniform has write access. + hasAnyFlags(usage, CommonUsage::IB_OR_CA | CommonUsage::VB_OR_DS) && !hasFlag(visibility, ShaderStageFlags::VERTEX), // color/ds/input not in fragment + hasAllFlags(usage, CommonUsage::ROM | CommonUsage::STORAGE), // storage ^ sampled + hasFlag(usage, CommonUsage::COPY_SRC) && hasAllFlags(MemoryAccess::READ_ONLY, access), // transfer src ==> read_only + hasFlag(usage, CommonUsage::COPY_DST) && hasAllFlags(MemoryAccess::WRITE_ONLY, access), // transfer dst ==> write_only + hasAllFlags(usage, CommonUsage::COPY_SRC | CommonUsage::COPY_DST), // both src and dst + hasFlag(usage, CommonUsage::VB_OR_DS) && hasAnyFlags(usage, CommonUsage::IB_OR_CA | CommonUsage::INDIRECT_OR_INPUT), + hasFlag(usage, CommonUsage::IB_OR_CA) && hasAnyFlags(usage, CommonUsage::VB_OR_DS | CommonUsage::INDIRECT_OR_INPUT), + hasFlag(usage, CommonUsage::INDIRECT_OR_INPUT) && hasAnyFlags(usage, CommonUsage::IB_OR_CA | CommonUsage::VB_OR_DS), + // exlusive + }; + res = !(*std::max_element(std::begin(conflicts), std::end(conflicts))); + } else if (type == ResourceType::TEXTURE) { + uint32_t conflicts[] = { + hasFlag(usage, CommonUsage::ROM) && hasFlag(access, MemoryAccess::WRITE_ONLY), // sampled texture has write access. + hasAnyFlags(usage, CommonUsage::IB_OR_CA | CommonUsage::VB_OR_DS | CommonUsage::INDIRECT_OR_INPUT) && !hasFlag(visibility, ShaderStageFlags::FRAGMENT), // color/ds/input not in fragment + hasFlag(usage, CommonUsage::INDIRECT_OR_INPUT) && !hasFlag(access, MemoryAccess::READ_ONLY), // input needs read + hasAllFlags(usage, CommonUsage::ROM | CommonUsage::STORAGE), // storage ^ sampled + hasFlag(usage, CommonUsage::COPY_SRC) && !hasAllFlags(MemoryAccess::READ_ONLY, access), // transfer src ==> read_only + hasFlag(usage, CommonUsage::COPY_DST) && !hasAllFlags(MemoryAccess::WRITE_ONLY, access), + hasFlag(usage, CommonUsage::INDIRECT_OR_INPUT) && !hasAnyFlags(usage, CommonUsage::IB_OR_CA | CommonUsage::VB_OR_DS), // input needs to specify color or ds // transfer dst ==> write_only + hasAllFlags(usage, CommonUsage::COPY_SRC | CommonUsage::COPY_DST), // both src and dst + }; + res = !(*std::max_element(std::begin(conflicts), std::end(conflicts))); } - info &= OPERABLE(usage) | IGNORE_CMNUSAGE; + return res; +} +constexpr AccessFlags getAccessFlagsImpl( + BufferUsage usage, MemoryUsage memUsage, + MemoryAccess access, + ShaderStageFlags visibility) noexcept { AccessFlags flags{AccessFlags::NONE}; - for (const auto& elem : ACCESS_MAP) { - auto testFlag = info & elem.mask; - // hasKey - if ((testFlag & elem.key) == elem.key) { - flags |= elem.access; + CommonUsage cmnUsage = bufferUsageToCommonUsage(usage); + if (validateAccess(ResourceType::BUFFER, cmnUsage, access, visibility)) { + uint32_t info = 0xFFFFFFFF; + info &= ((OPERABLE(access) << 18) | IGNORE_MEMACCESS); + info &= ((OPERABLE(memUsage) << 16) | IGNORE_MEMUSAGE); + info &= ((OPERABLE(ResourceType::TEXTURE) << 14) | IGNORE_RESTYPE); + info &= ((OPERABLE(visibility) << 8) | IGNORE_SHADERSTAGE); + info &= OPERABLE(cmnUsage) | IGNORE_CMNUSAGE; + + for (const auto& elem : ACCESS_MAP) { + auto testFlag = info & elem.mask; + // hasKey + if ((testFlag & elem.key) == elem.key) { + flags |= elem.access; + } } + + } else { + flags = INVALID_ACCESS_FLAGS; } return flags; } -AccessFlags getAccessFlags( +constexpr AccessFlags getAccessFlagsImpl( TextureUsage usage, - ShaderStageFlags visibility, - MemoryAccessBit access, - PassType passType) noexcept { - uint32_t info = 0xFFFFFFFF; - info &= (OPERABLE(access) << 20 | IGNORE_MEMACCESS); - info &= MEM_DEVICE; - info &= (1 << (OPERABLE(passType) + 12) | IGNORE_PASSTYPE); - info &= (1 << (OPERABLE(ResourceType::BUFFER) + 10) | IGNORE_RESTYPE); - switch (visibility) { - case ShaderStageFlags::NONE: - info &= IGNORE_SHADERSTAGE; - break; - case ShaderStageFlags::VERTEX: - info &= ((1 << 8) | IGNORE_SHADERSTAGE); - break; - case ShaderStageFlags::FRAGMENT: - info &= ((1 << 9) | IGNORE_SHADERSTAGE); - break; - default: - info |= ((0b11 << 8) | IGNORE_SHADERSTAGE); - } - info &= OPERABLE(usage) | IGNORE_CMNUSAGE; - + MemoryAccess access, + ShaderStageFlags visibility) noexcept { AccessFlags flags{AccessFlags::NONE}; - for (const auto& elem : ACCESS_MAP) { - auto testFlag = info & elem.mask; - // hasKey - if ((testFlag & elem.key) == elem.key) { - flags |= elem.access; + CommonUsage cmnUsage = textureUsageToCommonUsage(usage); + if (validateAccess(ResourceType::TEXTURE, cmnUsage, access, visibility)) { + uint32_t info = 0xFFFFFFFF; + info &= ((OPERABLE(access) << 18) | IGNORE_MEMACCESS); + info &= ((OPERABLE(MemoryUsage::DEVICE) << 16) | IGNORE_MEMUSAGE); + info &= ((OPERABLE(ResourceType::TEXTURE) << 14) | IGNORE_RESTYPE); + info &= ((OPERABLE(visibility) << 8) | IGNORE_SHADERSTAGE); + info &= OPERABLE(cmnUsage) | IGNORE_CMNUSAGE; + + for (const auto& elem : ACCESS_MAP) { + auto testFlag = info & elem.mask; + // hasKey + if ((testFlag & elem.key) == elem.key) { + flags |= elem.access; + } } + } else { + flags = INVALID_ACCESS_FLAGS; } return flags; } +} // namespace + +AccessFlags getAccessFlags( + BufferUsage usage, MemoryUsage memUsage, + MemoryAccess access, + ShaderStageFlags visibility) noexcept { + return getAccessFlagsImpl(usage, memUsage, access, visibility); +} + +AccessFlags getAccessFlags( + TextureUsage usage, + MemoryAccess access, + ShaderStageFlags visibility) noexcept { + return getAccessFlagsImpl(usage, access, visibility); +} + namespace { constexpr AccessFlags getDeviceAccessFlagsImpl( @@ -415,6 +499,57 @@ constexpr AccessFlags getDeviceAccessFlagsImpl( return flags; } +// auto res = getAccessFlags( +// TextureUsage::TRANSFER_DST | TextureUsage::COLOR_ATTACHMENT, // cannot be sampled +// MemoryAccess::WRITE_ONLY, +// ShaderStageFlags::ALL); +// +// auto res2 = res; + +static_assert( + (AccessFlags::VERTEX_SHADER_WRITE | AccessFlags::VERTEX_SHADER_READ_OTHER) == + getAccessFlagsImpl( + TextureUsage::STORAGE, + MemoryAccess::READ_WRITE, + ShaderStageFlags::VERTEX)); + +static_assert( + (AccessFlags::FRAGMENT_SHADER_WRITE | AccessFlags::FRAGMENT_SHADER_READ_OTHER) == + getAccessFlagsImpl( + TextureUsage::STORAGE, + MemoryAccess::READ_WRITE, + ShaderStageFlags::FRAGMENT)); + +static_assert( + (AccessFlags::COMPUTE_SHADER_WRITE | AccessFlags::COMPUTE_SHADER_READ_OTHER) == + getAccessFlagsImpl( + TextureUsage::STORAGE, + MemoryAccess::READ_WRITE, + ShaderStageFlags::COMPUTE)); + +static_assert( + (AccessFlags::FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT | AccessFlags::FRAGMENT_SHADER_READ_OTHER) == + getAccessFlagsImpl( + TextureUsage::COLOR_ATTACHMENT | TextureUsage::INPUT_ATTACHMENT | TextureUsage::STORAGE, + MemoryAccess::READ_ONLY, + ShaderStageFlags::FRAGMENT)); + +static_assert( + INVALID_ACCESS_FLAGS == + getAccessFlagsImpl( + TextureUsage::COLOR_ATTACHMENT | TextureUsage::INPUT_ATTACHMENT | TextureUsage::SAMPLED | TextureUsage::STORAGE, + MemoryAccess::READ_ONLY, + ShaderStageFlags::FRAGMENT)); + +static_assert( + (AccessFlags::TRANSFER_WRITE | AccessFlags::COLOR_ATTACHMENT_WRITE) == + getAccessFlagsImpl( + TextureUsage::TRANSFER_DST | TextureUsage::COLOR_ATTACHMENT, + MemoryAccess::WRITE_ONLY, + ShaderStageFlags::ALL)); + +//////////////////////////////////// + // VERTEX_SHADER_WRITE static_assert( AccessFlags::VERTEX_SHADER_WRITE == diff --git a/native/cocos/renderer/gfx-base/GFXBarrier.h b/native/cocos/renderer/gfx-base/GFXBarrier.h index 19008bda35..e65670060e 100644 --- a/native/cocos/renderer/gfx-base/GFXBarrier.h +++ b/native/cocos/renderer/gfx-base/GFXBarrier.h @@ -7,15 +7,13 @@ namespace gfx { AccessFlags getAccessFlags( BufferUsage usage, MemoryUsage memUsage, - ShaderStageFlagBit visibility, MemoryAccess access, - PassType passType) noexcept; + ShaderStageFlags visibility) noexcept; AccessFlags getAccessFlags( TextureUsage usage, - ShaderStageFlagBit visibility, MemoryAccess access, - PassType passType) noexcept; + ShaderStageFlags visibility) noexcept; constexpr AccessFlags INVALID_ACCESS_FLAGS = static_cast(0xFFFFFFFF); diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 51b5baf04e..1f927d70ab 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -107,7 +107,7 @@ using SamplerList = ccstd::vector; using DescriptorSetLayoutList = ccstd::vector; // make sure you have FILLED GRAPHs before enable this! -static constexpr bool ENABLE_GRAPH_AUTO_BARRIER{false}; +static constexpr bool ENABLE_GRAPH_AUTO_BARRIER{true}; /** * @en Graphics object type diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index 0bdb2ba3a1..3bcfc2aa84 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -140,6 +140,8 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { requestedFeatures2.features.samplerAnisotropy = deviceFeatures.samplerAnisotropy; requestedFeatures2.features.depthBounds = deviceFeatures.depthBounds; requestedFeatures2.features.multiDrawIndirect = deviceFeatures.multiDrawIndirect; + //requestedFeatures2.features.se + requestedVulkan12Features.separateDepthStencilLayouts = _gpuContext->physicalDeviceVulkan12Features.separateDepthStencilLayouts; if (_gpuContext->validationEnabled) { requestedLayers.push_back("VK_LAYER_KHRONOS_validation"); diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.cpp b/native/cocos/renderer/pipeline/InstancedBuffer.cpp index 1f7083b961..1038783fea 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.cpp +++ b/native/cocos/renderer/pipeline/InstancedBuffer.cpp @@ -131,8 +131,8 @@ void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx, gfx::Sh _hasPendingModels = true; } -void InstancedBuffer::uploadBuffers(gfx::CommandBuffer *cmdBuff) { - for (auto &instance : _instances) { +void InstancedBuffer::uploadBuffers(gfx::CommandBuffer *cmdBuff) const { + for (const auto &instance : _instances) { if (!instance.count) continue; cmdBuff->updateBuffer(instance.vb, instance.data, instance.vb->getSize()); diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.h b/native/cocos/renderer/pipeline/InstancedBuffer.h index f10404273c..aaeaf5b6df 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.h +++ b/native/cocos/renderer/pipeline/InstancedBuffer.h @@ -63,7 +63,7 @@ public: void destroy(); void merge(scene::SubModel *, uint32_t); void merge(scene::SubModel *, uint32_t, gfx::Shader *); - void uploadBuffers(gfx::CommandBuffer *cmdBuff); + void uploadBuffers(gfx::CommandBuffer *cmdBuff) const; void clear(); void setDynamicOffset(uint32_t idx, uint32_t value); diff --git a/native/cocos/renderer/pipeline/LODModelsUtil.cpp b/native/cocos/renderer/pipeline/LODModelsUtil.cpp index 49d0b16c58..a805c464a1 100644 --- a/native/cocos/renderer/pipeline/LODModelsUtil.cpp +++ b/native/cocos/renderer/pipeline/LODModelsUtil.cpp @@ -37,13 +37,13 @@ namespace pipeline { * @zh LOD所有级别中存储的model集合;包含多个LODGroup的所有LOD * @en The collection of models stored in all levels of LOD, All LODs containing multiple LODGroups. */ -ccstd::unordered_map modelsInAnyLODGroup; +ccstd::unordered_map modelsInAnyLODGroup; /** * @zh 指定相机下,某一级LOD使用的model集合;可能包含多个LODGroup的某一级LOD * @en Specify the model set used by a level of LOD under the camera, LOD of a level that may contain multiple LODGroups. */ -ccstd::unordered_map visibleModelsByAnyLODGroup; +ccstd::unordered_map visibleModelsByAnyLODGroup; void LODModelsCachedUtils::updateCachedLODModels(const scene::RenderScene *scene, const scene::Camera *camera) { for (const auto &lodGroup : scene->getLODGroups()) { @@ -86,7 +86,7 @@ void LODModelsCachedUtils::updateCachedLODModels(const scene::RenderScene *scene } } -bool LODModelsCachedUtils::isLODModelCulled(scene::Model *model) { +bool LODModelsCachedUtils::isLODModelCulled(const scene::Model *model) { return modelsInAnyLODGroup[model] && !visibleModelsByAnyLODGroup[model]; } diff --git a/native/cocos/renderer/pipeline/LODModelsUtil.h b/native/cocos/renderer/pipeline/LODModelsUtil.h index 0233c32da0..fd9069dda0 100644 --- a/native/cocos/renderer/pipeline/LODModelsUtil.h +++ b/native/cocos/renderer/pipeline/LODModelsUtil.h @@ -37,7 +37,7 @@ namespace pipeline { class LODModelsCachedUtils { public: static void updateCachedLODModels(const scene::RenderScene *scene, const scene::Camera *camera); - static bool isLODModelCulled(scene::Model *model); + static bool isLODModelCulled(const scene::Model *model); static void clearCachedLODModels(); }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h b/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h index 41d0846b7a..329b4934c7 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h @@ -275,84 +275,84 @@ addVertex(std::piecewise_construct_t /*tag*/, Component0&& c0, Component1&& c1, } // IncidenceGraph -inline EmptyGraph::vertex_descriptor -source(const EmptyGraph::edge_descriptor& e, const EmptyGraph& /*g*/) noexcept { +inline RelationGraph::vertex_descriptor +source(const RelationGraph::edge_descriptor& e, const RelationGraph& /*g*/) noexcept { return e.source; } -inline EmptyGraph::vertex_descriptor -target(const EmptyGraph::edge_descriptor& e, const EmptyGraph& /*g*/) noexcept { +inline RelationGraph::vertex_descriptor +target(const RelationGraph::edge_descriptor& e, const RelationGraph& /*g*/) noexcept { return e.target; } -inline std::pair -out_edges(EmptyGraph::vertex_descriptor u, const EmptyGraph& g) noexcept { // NOLINT +inline std::pair +out_edges(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT return std::make_pair( - EmptyGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), - EmptyGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); + RelationGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), + RelationGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); } -inline EmptyGraph::degree_size_type -out_degree(EmptyGraph::vertex_descriptor u, const EmptyGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getOutEdgeList(u).size()); +inline RelationGraph::degree_size_type +out_degree(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getOutEdgeList(u).size()); } -inline std::pair -edge(EmptyGraph::vertex_descriptor u, EmptyGraph::vertex_descriptor v, const EmptyGraph& g) noexcept { +inline std::pair +edge(RelationGraph::vertex_descriptor u, RelationGraph::vertex_descriptor v, const RelationGraph& g) noexcept { const auto& outEdgeList = g.getOutEdgeList(u); - auto iter = std::find(outEdgeList.begin(), outEdgeList.end(), EmptyGraph::OutEdge(v)); + auto iter = std::find(outEdgeList.begin(), outEdgeList.end(), RelationGraph::OutEdge(v)); bool hasEdge = (iter != outEdgeList.end()); - return {EmptyGraph::edge_descriptor(u, v), hasEdge}; + return {RelationGraph::edge_descriptor(u, v), hasEdge}; } // BidirectionalGraph(Directed) -inline std::pair -in_edges(EmptyGraph::vertex_descriptor u, const EmptyGraph& g) noexcept { // NOLINT +inline std::pair +in_edges(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT return std::make_pair( - EmptyGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), - EmptyGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); + RelationGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), + RelationGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); } -inline EmptyGraph::degree_size_type -in_degree(EmptyGraph::vertex_descriptor u, const EmptyGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getInEdgeList(u).size()); +inline RelationGraph::degree_size_type +in_degree(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getInEdgeList(u).size()); } -inline EmptyGraph::degree_size_type -degree(EmptyGraph::vertex_descriptor u, const EmptyGraph& g) noexcept { +inline RelationGraph::degree_size_type +degree(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { return in_degree(u, g) + out_degree(u, g); } // AdjacencyGraph -inline std::pair -adjacent_vertices(EmptyGraph::vertex_descriptor u, const EmptyGraph& g) noexcept { // NOLINT +inline std::pair +adjacent_vertices(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT auto edges = out_edges(u, g); - return std::make_pair(EmptyGraph::adjacency_iterator(edges.first, &g), EmptyGraph::adjacency_iterator(edges.second, &g)); + return std::make_pair(RelationGraph::adjacency_iterator(edges.first, &g), RelationGraph::adjacency_iterator(edges.second, &g)); } // VertexListGraph -inline std::pair -vertices(const EmptyGraph& g) noexcept { - return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); +inline std::pair +vertices(const RelationGraph& g) noexcept { + return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); } -inline EmptyGraph::vertices_size_type -num_vertices(const EmptyGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getVertexList().size()); +inline RelationGraph::vertices_size_type +num_vertices(const RelationGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getVertexList().size()); } // EdgeListGraph -inline std::pair -edges(const EmptyGraph& g0) noexcept { - auto& g = const_cast(g0); +inline std::pair +edges(const RelationGraph& g0) noexcept { + auto& g = const_cast(g0); return std::make_pair( - EmptyGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().begin(), g.getVertexList().end(), g), - EmptyGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().end(), g.getVertexList().end(), g)); + RelationGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().begin(), g.getVertexList().end(), g), + RelationGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().end(), g.getVertexList().end(), g)); } -inline EmptyGraph::edges_size_type -num_edges(const EmptyGraph& g) noexcept { // NOLINT - EmptyGraph::edges_size_type numEdges = 0; +inline RelationGraph::edges_size_type +num_edges(const RelationGraph& g) noexcept { // NOLINT + RelationGraph::edges_size_type numEdges = 0; auto range = vertices(g); for (auto iter = range.first; iter != range.second; ++iter) { @@ -362,49 +362,49 @@ num_edges(const EmptyGraph& g) noexcept { // NOLINT } // MutableGraph(Edge) -inline std::pair +inline std::pair add_edge( // NOLINT - EmptyGraph::vertex_descriptor u, - EmptyGraph::vertex_descriptor v, EmptyGraph& g) { + RelationGraph::vertex_descriptor u, + RelationGraph::vertex_descriptor v, RelationGraph& g) { auto& outEdgeList = g.getOutEdgeList(u); outEdgeList.emplace_back(v); auto& inEdgeList = g.getInEdgeList(v); inEdgeList.emplace_back(u); - return std::make_pair(EmptyGraph::edge_descriptor(u, v), true); + return std::make_pair(RelationGraph::edge_descriptor(u, v), true); } -inline void remove_edge(EmptyGraph::vertex_descriptor u, EmptyGraph::vertex_descriptor v, EmptyGraph& g) noexcept { // NOLINT +inline void remove_edge(RelationGraph::vertex_descriptor u, RelationGraph::vertex_descriptor v, RelationGraph& g) noexcept { // NOLINT auto& s = g._vertices[u]; auto& t = g._vertices[v]; - s.outEdges.erase(std::remove(s.outEdges.begin(), s.outEdges.end(), EmptyGraph::OutEdge(v)), s.outEdges.end()); - t.inEdges.erase(std::remove(t.inEdges.begin(), t.inEdges.end(), EmptyGraph::InEdge(u)), t.inEdges.end()); + s.outEdges.erase(std::remove(s.outEdges.begin(), s.outEdges.end(), RelationGraph::OutEdge(v)), s.outEdges.end()); + t.inEdges.erase(std::remove(t.inEdges.begin(), t.inEdges.end(), RelationGraph::InEdge(u)), t.inEdges.end()); } -inline void remove_edge(EmptyGraph::out_edge_iterator outIter, EmptyGraph& g) noexcept { // NOLINT +inline void remove_edge(RelationGraph::out_edge_iterator outIter, RelationGraph& g) noexcept { // NOLINT auto e = *outIter; const auto u = source(e, g); const auto v = target(e, g); auto& s = g._vertices[u]; auto& t = g._vertices[v]; - auto inIter = std::find(t.inEdges.begin(), t.inEdges.end(), EmptyGraph::InEdge(u)); + auto inIter = std::find(t.inEdges.begin(), t.inEdges.end(), RelationGraph::InEdge(u)); CC_EXPECTS(inIter != t.inEdges.end()); t.inEdges.erase(inIter); s.outEdges.erase(outIter.base()); } -inline void remove_edge(EmptyGraph::edge_descriptor e, EmptyGraph& g) noexcept { // NOLINT +inline void remove_edge(RelationGraph::edge_descriptor e, RelationGraph& g) noexcept { // NOLINT const auto u = source(e, g); const auto v = target(e, g); auto& s = g._vertices[u]; - auto outIter = std::find(s.outEdges.begin(), s.outEdges.end(), EmptyGraph::OutEdge(v)); + auto outIter = std::find(s.outEdges.begin(), s.outEdges.end(), RelationGraph::OutEdge(v)); CC_EXPECTS(outIter != s.outEdges.end()); - remove_edge(EmptyGraph::out_edge_iterator(outIter, u), g); + remove_edge(RelationGraph::out_edge_iterator(outIter, u), g); } // MutableGraph(Vertex) -inline void clear_out_edges(EmptyGraph::vertex_descriptor u, EmptyGraph& g) noexcept { // NOLINT +inline void clear_out_edges(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT // Bidirectional (OutEdges) auto& outEdgeList = g.getOutEdgeList(u); auto outEnd = outEdgeList.end(); @@ -418,7 +418,7 @@ inline void clear_out_edges(EmptyGraph::vertex_descriptor u, EmptyGraph& g) noex outEdgeList.clear(); } -inline void clear_in_edges(EmptyGraph::vertex_descriptor u, EmptyGraph& g) noexcept { // NOLINT +inline void clear_in_edges(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT // Bidirectional (InEdges) auto& inEdgeList = g.getInEdgeList(u); auto inEnd = inEdgeList.end(); @@ -432,13 +432,70 @@ inline void clear_in_edges(EmptyGraph::vertex_descriptor u, EmptyGraph& g) noexc inEdgeList.clear(); } -inline void clear_vertex(EmptyGraph::vertex_descriptor u, EmptyGraph& g) noexcept { // NOLINT +inline void clear_vertex(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT clear_out_edges(u, g); clear_in_edges(u, g); } -inline void remove_vertex(EmptyGraph::vertex_descriptor u, EmptyGraph& g) noexcept { // NOLINT - impl::removeVectorVertex(const_cast(g), u, EmptyGraph::directed_category{}); +inline void remove_vertex(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT + { // UuidGraph + const auto& key = g.descID[u]; + auto num = g.vertexMap.erase(key); + CC_ENSURES(num == 1); + for (auto&& pair : g.vertexMap) { + auto& v = pair.second; + if (v > u) { + --v; + } + } + } + impl::removeVectorVertex(const_cast(g), u, RelationGraph::directed_category{}); + + // remove components + g.descID.erase(g.descID.begin() + std::ptrdiff_t(u)); +} + +// MutablePropertyGraph(Vertex) +template +inline RelationGraph::vertex_descriptor +addVertex(Component0&& c0, RelationGraph& g) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + + { // UuidGraph + const auto& uuid = c0; + auto res = g.vertexMap.emplace(uuid, v); + CC_ENSURES(res.second); + } + g.descID.emplace_back(std::forward(c0)); + + return v; +} + +template +inline RelationGraph::vertex_descriptor +addVertex(std::piecewise_construct_t /*tag*/, Component0&& c0, RelationGraph& g) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + + { // UuidGraph + std::apply( + [&](const auto&... args) { + auto res = g.vertexMap.emplace(std::piecewise_construct, std::forward_as_tuple(args...), std::forward_as_tuple(v)); + CC_ENSURES(res.second); + }, + c0); + } + + std::apply( + [&](auto&&... args) { + g.descID.emplace_back(std::forward(args)...); + }, + std::forward(c0)); + + return v; } } // namespace render @@ -509,11 +566,28 @@ struct property_map -struct property_map { +struct property_map { using const_type = identity_property_map; using type = identity_property_map; }; +// Vertex Component +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + const cc::render::RelationGraph, + const ccstd::pmr::vector, + cc::render::ResourceAccessGraph::vertex_descriptor, + const cc::render::ResourceAccessGraph::vertex_descriptor&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + cc::render::RelationGraph, + ccstd::pmr::vector, + cc::render::ResourceAccessGraph::vertex_descriptor, + cc::render::ResourceAccessGraph::vertex_descriptor&>; +}; + } // namespace boost namespace cc { @@ -646,29 +720,103 @@ add_vertex(ResourceAccessGraph& g, const RenderGraph::vertex_descriptor& key) { } // Vertex Index -inline boost::property_map::const_type -get(boost::vertex_index_t /*tag*/, const EmptyGraph& /*g*/) noexcept { +inline boost::property_map::const_type +get(boost::vertex_index_t /*tag*/, const RelationGraph& /*g*/) noexcept { return {}; } -inline boost::property_map::type -get(boost::vertex_index_t /*tag*/, EmptyGraph& /*g*/) noexcept { +inline boost::property_map::type +get(boost::vertex_index_t /*tag*/, RelationGraph& /*g*/) noexcept { return {}; } -inline impl::ColorMap -get(ccstd::pmr::vector& colors, const EmptyGraph& /*g*/) noexcept { +inline impl::ColorMap +get(ccstd::pmr::vector& colors, const RelationGraph& /*g*/) noexcept { return {colors}; } +// Vertex Component +inline typename boost::property_map::const_type +get(RelationGraph::DescIDTag /*tag*/, const RelationGraph& g) noexcept { + return {g.descID}; +} + +inline typename boost::property_map::type +get(RelationGraph::DescIDTag /*tag*/, RelationGraph& g) noexcept { + return {g.descID}; +} + +// Vertex Constant Getter +template +inline decltype(auto) +get(Tag tag, const RelationGraph& g, RelationGraph::vertex_descriptor v) noexcept { + return get(get(tag, g), v); +} + +// Vertex Mutable Getter +template +inline decltype(auto) +get(Tag tag, RelationGraph& g, RelationGraph::vertex_descriptor v) noexcept { + return get(get(tag, g), v); +} + +// Vertex Setter +template +inline void put( + Tag tag, RelationGraph& g, + RelationGraph::vertex_descriptor v, + Args&&... args) { + put(get(tag, g), v, std::forward(args)...); +} + +// UuidGraph +inline RelationGraph::vertex_descriptor +vertex(const ResourceAccessGraph::vertex_descriptor& key, const RelationGraph& g) { + return g.vertexMap.at(key); +} + +template +inline RelationGraph::vertex_descriptor +vertex(const KeyLike& key, const RelationGraph& g) { + const auto& index = g.vertexMap; + auto iter = index.find(key); + if (iter == index.end()) { + throw std::out_of_range("at(key, RelationGraph) out of range"); + } + return iter->second; +} + +template +inline RelationGraph::vertex_descriptor +findVertex(const KeyLike& key, const RelationGraph& g) noexcept { + const auto& index = g.vertexMap; + auto iter = index.find(key); + if (iter == index.end()) { + return RelationGraph::null_vertex(); + } + return iter->second; +} + +inline bool +contains(const ResourceAccessGraph::vertex_descriptor& key, const RelationGraph& g) noexcept { + auto iter = g.vertexMap.find(key); + return iter != g.vertexMap.end(); +} + +template +inline bool +contains(const KeyLike& key, const RelationGraph& g) noexcept { + auto iter = g.vertexMap.find(key); + return iter != g.vertexMap.end(); +} + // MutableGraph(Vertex) -inline EmptyGraph::vertex_descriptor -addVertex(EmptyGraph& g) { - auto v = gsl::narrow_cast(g._vertices.size()); - - g._vertices.emplace_back(); - - return v; +inline RelationGraph::vertex_descriptor +add_vertex(RelationGraph& g, const ResourceAccessGraph::vertex_descriptor& key) { // NOLINT + return addVertex( + std::piecewise_construct, + std::forward_as_tuple(key), // descID + g); } } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp index 13805e36ba..029455afb9 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp @@ -44,7 +44,9 @@ ResourceAccessGraph::ResourceAccessGraph(const allocator_type& alloc) noexcept resourceIndex(alloc), leafPasses(alloc), culledPasses(alloc), - accessRecord(alloc) {} + accessRecord(alloc), + resourceLifeRecord(alloc), + topologicalOrder(alloc) {} // ContinuousContainer void ResourceAccessGraph::reserve(vertices_size_type sz) { @@ -65,13 +67,37 @@ ResourceAccessGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& all : outEdges(rhs.outEdges, alloc), inEdges(rhs.inEdges, alloc) {} +RelationGraph::RelationGraph(const allocator_type& alloc) noexcept +: _vertices(alloc), + descID(alloc), + vertexMap(alloc) {} + +// ContinuousContainer +void RelationGraph::reserve(vertices_size_type sz) { + _vertices.reserve(sz); + descID.reserve(sz); +} + +RelationGraph::Vertex::Vertex(const allocator_type& alloc) noexcept +: outEdges(alloc), + inEdges(alloc) {} + +RelationGraph::Vertex::Vertex(Vertex&& rhs, const allocator_type& alloc) +: outEdges(std::move(rhs.outEdges), alloc), + inEdges(std::move(rhs.inEdges), alloc) {} + +RelationGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) +: outEdges(rhs.outEdges, alloc), + inEdges(rhs.inEdges, alloc) {} + FrameGraphDispatcher::FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept : resourceAccessGraph(alloc), resourceGraph(resourceGraphIn), graph(graphIn), layoutGraph(layoutGraphIn), scratch(scratchIn), - externalResMap(alloc) {} + externalResMap(alloc), + relationGraph(alloc) {} } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h index d4dfbb7f4c..b0239ab47a 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h @@ -50,6 +50,11 @@ namespace render { struct NullTag {}; +struct ResourceLifeRecord { + uint32_t start{0}; + uint32_t end{0}; +}; + struct LeafStatus { bool isExternal{false}; bool needCulling{false}; @@ -86,6 +91,7 @@ struct AccessStatus { gfx::ShaderStageFlagBit visibility{gfx::ShaderStageFlagBit::NONE}; gfx::MemoryAccessBit access{gfx::MemoryAccessBit::NONE}; gfx::PassType passType{gfx::PassType::RASTER}; + gfx::AccessFlagBit accessFlag{gfx::AccessFlagBit::NONE}; ResourceUsage usage; Range range; }; @@ -236,18 +242,29 @@ struct ResourceAccessGraph { // Members ccstd::pmr::vector resourceNames; PmrUnorderedStringMap resourceIndex; - RenderGraph::vertex_descriptor presentPassID{0xFFFFFFFF}; - PmrFlatMap leafPasses; - PmrFlatSet culledPasses; + vertex_descriptor presentPassID{0xFFFFFFFF}; + PmrFlatMap leafPasses; + PmrFlatSet culledPasses; PmrFlatMap accessRecord; + PmrFlatMap resourceLifeRecord; + ccstd::pmr::vector topologicalOrder; }; -struct EmptyGraph { - EmptyGraph() = default; - EmptyGraph(EmptyGraph&& rhs) = delete; - EmptyGraph(EmptyGraph const& rhs) = delete; - EmptyGraph& operator=(EmptyGraph&& rhs) = delete; - EmptyGraph& operator=(EmptyGraph const& rhs) = delete; +struct RelationGraph { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {_vertices.get_allocator().resource()}; + } + + inline boost::container::pmr::memory_resource* resource() const noexcept { + return get_allocator().resource(); + } + + RelationGraph(const allocator_type& alloc) noexcept; // NOLINT + RelationGraph(RelationGraph&& rhs) = delete; + RelationGraph(RelationGraph const& rhs) = delete; + RelationGraph& operator=(RelationGraph&& rhs) = delete; + RelationGraph& operator=(RelationGraph const& rhs) = delete; // Graph using directed_category = boost::bidirectional_tag; @@ -268,36 +285,36 @@ struct EmptyGraph { // IncidenceGraph using OutEdge = impl::StoredEdge; using out_edge_iterator = impl::OutEdgeIter< - std::vector::iterator, + ccstd::pmr::vector::iterator, vertex_descriptor, edge_descriptor, int32_t>; using degree_size_type = uint32_t; // BidirectionalGraph using InEdge = impl::StoredEdge; using in_edge_iterator = impl::InEdgeIter< - std::vector::iterator, + ccstd::pmr::vector::iterator, vertex_descriptor, edge_descriptor, int32_t>; // AdjacencyGraph using adjacency_iterator = boost::adjacency_iterator_generator< - EmptyGraph, vertex_descriptor, out_edge_iterator>::type; + RelationGraph, vertex_descriptor, out_edge_iterator>::type; // VertexListGraph using vertex_iterator = boost::integer_range::iterator; using vertices_size_type = uint32_t; // VertexList help functions - inline std::vector& getOutEdgeList(vertex_descriptor v) noexcept { + inline ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) noexcept { return _vertices[v].outEdges; } - inline const std::vector& getOutEdgeList(vertex_descriptor v) const noexcept { + inline const ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) const noexcept { return _vertices[v].outEdges; } - inline std::vector& getInEdgeList(vertex_descriptor v) noexcept { + inline ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) noexcept { return _vertices[v].inEdges; } - inline const std::vector& getInEdgeList(vertex_descriptor v) const noexcept { + inline const ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) const noexcept { return _vertices[v].inEdges; } @@ -314,7 +331,7 @@ struct EmptyGraph { } // EdgeListGraph - using edge_iterator = impl::DirectedEdgeIterator; + using edge_iterator = impl::DirectedEdgeIterator; using edges_size_type = uint32_t; // ContinuousContainer @@ -322,16 +339,39 @@ struct EmptyGraph { // Members struct Vertex { - std::vector outEdges; - std::vector inEdges; + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {outEdges.get_allocator().resource()}; + } + + Vertex(const allocator_type& alloc) noexcept; // NOLINT + Vertex(Vertex&& rhs, const allocator_type& alloc); + Vertex(Vertex const& rhs, const allocator_type& alloc); + + Vertex(Vertex&& rhs) noexcept = default; + Vertex(Vertex const& rhs) = delete; + Vertex& operator=(Vertex&& rhs) = default; + Vertex& operator=(Vertex const& rhs) = default; + + ccstd::pmr::vector outEdges; + ccstd::pmr::vector inEdges; }; + + struct DescIDTag { + } static constexpr DescID{}; // NOLINT + // Vertices - std::vector _vertices; + ccstd::pmr::vector _vertices; + // Components + ccstd::pmr::vector descID; + // UuidGraph + PmrUnorderedMap vertexMap; }; struct Barrier { - RenderGraph::vertex_descriptor resourceID{0xFFFFFFFF}; + ResourceGraph::vertex_descriptor resourceID{0xFFFFFFFF}; gfx::BarrierType type{gfx::BarrierType::FULL}; + gfx::GFXObject* barrier{nullptr}; AccessStatus beginStatus; AccessStatus endStatus; }; @@ -381,7 +421,7 @@ struct FrameGraphDispatcher { LayoutGraphData& layoutGraph; boost::container::pmr::memory_resource* scratch{nullptr}; PmrFlatMap externalResMap; - EmptyGraph relationGraph; + RelationGraph relationGraph; bool _enablePassReorder{false}; bool _enableAutoBarrier{true}; bool _enableMemoryAliasing{false}; diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index 4529080436..8594efe4a2 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -44,9 +44,12 @@ #include "boost/graph/hawick_circuits.hpp" #include "boost/graph/visitors.hpp" #include "boost/lexical_cast.hpp" +#include "gfx-base/GFXBarrier.h" #include "gfx-base/GFXDef-common.h" #include "gfx-base/GFXDef.h" #include "gfx-base/GFXDevice.h" +#include "gfx-base/states/GFXBufferBarrier.h" +#include "gfx-base/states/GFXTextureBarrier.h" #include "math/Vec2.h" #include "pipeline/custom/GslUtils.h" #include "pipeline/custom/RenderCommonFwd.h" @@ -96,22 +99,23 @@ using AccessVertex = ResourceAccessGraph::vertex_descriptor; using InputStatusTuple = std::tuple; using ResourceHandle = ResourceGraph::vertex_descriptor; using ResourceNames = PmrFlatSet; -using EdgeList = std::pair; +using EdgeList = std::pair; using CloseCircuit = std::pair; using CloseCircuits = std::vector; -using EmptyVert = EmptyGraph::vertex_descriptor; -using EmptyVerts = std::vector; -using EmptyEdge = EmptyGraph::edge_descriptor; -using EmptyEdges = std::vector; -using ScoreMap = std::map>; +using RelationVert = RelationGraph::vertex_descriptor; +using RelationVerts = std::vector; +using RelationEdge = RelationGraph::edge_descriptor; +using RelationEdges = std::vector; +using ScoreMap = std::map>; using RasterViewsMap = PmrTransparentMap; using ComputeViewsMap = PmrTransparentMap>; +using ResourceLifeRecordMap = PmrFlatMap; struct Graphs { const ResourceGraph &resourceGraph; const LayoutGraphData &layoutGraphData; ResourceAccessGraph &resourceAccessGraph; - EmptyGraph &relationGraph; + RelationGraph &relationGraph; }; struct ViewStatus { @@ -119,6 +123,7 @@ struct ViewStatus { const PassType passType; const gfx::ShaderStageFlagBit visibility; const gfx::MemoryAccessBit access; + const gfx::AccessFlags accessFlag; const ResourceUsage usage; }; @@ -166,7 +171,7 @@ void processComputePass(const Graphs &graphs, uint32_t passID, const ComputePass void processCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass); void processRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePass &pass); void processPresentPass(const Graphs &graphs, uint32_t passID, const PresentPass &pass); -auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAccess memAccess, gfx::ShaderStageFlags visbility, const ResourceGraph &resourceGraph); +auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAccess memAccess, gfx::ShaderStageFlags visibility, const ResourceGraph &resourceGraph); // execution order BUT NOT LOGICALLY bool isPassExecAdjecent(uint32_t passLID, uint32_t passRID) { @@ -177,8 +182,10 @@ bool isStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs); template bool tryAddEdge(uint32_t srcVertex, uint32_t dstVertex, Graph &graph); -inline EmptyGraph::vertex_descriptor add_vertex(EmptyGraph &g) { // NOLINT - return addVertex(g); +// for transive_closure.hpp line 231 +inline RelationGraph::vertex_descriptor add_vertex(RelationGraph &g) { // NOLINT + thread_local uint32_t count = 0; // unused + return add_vertex(g, count++); } // status of resource access @@ -201,6 +208,14 @@ void buildAccessGraph(const RenderGraph &renderGraph, const Graphs &graphs) { resourceAccessGraph.resourceNames.reserve(128); resourceAccessGraph.resourceIndex.reserve(128); + resourceAccessGraph.topologicalOrder.reserve(numPasses); + resourceAccessGraph.topologicalOrder.clear(); + resourceAccessGraph.resourceLifeRecord.reserve(resourceGraph.names.size()); + + if (!resourceAccessGraph.resourceLifeRecord.empty()) { + resourceAccessGraph.resourceLifeRecord.clear(); + } + if (!resourceAccessGraph.leafPasses.empty()) { resourceAccessGraph.leafPasses.clear(); } @@ -213,10 +228,10 @@ void buildAccessGraph(const RenderGraph &renderGraph, const Graphs &graphs) { resourceAccessGraph.leafPasses.emplace(i, LeafStatus{false, false}); } - auto startID = add_vertex(resourceAccessGraph, INVALID_ID); + auto startID = add_vertex(resourceAccessGraph, INVALID_ID - 1); CC_EXPECTS(startID == EXPECT_START_ID); - add_vertex(relationGraph); + add_vertex(relationGraph, startID); for (const auto passID : makeRange(vertices(renderGraph))) { visitObject( @@ -270,16 +285,18 @@ void buildAccessGraph(const RenderGraph &renderGraph, const Graphs &graphs) { // no present pass found, add a fake node to gather leaf node(s). if (resourceAccessGraph.presentPassID == 0xFFFFFFFF) { - auto ragEndNode = add_vertex(rag, rag.getCurrentID()); - auto rlgEndNode = add_vertex(relationGraph); + auto ragEndNode = add_vertex(rag, RenderGraph::null_vertex()); + auto rlgEndNode = add_vertex(relationGraph, ragEndNode); // keep sync before pass reorder done. CC_EXPECTS(ragEndNode == rlgEndNode); resourceAccessGraph.presentPassID = ragEndNode; auto iter = resourceAccessGraph.leafPasses.find(ragEndNode); + constexpr bool isExternal = true; + constexpr bool needCulling = false; if (iter == resourceAccessGraph.leafPasses.end()) { - resourceAccessGraph.leafPasses.emplace(ragEndNode, LeafStatus{true, false}); + resourceAccessGraph.leafPasses.emplace(ragEndNode, LeafStatus{isExternal, needCulling}); } else { - resourceAccessGraph.leafPasses.at(ragEndNode) = LeafStatus{true, false}; + resourceAccessGraph.leafPasses.at(ragEndNode) = LeafStatus{isExternal, needCulling}; } } @@ -303,6 +320,11 @@ void buildAccessGraph(const RenderGraph &renderGraph, const Graphs &graphs) { // remove culled vertices, std::less make this set ascending order, so reverse iterate remove_vertex(*rit, relationGraph); } + + for (auto rlgVert : makeRange(vertices(relationGraph))) { + auto ragVert = get(RelationGraph::DescID, relationGraph, rlgVert); + rag.topologicalOrder.emplace_back(ragVert); + } } #pragma region BUILD_BARRIERS @@ -311,8 +333,25 @@ struct BarrierVisitor : public boost::bfs_visitor<> { using Edge = ResourceAccessGraph::edge_descriptor; using Graph = ResourceAccessGraph; - explicit BarrierVisitor(const ResourceGraph &rg, BarrierMap &barriers, ExternalResMap &extMap, ResourceNames &externalNames, const AccessTable &accessRecordIn) - : barrierMap(barriers), resourceGraph(rg), externalMap(extMap), externalResNames(externalNames), accessRecord(accessRecordIn) { + explicit BarrierVisitor( + const ResourceGraph &rg, + BarrierMap &barriers, // what we get + ExternalResMap &extMap, // record external res between frames + ResourceNames &externalNames, // for external record + const AccessTable &accessRecordIn, // resource last meet + ResourceLifeRecordMap &rescLifeRecord // resource lifetime + ) + : barrierMap(barriers), resourceGraph(rg), externalMap(extMap), externalResNames(externalNames), accessRecord(accessRecordIn), resourceLifeRecord(rescLifeRecord) {} + + void updateResourceLifeTime(const ResourceAccessNode &node, ResourceAccessGraph::vertex_descriptor u) { + for (auto access : node.attachmentStatus) { + auto name = get(ResourceGraph::Name, resourceGraph, access.vertID); + if (resourceLifeRecord.find(name) == resourceLifeRecord.end()) { + resourceLifeRecord.emplace(name, ResourceLifeRecord{u, u}); + } else { + resourceLifeRecord.at(name).end = u; + } + } } struct AccessNodeInfo { @@ -322,7 +361,13 @@ struct BarrierVisitor : public boost::bfs_visitor<> { }; void processVertex(Vertex u, const Graph &g) { + if (in_degree(u, g) == 0 && out_degree(u, g) == 0) { + // culled + return; + } + const ResourceAccessNode &access = get(ResourceAccessGraph::AccessNode, g, u); + updateResourceLifeTime(access, u); if (barrierMap.find(u) == barrierMap.end()) { barrierMap.emplace(u, BarrierNode{{}, {}}); @@ -428,6 +473,7 @@ struct BarrierVisitor : public boost::bfs_visitor<> { srcRearBarriers.emplace_back(Barrier{ resourceID, isAdjacent ? gfx::BarrierType::FULL : gfx::BarrierType::SPLIT_BEGIN, + nullptr, // generate later srcAccess, dstAccess, }); @@ -472,6 +518,7 @@ struct BarrierVisitor : public boost::bfs_visitor<> { dstFrontBarriers.emplace_back(Barrier{ resourceID, gfx::BarrierType::SPLIT_END, + nullptr, srcAccess, dstAccess, }); @@ -545,6 +592,7 @@ struct BarrierVisitor : public boost::bfs_visitor<> { barrierMap[vert].blockBarrier.frontBarriers.emplace_back(Barrier{ rescID, gfx::BarrierType::SPLIT_END, + nullptr, externalMap[resName].lastStatus, externalMap[resName].currStatus, }); @@ -656,81 +704,119 @@ struct BarrierVisitor : public boost::bfs_visitor<> { const ResourceGraph &resourceGraph; ExternalResMap &externalMap; // last frame to curr frame status transition ResourceNames &externalResNames; // first meet in this frame + ResourceLifeRecordMap &resourceLifeRecord; }; void buildBarriers(FrameGraphDispatcher &fgDispatcher) { + auto *scratch = fgDispatcher.scratch; + const auto &graph = fgDispatcher.graph; + const auto &layoutGraph = fgDispatcher.layoutGraph; + const auto &resourceGraph = fgDispatcher.resourceGraph; + auto &relationGraph = fgDispatcher.relationGraph; + auto &externalResMap = fgDispatcher.externalResMap; + auto &rag = fgDispatcher.resourceAccessGraph; + + // record resource current in-access and out-access for every single node + if (!fgDispatcher._accessGraphBuilt) { + const Graphs graphs{resourceGraph, layoutGraph, rag, relationGraph}; + buildAccessGraph(graph, graphs); + fgDispatcher._accessGraphBuilt = true; + } + + // found pass id in this map ? barriers you should commit when run into this pass + // : or no extra barrier needed. + BarrierMap &batchedBarriers = fgDispatcher.barrierMap; + ResourceNames namesSet; { - auto *scratch = fgDispatcher.scratch; - const auto &graph = fgDispatcher.graph; - const auto &layoutGraph = fgDispatcher.layoutGraph; - const auto &resourceGraph = fgDispatcher.resourceGraph; - auto &relationGraph = fgDispatcher.relationGraph; - auto &externalResMap = fgDispatcher.externalResMap; - auto &rag = fgDispatcher.resourceAccessGraph; + // _externalResNames records external resource between frames + BarrierVisitor visitor(resourceGraph, batchedBarriers, externalResMap, namesSet, rag.accessRecord, rag.resourceLifeRecord); + auto colors = rag.colors(scratch); + boost::queue q; - // record resource current in-access and out-access for every single node - if (!fgDispatcher._accessGraphBuilt) { - const Graphs graphs{resourceGraph, layoutGraph, rag, relationGraph}; - buildAccessGraph(graph, graphs); - fgDispatcher._accessGraphBuilt = true; + boost::breadth_first_visit( + rag, + EXPECT_START_ID, + q, + visitor, + get(colors, rag)); + } + + // external res barrier for next frame + for (const auto &externalPair : externalResMap) { + const auto &transition = externalPair.second; + auto resID = resourceGraph.valueIndex.at(externalPair.first); + auto passID = transition.currStatus.vertID; + if (batchedBarriers.find(passID) == batchedBarriers.end()) { + batchedBarriers.emplace(passID, BarrierNode{}); } - // found pass id in this map ? barriers you should commit when run into this pass - // : or no extra barrier needed. - BarrierMap &batchedBarriers = fgDispatcher.barrierMap; - ResourceNames namesSet; - { - // _externalResNames records external resource between frames - BarrierVisitor visitor(resourceGraph, batchedBarriers, externalResMap, namesSet, rag.accessRecord); - auto colors = rag.colors(scratch); - boost::queue q; + Barrier nextFrameResBarrier{ + resID, + gfx::BarrierType::SPLIT_BEGIN, + nullptr, + externalResMap[externalPair.first].currStatus, + {}}; - boost::breadth_first_visit( - rag, - EXPECT_START_ID, - q, - visitor, - get(colors, rag)); - } + bool hasSubpass = !batchedBarriers[passID].subpassBarriers.empty(); - // external res barrier for next frame - for (const auto &externalPair : externalResMap) { - const auto &transition = externalPair.second; - auto resID = resourceGraph.valueIndex.at(externalPair.first); - auto passID = transition.currStatus.vertID; - if (batchedBarriers.find(passID) == batchedBarriers.end()) { - batchedBarriers.emplace(passID, BarrierNode{}); - } + if (hasSubpass) { + auto &subpassBarriers = batchedBarriers[passID].subpassBarriers; + for (int i = static_cast(subpassBarriers.size()) - 1; i >= 0; --i) { + auto findBarrierByResID = [resID](const Barrier &barrier) { + return barrier.resourceID == resID; + }; - Barrier nextFrameResBarrier{ - resID, - gfx::BarrierType::SPLIT_BEGIN, - externalResMap[externalPair.first].currStatus, - {}}; - - bool hasSubpass = !batchedBarriers[passID].subpassBarriers.empty(); - - if (hasSubpass) { - auto &subpassBarriers = batchedBarriers[passID].subpassBarriers; - for (int i = static_cast(subpassBarriers.size()) - 1; i >= 0; --i) { - auto findBarrierByResID = [resID](const Barrier &barrier) { - return barrier.resourceID == resID; - }; - - const auto &frontBarriers = subpassBarriers[i].frontBarriers; - auto &rearBarriers = subpassBarriers[i].rearBarriers; - auto found = std::find_if(frontBarriers.begin(), frontBarriers.end(), findBarrierByResID) != frontBarriers.end() || - std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID) != rearBarriers.end(); - if (found) { - // put into rear barriers in order not to stuck - rearBarriers.push_back({}); - break; - } + const auto &frontBarriers = subpassBarriers[i].frontBarriers; + auto &rearBarriers = subpassBarriers[i].rearBarriers; + auto found = std::find_if(frontBarriers.begin(), frontBarriers.end(), findBarrierByResID) != frontBarriers.end() || + std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID) != rearBarriers.end(); + if (found) { + // put into rear barriers in order not to stuck + rearBarriers.push_back({}); + break; } - } else { - auto &rearBarriers = batchedBarriers[passID].blockBarrier.rearBarriers; - rearBarriers.emplace_back(nextFrameResBarrier); } + } else { + auto &rearBarriers = batchedBarriers[passID].blockBarrier.rearBarriers; + rearBarriers.emplace_back(nextFrameResBarrier); + } + } + + const auto &resDescs = get(ResourceGraph::Desc, resourceGraph); + auto genGFXBarrier = [&resDescs](std::vector &barriers) { + for (auto &passBarrier : barriers) { + const auto &desc = get(resDescs, passBarrier.resourceID); + if (desc.dimension == ResourceDimension::BUFFER) { + gfx::BufferBarrierInfo info; + info.prevAccesses = passBarrier.beginStatus.accessFlag; + info.nextAccesses = passBarrier.endStatus.accessFlag; + const auto &range = ccstd::get(passBarrier.beginStatus.range); + info.offset = range.offset; + info.size = range.size; + info.type = passBarrier.type; + passBarrier.barrier = gfx::Device::getInstance()->getBufferBarrier(info); + } else { + gfx::TextureBarrierInfo info; + info.prevAccesses = passBarrier.beginStatus.accessFlag; + info.nextAccesses = passBarrier.endStatus.accessFlag; + const auto &range = ccstd::get(passBarrier.beginStatus.range); + info.baseMipLevel = range.mipLevel; + info.levelCount = range.levelCount; + info.baseSlice = range.firstSlice; + info.sliceCount = range.numSlices; + info.type = passBarrier.type; + passBarrier.barrier = gfx::Device::getInstance()->getTextureBarrier(info); + } + } + }; + + for (auto &passBarrierInfo : batchedBarriers) { + auto &passBarrierNode = passBarrierInfo.second; + genGFXBarrier(passBarrierNode.blockBarrier.frontBarriers); + genGFXBarrier(passBarrierNode.blockBarrier.rearBarriers); + for (auto &subpassBarrier : passBarrierNode.subpassBarriers) { + genGFXBarrier(subpassBarrier.frontBarriers); + genGFXBarrier(subpassBarrier.rearBarriers); } } } @@ -739,26 +825,25 @@ void buildBarriers(FrameGraphDispatcher &fgDispatcher) { #pragma region PASS_REORDER struct PassVisitor : boost::dfs_visitor<> { - using Vertex = ResourceAccessGraph::vertex_descriptor; - using Edge = ResourceAccessGraph::edge_descriptor; - using Graph = ResourceAccessGraph; - using InEdgeRange = std::pair; - using OutEdgeRange = std::pair; + using RLGVertex = RelationGraph::vertex_descriptor; + using RLGEdge = RelationGraph::edge_descriptor; + using InEdgeRange = std::pair; + using OutEdgeRange = std::pair; - PassVisitor(const Graph &ragIn, EmptyGraph &tcIn, CloseCircuits &circuitsIn) : _rag(ragIn), _relationGraph(tcIn), _circuits(circuitsIn) {} + PassVisitor(RelationGraph &tcIn, CloseCircuits &circuitsIn) : _relationGraph(tcIn), _circuits(circuitsIn) {} - void start_vertex(Vertex u, const Graph &g) {} + void start_vertex(RLGVertex u, const RelationGraph &g) {} - void discover_vertex(Vertex u, const Graph &g) {} + void discover_vertex(RLGVertex u, const RelationGraph &g) {} - void examine_edge(Edge e, const Graph &g) { + void examine_edge(RLGEdge e, const RelationGraph &g) { } - void tree_edge(Edge e, const Graph &g) {} + void tree_edge(RLGEdge e, const RelationGraph &g) {} - void back_edge(Edge e, const Graph &g) {} + void back_edge(RLGEdge e, const RelationGraph &g) {} - void forward_or_cross_edge(Edge e, const Graph &g) { + void forward_or_cross_edge(RLGEdge e, const RelationGraph &g) { // the vertex which: // 1. is ancestor of targetID; // 2. sourceID is reachable at this specific vert; @@ -767,7 +852,7 @@ struct PassVisitor : boost::dfs_visitor<> { auto sourceID = source(e, g); auto targetID = target(e, g); - using RhsRangePair = std::pair; + using RhsRangePair = std::pair; bool foundIntersect = false; std::queue vertQ; @@ -800,7 +885,7 @@ struct PassVisitor : boost::dfs_visitor<> { } assert(foundIntersect); - using LhsRangePair = std::pair; + using LhsRangePair = std::pair; auto branchVert = source(rhsPath.first, g); bool found = false; std::queue forwardVertQ; @@ -836,16 +921,15 @@ struct PassVisitor : boost::dfs_visitor<> { }; private: - const RAG &_rag; - EmptyGraph &_relationGraph; + RelationGraph &_relationGraph; CloseCircuits &_circuits; }; // forward (vertex ascending): // -- true: how much resource this pass writes to, which has an effect of later passes; // -- false: how much resource this pass reads from, which is dependent from former passes. -auto evaluateHeaviness(const RAG &rag, const ResourceGraph &rescGraph, EmptyVert vert, bool forward) { - const ResourceAccessNode &accessNode = get(RAG::AccessNode, rag, static_cast(vert)); +auto evaluateHeaviness(const RAG &rag, const ResourceGraph &rescGraph, ResourceAccessGraph::vertex_descriptor vert, bool forward) { + const ResourceAccessNode &accessNode = get(RAG::AccessNode, rag, vert); int64_t score = 0; bool forceAdjacent = false; for (const auto &resc : accessNode.attachmentStatus) { @@ -880,12 +964,13 @@ auto evaluateHeaviness(const RAG &rag, const ResourceGraph &rescGraph, EmptyVert return std::tie(forceAdjacent, score); }; -void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, EmptyGraph &relationGraph, const EmptyGraph &relationGraphTc, const EmptyVerts &lhsVerts, const EmptyVerts &rhsVerts) { +void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, RelationGraph &relationGraph, const RelationGraph &relationGraphTc, const RelationVerts &lhsVerts, const RelationVerts &rhsVerts) { assert(lhsVerts.size() >= 2); assert(rhsVerts.size() >= 2); - auto evaluate = [&rag, &rescGraph](EmptyVert vert, bool forward) { - return evaluateHeaviness(rag, rescGraph, vert, forward); + auto evaluate = [&rag, &rescGraph, &relationGraph](RelationVert vert, bool forward) { + auto ragVert = get(RelationGraph::DescID, relationGraph, vert); + return evaluateHeaviness(rag, rescGraph, ragVert, forward); }; if (lhsVerts.size() == 2 || rhsVerts.size() == 2) { @@ -895,7 +980,7 @@ void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, EmptyGr 3 --`` no extra choice, only 1 - 3 - 2 */ - const EmptyVerts *shorterPath = lhsVerts.size() == 2 ? &lhsVerts : &rhsVerts; + const RelationVerts *shorterPath = lhsVerts.size() == 2 ? &lhsVerts : &rhsVerts; remove_edge((*shorterPath)[0], (*shorterPath)[1], relationGraph); } else { // fist and last joint pass in this circuit don't get involved in reorder. @@ -916,8 +1001,8 @@ void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, EmptyGr bool rhsAdjacentToEnd = std::get<0>(rhsForwardStatus); if (lhsAdjacentToStart || rhsAdjacentToEnd || lhsAdjacentToEnd || rhsAdjacentToStart) { - const EmptyVerts *formerPath = &lhsVerts; - const EmptyVerts *latterPath = &rhsVerts; + const RelationVerts *formerPath = &lhsVerts; + const RelationVerts *latterPath = &rhsVerts; if (rhsAdjacentToStart || lhsAdjacentToEnd) { swap(formerPath, latterPath); } @@ -930,8 +1015,8 @@ void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, EmptyGr assert(lhsVerts.size() >= 3 && rhsVerts.size() >= 3); constexpr int64_t score = std::numeric_limits::lowest(); - ccstd::vector> candidateSections; - std::queue lhsSection; + ccstd::vector> candidateSections; + std::queue lhsSection; for (size_t i = 1; i < lhsVerts.size(); ++i) { auto tryE = edge(lhsVerts[i], lhsVerts[i - 1], relationGraphTc); auto tryRE = edge(lhsVerts[i - 1], lhsVerts[i], relationGraphTc); @@ -939,7 +1024,7 @@ void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, EmptyGr if (!tryE.second && !tryRE.second) { remove_edge(lhsVerts[i - 1], lhsVerts[i], relationGraph); candidateSections.emplace_back(lhsSection); - std::queue clearQ; + std::queue clearQ; lhsSection.swap(clearQ); } auto e = edge(lhsVerts[i], lhsVerts[i - 1], relationGraph); @@ -956,14 +1041,14 @@ void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, EmptyGr candidateSections.emplace_back(std::move(lhsSection)); } - std::queue rhsSection; + std::queue rhsSection; for (size_t i = 1; i < rhsVerts.size(); ++i) { auto tryE = edge(rhsVerts[i], rhsVerts[i - 1], relationGraphTc); auto tryRE = edge(rhsVerts[i - 1], rhsVerts[i], relationGraphTc); if (!tryE.second && !tryRE.second) { remove_edge(rhsVerts[i - 1], rhsVerts[i], relationGraph); candidateSections.emplace_back(rhsSection); - std::queue clearQ; + std::queue clearQ; rhsSection.swap(clearQ); } auto e = edge(rhsVerts[i], rhsVerts[i - 1], relationGraph); @@ -1039,8 +1124,8 @@ void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, EmptyGr } // return : can be further reduced? -bool reduce(const RAG &rag, const ResourceGraph &rescGraph, EmptyGraph &relationGraph, EmptyGraph &relationGraphTc, const CloseCircuit &circuit) { - auto checkPath = [&relationGraph](std::stack &vertices, EmptyGraph::vertex_descriptor endVert, EmptyVerts &stackTrace) { +bool reduce(const RAG &rag, const ResourceGraph &rescGraph, RelationGraph &relationGraph, RelationGraph &relationGraphTc, const CloseCircuit &circuit) { + auto checkPath = [&relationGraph](std::stack &vertices, RelationGraph::vertex_descriptor endVert, RelationVerts &stackTrace) { bool simpleGraph = true; while (!vertices.empty()) { auto vert = vertices.top(); @@ -1072,10 +1157,10 @@ bool reduce(const RAG &rag, const ResourceGraph &rescGraph, EmptyGraph &relation auto startVert = target(lhsEdges.first, relationGraph); auto endVert = source(lhsEdges.second, relationGraph); - std::stack vertices; + std::stack vertices; vertices.emplace(startVert); - EmptyVerts lhsVisited; + RelationVerts lhsVisited; auto branchStartVert = source(lhsEdges.first, relationGraph); auto branchEndVert = target(lhsEdges.second, relationGraph); lhsVisited.push_back(branchStartVert); @@ -1092,7 +1177,7 @@ bool reduce(const RAG &rag, const ResourceGraph &rescGraph, EmptyGraph &relation endVert = source(rhsEdges.second, relationGraph); vertices.emplace(startVert); - EmptyVerts rhsVisited; + RelationVerts rhsVisited; rhsVisited.push_back(branchStartVert); if (!checkPath(vertices, endVert, rhsVisited)) { return false; @@ -1155,14 +1240,14 @@ void passReorder(FrameGraphDispatcher &fgDispatcher) { { // determine do mem saving how many times - EmptyGraph relationGraphTc; + RelationGraph relationGraphTc(fgDispatcher.get_allocator()); boost::transitive_closure(relationGraph, relationGraphTc); CloseCircuits circuits; std::vector crossEdges; - PassVisitor visitor(rag, relationGraphTc, circuits); - auto colors = rag.colors(scratch); - boost::depth_first_search(rag, visitor, get(colors, rag)); + PassVisitor visitor(relationGraphTc, circuits); + auto colors = relationGraph.colors(scratch); + boost::depth_first_search(relationGraph, visitor, get(colors, relationGraph)); float percent = 0.0F; uint32_t count = 0; @@ -1181,32 +1266,26 @@ void passReorder(FrameGraphDispatcher &fgDispatcher) { } // topological sort + rag.topologicalOrder.clear(); bool empty = relationGraph._vertices.empty(); ScoreMap scoreMap; - std::queue vertQ; - EmptyVerts candidates; + RelationVerts candidates; + candidates.push_back(EXPECT_START_ID); - for (size_t i = 0; i < relationGraph._vertices.size(); ++i) { - if (in_degree(static_cast(i), relationGraph) == 0) { - if (std::find(candidates.begin(), candidates.end(), i) == candidates.end()) { - candidates.push_back(static_cast(i)); - } - } - } - - std::vector candidateBuffer; + std::vector candidateBuffer; uint32_t coloredVerts = 0; while (coloredVerts < relationGraph._vertices.size()) { // decreasing order, pop back from vector, push into queue, then it's ascending order. - std::sort(candidates.begin(), candidates.end(), [&](EmptyVert lhsVert, EmptyVert rhsVert) { + std::sort(candidates.begin(), candidates.end(), [&](RelationVert lhsVert, RelationVert rhsVert) { int64_t lhsForwardScore{0}; int64_t rhsForwardScore{0}; int64_t lhsBackwardScore{0}; int64_t rhsBackwardScore{0}; if (scoreMap.find(lhsVert) == scoreMap.end()) { - const auto &lhsForwardStatus = evaluateHeaviness(rag, resourceGraph, lhsVert, true); + auto lhsRagVert = get(RelationGraph::DescID, relationGraph, lhsVert); + const auto &lhsForwardStatus = evaluateHeaviness(rag, resourceGraph, lhsRagVert, true); lhsForwardScore = get<1>(lhsForwardStatus); - const auto &lhsBackwardStatus = evaluateHeaviness(rag, resourceGraph, lhsVert, false); + const auto &lhsBackwardStatus = evaluateHeaviness(rag, resourceGraph, lhsRagVert, false); lhsBackwardScore = get<1>(lhsBackwardStatus); scoreMap.emplace(lhsVert, std::pair{lhsBackwardScore, lhsForwardScore}); } else { @@ -1215,9 +1294,10 @@ void passReorder(FrameGraphDispatcher &fgDispatcher) { } if (scoreMap.find(rhsVert) == scoreMap.end()) { - const auto &rhsForwardStatus = evaluateHeaviness(rag, resourceGraph, rhsVert, true); + auto rhsRagVert = get(RelationGraph::DescID, relationGraph, rhsVert); + const auto &rhsForwardStatus = evaluateHeaviness(rag, resourceGraph, rhsRagVert, true); rhsForwardScore = get<1>(rhsForwardStatus); - const auto &rhsBackwardStatus = evaluateHeaviness(rag, resourceGraph, rhsVert, false); + const auto &rhsBackwardStatus = evaluateHeaviness(rag, resourceGraph, rhsRagVert, false); rhsBackwardScore = get<1>(rhsBackwardStatus); scoreMap.emplace(rhsVert, std::pair{rhsBackwardScore, rhsForwardScore}); } else { @@ -1229,7 +1309,9 @@ void passReorder(FrameGraphDispatcher &fgDispatcher) { const auto vert = candidates.back(); candidates.pop_back(); - vertQ.push(vert); + + auto ragVert = get(RelationGraph::DescID, relationGraph, vert); + rag.topologicalOrder.emplace_back(ragVert); if (!candidateBuffer.empty()) { candidates.insert(candidates.end(), candidateBuffer.begin(), candidateBuffer.end()); candidateBuffer.clear(); @@ -1257,19 +1339,21 @@ void passReorder(FrameGraphDispatcher &fgDispatcher) { coloredVerts++; } - // sort graph by the order in queue - for (const auto &vert : makeRange(vertices(rag))) { + // remove all edges + for (auto vert : makeRange(vertices(rag))) { clear_in_edges(vert, rag); clear_out_edges(vert, rag); } - auto vert = vertQ.front(); - vertQ.pop(); - while (!vertQ.empty()) { - auto nextVert = vertQ.front(); - vertQ.pop(); - add_edge(vert, nextVert, rag); - vert = nextVert; + // apply relation + for (auto rlgVert : makeRange(vertices(relationGraph))) { + auto ragVert = get(RelationGraph::DescID, relationGraph, rlgVert); + auto inEdges = in_edges(rlgVert, relationGraph); + for (auto e : makeRange(inEdges)) { + auto srcRlgVert = source(e, relationGraph); + auto srcRagVert = get(RelationGraph::DescID, relationGraph, srcRlgVert); + add_edge(srcRagVert, ragVert, rag); + } } } } @@ -1303,25 +1387,27 @@ bool isStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs) { return res; } -auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAccess memAccess, gfx::ShaderStageFlags visbility, const ResourceGraph &resourceGraph) { +auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAccess memAccess, gfx::ShaderStageFlags visibility, const ResourceGraph &resourceGraph) { ResourceUsage usage; gfx::ShaderStageFlags vis; - vis = visbility; + vis = visibility; + gfx::AccessFlags accesFlag; auto vertex = resourceGraph.valueIndex.at(name); const auto &desc = get(ResourceGraph::Desc, resourceGraph, vertex); if (desc.dimension == ResourceDimension::BUFFER) { + gfx::BufferUsage bufferUsage{gfx::BufferUsage::NONE}; // copy is not included in this logic because copy can be set TRANSFER_xxx directly. if (gfx::hasFlag(memAccess, gfx::MemoryAccessBit::WRITE_ONLY)) { - usage = gfx::BufferUsage::STORAGE; + bufferUsage = gfx::BufferUsage::STORAGE; } else if (gfx::hasFlag(memAccess, gfx::MemoryAccessBit::READ_ONLY)) { bool uniformFlag = (desc.flags & ResourceFlags::UNIFORM) != ResourceFlags::NONE; bool storageFlag = (desc.flags & ResourceFlags::STORAGE) != ResourceFlags::NONE; CC_EXPECTS(uniformFlag ^ storageFlag); // uniform or read-only storage buffer - usage = uniformFlag ? gfx::BufferUsage::UNIFORM : gfx::BufferUsage::STORAGE; + bufferUsage = uniformFlag ? gfx::BufferUsage::UNIFORM : gfx::BufferUsage::STORAGE; } else { - usage = gfx::BufferUsage::NONE; + bufferUsage = gfx::BufferUsage::NONE; } // those buffers not found in descriptorlayout but appear here, // can and only can be VERTEX/INDEX/INDIRECT BUFFER, @@ -1329,9 +1415,12 @@ auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAcce if (vis == gfx::ShaderStageFlags::NONE) { CC_EXPECTS(passType == PassType::COPY); } + usage = bufferUsage; + accesFlag = gfx::getAccessFlags(bufferUsage, gfx::MemoryUsage::DEVICE, memAccess, vis); } else { // can't find this resource in layoutdata, not in descriptor so either input or output attachment. - bool isAttachment = visbility == gfx::ShaderStageFlags::NONE; + gfx::TextureUsage texUsage = gfx::TextureUsage::NONE; + bool isAttachment = visibility == gfx::ShaderStageFlags::NONE; if (isAttachment) { vis = gfx::ShaderStageFlags::FRAGMENT; bool outColorFlag = (desc.flags & ResourceFlags::COLOR_ATTACHMENT) != ResourceFlags::NONE; @@ -1341,34 +1430,34 @@ auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAcce CC_EXPECTS(outColorFlag ^ depthStencilFlag); inputFlag &= gfx::hasFlag(memAccess, gfx::MemoryAccess::READ_ONLY); - outColorFlag &= gfx::hasFlag(memAccess, gfx::MemoryAccess::WRITE_ONLY); - depthStencilFlag &= gfx::hasFlag(memAccess, gfx::MemoryAccess::WRITE_ONLY); - gfx::TextureUsage texUsage = gfx::TextureUsage::NONE; if (outColorFlag) texUsage |= gfx::TextureUsage::COLOR_ATTACHMENT; if (inputFlag) texUsage |= gfx::TextureUsage::INPUT_ATTACHMENT; if (depthStencilFlag) texUsage |= gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT; - usage = texUsage; } else { if (gfx::hasFlag(memAccess, gfx::MemoryAccess::WRITE_ONLY)) { - usage = gfx::TextureUsage::STORAGE; + texUsage = gfx::TextureUsage::STORAGE; } else if (gfx::hasFlag(memAccess, gfx::MemoryAccess::READ_ONLY)) { bool uniformFlag = (desc.flags & ResourceFlags::SAMPLED) != ResourceFlags::NONE; bool storageFlag = (desc.flags & ResourceFlags::STORAGE) != ResourceFlags::NONE; CC_EXPECTS(uniformFlag ^ storageFlag); - usage = uniformFlag ? gfx::TextureUsage::SAMPLED : gfx::TextureUsage::STORAGE; + texUsage = uniformFlag ? gfx::TextureUsage::SAMPLED : gfx::TextureUsage::STORAGE; } else { - usage = gfx::TextureUsage::NONE; + texUsage = gfx::TextureUsage::NONE; } } + usage = texUsage; + accesFlag = gfx::getAccessFlags(texUsage, memAccess, vis); } - return std::tie(vis, usage); + + return std::tie(vis, usage, accesFlag); } void addCopyAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status, const Range &range) { - const auto &[name, passType, visibility, access, usage] = status; + const auto &[name, passType, visibility, access, accessFlag, usage] = status; + CC_EXPECTS(hasAnyFlags(accessFlag, gfx::AccessFlags::TRANSFER_READ | gfx::AccessFlags::TRANSFER_WRITE)); uint32_t rescID = rg.valueIndex.at(name); @@ -1383,13 +1472,14 @@ void addCopyAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode & visibility, access, passType, + accessFlag, usage, range, }); } void addAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status) { - const auto &[name, passType, visibility, access, usage] = status; + const auto &[name, passType, visibility, access, accessFlag, usage] = status; uint32_t rescID = rg.valueIndex.at(name); const auto &resourceDesc = get(ResourceGraph::Desc, rg, rescID); Range range; @@ -1410,13 +1500,14 @@ void addAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node visibility, access, passType, + accessFlag, usage, range, }); } AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ResourceGraph &rg, const ViewStatus &viewStatus) { - const auto &[name, passType, visibility, access, usage] = viewStatus; + const auto &[name, passType, visibility, access, accessFlag, usage] = viewStatus; auto &accessRecord = rag.accessRecord; AccessVertex lastVertID = INVALID_ID; @@ -1429,7 +1520,7 @@ AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ResourceGra resourceID, ResourceTransition{ {}, - {curVertID, visibility, access, passType, usage, Range{}}}); + {curVertID, visibility, access, passType, accessFlag, usage, Range{}}}); if (isExternalPass) { rag.leafPasses[curVertID] = LeafStatus{true, access == gfx::MemoryAccessBit::READ_ONLY && passType != PassType::PRESENT}; } @@ -1451,14 +1542,14 @@ AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ResourceGra if (isExternalPass) { rag.leafPasses[curVertID] = LeafStatus{true, access == gfx::MemoryAccessBit::READ_ONLY && passType != PassType::PRESENT}; } - trans.currStatus = {curVertID, visibility, access, passType, usage, Range{}}; + trans.currStatus = {curVertID, visibility, access, passType, accessFlag, usage, Range{}}; lastVertID = trans.lastStatus.vertID; } else { // avoid subpass self depends if (trans.currStatus.vertID != curVertID) { lastVertID = trans.currStatus.vertID; trans.lastStatus = trans.currStatus; - trans.currStatus = {curVertID, visibility, access, passType, usage, Range{}}; + trans.currStatus = {curVertID, visibility, access, passType, accessFlag, usage, Range{}}; if (rag.leafPasses.find(trans.lastStatus.vertID) != rag.leafPasses.end()) { rag.leafPasses.erase(trans.lastStatus.vertID); } @@ -1469,7 +1560,7 @@ AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ResourceGra } } } else { - trans.currStatus = {curVertID, visibility, trans.currStatus.access | access, passType, usage, Range{}}; + trans.currStatus = {curVertID, visibility, trans.currStatus.access | access, passType, accessFlag, usage, Range{}}; } } } @@ -1500,8 +1591,8 @@ bool checkRasterViews(const Graphs &graphs, uint32_t vertID, uint32_t passID, Pa const auto &rasterView = pair.second; auto access = toGfxAccess(rasterView.accessType); gfx::ShaderStageFlagBit tryGotVis = getVisibilityByDescName(layoutGraphData, passID, pair.first); - const auto &[vis, usage] = getResourceStatus(passType, pair.first, access, tryGotVis, resourceGraph); - ViewStatus viewStatus{pair.first, passType, vis, access, usage}; + const auto &[vis, usage, accessFlag] = getResourceStatus(passType, pair.first, access, tryGotVis, resourceGraph); + ViewStatus viewStatus{pair.first, passType, vis, access, accessFlag, usage}; addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, viewStatus); if (lastVertId != INVALID_ID && lastVertId != vertID) { @@ -1526,8 +1617,8 @@ bool checkComputeViews(const Graphs &graphs, uint32_t vertID, uint32_t passID, P for (const auto &computeView : values) { auto access = toGfxAccess(computeView.accessType); gfx::ShaderStageFlagBit tryGotVis = getVisibilityByDescName(layoutGraphData, passID, pair.first); - const auto &[vis, usage] = getResourceStatus(passType, pair.first, access, tryGotVis, resourceGraph); - ViewStatus viewStatus{pair.first, passType, vis, access, usage}; + const auto &[vis, usage, accessFlag] = getResourceStatus(passType, pair.first, access, tryGotVis, resourceGraph); + ViewStatus viewStatus{pair.first, passType, vis, access, accessFlag, usage}; addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, viewStatus); if (lastVertId != INVALID_ID) { @@ -1547,8 +1638,8 @@ bool checkComputeViews(const Graphs &graphs, uint32_t vertID, uint32_t passID, P void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass &pass) { const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - auto rlgVertID = add_vertex(relationGraph); auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); auto &node = get(RAG::AccessNode, resourceAccessGraph, vertID); @@ -1564,7 +1655,7 @@ void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass & dependent |= checkRasterViews(graphs, vertID, passID, PassType::RASTER, *head, subpass.rasterViews); dependent |= checkComputeViews(graphs, vertID, passID, PassType::RASTER, *head, subpass.computeViews); - for (const auto &attachment : head->attachmentStatus) { + for (auto &attachment : head->attachmentStatus) { auto resID = attachment.vertID; auto findByResID = [resID](const AccessStatus &status) { return status.vertID == resID; @@ -1573,9 +1664,18 @@ void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass & auto iter = std::find_if(node.attachmentStatus.begin(), node.attachmentStatus.end(), findByResID); if (iter == node.attachmentStatus.end()) { node.attachmentStatus.emplace_back(attachment); + iter = std::prev(node.attachmentStatus.end()); } else { (*iter) = attachment; } + const auto &name = get(ResourceGraph::Name, resourceGraph, resID); + auto rasterIter = subpass.rasterViews.find(name); + if (rasterIter != subpass.rasterViews.end()) { + if (rasterIter->second.loadOp == gfx::LoadOp::LOAD) { + // subpass load access + attachment.accessFlag |= rasterIter->second.attachmentType == AttachmentType::RENDER_TARGET ? gfx::AccessFlags::COLOR_ATTACHMENT_READ : gfx::AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ; + } + } } lastNode = head; } @@ -1592,8 +1692,8 @@ void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass & void processComputePass(const Graphs &graphs, uint32_t passID, const ComputePass &pass) { const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - auto rlgVertID = add_vertex(relationGraph); auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); auto &node = get(RAG::AccessNode, resourceAccessGraph, vertID); @@ -1608,8 +1708,8 @@ void processComputePass(const Graphs &graphs, uint32_t passID, const ComputePass void processCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass) { const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - auto rlgVertID = add_vertex(relationGraph); auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); auto &node = get(RAG::AccessNode, resourceAccessGraph, vertID); @@ -1630,10 +1730,10 @@ void processCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass pair.numSlices, }}; ResourceUsage srcUsage = gfx::TextureUsage::TRANSFER_SRC; - ViewStatus srcViewStatus{pair.source, PassType::COPY, defaultVisibility, gfx::MemoryAccessBit::READ_ONLY, srcUsage}; + ViewStatus srcViewStatus{pair.source, PassType::COPY, defaultVisibility, gfx::MemoryAccessBit::READ_ONLY, gfx::AccessFlags::TRANSFER_READ, srcUsage}; addCopyAccessStatus(resourceAccessGraph, resourceGraph, node, srcViewStatus, sourceRange); ResourceUsage dstUsage = gfx::TextureUsage::TRANSFER_DST; - ViewStatus dstViewStatus{pair.target, PassType::COPY, defaultVisibility, gfx::MemoryAccessBit::WRITE_ONLY, dstUsage}; + ViewStatus dstViewStatus{pair.target, PassType::COPY, defaultVisibility, gfx::MemoryAccessBit::WRITE_ONLY, gfx::AccessFlags::TRANSFER_WRITE, dstUsage}; addCopyAccessStatus(resourceAccessGraph, resourceGraph, node, dstViewStatus, targetRange); uint32_t lastVertSrc = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, srcViewStatus); @@ -1659,8 +1759,8 @@ void processCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass void processRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePass &pass) { const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - auto rlgVertID = add_vertex(relationGraph); auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); auto &node = get(RAG::AccessNode, resourceAccessGraph, vertID); @@ -1675,14 +1775,14 @@ void processRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePa void processPresentPass(const Graphs &graphs, uint32_t passID, const PresentPass &pass) { const auto &[resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - auto rlgVertID = add_vertex(relationGraph); auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); auto &node = get(RAG::AccessNode, resourceAccessGraph, vertID); bool dependent = false; for (const auto &pair : pass.presents) { - ViewStatus viewStatus{pair.first, PassType::PRESENT, gfx::ShaderStageFlagBit::NONE, gfx::MemoryAccessBit::READ_ONLY, gfx::TextureUsage::NONE}; + ViewStatus viewStatus{pair.first, PassType::PRESENT, gfx::ShaderStageFlagBit::NONE, gfx::MemoryAccessBit::READ_ONLY, gfx::AccessFlags::PRESENT, gfx::TextureUsage::NONE}; auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, viewStatus); addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); diff --git a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp index eb11df0c5b..486ef012a5 100644 --- a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp @@ -16,9 +16,11 @@ #include "cocos/renderer/gfx-base/GFXBarrier.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/gfx-base/GFXDevice.h" +#include "cocos/renderer/pipeline/InstancedBuffer.h" #include "cocos/renderer/pipeline/LODModelsUtil.h" #include "cocos/scene/Model.h" #include "cocos/scene/Octree.h" +#include "cocos/scene/Pass.h" #include "cocos/scene/RenderScene.h" #include "cocos/scene/Skybox.h" @@ -41,6 +43,7 @@ struct RenderGraphVisitorContext { ccstd::pmr::unordered_map< const scene::RenderScene*, ccstd::pmr::unordered_map>& sceneQueuesIn, + PipelineRuntime* pplIn, boost::container::pmr::memory_resource* scratchIn) : context(contextIn), g(gIn), @@ -51,6 +54,7 @@ struct RenderGraphVisitorContext { device(deviceIn), cmdBuff(cmdBuffIn), sceneQueues(sceneQueuesIn), + ppl(pplIn), scratch(scratchIn) {} NativeRenderContext& context; @@ -66,6 +70,7 @@ struct RenderGraphVisitorContext { ccstd::pmr::unordered_map< const scene::RenderScene*, ccstd::pmr::unordered_map>& sceneQueues; + PipelineRuntime* ppl = nullptr; }; void clear(gfx::RenderPassInfo& info) { @@ -258,14 +263,12 @@ gfx::BufferBarrierInfo getBufferBarrier(const cc::render::Barrier& barrier) { return { gfx::getAccessFlags( beginUsage, memUsage, - barrier.beginStatus.visibility, barrier.beginStatus.access, - barrier.beginStatus.passType), + barrier.beginStatus.visibility), gfx::getAccessFlags( endUsage, memUsage, - barrier.endStatus.visibility, barrier.endStatus.access, - barrier.endStatus.passType), + barrier.endStatus.visibility), barrier.type, bufferRange.offset, bufferRange.size}; } @@ -298,12 +301,12 @@ std::pair getTextureBarrier( const auto& beginUsage = get(barrier.beginStatus.usage); const auto& endUsage = get(barrier.endStatus.usage); - auto beginAccesFlags = gfx::getDeviceAccessFlags( + auto beginAccesFlags = gfx::getAccessFlags( beginUsage, barrier.beginStatus.access, barrier.beginStatus.visibility); - auto endAccessFlags = gfx::getDeviceAccessFlags( + auto endAccessFlags = gfx::getAccessFlags( endUsage, barrier.endStatus.access, barrier.endStatus.visibility); @@ -355,8 +358,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { const auto& resource = get(ResourceGraph::DescTag{}, resg, resID); switch (desc.dimension) { case ResourceDimension::BUFFER: { - gfx::BufferBarrierInfo info = getBufferBarrier(barrier); - const auto* bufferBarrier = ctx.device->getBufferBarrier(info); + const auto* bufferBarrier = static_cast(barrier.barrier); buffers.emplace_back(nullptr); bufferBarriers.emplace_back(bufferBarrier); break; @@ -366,7 +368,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { case ResourceDimension::TEXTURE3D: default: { auto [info, texture] = getTextureBarrier(resg, resID, barrier); - const auto* textureBarrier = ctx.device->getTextureBarrier(info); + const auto* textureBarrier = static_cast(barrier.barrier); textures.emplace_back(texture); textureBarriers.emplace_back(textureBarrier); break; @@ -423,6 +425,10 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { data.clearDepth, data.clearStencil); ctx.currentPass = data.renderPass.get(); + + // update states + // auto offset = ctx.ppl->getPipelineUBO()->getCurrentCameraUBOOffset(); + // cmdBuff->bindDescriptorSet(pipeline::globalSet, ctx.getDescriptorSet(), 1, &offset); } void begin(const ComputePass& pass) const { // NOLINT(readability-convert-member-functions-to-static) std::ignore = pass; @@ -458,8 +464,40 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { CC_EXPECTS(false); } void begin(const RenderQueue& pass) const { + // update uniform buffers and descriptor sets } - void begin(const SceneData& pass) const { + void begin(const SceneData& sceneData) const { + return; + auto* camera = sceneData.camera; + const auto* scene = camera->getScene(); + const auto& queues = ctx.sceneQueues.at(scene); + const auto& queue = queues.at(camera); + bool bDraw = any(sceneData.flags & SceneFlags::DRAW_NON_INSTANCING); + bool bDrawInstancing = any(sceneData.flags & SceneFlags::DRAW_INSTANCING); + if (!bDraw && !bDrawInstancing) { + bDraw = true; + bDrawInstancing = true; + } + if (any(sceneData.flags & (SceneFlags::OPAQUE_OBJECT | SceneFlags::CUTOUT_OBJECT))) { + if (bDraw) { + queue.opaqueQueue.recordCommandBuffer( + ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); + } + if (bDrawInstancing) { + queue.opaqueInstancingQueue.recordCommandBuffer( + ctx.currentPass, ctx.cmdBuff); + } + } + if (any(sceneData.flags & SceneFlags::TRANSPARENT_OBJECT)) { + if (bDraw) { + queue.transparentQueue.recordCommandBuffer( + ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); + } + if (bDrawInstancing) { + queue.transparentInstancingQueue.recordCommandBuffer( + ctx.currentPass, ctx.cmdBuff); + } + } } void begin(const Blit& pass) const { } @@ -658,7 +696,11 @@ struct ResourceCleaner { struct RenderGraphContextCleaner { explicit RenderGraphContextCleaner(NativeRenderContext& contextIn) noexcept - : context(contextIn) {} + : context(contextIn), + prevFenceValue(context.nextFenceValue) { + ++context.nextFenceValue; + context.clearPreviousResources(prevFenceValue); + } RenderGraphContextCleaner(const RenderGraphContextCleaner&) = delete; RenderGraphContextCleaner& operator=(const RenderGraphContextCleaner&) = delete; ~RenderGraphContextCleaner() noexcept { @@ -671,6 +713,7 @@ struct RenderGraphContextCleaner { } } NativeRenderContext& context; + uint64_t prevFenceValue = 0; }; struct CommandSubmitter { @@ -692,25 +735,24 @@ struct CommandSubmitter { gfx::CommandBuffer* primaryCommandBuffer = nullptr; }; -bool isNodeVisible(const scene::Model* model, const uint32_t visibility) { - CC_EXPECTS(model); - const auto* const node = model->getNode(); +bool isNodeVisible(const scene::Model& model, const uint32_t visibility) { + const auto* const node = model.getNode(); CC_EXPECTS(node); - return model->getNode() && ((visibility & node->getLayer()) == node->getLayer()); + return model.getNode() && ((visibility & node->getLayer()) == node->getLayer()); } -bool isInstanceVisible(const scene::Model* model, const uint32_t visibility) { - return isNodeVisible(model, visibility) && - (visibility & static_cast(model->getVisFlags())); +bool isInstanceVisible(const scene::Model& model, const uint32_t visibility) { + return isNodeVisible(model, visibility) || + (visibility & static_cast(model.getVisFlags())); } -bool isPointInstanceAndNotSkybox(const scene::Model* model, const scene::Skybox* skyBox) { - const auto* modelWorldBounds = model->getWorldBounds(); - return !modelWorldBounds && (skyBox == nullptr || skyBox->getModel() != model); +bool isPointInstanceAndNotSkybox(const scene::Model& model, const scene::Skybox* skyBox) { + const auto* modelWorldBounds = model.getWorldBounds(); + return !modelWorldBounds && (skyBox == nullptr || skyBox->getModel() != &model); } -bool isPointInstance(const scene::Model* model) { - return !model->getWorldBounds(); +bool isPointInstance(const scene::Model& model) { + return !model.getWorldBounds(); } void addShadowCastObject() { @@ -718,76 +760,150 @@ void addShadowCastObject() { // csmLayers->addLayerObject(genRenderObject(model, camera)); } -void addRenderObject(const scene::Camera* camera, const scene::Model* model) { +bool isTransparent(const scene::Pass& pass) { + bool bBlend = false; + for (const auto& target : pass.getBlendState()->targets) { + if (target.blend) { + bBlend = true; + } + } + return bBlend; +} + +float computeSortingDepth(const scene::Camera& camera, const scene::Model& model) { + float depth = 0; + if (model.getNode()) { + const auto* node = model.getTransform(); + cc::Vec3 position; + cc::Vec3::subtract(node->getWorldPosition(), camera.getPosition(), &position); + depth = position.dot(camera.getForward()); + } + return depth; +} + +void addRenderObject( + const scene::Camera& camera, const scene::Model& model, NativeRenderQueue& queue) { + const bool bDrawTransparent = any(queue.sceneFlags & SceneFlags::TRANSPARENT_OBJECT); + bool bDrawOpaqueOrCutout = any(queue.sceneFlags & (SceneFlags::OPAQUE_OBJECT | SceneFlags::CUTOUT_OBJECT)); + if (!bDrawTransparent && !bDrawOpaqueOrCutout) { + bDrawOpaqueOrCutout = true; + } + + const auto& subModels = model.getSubModels(); + const auto subModelCount = subModels.size(); + for (uint32_t subModelIdx = 0; subModelIdx < subModelCount; ++subModelIdx) { + const auto& subModel = subModels[subModelIdx]; + const auto& passes = subModel->getPasses(); + const auto passCount = passes.size(); + for (uint32_t passIdx = 0; passIdx < passCount; ++passIdx) { + auto& pass = *passes[passIdx]; + const bool bTransparent = isTransparent(pass); + const bool bOpaqueOrCutout = !bTransparent; + + if (!bDrawTransparent && bTransparent) { + // skip transparent object + continue; + } + + if (!bDrawOpaqueOrCutout && bOpaqueOrCutout) { + // skip opaque object + continue; + } + + if (pass.getBatchingScheme() == scene::BatchingSchemes::INSTANCING) { + auto& instancedBuffer = *pass.getInstancedBuffer(); + instancedBuffer.merge(subModel, passIdx); + if (bTransparent) { + queue.transparentInstancingQueue.add(instancedBuffer); + } else { + queue.opaqueInstancingQueue.add(instancedBuffer); + } + } else { + const float depth = computeSortingDepth(camera, model); + if (bTransparent) { + queue.transparentQueue.add(model, depth, subModelIdx, passIdx); + } else { + queue.opaqueQueue.add(model, depth, subModelIdx, passIdx); + } + } + } + } } void octreeCulling( const scene::Octree* octree, const scene::RenderScene* scene, const scene::Skybox* skyBox, - const scene::Camera* camera, - SceneFlags mergedFlags) { + const scene::Camera& camera, + NativeRenderQueue& queue) { // add special instances - for (const auto& model : scene->getModels()) { + for (const auto& pModel : scene->getModels()) { + CC_EXPECTS(pModel); + const auto& model = *pModel; // filter model by view visibility - if (!model->isEnabled()) { + if (!model.isEnabled()) { continue; } - if (pipeline::LODModelsCachedUtils::isLODModelCulled(model)) { + if (pipeline::LODModelsCachedUtils::isLODModelCulled(&model)) { continue; } - if (any(mergedFlags & SceneFlags::SHADOW_CASTER) && model->isCastShadow()) { + if (any(queue.sceneFlags & SceneFlags::SHADOW_CASTER) && model.isCastShadow()) { addShadowCastObject(); } - const auto visibility = camera->getVisibility(); + const auto visibility = camera.getVisibility(); if (isInstanceVisible(model, visibility) && isPointInstanceAndNotSkybox(model, skyBox)) { - addRenderObject(camera, model); + addRenderObject(camera, model, queue); } } // add plain instances ccstd::vector models; models.reserve(scene->getModels().size() / 4); - octree->queryVisibility(camera, camera->getFrustum(), false, models); - for (const auto& model : models) { + octree->queryVisibility(&camera, camera.getFrustum(), false, models); + for (const auto& pModel : models) { + const auto& model = *pModel; CC_EXPECTS(!isPointInstance(model)); - if (pipeline::LODModelsCachedUtils::isLODModelCulled(model)) { + if (pipeline::LODModelsCachedUtils::isLODModelCulled(&model)) { continue; } - addRenderObject(camera, model); + addRenderObject(camera, model, queue); } } void frustumCulling( const scene::RenderScene* scene, - const scene::Camera* camera, - SceneFlags mergedFlags) { - for (const auto& model : scene->getModels()) { - if (!model->isEnabled()) { + const scene::Camera& camera, + NativeRenderQueue& queue) { + const auto& models = scene->getModels(); + for (const auto& pModel : models) { + CC_EXPECTS(pModel); + const auto& model = *pModel; + if (!model.isEnabled()) { continue; } // filter model by view visibility - if (pipeline::LODModelsCachedUtils::isLODModelCulled(model)) { + if (pipeline::LODModelsCachedUtils::isLODModelCulled(&model)) { continue; } - const auto visibility = camera->getVisibility(); - const auto* const node = model->getNode(); + const auto visibility = camera.getVisibility(); + const auto* const node = model.getNode(); // cast shadow render Object - if (any(mergedFlags & SceneFlags::SHADOW_CASTER) && model->isCastShadow()) { + if (any(queue.sceneFlags & SceneFlags::SHADOW_CASTER) && model.isCastShadow()) { addShadowCastObject(); } // add render objects if (isInstanceVisible(model, visibility)) { - const auto* modelWorldBounds = model->getWorldBounds(); + const auto* modelWorldBounds = model.getWorldBounds(); + // object has no volume if (!modelWorldBounds) { - addRenderObject(camera, model); + addRenderObject(camera, model, queue); continue; } // frustum culling - if (modelWorldBounds->aabbFrustum(camera->getFrustum())) { - addRenderObject(camera, model); + if (modelWorldBounds->aabbFrustum(camera.getFrustum())) { + addRenderObject(camera, model, queue); } } } @@ -811,20 +927,43 @@ void mergeSceneFlags( } } -void sceneCulling( +void extendResourceLifetime(const NativeRenderQueue& queue, ResourceGroup& group) { + // keep instanceBuffers + for (const auto& batch : queue.opaqueInstancingQueue.batches) { + group.instancingBuffers.emplace(batch); + } + for (const auto& batch : queue.transparentInstancingQueue.batches) { + group.instancingBuffers.emplace(batch); + } +} + +void buildRenderQueues( + NativeRenderContext& context, ccstd::pmr::unordered_map< const scene::RenderScene*, ccstd::pmr::unordered_map>& sceneQueues) { const scene::Skybox* skyBox = nullptr; - for (const auto& [scene, queues] : sceneQueues) { + + auto& group = context.resourceGroups[context.nextFenceValue]; + + for (auto&& [scene, queues] : sceneQueues) { const scene::Octree* octree = scene->getOctree(); - for (const auto& [camera, queue] : queues) { + for (auto&& [camera, queue] : queues) { + CC_EXPECTS(camera); + if (!camera->isCullingEnabled()) { + continue; + } pipeline::LODModelsCachedUtils::updateCachedLODModels(scene, camera); if (octree && octree->isEnabled()) { - octreeCulling(octree, scene, skyBox, camera, queue.sceneFlags); + octreeCulling(octree, scene, skyBox, *camera, queue); } else { - frustumCulling(scene, camera, queue.sceneFlags); + frustumCulling(scene, *camera, queue); } + pipeline::LODModelsCachedUtils::clearCachedLODModels(); + + queue.sort(); + + extendResourceLifetime(queue, group); } } } @@ -834,7 +973,8 @@ void sceneCulling( void NativePipeline::executeRenderGraph(const RenderGraph& rg) { auto& ppl = *this; auto* scratch = &ppl.unsyncPool; - CC_LOG_INFO(rg.print(scratch).c_str()); + + //CC_LOG_INFO(rg.print(scratch).c_str()); RenderGraphContextCleaner contextCleaner(ppl.nativeContext); ResourceCleaner cleaner(ppl.resourceGraph); @@ -868,20 +1008,36 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { const scene::RenderScene*, ccstd::pmr::unordered_map> sceneQueues(scratch); - mergeSceneFlags(rg, sceneQueues); - sceneCulling(sceneQueues); + { + mergeSceneFlags(rg, sceneQueues); + buildRenderQueues(ppl.nativeContext, sceneQueues); + } - { // Execute all valid passes - boost::filtered_graph, boost::keep_all, RenderGraphFilter> + // Execute all valid passes + { + boost::filtered_graph< + AddressableView, + boost::keep_all, RenderGraphFilter> fg(graphView, boost::keep_all{}, RenderGraphFilter{&validPasses}); CommandSubmitter submit(ppl.device, ppl.getCommandBuffers()); + + // upload buffers + for (const auto& [scene, queues] : sceneQueues) { + for (const auto& [camera, queue] : queues) { + queue.opaqueInstancingQueue.uploadBuffers(submit.primaryCommandBuffer); + queue.transparentInstancingQueue.uploadBuffers(submit.primaryCommandBuffer); + } + } + + // submit commands RenderGraphVisitorContext ctx( ppl.nativeContext, rg, ppl.resourceGraph, fgd, fgd.barrierMap, validPasses, ppl.device, submit.primaryCommandBuffer, sceneQueues, + &ppl, scratch); RenderGraphVisitor visitor{{}, ctx}; diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h index 556783045e..dc904a47be 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineFwd.h @@ -31,6 +31,7 @@ // clang-format off #pragma once #include "cocos/base/std/variant.h" +#include "cocos/renderer/pipeline/InstancedBuffer.h" #include "cocos/renderer/pipeline/custom/LayoutGraphFwd.h" #include "cocos/renderer/pipeline/custom/RenderGraphFwd.h" #include "cocos/renderer/pipeline/custom/RenderInterfaceFwd.h" @@ -48,16 +49,13 @@ class NativeMovePassBuilder; class NativeCopyPassBuilder; class NativeSceneTransversal; struct PersistentRenderPassAndFramebuffer; -struct ScenePassHandle; -struct ScenePass; -struct ScenePassQueue; -struct RenderInstance; -struct RenderInstancePack; -struct RenderBatch; -struct RenderBatchPack; +struct RenderInstancingQueue; +struct DrawInstance; +struct RenderDrawQueue; struct NativeRenderQueue; class DefaultSceneVisitor; class DefaultForwardLightingTransversal; +struct ResourceGroup; struct NativeRenderContext; class NativePipeline; diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp index 1c882d95ee..e0079793ea 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.cpp @@ -54,61 +54,46 @@ PersistentRenderPassAndFramebuffer::PersistentRenderPassAndFramebuffer(Persisten clearStencil(rhs.clearStencil), refCount(rhs.refCount) {} -ScenePassQueue::ScenePassQueue(const allocator_type& alloc) noexcept -: queue(alloc) {} +RenderInstancingQueue::RenderInstancingQueue(const allocator_type& alloc) noexcept +: batches(alloc), + sortedBatches(alloc) {} -RenderInstancePack::RenderInstancePack(const allocator_type& alloc) noexcept +RenderInstancingQueue::RenderInstancingQueue(RenderInstancingQueue&& rhs, const allocator_type& alloc) +: batches(std::move(rhs.batches), alloc), + sortedBatches(std::move(rhs.sortedBatches), alloc) {} + +RenderInstancingQueue::RenderInstancingQueue(RenderInstancingQueue const& rhs, const allocator_type& alloc) +: batches(rhs.batches, alloc), + sortedBatches(rhs.sortedBatches, alloc) {} + +RenderDrawQueue::RenderDrawQueue(const allocator_type& alloc) noexcept : instances(alloc) {} -RenderInstancePack::RenderInstancePack(RenderInstancePack&& rhs, const allocator_type& alloc) +RenderDrawQueue::RenderDrawQueue(RenderDrawQueue&& rhs, const allocator_type& alloc) : instances(std::move(rhs.instances), alloc) {} -RenderBatch::RenderBatch(const allocator_type& alloc) noexcept -: vertexBuffers(alloc), - vertexBufferData(alloc), - uniformBufferData(alloc) {} - -RenderBatch::RenderBatch(RenderBatch&& rhs, const allocator_type& alloc) -: vertexBuffers(std::move(rhs.vertexBuffers), alloc), - vertexBufferData(std::move(rhs.vertexBufferData), alloc), - indexBuffer(rhs.indexBuffer), - indexBufferData(rhs.indexBufferData), - vertexBufferCount(rhs.vertexBufferCount), - mergeCount(rhs.mergeCount), - inputAssembler(rhs.inputAssembler), - uniformBufferData(std::move(rhs.uniformBufferData), alloc), - uniformBuffer(rhs.uniformBuffer), - descriptorSet(rhs.descriptorSet), - scenePass(rhs.scenePass), - shader(rhs.shader) {} - -RenderBatchPack::RenderBatchPack(const allocator_type& alloc) noexcept -: batches(alloc), - bufferOffset(alloc) {} - -RenderBatchPack::RenderBatchPack(RenderBatchPack&& rhs, const allocator_type& alloc) -: batches(std::move(rhs.batches), alloc), - bufferOffset(std::move(rhs.bufferOffset), alloc) {} +RenderDrawQueue::RenderDrawQueue(RenderDrawQueue const& rhs, const allocator_type& alloc) +: instances(rhs.instances, alloc) {} NativeRenderQueue::NativeRenderQueue(const allocator_type& alloc) noexcept -: scenePassQueue(alloc), - batchingQueue(alloc), - instancingQueue(alloc), - instancePacks(alloc) {} +: opaqueQueue(alloc), + transparentQueue(alloc), + opaqueInstancingQueue(alloc), + transparentInstancingQueue(alloc) {} NativeRenderQueue::NativeRenderQueue(SceneFlags sceneFlagsIn, const allocator_type& alloc) noexcept -: sceneFlags(sceneFlagsIn), - scenePassQueue(alloc), - batchingQueue(alloc), - instancingQueue(alloc), - instancePacks(alloc) {} +: opaqueQueue(alloc), + transparentQueue(alloc), + opaqueInstancingQueue(alloc), + transparentInstancingQueue(alloc), + sceneFlags(sceneFlagsIn) {} NativeRenderQueue::NativeRenderQueue(NativeRenderQueue&& rhs, const allocator_type& alloc) -: sceneFlags(rhs.sceneFlags), - scenePassQueue(std::move(rhs.scenePassQueue), alloc), - batchingQueue(std::move(rhs.batchingQueue), alloc), - instancingQueue(std::move(rhs.instancingQueue), alloc), - instancePacks(std::move(rhs.instancePacks), alloc) {} +: opaqueQueue(std::move(rhs.opaqueQueue), alloc), + transparentQueue(std::move(rhs.transparentQueue), alloc), + opaqueInstancingQueue(std::move(rhs.opaqueInstancingQueue), alloc), + transparentInstancingQueue(std::move(rhs.transparentInstancingQueue), alloc), + sceneFlags(rhs.sceneFlags) {} DefaultSceneVisitor::DefaultSceneVisitor(const allocator_type& alloc) noexcept : name(alloc) {} @@ -116,10 +101,12 @@ DefaultSceneVisitor::DefaultSceneVisitor(const allocator_type& alloc) noexcept DefaultForwardLightingTransversal::DefaultForwardLightingTransversal(const allocator_type& alloc) noexcept : name(alloc) {} +ResourceGroup::ResourceGroup(const allocator_type& alloc) noexcept +: instancingBuffers(alloc) {} + NativeRenderContext::NativeRenderContext(const allocator_type& alloc) noexcept : renderPasses(alloc), - freeRenderQueues(alloc), - freeInstancePacks(alloc) {} + resourceGroups(alloc) {} } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h index eb827a3159..bbb878264a 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h +++ b/native/cocos/renderer/pipeline/custom/NativePipelineTypes.h @@ -30,16 +30,18 @@ */ // clang-format off #pragma once +#include "base/std/container/map.h" #include "cocos/base/Ptr.h" #include "cocos/base/std/container/string.h" #include "cocos/renderer/gfx-base/GFXFramebuffer.h" #include "cocos/renderer/gfx-base/GFXRenderPass.h" #include "cocos/renderer/pipeline/GlobalDescriptorSetManager.h" +#include "cocos/renderer/pipeline/InstancedBuffer.h" #include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" -#include "cocos/renderer/pipeline/custom/Map.h" #include "cocos/renderer/pipeline/custom/NativePipelineFwd.h" #include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" #include "cocos/renderer/pipeline/custom/RenderInterfaceTypes.h" +#include "cocos/renderer/pipeline/custom/Set.h" namespace cc { @@ -267,118 +269,71 @@ struct PersistentRenderPassAndFramebuffer { int32_t refCount{1}; }; -struct ScenePassHandle { - const scene::Pass* handle{nullptr}; -}; - -inline bool operator<(const ScenePassHandle& lhs, const ScenePassHandle& rhs) noexcept { - return std::forward_as_tuple(lhs.handle) < - std::forward_as_tuple(rhs.handle); -} - -struct ScenePass { - uint32_t priority{0}; - float depth{0}; - uint32_t haderID{0}; - uint32_t assIndex{0}; - const scene::SubModel* subModel{nullptr}; -}; - -struct ScenePassQueue { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {queue.get_allocator().resource()}; - } - - ScenePassQueue(const allocator_type& alloc) noexcept; // NOLINT - ScenePassQueue(ScenePassQueue&& rhs) = delete; - ScenePassQueue(ScenePassQueue const& rhs) = delete; - ScenePassQueue& operator=(ScenePassQueue&& rhs) = delete; - ScenePassQueue& operator=(ScenePassQueue const& rhs) = delete; - - ccstd::pmr::vector queue; -}; - -struct alignas(64) RenderInstance { - uint32_t count{0}; - uint32_t capacity{0}; - gfx::Buffer* vertexBuffer{nullptr}; - uint8_t* data{nullptr}; - gfx::InputAssembler* inputAssembler{nullptr}; - uint32_t stride{0}; - uint32_t bufferOffset{0}; - gfx::Shader* shader{nullptr}; - gfx::DescriptorSet* descriptorSet{nullptr}; - gfx::Texture* lightmap{nullptr}; -}; - -struct RenderInstancePack { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {instances.get_allocator().resource()}; - } - - RenderInstancePack(const allocator_type& alloc) noexcept; // NOLINT - RenderInstancePack(RenderInstancePack&& rhs, const allocator_type& alloc); - - RenderInstancePack(RenderInstancePack&& rhs) noexcept = default; - RenderInstancePack(RenderInstancePack const& rhs) = delete; - RenderInstancePack& operator=(RenderInstancePack&& rhs) = default; - RenderInstancePack& operator=(RenderInstancePack const& rhs) = delete; - - ccstd::pmr::vector instances; -}; - -struct RenderBatch { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {vertexBuffers.get_allocator().resource()}; - } - - RenderBatch(const allocator_type& alloc) noexcept; // NOLINT - RenderBatch(RenderBatch&& rhs, const allocator_type& alloc); - - RenderBatch(RenderBatch&& rhs) noexcept = default; - RenderBatch(RenderBatch const& rhs) = delete; - RenderBatch& operator=(RenderBatch&& rhs) = default; - RenderBatch& operator=(RenderBatch const& rhs) = delete; - - ccstd::pmr::vector vertexBuffers; - ccstd::pmr::vector vertexBufferData; - gfx::Buffer* indexBuffer{nullptr}; - float* indexBufferData{nullptr}; - uint32_t vertexBufferCount{0}; - uint32_t mergeCount{0}; - gfx::InputAssembler* inputAssembler{nullptr}; - ccstd::pmr::vector uniformBufferData; - gfx::Buffer* uniformBuffer{nullptr}; - gfx::DescriptorSet* descriptorSet{nullptr}; - const scene::Pass* scenePass{nullptr}; - gfx::Shader* shader{nullptr}; -}; - -struct RenderBatchPack { +struct RenderInstancingQueue { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT return {batches.get_allocator().resource()}; } - RenderBatchPack(const allocator_type& alloc) noexcept; // NOLINT - RenderBatchPack(RenderBatchPack&& rhs, const allocator_type& alloc); + RenderInstancingQueue(const allocator_type& alloc) noexcept; // NOLINT + RenderInstancingQueue(RenderInstancingQueue&& rhs, const allocator_type& alloc); + RenderInstancingQueue(RenderInstancingQueue const& rhs, const allocator_type& alloc); - RenderBatchPack(RenderBatchPack&& rhs) noexcept = default; - RenderBatchPack(RenderBatchPack const& rhs) = delete; - RenderBatchPack& operator=(RenderBatchPack&& rhs) = default; - RenderBatchPack& operator=(RenderBatchPack const& rhs) = delete; + RenderInstancingQueue(RenderInstancingQueue&& rhs) noexcept = default; + RenderInstancingQueue(RenderInstancingQueue const& rhs) = delete; + RenderInstancingQueue& operator=(RenderInstancingQueue&& rhs) = default; + RenderInstancingQueue& operator=(RenderInstancingQueue const& rhs) = default; - ccstd::pmr::vector> batches; - ccstd::pmr::vector bufferOffset; + void add(pipeline::InstancedBuffer &instancedBuffer); + void sort(); + void uploadBuffers(gfx::CommandBuffer *cmdBuffer) const; + void recordCommandBuffer( + gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer, + gfx::DescriptorSet *ds = nullptr, uint32_t offset = 0, + const ccstd::vector *dynamicOffsets = nullptr) const; + + PmrUnorderedSet batches; + ccstd::pmr::vector sortedBatches; +}; + +struct alignas(32) DrawInstance { + const scene::SubModel* subModel{nullptr}; + uint32_t priority{0}; + uint32_t hash{0}; + float depth{0}; + uint32_t shaderID{0}; + uint32_t passIndex{0}; +}; + +struct RenderDrawQueue { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {instances.get_allocator().resource()}; + } + + RenderDrawQueue(const allocator_type& alloc) noexcept; // NOLINT + RenderDrawQueue(RenderDrawQueue&& rhs, const allocator_type& alloc); + RenderDrawQueue(RenderDrawQueue const& rhs, const allocator_type& alloc); + + RenderDrawQueue(RenderDrawQueue&& rhs) noexcept = default; + RenderDrawQueue(RenderDrawQueue const& rhs) = delete; + RenderDrawQueue& operator=(RenderDrawQueue&& rhs) = default; + RenderDrawQueue& operator=(RenderDrawQueue const& rhs) = default; + + void add(const scene::Model& model, float depth, uint32_t subModelIdx, uint32_t passIdx); + void sortOpaqueOrCutout(); + void sortTransparent(); + void recordCommandBuffer(gfx::Device *device, const scene::Camera *camera, + gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer, + uint32_t subpassIndex) const; + + ccstd::pmr::vector instances; }; struct NativeRenderQueue { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT - return {scenePassQueue.get_allocator().resource()}; + return {opaqueQueue.get_allocator().resource()}; } NativeRenderQueue(const allocator_type& alloc) noexcept; // NOLINT @@ -390,11 +345,13 @@ struct NativeRenderQueue { NativeRenderQueue& operator=(NativeRenderQueue&& rhs) = default; NativeRenderQueue& operator=(NativeRenderQueue const& rhs) = delete; + void sort(); + + RenderDrawQueue opaqueQueue; + RenderDrawQueue transparentQueue; + RenderInstancingQueue opaqueInstancingQueue; + RenderInstancingQueue transparentInstancingQueue; SceneFlags sceneFlags{SceneFlags::NONE}; - ccstd::pmr::vector scenePassQueue; - ccstd::pmr::vector batchingQueue; - ccstd::pmr::vector instancingQueue; - PmrFlatMap> instancePacks; }; class DefaultSceneVisitor final : public SceneVisitor { @@ -432,6 +389,22 @@ public: ccstd::pmr::string name; }; +struct ResourceGroup { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {instancingBuffers.get_allocator().resource()}; + } + + ResourceGroup(const allocator_type& alloc) noexcept; // NOLINT + ResourceGroup(ResourceGroup&& rhs) = delete; + ResourceGroup(ResourceGroup const& rhs) = delete; + ResourceGroup& operator=(ResourceGroup&& rhs) = delete; + ResourceGroup& operator=(ResourceGroup const& rhs) = delete; + ~ResourceGroup() noexcept; + + PmrUnorderedSet> instancingBuffers; +}; + struct NativeRenderContext { using allocator_type = boost::container::pmr::polymorphic_allocator; allocator_type get_allocator() const noexcept { // NOLINT @@ -444,9 +417,11 @@ struct NativeRenderContext { NativeRenderContext& operator=(NativeRenderContext&& rhs) = delete; NativeRenderContext& operator=(NativeRenderContext const& rhs) = delete; + void clearPreviousResources(uint64_t finishedFenceValue) noexcept; + ccstd::pmr::unordered_map renderPasses; - ccstd::pmr::vector> freeRenderQueues; - ccstd::pmr::vector> freeInstancePacks; + ccstd::pmr::map resourceGroups; + uint64_t nextFenceValue{0}; }; class NativePipeline final : public Pipeline { diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp new file mode 100644 index 0000000000..d4f2e62db2 --- /dev/null +++ b/native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp @@ -0,0 +1,123 @@ +#include +#include +#include "GslUtils.h" +#include "NativePipelineTypes.h" +#include "cocos/renderer/pipeline/Define.h" +#include "cocos/renderer/pipeline/PipelineStateManager.h" + +namespace cc { + +namespace render { + +// NOLINTNEXTLINE(bugprone-easily-swappable-parameters) +void RenderDrawQueue::add(const scene::Model &model, float depth, uint32_t subModelIdx, uint32_t passIdx) { + const auto *subModel = model.getSubModels()[subModelIdx].get(); + const auto *const pass = subModel->getPass(passIdx); + + auto passPriority = static_cast(pass->getPriority()); + auto modelPriority = static_cast(subModel->getPriority()); + auto shaderId = static_cast(reinterpret_cast(subModel->getShader(passIdx))); + const auto hash = (0 << 30) | (passPriority << 16) | (modelPriority << 8) | passIdx; + const auto priority = model.getPriority(); + + instances.emplace_back(DrawInstance{subModel, priority, hash, depth, shaderId, passIdx}); +} + +void RenderDrawQueue::sortOpaqueOrCutout() { + std::sort(instances.begin(), instances.end(), [](const DrawInstance &lhs, const DrawInstance &rhs) { + return std::forward_as_tuple(lhs.hash, lhs.depth, lhs.shaderID) < + std::forward_as_tuple(rhs.hash, rhs.depth, rhs.shaderID); + }); +} + +void RenderDrawQueue::sortTransparent() { + std::sort(instances.begin(), instances.end(), [](const DrawInstance &lhs, const DrawInstance &rhs) { + return std::forward_as_tuple(lhs.priority, lhs.hash, -lhs.depth, lhs.shaderID) < + std::forward_as_tuple(rhs.priority, rhs.hash, -rhs.depth, rhs.shaderID); + }); +} + +void RenderDrawQueue::recordCommandBuffer( + gfx::Device * /*device*/, const scene::Camera * /*camera*/, + gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, + uint32_t subpassIndex) const { + for (const auto &instance : instances) { + const auto *subModel = instance.subModel; + + const auto passIdx = instance.passIndex; + auto *inputAssembler = subModel->getInputAssembler(); + const auto *pass = subModel->getPass(passIdx); + auto *shader = subModel->getShader(passIdx); + auto *pso = pipeline::PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass, subpassIndex); + + cmdBuff->bindPipelineState(pso); + cmdBuff->bindDescriptorSet(pipeline::materialSet, pass->getDescriptorSet()); + cmdBuff->bindDescriptorSet(pipeline::localSet, subModel->getDescriptorSet()); + cmdBuff->bindInputAssembler(inputAssembler); + cmdBuff->draw(inputAssembler); + } +} + +void RenderInstancingQueue::add(pipeline::InstancedBuffer &instancedBuffer) { + batches.emplace(&instancedBuffer); +} + +void RenderInstancingQueue::sort() { + sortedBatches.reserve(batches.size()); + std::copy(batches.begin(), batches.end(), std::back_inserter(sortedBatches)); +} + +void RenderInstancingQueue::uploadBuffers(gfx::CommandBuffer *cmdBuffer) const { + for (const auto *instanceBuffer : batches) { + if (instanceBuffer->hasPendingModels()) { + instanceBuffer->uploadBuffers(cmdBuffer); + } + } +} + +void RenderInstancingQueue::recordCommandBuffer( + gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer, + gfx::DescriptorSet *ds, uint32_t offset, const ccstd::vector *dynamicOffsets) const { + const auto &renderQueue = sortedBatches; + for (const auto *instanceBuffer : renderQueue) { + if (!instanceBuffer->hasPendingModels()) { + continue; + } + const auto &instances = instanceBuffer->getInstances(); + const auto *drawPass = instanceBuffer->getPass(); + cmdBuffer->bindDescriptorSet(pipeline::materialSet, drawPass->getDescriptorSet()); + gfx::PipelineState *lastPSO = nullptr; + for (const auto &instance : instances) { + if (!instance.count) { + continue; + } + auto *pso = pipeline::PipelineStateManager::getOrCreatePipelineState( + drawPass, instance.shader, instance.ia, renderPass); + if (lastPSO != pso) { + cmdBuffer->bindPipelineState(pso); + lastPSO = pso; + } + if (ds) { + cmdBuffer->bindDescriptorSet(pipeline::globalSet, ds, 1, &offset); + } + if (dynamicOffsets) { + cmdBuffer->bindDescriptorSet(pipeline::localSet, instance.descriptorSet, *dynamicOffsets); + } else { + cmdBuffer->bindDescriptorSet(pipeline::localSet, instance.descriptorSet, instanceBuffer->dynamicOffsets()); + } + cmdBuffer->bindInputAssembler(instance.ia); + cmdBuffer->draw(instance.ia); + } + } +} + +void NativeRenderQueue::sort() { + opaqueQueue.sortOpaqueOrCutout(); + transparentQueue.sortTransparent(); + opaqueInstancingQueue.sort(); + transparentInstancingQueue.sort(); +} + +} // namespace render + +} // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp index a381447b3b..db988d875c 100644 --- a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp @@ -23,6 +23,7 @@ THE SOFTWARE. ****************************************************************************/ +#include "NativePipelineTypes.h" #include "Range.h" #include "RenderGraphGraphs.h" #include "RenderGraphTypes.h" @@ -34,6 +35,22 @@ namespace cc { namespace render { +ResourceGroup::~ResourceGroup() noexcept { + for (const auto& buffer : instancingBuffers) { + buffer->clear(); + } +} + +void NativeRenderContext::clearPreviousResources(uint64_t finishedFenceValue) noexcept { + for (auto iter = resourceGroups.begin(); iter != resourceGroups.end();) { + if (iter->first <= finishedFenceValue) { + iter = resourceGroups.erase(iter); + } else { + break; + } + } +} + namespace { gfx::BufferInfo getBufferInfo(const ResourceDesc& desc) { diff --git a/native/cocos/renderer/pipeline/custom/Set.h b/native/cocos/renderer/pipeline/custom/Set.h index 02e9e08bd9..a15338167c 100644 --- a/native/cocos/renderer/pipeline/custom/Set.h +++ b/native/cocos/renderer/pipeline/custom/Set.h @@ -68,12 +68,12 @@ using PmrFlatMultiSet = boost::container::pmr::flat_multiset> // unordered_set template using PmrUnorderedSet = std::unordered_set< - Value, std::hash, std::equal_to, + Value, ccstd::hash, std::equal_to, boost::container::pmr::polymorphic_allocator>; template using PmrUnorderedMultiSet = std::unordered_multiset< - Value, std::hash, std::equal_to, + Value, ccstd::hash, std::equal_to, boost::container::pmr::polymorphic_allocator>; // transparent string unordered_set