From b48581d91a42a3bf5419ff2dc503c9cb23cca89c Mon Sep 17 00:00:00 2001 From: hyde zhou Date: Wed, 9 Aug 2023 15:23:40 +0800 Subject: [PATCH] V3.8.1 pipeline (#15875) --- cocos/core/geometry/intersect.ts | 54 +- cocos/gfx/base/define.ts | 3 +- cocos/render-scene/scene/camera.ts | 39 +- cocos/rendering/custom/compiler.ts | 118 +- cocos/rendering/custom/define.ts | 65 +- cocos/rendering/custom/executor.ts | 418 +-- cocos/rendering/custom/scene-culling.ts | 416 +++ cocos/rendering/custom/web-pipeline-types.ts | 234 ++ cocos/rendering/custom/web-pipeline.ts | 36 +- .../post-process/passes/forward-pass.ts | 20 +- .../post-process/passes/skin-pass.ts | 52 +- .../cocos/renderer/gfx-base/GFXDef-common.h | 16 +- native/cocos/renderer/gfx-base/GFXTexture.cpp | 2 + native/cocos/renderer/gfx-base/GFXTexture.h | 2 +- .../renderer/gfx-gles3/GLES3Commands.cpp | 19 +- .../renderer/gfx-gles3/GLES3GPUObjects.h | 2 + .../renderer/gfx-gles3/GLES3PipelineState.cpp | 12 +- .../cocos/renderer/gfx-gles3/GLES3Texture.cpp | 2 + .../renderer/gfx-metal/MTLCommandBuffer.mm | 11 +- native/cocos/renderer/gfx-metal/MTLDevice.mm | 2 +- .../renderer/gfx-metal/MTLPipelineState.mm | 5 +- .../cocos/renderer/gfx-metal/MTLRenderPass.mm | 8 +- native/cocos/renderer/gfx-metal/MTLShader.mm | 8 +- native/cocos/renderer/gfx-metal/MTLTexture.mm | 11 +- native/cocos/renderer/gfx-metal/MTLUtils.h | 3 +- native/cocos/renderer/gfx-metal/MTLUtils.mm | 20 +- .../cocos/renderer/gfx-vulkan/VKCommands.cpp | 31 +- .../cocos/renderer/gfx-vulkan/VKGPUObjects.h | 2 + .../cocos/renderer/gfx-vulkan/VKTexture.cpp | 4 + .../pipeline/custom/FGDispatcherGraphs.h | 1786 ++++----- .../pipeline/custom/FGDispatcherTypes.cpp | 280 +- .../pipeline/custom/FGDispatcherTypes.h | 953 ++--- .../pipeline/custom/FrameGraphDispatcher.cpp | 3248 ++++++++--------- .../pipeline/custom/NativeExecutor.cpp | 359 +- .../pipeline/custom/NativePipeline.cpp | 50 +- .../pipeline/custom/NativeRenderGraph.cpp | 36 +- .../pipeline/custom/NativeRenderGraphUtils.h | 13 + .../pipeline/custom/NativeResourceGraph.cpp | 35 +- .../pipeline/custom/NativeSceneCulling.cpp | 55 +- .../renderer/pipeline/custom/test/test.h | 300 +- .../src/complicated_barrier_case.cpp | 195 +- .../unit-test/src/simple_barrier_test.cpp | 40 +- .../src/simple_closed_barrier_test.cpp | 137 +- 43 files changed, 4507 insertions(+), 4595 deletions(-) create mode 100644 cocos/rendering/custom/scene-culling.ts create mode 100644 cocos/rendering/custom/web-pipeline-types.ts diff --git a/cocos/core/geometry/intersect.ts b/cocos/core/geometry/intersect.ts index 157b6578df..fff0a2702d 100644 --- a/cocos/core/geometry/intersect.ts +++ b/cocos/core/geometry/intersect.ts @@ -413,10 +413,12 @@ const lineTriangle = (function (): (line: Line, triangle: Triangle, outPt?: Vec3 const u = 1.0 - v - w; // outPt = u*a + v*d + w*c; - Vec3.set(outPt, + Vec3.set( + outPt, triangle.a.x * u + triangle.b.x * v + triangle.c.x * w, triangle.a.y * u + triangle.b.y * v + triangle.c.y * w, - triangle.a.z * u + triangle.b.z * v + triangle.c.z * w); + triangle.a.z * u + triangle.b.z * v + triangle.c.z * w, + ); } return 1; @@ -527,38 +529,54 @@ function getAABBVertices (min: Vec3, max: Vec3, out: Vec3[]): void { } function getOBBVertices (c: Vec3, e: Vec3, a1: Vec3, a2: Vec3, a3: Vec3, out: Vec3[]): void { - Vec3.set(out[0], + Vec3.set( + out[0], c.x + a1.x * e.x + a2.x * e.y + a3.x * e.z, c.y + a1.y * e.x + a2.y * e.y + a3.y * e.z, - c.z + a1.z * e.x + a2.z * e.y + a3.z * e.z); - Vec3.set(out[1], + c.z + a1.z * e.x + a2.z * e.y + a3.z * e.z, + ); + Vec3.set( + out[1], c.x - a1.x * e.x + a2.x * e.y + a3.x * e.z, c.y - a1.y * e.x + a2.y * e.y + a3.y * e.z, - c.z - a1.z * e.x + a2.z * e.y + a3.z * e.z); - Vec3.set(out[2], + c.z - a1.z * e.x + a2.z * e.y + a3.z * e.z, + ); + Vec3.set( + out[2], c.x + a1.x * e.x - a2.x * e.y + a3.x * e.z, c.y + a1.y * e.x - a2.y * e.y + a3.y * e.z, - c.z + a1.z * e.x - a2.z * e.y + a3.z * e.z); - Vec3.set(out[3], + c.z + a1.z * e.x - a2.z * e.y + a3.z * e.z, + ); + Vec3.set( + out[3], c.x + a1.x * e.x + a2.x * e.y - a3.x * e.z, c.y + a1.y * e.x + a2.y * e.y - a3.y * e.z, - c.z + a1.z * e.x + a2.z * e.y - a3.z * e.z); - Vec3.set(out[4], + c.z + a1.z * e.x + a2.z * e.y - a3.z * e.z, + ); + Vec3.set( + out[4], c.x - a1.x * e.x - a2.x * e.y - a3.x * e.z, c.y - a1.y * e.x - a2.y * e.y - a3.y * e.z, - c.z - a1.z * e.x - a2.z * e.y - a3.z * e.z); - Vec3.set(out[5], + c.z - a1.z * e.x - a2.z * e.y - a3.z * e.z, + ); + Vec3.set( + out[5], c.x + a1.x * e.x - a2.x * e.y - a3.x * e.z, c.y + a1.y * e.x - a2.y * e.y - a3.y * e.z, - c.z + a1.z * e.x - a2.z * e.y - a3.z * e.z); - Vec3.set(out[6], + c.z + a1.z * e.x - a2.z * e.y - a3.z * e.z, + ); + Vec3.set( + out[6], c.x - a1.x * e.x + a2.x * e.y - a3.x * e.z, c.y - a1.y * e.x + a2.y * e.y - a3.y * e.z, - c.z - a1.z * e.x + a2.z * e.y - a3.z * e.z); - Vec3.set(out[7], + c.z - a1.z * e.x + a2.z * e.y - a3.z * e.z, + ); + Vec3.set( + out[7], c.x - a1.x * e.x - a2.x * e.y + a3.x * e.z, c.y - a1.y * e.x - a2.y * e.y + a3.y * e.z, - c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z); + c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z, + ); } function getInterval (vertices: any[] | Vec3[], axis: Vec3): number[] { diff --git a/cocos/gfx/base/define.ts b/cocos/gfx/base/define.ts index 53eeb4062c..6e614fb363 100644 --- a/cocos/gfx/base/define.ts +++ b/cocos/gfx/base/define.ts @@ -407,7 +407,8 @@ export enum TextureFlagBit { GENERAL_LAYOUT = 0x2, // For inout framebuffer attachments EXTERNAL_OES = 0x4, // External oes texture EXTERNAL_NORMAL = 0x8, // External normal texture - LAZILY_ALLOCATED = 0x10 // Try lazily allocated mode. + LAZILY_ALLOCATED = 0x10, // Try lazily allocated mode. + MUTABLE_VIEW_FORMAT = 0x40, // texture view as different format } export enum FormatFeatureBit { diff --git a/cocos/render-scene/scene/camera.ts b/cocos/render-scene/scene/camera.ts index 31171d10ac..ab8cedbd6c 100644 --- a/cocos/render-scene/scene/camera.ts +++ b/cocos/render-scene/scene/camera.ts @@ -1032,14 +1032,33 @@ export class Camera { const wndXREye = xr.webXRWindowMap.get(this._window); this._matProj.set(xr.webXRMatProjs[wndXREye]); } else { - Mat4.perspective(this._matProj, this._fov, this._aspect, this._nearClip, this._farClip, - this._fovAxis === CameraFOVAxis.VERTICAL, this._device.capabilities.clipSpaceMinZ, projectionSignY, orientation); + Mat4.perspective( + this._matProj, + this._fov, + this._aspect, + this._nearClip, + this._farClip, + this._fovAxis === CameraFOVAxis.VERTICAL, + this._device.capabilities.clipSpaceMinZ, + projectionSignY, + orientation, + ); } } else { const x = this._orthoHeight * this._aspect; const y = this._orthoHeight; - Mat4.ortho(this._matProj, -x, x, -y, y, this._nearClip, this._farClip, - this._device.capabilities.clipSpaceMinZ, projectionSignY, orientation); + Mat4.ortho( + this._matProj, + -x, + x, + -y, + y, + this._nearClip, + this._farClip, + this._device.capabilities.clipSpaceMinZ, + projectionSignY, + orientation, + ); } Mat4.invert(this._matProjInv, this._matProj); viewProjDirty = true; @@ -1240,10 +1259,12 @@ export class Camera { if (this._proj === CameraProjection.PERSPECTIVE) { // calculate screen pos in far clip plane - Vec3.set(out, + Vec3.set( + out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, - 1.0); + 1.0, + ); // transform to world const { x, y } = out; @@ -1256,10 +1277,12 @@ export class Camera { Vec3.lerp(out, v_a, out, lerp(this._nearClip / this._farClip, 1, screenPos.z)); } else { - Vec3.set(out, + Vec3.set( + out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, - screenPos.z * 2 - 1); + screenPos.z * 2 - 1, + ); // transform to world const { x, y } = out; diff --git a/cocos/rendering/custom/compiler.ts b/cocos/rendering/custom/compiler.ts index 651729239d..da170462e2 100644 --- a/cocos/rendering/custom/compiler.ts +++ b/cocos/rendering/custom/compiler.ts @@ -32,68 +32,50 @@ import { Blit, ClearView, ComputePass, ComputeSubpass, CopyPass, Dispatch, Forma RasterPass, RasterSubpass, RaytracePass, RenderGraph, RenderGraphVisitor, RasterView, ComputeView, RenderQueue, RenderSwapchain, ResolvePass, ResourceGraph, ResourceGraphVisitor, SceneData, SubresourceView } from './render-graph'; import { AccessType, ResourceResidency, SceneFlags } from './types'; +import { hashCombineNum, hashCombineStr } from './define'; -let hashCode = 0; - -function hashCombine (hash): void { - hashCode ^= (hash >>> 0) + 0x9e3779b9 + (hashCode << 6) + (hashCode >> 2); -} - -function hashCombineNum (val: number): void { - const hash = 5381; - hashCombine((hash * 33) ^ val); -} - -function hashCombineStr (str: string): void { - // DJB2 HASH - let hash = 5381; - for (let i = 0; i < str.length; i++) { - hash = (hash * 33) ^ str.charCodeAt(i); - } - hashCombine(hash); -} function genHashValue (pass: RasterPass): void { - hashCode = 0; + let hashCode = 0; for (const [name, raster] of pass.rasterViews) { - hashCombineStr('raster'); - hashCombineStr(name); - hashCombineStr(raster.slotName); - hashCombineNum(raster.accessType); - hashCombineNum(raster.attachmentType); - hashCombineNum(raster.loadOp); - hashCombineNum(raster.storeOp); - hashCombineNum(raster.clearFlags); - hashCombineNum(raster.clearColor.x); - hashCombineNum(raster.clearColor.y); - hashCombineNum(raster.clearColor.z); - hashCombineNum(raster.clearColor.w); - hashCombineNum(raster.slotID); - hashCombineNum(raster.shaderStageFlags); + hashCode = hashCombineStr('raster', hashCode); + hashCode = hashCombineStr(name, hashCode); + hashCode = hashCombineStr(raster.slotName, hashCode); + hashCode = hashCombineNum(raster.accessType, hashCode); + hashCode = hashCombineNum(raster.attachmentType, hashCode); + hashCode = hashCombineNum(raster.loadOp, hashCode); + hashCode = hashCombineNum(raster.storeOp, hashCode); + hashCode = hashCombineNum(raster.clearFlags, hashCode); + hashCode = hashCombineNum(raster.clearColor.x, hashCode); + hashCode = hashCombineNum(raster.clearColor.y, hashCode); + hashCode = hashCombineNum(raster.clearColor.z, hashCode); + hashCode = hashCombineNum(raster.clearColor.w, hashCode); + hashCode = hashCombineNum(raster.slotID, hashCode); + hashCode = hashCombineNum(raster.shaderStageFlags, hashCode); } for (const [name, computes] of pass.computeViews) { - hashCombineStr(name); + hashCode = hashCombineStr(name, hashCode); for (const compute of computes) { - hashCombineStr('compute'); - hashCombineStr(compute.name); - hashCombineNum(compute.accessType); - hashCombineNum(compute.clearFlags); - hashCombineNum(compute.clearValueType); - hashCombineNum(compute.clearValue.x); - hashCombineNum(compute.clearValue.y); - hashCombineNum(compute.clearValue.z); - hashCombineNum(compute.clearValue.w); - hashCombineNum(compute.shaderStageFlags); + hashCode = hashCombineStr('compute', hashCode); + hashCode = hashCombineStr(compute.name, hashCode); + hashCode = hashCombineNum(compute.accessType, hashCode); + hashCode = hashCombineNum(compute.clearFlags, hashCode); + hashCode = hashCombineNum(compute.clearValueType, hashCode); + hashCode = hashCombineNum(compute.clearValue.x, hashCode); + hashCode = hashCombineNum(compute.clearValue.y, hashCode); + hashCode = hashCombineNum(compute.clearValue.z, hashCode); + hashCode = hashCombineNum(compute.clearValue.w, hashCode); + hashCode = hashCombineNum(compute.shaderStageFlags, hashCode); } } - hashCombineNum(pass.width); - hashCombineNum(pass.height); - hashCombineNum(pass.viewport.left); - hashCombineNum(pass.viewport.top); - hashCombineNum(pass.viewport.width); - hashCombineNum(pass.viewport.height); - hashCombineNum(pass.viewport.minDepth); - hashCombineNum(pass.viewport.maxDepth); - hashCombineNum(pass.showStatistics ? 1 : 0); + hashCode = hashCombineNum(pass.width, hashCode); + hashCode = hashCombineNum(pass.height, hashCode); + hashCode = hashCombineNum(pass.viewport.left, hashCode); + hashCode = hashCombineNum(pass.viewport.top, hashCode); + hashCode = hashCombineNum(pass.viewport.width, hashCode); + hashCode = hashCombineNum(pass.viewport.height, hashCode); + hashCode = hashCombineNum(pass.viewport.minDepth, hashCode); + hashCode = hashCombineNum(pass.viewport.maxDepth, hashCode); + hashCode = hashCombineNum(pass.showStatistics ? 1 : 0, hashCode); pass.hashValue = hashCode; } @@ -157,8 +139,10 @@ class PassVisitor implements RenderGraphVisitor { isPreRaster = true; // TODO: Shadow map is rather special, as it will be merged into one pass later, and then this determination can be removed. if (!this._isShadowMap(this.sceneID)) { - assert(currRaster.loadOp === LoadOp.LOAD, - `The resource with name ${input} is being used, and the pass that uses this resource must have loadOp set to 'load'`); + assert( + currRaster.loadOp === LoadOp.LOAD, + `The resource with name ${input} is being used, and the pass that uses this resource must have loadOp set to 'load'`, + ); } } } @@ -287,7 +271,7 @@ class PassVisitor implements RenderGraphVisitor { this._currPass = value; const outputId = this.resID; const outputName = resourceGraph.vertexName(outputId); - let vertID; + let vertID: number; for (const pair of value.copyPairs) { if (pair.target === outputName) { rg.setValid(this.passID, true); @@ -345,7 +329,7 @@ class PassManagerVisitor extends DefaultVisitor { class ResourceVisitor implements ResourceGraphVisitor { private readonly _context: CompilerContext; public resID = 0xFFFFFFFF; - private _passManagerVis; + private _passManagerVis!: PassManagerVisitor; constructor (context: CompilerContext) { this._context = context; } @@ -392,10 +376,12 @@ class ResourceUseContext { computes: Map = new Map(); } class CompilerContext { - set (pipeline: BasicPipeline, + set ( + pipeline: BasicPipeline, resGraph: ResourceGraph, renderGraph: RenderGraph, - layoutGraph: LayoutGraphData): void { + layoutGraph: LayoutGraphData, + ): void { this.pipeline = pipeline; this.resourceGraph = resGraph; this.renderGraph = renderGraph; @@ -417,10 +403,12 @@ export class Compiler { private _pipeline: BasicPipeline; private _layoutGraph: LayoutGraphData; private _visitor: ResourceManagerVisitor; - constructor (pipeline: BasicPipeline, + constructor ( + pipeline: BasicPipeline, renderGraph: RenderGraph, resGraph: ResourceGraph, - layoutGraph: LayoutGraphData) { + layoutGraph: LayoutGraphData, + ) { this._pipeline = pipeline; this._resourceGraph = resGraph; this._layoutGraph = layoutGraph; @@ -447,8 +435,10 @@ export class Compiler { const firstRaster = use.rasters.get(min)!; switch (trait.residency) { case ResourceResidency.PERSISTENT: - assert(firstRaster.loadOp !== LoadOp.DISCARD, - `The loadOp for persistent resources in the top-level pass cannot be set to 'discard'.`); + assert( + firstRaster.loadOp !== LoadOp.DISCARD, + `The loadOp for persistent resources in the top-level pass cannot be set to 'discard'.`, + ); break; case ResourceResidency.MANAGED: assert(firstRaster.loadOp === LoadOp.CLEAR, `The loadOp for Managed resources in the top-level pass can only be set to 'clear'.`); diff --git a/cocos/rendering/custom/define.ts b/cocos/rendering/custom/define.ts index a2a983c9b3..b131e82035 100644 --- a/cocos/rendering/custom/define.ts +++ b/cocos/rendering/custom/define.ts @@ -44,9 +44,9 @@ import { Vec2, Vec3, Vec4, macro, geometry, toRadian, cclegacy, assert, nextPow2 import { ImageAsset, Material, Texture2D } from '../../asset/assets'; import { getProfilerCamera, SRGBToLinear } from '../pipeline-funcs'; import { RenderWindow } from '../../render-scene/core/render-window'; -import { RenderData } from './render-graph'; +import { RenderData, RenderGraph } from './render-graph'; import { WebPipeline } from './web-pipeline'; -import { DescriptorSetData } from './layout-graph'; +import { DescriptorSetData, LayoutGraph, LayoutGraphData } from './layout-graph'; import { AABB } from '../../core/geometry'; import { DebugViewCompositeType, DebugViewSingleType } from '../debug-view'; import { ReflectionProbeManager } from '../../3d/reflection-probe/reflection-probe-manager'; @@ -685,7 +685,7 @@ export function buildShadowPass ( queue.addSceneOfCamera( camera, new LightInfo(light, level), - SceneFlags.SHADOW_CASTER, + SceneFlags.SHADOW_CASTER | SceneFlags.OPAQUE_OBJECT | SceneFlags.TRANSPARENT_OBJECT, ); queue.setViewport(new Viewport(area.x, area.y, area.width, area.height)); } @@ -706,6 +706,7 @@ export function buildReflectionProbePasss ( } else if (EDITOR) { for (let faceIdx = 0; faceIdx < probe.bakedCubeTextures.length; faceIdx++) { probe.updateCameraDir(faceIdx); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument buildReflectionProbePass(camera, ppl, probe, probe.bakedCubeTextures[faceIdx].window!, faceIdx); } probe.needRender = false; @@ -1127,7 +1128,9 @@ function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = fa const constants = data.constants; const samplers = data.samplers; const textures = data.textures; - const device = cclegacy.director.root.device; + const root = cclegacy.director.root; + const device = root.device; + const pipeline = root.pipeline as WebPipeline; const descriptorSetData = getDescriptorSetDataFromLayout(layout)!; const descriptorSet = descriptorSetData.descriptorSet!; for (const [key, value] of constants) { @@ -1160,7 +1163,7 @@ function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = fa const bindId = getDescBinding(key, descriptorSetData); if (bindId === -1) { continue; } const tex = descriptorSet.getTexture(bindId); - if (!tex || isUpdate) { + if (!tex || (isUpdate && value !== pipeline.defaultTexture)) { bindGlobalDesc(descriptorSet, bindId, value); } } @@ -1168,7 +1171,7 @@ function applyGlobalDescBinding (data: RenderData, layout: string, isUpdate = fa const bindId = getDescBinding(key, descriptorSetData); if (bindId === -1) { continue; } const sampler = descriptorSet.getSampler(bindId); - if (!sampler || isUpdate) { + if (!sampler || (isUpdate && value !== pipeline.defaultSampler)) { bindGlobalDesc(descriptorSet, bindId, value); } } @@ -2440,3 +2443,53 @@ export function buildClusterPasses (camera: Camera, pipeline: BasicPipeline): vo buildLightClusterBuildPass(camera, _clusterLightData, ppl); buildLightClusterCullingPass(camera, _clusterLightData, ppl); } + +function hashCombine (hash, currHash: number): number { + return currHash ^= (hash >>> 0) + 0x9e3779b9 + (currHash << 6) + (currHash >> 2); +} + +export function hashCombineNum (val: number, currHash: number): number { + const hash = 5381; + return hashCombine((hash * 33) ^ val, currHash); +} + +export function hashCombineStr (str: string, currHash: number): number { + // DJB2 HASH + let hash = 5381; + for (let i = 0; i < str.length; i++) { + hash = (hash * 33) ^ str.charCodeAt(i); + } + return hashCombine(hash, currHash); +} + +export function bool (val): boolean { + return !!val; +} + +export function getSubpassOrPassID (sceneId: number, rg: RenderGraph, lg: LayoutGraphData): number { + const queueId = rg.getParent(sceneId); + assert(queueId !== 0xFFFFFFFF); + const subpassOrPassID = rg.getParent(queueId); + assert(subpassOrPassID !== 0xFFFFFFFF); + const passId = rg.getParent(subpassOrPassID); + let layoutId = lg.nullVertex(); + // single render pass + if (passId === rg.nullVertex()) { + const layoutName: string = rg.getLayout(subpassOrPassID); + assert(!!layoutName); + layoutId = lg.locateChild(lg.nullVertex(), layoutName); + } else { + const passLayoutName: string = rg.getLayout(passId); + assert(!!passLayoutName); + const passLayoutId = lg.locateChild(lg.nullVertex(), passLayoutName); + assert(passLayoutId !== lg.nullVertex()); + + const subpassLayoutName: string = rg.getLayout(subpassOrPassID); + assert(!!subpassLayoutName); + const subpassLayoutId = lg.locateChild(passLayoutId, subpassLayoutName); + assert(subpassLayoutId !== lg.nullVertex()); + layoutId = subpassLayoutId; + } + assert(layoutId !== lg.nullVertex()); + return layoutId; +} diff --git a/cocos/rendering/custom/executor.ts b/cocos/rendering/custom/executor.ts index 548ab24cc3..445a712e1e 100644 --- a/cocos/rendering/custom/executor.ts +++ b/cocos/rendering/custom/executor.ts @@ -72,7 +72,7 @@ import { import { legacyCC } from '../../core/global-exports'; import { Vec3 } from '../../core/math/vec3'; import { Vec4 } from '../../core/math/vec4'; -import { BatchingSchemes, Pass } from '../../render-scene'; +import { Pass } from '../../render-scene'; import { Camera } from '../../render-scene/scene/camera'; import { ShadowType } from '../../render-scene/scene/shadows'; import { Root } from '../../root'; @@ -125,8 +125,6 @@ import { PipelineUBO } from '../pipeline-ubo'; import { RenderInfo, RenderObject, WebSceneTask, WebSceneTransversal } from './web-scene'; import { WebSceneVisitor } from './web-scene-visitor'; import { RenderAdditiveLightQueue } from '../render-additive-light-queue'; -import { RenderShadowMapBatchedQueue } from '../render-shadow-map-batched-queue'; -import { PlanarShadowQueue } from '../planar-shadow-queue'; import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph'; import { VectorGraphColorMap } from './effect'; import { @@ -141,6 +139,7 @@ import { import { RenderReflectionProbeQueue } from '../render-reflection-probe-queue'; import { builtinResMgr } from '../../asset/asset-manager/builtin-res-mgr'; import { Texture2D } from '../../asset/assets/texture-2d'; +import { SceneCulling } from './scene-culling'; class ResourceVisitor implements ResourceGraphVisitor { name: string; @@ -448,7 +447,7 @@ class BlitDesc { const deferredLitsBufView = context.blit.deferredLitsBufView; this._lightBufferData = context.blit.lightBufferData; this._lightBufferData.fill(0); - const binding = isEnableEffect() ? getDescBindingFromName('CCForwardLight') : UBOForwardLight.BINDING; + // const binding = isEnableEffect() ? getDescBindingFromName('CCForwardLight') : UBOForwardLight.BINDING; this._stageDesc.bindBuffer(UBOForwardLight.BINDING, deferredLitsBufView); } this._stageDesc.bindBuffer(UBOLocal.BINDING, context.blit.emptyLocalUBO); @@ -506,7 +505,7 @@ class DeviceRenderQueue { } this.queueId = id; this._devicePass = devicePass; - if (isEnableEffect()) this._phaseID = cclegacy.rendering.getPhaseID(devicePass.passID, context.renderGraph.getLayout(id) || 'default'); + this._phaseID = cclegacy.rendering.getPhaseID(devicePass.passID, context.renderGraph.getLayout(id)); if (!this._sceneVisitor) { this._sceneVisitor = new WebSceneVisitor( context.commandBuffer, @@ -573,39 +572,11 @@ class DeviceRenderQueue { } class SubmitInfo { - public instances = new Set(); - public renderInstanceQueue: InstancedBuffer[] = []; - public opaqueList: RenderInfo[] = []; - public transparentList: RenderInfo[] = []; - public planarQueue: PlanarShadowQueue | null = null; // - public shadowMap: Map = new Map(); public additiveLight: RenderAdditiveLightQueue | null = null; public reflectionProbe: RenderReflectionProbeQueue | null = null; - private _clearInstances (): void { - const it = this.instances.values(); let res = it.next(); - while (!res.done) { - res.value.clear(); - res = it.next(); - } - this.instances.clear(); - } - - private _clearShadowMap (): void { - for (const shadowMap of this.shadowMap) { - shadowMap[1].clear(); - } - this.shadowMap.clear(); - } - reset (): void { - this._clearInstances(); - this.renderInstanceQueue.length = 0; - this.opaqueList.length = 0; - this.transparentList.length = 0; - this.planarQueue = null; - this._clearShadowMap(); this.additiveLight = null; this.reflectionProbe = null; } @@ -961,23 +932,7 @@ class DeviceRenderPass { cmdBuff.endRenderPass(); } - private _clear (): void { - for (const [cam, infoMap] of context.submitMap) { - for (const [id, info] of infoMap) { - info.additiveLight?.clear(); - const it = info.instances.values(); let res = it.next(); - while (!res.done) { - res.value.clear(); - res = it.next(); - } - info.renderInstanceQueue = []; - info.instances.clear(); - } - } - } - postPass (): void { - this._clear(); // this.submitMap.clear(); for (const queue of this._deviceQueues) { queue.postRecord(); @@ -1151,182 +1106,17 @@ class DevicePreSceneTask extends WebSceneTask { public start (): void { if (this.graphScene.blit) { this._currentQueue.createBlitDesc(this.graphScene.blit); - return; } - if (!this.camera) { - return; - } - const devicePass = this._currentQueue.devicePass; - const submitMap = context.submitMap; - let submitInfoMap = submitMap.get(this.camera); - if (submitInfoMap && submitInfoMap.has(this._currentQueue.phaseID)) { - this._submitInfo = submitInfoMap.get(this._currentQueue.phaseID)!; - } else { - if (!submitInfoMap) { - submitInfoMap = new Map(); - submitMap.set(this.camera, submitInfoMap); - } - this._submitInfo = new SubmitInfo(); - submitInfoMap.set(this._currentQueue.phaseID, this._submitInfo); - } - // culling - if ((!isShadowMap(this.graphScene) || (isShadowMap(this.graphScene) && this.graphScene.scene!.light.level === 0)) - && this.camera !== context.cullCamera) { - super.start(); - context.cullCamera = this.camera; - } - - // shadowmap - if (isShadowMap(this.graphScene)) { - const scene = this.graphScene.scene!; - assert(scene.light.light !== null); - let shadowQueue = this._submitInfo.shadowMap.get(this.graphScene.sceneID); - if (!shadowQueue) { - shadowQueue = new RenderShadowMapBatchedQueue(context.pipeline); - this._submitInfo.shadowMap.set(this.graphScene.sceneID, shadowQueue); - } - this.sceneData.shadowFrameBufferMap.set(scene.light.light, devicePass.framebuffer); - shadowQueue.gatherLightPasses(this.camera, scene.light.light, this._cmdBuff, scene.light.level); - return; - } - // reflection probe - if (this.graphScene.scene!.flags & SceneFlags.REFLECTION_PROBE && !this._submitInfo.reflectionProbe) { - this._submitInfo.reflectionProbe = context.pools.addReflectionProbe(); - this._submitInfo.reflectionProbe.clear(); - if (cclegacy.internal.reflectionProbeManager) { - const probes = cclegacy.internal.reflectionProbeManager.getProbes(); - for (let i = 0; i < probes.length; i++) { - if (probes[i].hasFrameBuffer(this._currentQueue.devicePass.framebuffer)) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - this._submitInfo.reflectionProbe.gatherRenderObjects(probes[i], this.camera, this._cmdBuff); - break; - } - } - } - return; - } - const sceneFlag = this._graphScene.scene!.flags; - // If it is not empty, it means that it has been added and will not be traversed. - const isEmpty = !this._submitInfo.opaqueList.length - && !this._submitInfo.transparentList.length - && !this._submitInfo.instances.size; - if (isEmpty) { - for (const ro of this.sceneData.renderObjects) { - const subModels = ro.model.subModels; - for (const subModel of subModels) { - const passes = subModel.passes; - for (const p of passes) { - if (((isEnableEffect()) ? p.phaseID : p.phase) !== this._currentQueue.phaseID) continue; - const batchingScheme = p.batchingScheme; - if (batchingScheme === BatchingSchemes.INSTANCING) { - const instancedBuffer = p.getInstancedBuffer(); - instancedBuffer.merge(subModel, passes.indexOf(p)); - this._submitInfo.instances.add(instancedBuffer); - } else { - this._insertRenderList(ro, subModels.indexOf(subModel), passes.indexOf(p)); - this._insertRenderList(ro, subModels.indexOf(subModel), passes.indexOf(p), true); - } - } - } - } - this._instancedSort(); - } - if (sceneFlag & SceneFlags.DEFAULT_LIGHTING) { - this._submitInfo.additiveLight = context.additiveLight; - validPunctualLightsCulling(context.pipeline, this.camera); - this._submitInfo.additiveLight.gatherLightPasses(this.camera, this._cmdBuff, this._currentQueue.devicePass.layoutName); - } - if (sceneFlag & SceneFlags.PLANAR_SHADOW) { - this._submitInfo.planarQueue = context.planarShadow; - this._submitInfo.planarQueue.gatherShadowPasses(this.camera, this._cmdBuff); - } - if (sceneFlag & SceneFlags.OPAQUE_OBJECT) { this._submitInfo.opaqueList.sort(this._opaqueCompareFn); } - if (sceneFlag & SceneFlags.TRANSPARENT_OBJECT) { this._submitInfo.transparentList.sort(this._transparentCompareFn); } - } - - protected _instancedSort (): void { - let it = this._submitInfo!.instances.values(); - let res = it.next(); - while (!res.done) { - if (!(res.value.pass.blendState.targets[0].blend)) { - this._submitInfo!.renderInstanceQueue.push(res.value); - } - res = it.next(); - } - it = this._submitInfo!.renderInstanceQueue.values(); - res = it.next(); - while (!res.done) { - if (res.value.pass.blendState.targets[0].blend) { - this._submitInfo!.renderInstanceQueue.push(res.value); - } - res = it.next(); - } - } - - protected _insertRenderList (ro: RenderObject, subModelIdx: number, passIdx: number, isTransparent = false): void { - const subModel = ro.model.subModels[subModelIdx]; - const pass: Pass = subModel.passes[passIdx]; - const shader = subModel.shaders[passIdx]; - const currTransparent = pass.blendState.targets[0].blend; - const devicePass = this._currentQueue.devicePass; - const passId = devicePass.passID; - const phase = isEnableEffect() ? this._currentQueue.phaseID // | cclegacy.rendering.getPhaseID(passId, 'planarShadow') - : getPhaseID('default') | getPhaseID('planarShadow'); - if (currTransparent !== isTransparent || !(pass.phaseID & (isTransparent ? phase : this._currentQueue.phaseID))) { - return; - } - const hash = (0 << 30) | pass.priority as number << 16 | subModel.priority as number << 8 | passIdx; - const rp = context.pools.addPassInfo(); - rp.priority = ro.model.priority; - rp.hash = hash; - rp.depth = ro.depth || 0; - rp.shaderId = shader.typedID; - rp.subModel = subModel; - rp.passIdx = passIdx; - if (isTransparent) this._submitInfo!.transparentList.push(rp); - else this._submitInfo!.opaqueList.push(rp); - } - - /** - * @en Comparison sorting function. Opaque objects are sorted by priority -> depth front to back -> shader ID. - * @zh 比较排序函数。不透明对象按优先级 -> 深度由前向后 -> Shader ID 顺序排序。 - */ - protected _opaqueCompareFn (a: RenderInfo, b: RenderInfo): number { - return (a.hash - b.hash) || (a.depth - b.depth) || (a.shaderId - b.shaderId); - } - /** - * @en Comparison sorting function. Transparent objects are sorted by priority -> depth back to front -> shader ID. - * @zh 比较排序函数。半透明对象按优先级 -> 深度由后向前 -> Shader ID 顺序排序。 - */ - protected _transparentCompareFn (a: RenderInfo, b: RenderInfo): number { - return (a.priority - b.priority) || (a.hash - b.hash) || (b.depth - a.depth) || (a.shaderId - b.shaderId); - } - - private _uploadInstanceBuffers (): void { - if (this._currentQueue.isUploadInstance) return; - const it = this._submitInfo!.instances.values(); let res = it.next(); - while (!res.done) { - if (res.value.hasPendingModels) res.value.uploadBuffers(this._cmdBuff); - res = it.next(); - } - this._currentQueue.isUploadInstance = true; - } - - protected _updateGlobal (data: RenderData): void { - const devicePass = this._currentQueue.devicePass; - updateGlobalDescBinding(data, isEnableEffect() ? context.renderGraph.getLayout(devicePass.rasterPassInfo.id) : 'default'); - if (!isEnableEffect()) context.pipeline.descriptorSet.update(); } public submit (): void { if (this.graphScene.blit) { this._currentQueue.blitDesc!.update(); - return; } - if (isShadowMap(this.graphScene)) { - return; - } - this._uploadInstanceBuffers(); + // if (isShadowMap(this.graphScene)) { + + // } + // this._uploadInstanceBuffers(); } } @@ -1358,70 +1148,7 @@ class DeviceSceneTask extends WebSceneTask { } get graphScene (): GraphScene { return this._graphScene; } public start (): void {} - protected _recordRenderList (isTransparent: boolean): void { - const submitMap = context.submitMap; - const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - const renderList = isTransparent ? currSubmitInfo.transparentList - : currSubmitInfo.opaqueList; - for (let i = 0; i < renderList.length; ++i) { - const { subModel, passIdx } = renderList[i]; - const inputAssembler: InputAssembler = subModel.inputAssembler; - const pass: Pass = subModel.passes[passIdx]; - const shader: Shader = subModel.shaders[passIdx]; - const descriptorSet: DescriptorSet = subModel.descriptorSet; - const pso = PipelineStateManager.getOrCreatePipelineState( - deviceManager.gfxDevice, - pass, - shader, - this._renderPass, - inputAssembler, - ); - this.visitor.bindPipelineState(pso); - this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); - this.visitor.bindDescriptorSet(SetIndex.LOCAL, descriptorSet); - this.visitor.bindInputAssembler(inputAssembler); - this.visitor.draw(inputAssembler); - } - } - protected _recordOpaqueList (): void { - this._recordRenderList(false); - } - protected _recordInstences (): void { - const submitMap = context.submitMap; - const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - const it = currSubmitInfo.renderInstanceQueue.length === 0 - ? currSubmitInfo.instances.values() - : currSubmitInfo.renderInstanceQueue.values(); - let res = it.next(); - while (!res.done) { - const { instances, pass, hasPendingModels } = res.value; - if (hasPendingModels) { - this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); - let lastPSO: PipelineState | null = null; - for (let b = 0; b < instances.length; ++b) { - const instance = instances[b]; - if (!instance.count) { continue; } - const shader = instance.shader!; - const pso = PipelineStateManager.getOrCreatePipelineState( - deviceManager.gfxDevice, - pass, - shader, - this._renderPass, - instance.ia, - ); - if (lastPSO !== pso) { - this.visitor.bindPipelineState(pso); - lastPSO = pso; - } - const ia: InputAssembler = instance.ia; - this.visitor.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, res.value.dynamicOffsets); - this.visitor.bindInputAssembler(ia); - this.visitor.draw(ia); - } - } - res = it.next(); - } - } + protected _recordUI (): void { const batches = this.camera!.scene!.batches; for (let i = 0; i < batches.length; i++) { @@ -1436,7 +1163,7 @@ class DeviceSceneTask extends WebSceneTask { const count = batch.shaders.length; for (let j = 0; j < count; j++) { const pass = batch.passes[j]; - if (((isEnableEffect()) ? pass.phaseID : pass.phase) !== this._currentQueue.phaseID) continue; + if (pass.phaseID !== this._currentQueue.phaseID) continue; const shader = batch.shaders[j]; const inputAssembler: InputAssembler = batch.inputAssembler!; const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, pass, shader, this._renderPass, inputAssembler); @@ -1449,19 +1176,7 @@ class DeviceSceneTask extends WebSceneTask { } } } - protected _recordTransparentList (): void { - this._recordRenderList(true); - } - protected _recordShadowMap (): void { - const submitMap = context.submitMap; - const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.shadowMap.get(this.graphScene.sceneID)!.recordCommandBuffer( - context.device, - this._renderPass, - context.commandBuffer, - ); - } protected _recordReflectionProbe (): void { const submitMap = context.submitMap; const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; @@ -1513,63 +1228,22 @@ class DeviceSceneTask extends WebSceneTask { this.visitor.bindPipelineState(pso); const layoutStage = devicePass.renderLayout; const layoutDesc = layoutStage!.descriptorSet!; - const extResId: number[] = isEnableEffect() ? [] : mergeSrcToTargetDesc(pass.descriptorSet, layoutDesc); + const extResId: number[] = []; // if (isEnableEffect()) this.visitor.bindDescriptorSet(SetIndex.GLOBAL, layoutDesc); - this.visitor.bindDescriptorSet(SetIndex.MATERIAL, isEnableEffect() ? pass.descriptorSet : layoutDesc); + this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); this.visitor.bindDescriptorSet(SetIndex.LOCAL, this._currentQueue.blitDesc!.stageDesc!); this.visitor.bindInputAssembler(screenIa); this.visitor.draw(screenIa); // The desc data obtained from the outside should be cleaned up so that the data can be modified this._clearExtBlitDesc(layoutDesc, extResId); - // if (isEnableEffect()) this.visitor.bindDescriptorSet(SetIndex.GLOBAL, globalDesc); } } - private _recordAdditiveLights (): void { - const devicePass = this._currentQueue.devicePass; - const submitMap = context.submitMap; - const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.additiveLight?.recordCommandBuffer( - context.device, - this._renderPass, - context.commandBuffer, - ); - } - private _recordPlanarShadows (): void { - const devicePass = this._currentQueue.devicePass; - const submitMap = context.submitMap; - const currSubmitInfo = submitMap.get(this.camera!)!.get(this._currentQueue.phaseID)!; - currSubmitInfo.planarQueue?.recordCommandBuffer( - context.device, - this._renderPass, - context.commandBuffer, - ); - } protected _updateGlobal (data: RenderData): void { const devicePass = this._currentQueue.devicePass; - updateGlobalDescBinding(data, isEnableEffect() ? context.renderGraph.getLayout(devicePass.rasterPassInfo.id) : 'default'); - if (!isEnableEffect()) context.pipeline.descriptorSet.update(); - } - protected _setMainLightShadowTex (data: RenderData): void { - const graphScene = this.graphScene; - if (graphScene.scene && graphScene.scene.camera) { - const mainLight = graphScene.scene.camera.scene!.mainLight; - const shadowFrameBufferMap = this.sceneData.shadowFrameBufferMap; - if (mainLight && shadowFrameBufferMap.has(mainLight)) { - const shadowAttrID = context.layoutGraph.attributeIndex.get('cc_shadowMap'); - const defaultTex = builtinResMgr.get('default-texture').getGFXTexture()!; - for (const [key, value] of data.textures) { - if (key === shadowAttrID) { - const tex = data.textures.get(shadowAttrID); - if (tex === defaultTex) { - data.textures.set(key, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); - } - return; - } - } - } - } + updateGlobalDescBinding(data, context.renderGraph.getLayout(devicePass.rasterPassInfo.id)); } + protected _updateRenderData (): void { if (this._currentQueue.isUpdateUBO) return; const devicePass = this._currentQueue.devicePass; @@ -1580,19 +1254,16 @@ class DeviceSceneTask extends WebSceneTask { // CCCamera, CCShadow, CCCSM const queueId = this._currentQueue.queueId; const queueRenderData = context.renderGraph.getData(queueId)!; - this._setMainLightShadowTex(queueRenderData); this._updateGlobal(queueRenderData); - if (isEnableEffect()) { - const layoutName = context.renderGraph.getLayout(rasterId); - const descSetData = getDescriptorSetDataFromLayout(layoutName); - mergeSrcToTargetDesc(descSetData!.descriptorSet, context.pipeline.descriptorSet, true); - } + + const layoutName = context.renderGraph.getLayout(rasterId); + const descSetData = getDescriptorSetDataFromLayout(layoutName); + mergeSrcToTargetDesc(descSetData!.descriptorSet, context.pipeline.descriptorSet, true); this._currentQueue.isUpdateUBO = true; } - public submit (): void { - const devicePass = this._currentQueue.devicePass; + + private _applyViewport (): void { const queueViewport = this._currentQueue.viewport; - this._updateRenderData(); if (queueViewport) { this.visitor.setViewport(queueViewport); this.visitor.setScissor(this._currentQueue.scissor!); @@ -1610,41 +1281,29 @@ class DeviceSceneTask extends WebSceneTask { this.visitor.setViewport(sceneViewport); this.visitor.setScissor(area); } + } + + public submit (): void { + const devicePass = this._currentQueue.devicePass; + const sceneCulling = context.culling; + this._updateRenderData(); + this._applyViewport(); // Currently processing blit and camera first if (this.graphScene.blit) { this._recordBlit(); return; } - if (isShadowMap(this.graphScene)) { - this._recordShadowMap(); - return; - } + const renderQueueDesc = sceneCulling.sceneQueryIndex.get(this.graphScene.sceneID)!; + const renderQueue = sceneCulling.renderQueues[renderQueueDesc.renderQueueTarget]; const graphSceneData = this.graphScene.scene!; - if (graphSceneData.flags & SceneFlags.OPAQUE_OBJECT - || graphSceneData.flags & SceneFlags.CUTOUT_OBJECT) { - this._recordOpaqueList(); - } - if (graphSceneData.flags & SceneFlags.DRAW_INSTANCING) { - this._recordInstences(); - } - if (graphSceneData.flags & SceneFlags.DEFAULT_LIGHTING) { - this._recordAdditiveLights(); - } - this.visitor.bindDescriptorSet( - SetIndex.GLOBAL, - context.pipeline.descriptorSet, - ); - if (graphSceneData.flags & SceneFlags.PLANAR_SHADOW) { - this._recordPlanarShadows(); - } - if (graphSceneData.flags & SceneFlags.TRANSPARENT_OBJECT) { - this._recordTransparentList(); - } + renderQueue.opaqueQueue.recordCommandBuffer(deviceManager.gfxDevice, this._renderPass, context.commandBuffer); + renderQueue.opaqueInstancingQueue.recordCommandBuffer(this._renderPass, context.commandBuffer); + renderQueue.transparentInstancingQueue.recordCommandBuffer(this._renderPass, context.commandBuffer); + renderQueue.transparentQueue.recordCommandBuffer(deviceManager.gfxDevice, this._renderPass, context.commandBuffer); if (graphSceneData.flags & SceneFlags.GEOMETRY) { this.camera!.geometryRenderer?.render( devicePass.renderPass, context.commandBuffer, - context.pipeline.pipelineSceneData, ); } @@ -1907,12 +1566,12 @@ class ExecutorContext { this.width = width; this.height = height; this.additiveLight = new RenderAdditiveLightQueue(pipeline); - this.shadowMapBatched = new RenderShadowMapBatchedQueue(pipeline); - this.planarShadow = new PlanarShadowQueue(pipeline); this.pools = new ExecutorPools(this); this.blit = new BlitInfo(this); + this.culling = new SceneCulling(); } reset (): void { + this.culling.clear(); this.pools.reset(); this.cullCamera = null; for (const infoMap of this.submitMap) { @@ -1935,11 +1594,10 @@ class ExecutorContext { readonly root: Root; readonly ubo: PipelineUBO; readonly additiveLight: RenderAdditiveLightQueue; - readonly shadowMapBatched: RenderShadowMapBatchedQueue; - readonly planarShadow: PlanarShadowQueue; readonly submitMap: Map> = new Map>(); readonly pools: ExecutorPools; readonly blit: BlitInfo; + readonly culling: SceneCulling; renderGraph: RenderGraph; width: number; height: number; @@ -1998,8 +1656,10 @@ export class Executor { execute (rg: RenderGraph): void { context.renderGraph = rg; context.reset(); - this._removeDeviceResource(); const cmdBuff = context.commandBuffer; + context.culling.buildRenderQueues(rg, context.layoutGraph, context.pipelineSceneData); + context.culling.uploadInstancing(cmdBuff); + this._removeDeviceResource(); cmdBuff.begin(); if (!this._visitor) this._visitor = new RenderVisitor(); depthFirstSearch(this._visitor.graphView, this._visitor, this._visitor.colorMap); diff --git a/cocos/rendering/custom/scene-culling.ts b/cocos/rendering/custom/scene-culling.ts new file mode 100644 index 0000000000..b337a00f6d --- /dev/null +++ b/cocos/rendering/custom/scene-culling.ts @@ -0,0 +1,416 @@ +import { Vec3, assert } from '../../core'; +import { Frustum, intersect, AABB } from '../../core/geometry'; +import { CommandBuffer } from '../../gfx'; +import { BatchingSchemes, Pass, RenderScene } from '../../render-scene'; +import { CSMLevel, Camera, DirectionalLight, Light, LightType, Model, SKYBOX_FLAG, ShadowType, SpotLight } from '../../render-scene/scene'; +import { Node } from '../../scene-graph'; +import { PipelineSceneData } from '../pipeline-scene-data'; +import { hashCombineStr, getSubpassOrPassID, bool } from './define'; +import { LayoutGraphData } from './layout-graph'; +import { RenderGraph, RenderGraphValue, SceneData } from './render-graph'; +import { SceneFlags } from './types'; +import { RenderQueue, RenderQueueDesc } from './web-pipeline-types'; + +function computeCullingKey (camera: Camera | null, light: Light | null, castShadows: boolean, lightLevel: number): number { + let hashCode = 0; + if (camera) { + // camera + hashCode = hashCombineStr(`u${camera.node.uuid}`, hashCode); + hashCode = hashCombineStr(`p${camera.priority}`, hashCode); + hashCode = hashCombineStr(`v${camera.visibility}`, hashCode); + hashCode = hashCombineStr(`f${camera.clearFlag}`, hashCode); + hashCode = hashCombineStr(`cx${camera.clearColor.x}cy${camera.clearColor.y}cz${camera.clearColor.z}cw${camera.clearColor.w}`, hashCode); + hashCode = hashCombineStr(`cd${camera.clearDepth}cs${camera.clearStencil}`, hashCode); + hashCode = hashCombineStr(`pj${camera.projectionType}`, hashCode); + hashCode = hashCombineStr(`fa${camera.fovAxis}`, hashCode); + hashCode = hashCombineStr(`fov${camera.fov}`, hashCode); + hashCode = hashCombineStr(`n${camera.nearClip}`, hashCode); + hashCode = hashCombineStr(`far${camera.farClip}`, hashCode); + hashCode = hashCombineStr(`apt${camera.aperture}`, hashCode); + hashCode = hashCombineStr(`sht${camera.shutter}`, hashCode); + hashCode = hashCombineStr(`iso${camera.iso}`, hashCode); + hashCode = hashCombineStr(`rx${camera.viewport.x}ry${camera.viewport.y}rw${camera.viewport.width}rh${camera.viewport.height}`, hashCode); + hashCode = hashCombineStr(`upp${camera.usePostProcess}`, hashCode); + } + // light + if (light) { + hashCode = hashCombineStr(`u${light.node!.uuid}`, hashCode); + // hashCode = hashCombineStr(`cx${light.finalColor.x}cy${light.finalColor.y}cz${light.finalColor.z}`, hashCode); + // hashCode = hashCombineStr(`ct${light.useColorTemperature}`, hashCode); + // hashCode = hashCombineStr(`ctv${light.colorTemperature}`, hashCode); + // hashCode = hashCombineStr(`vis${light.visibility}`, hashCode); + // hashCode = hashCombineStr(`tp${light.type}`, hashCode); + // switch (light.type) { + // case LightType.DIRECTIONAL: + // hashCode = hashCombineStr(`${(light as DirectionalLight).illuminance}`, hashCode); + // break; + // default: + // } + } + hashCode = hashCombineStr(`cast${castShadows}`, hashCode); + hashCode = hashCombineStr(`level${lightLevel}`, hashCode); + return hashCode; +} + +class CullingKey { + camera: Camera | null; + light: Light | null; + castShadows = false; + lightLevel = 0xffffffff; + constructor (camera: Camera | null, light: Light | null, castShadows: boolean, lightLevel: number) { + this.camera = camera; + this.light = light; + this.castShadows = castShadows; + this.lightLevel = lightLevel; + } +} + +let pSceneData: PipelineSceneData; + +class CullingQueries { + // key: hash val + culledResultIndex: Map = new Map(); + cullingKeyResult: Map = new Map(); +} + +function isNodeVisible (node: Node, visibility: number): boolean { + return node && ((visibility & node.layer) === node.layer); +} + +function isModelVisible (model: Model, visibility: number): boolean { + return !!(visibility & model.visFlags); +} +const transWorldBounds = new AABB(); +function isFrustumVisible (model: Model, frustum: Readonly, castShadow: boolean): boolean { + const modelWorldBounds = model.worldBounds; + if (!modelWorldBounds) { + return false; + } + transWorldBounds.copy(modelWorldBounds); + const shadows = pSceneData.shadows; + if (shadows.type === ShadowType.Planar && castShadow) { + AABB.transform(transWorldBounds, modelWorldBounds, shadows.matLight); + } + return !intersect.aabbFrustum(transWorldBounds, frustum); +} + +function sceneCulling ( + skyboxModelToSkip: Model | null, + scene: RenderScene, + camera: Camera, + camOrLightFrustum: Readonly, + castShadow: boolean, + models: Array, +): void { + const visibility = camera.visibility; + for (const model of scene.models) { + assert(!!model); + if (!model.enabled || model === skyboxModelToSkip || (castShadow && !model.castShadow)) { + continue; + } + if (scene && scene.isCulledByLod(camera, model)) { + continue; + } + + if (isNodeVisible(model.node, visibility) + || isModelVisible(model, visibility)) { + // frustum culling + if (isFrustumVisible(model, camOrLightFrustum, castShadow)) { + continue; + } + + models.push(model); + } + } +} + +function isBlend (pass: Pass): boolean { + let bBlend = false; + for (const target of pass.blendState.targets) { + if (target.blend) { + bBlend = true; + } + } + return bBlend; +} + +function computeSortingDepth (camera: Camera, model: Model): number { + let depth = 0; + if (model.node) { + const node = model.transform; + const tempVec3 = new Vec3(); + const position = Vec3.subtract(tempVec3, node.worldPosition, camera.position); + depth = position.dot(camera.forward); + } + return depth; +} + +function addRenderObject ( + phaseLayoutId: number, + isDrawOpaqueOrMask: boolean, + isDrawBlend: boolean, + camera: Camera, + model: Model, + queue: RenderQueue, +): void { + const subModels = model.subModels; + const subModelCount = subModels.length; + for (let subModelIdx = 0; subModelIdx < subModelCount; ++subModelIdx) { + const subModel = subModels[subModelIdx]; + const passes = subModel.passes; + const passCount = passes.length; + for (let passIdx = 0; passIdx < passCount; ++passIdx) { + const pass = passes[passIdx]; + // check phase + const phaseAllowed = phaseLayoutId === pass.phaseID; + if (!phaseAllowed) { + continue; + } + // check scene flags + const is_blend = isBlend(pass); + const isOpaqueOrMask = !is_blend; + if (!isDrawBlend && is_blend) { + // skip transparent object + continue; + } + if (!isDrawOpaqueOrMask && isOpaqueOrMask) { + // skip opaque object + continue; + } + + // add object to queue + if (pass.batchingScheme === BatchingSchemes.INSTANCING) { + const instancedBuffer = pass.getInstancedBuffer(); + instancedBuffer.merge(subModel, passIdx); + if (is_blend) { + queue.transparentInstancingQueue.add(instancedBuffer); + } else { + queue.opaqueInstancingQueue.add(instancedBuffer); + } + } else { + const depth = computeSortingDepth(camera, model); + if (is_blend) { + queue.transparentQueue.add(model, depth, subModelIdx, passIdx); + } else { + queue.opaqueQueue.add(model, depth, subModelIdx, passIdx); + } + } + } + } +} + +export class SceneCulling { + sceneQueries: Map = new Map(); + culledResults: Array> = new Array>(); + renderQueues: Array = new Array(); + sceneQueryIndex: Map = new Map(); + // source id + numCullingQueries = 0; + // target id + numRenderQueues = 0; + layoutGraph; + renderGraph; + clear (): void { + this.sceneQueries.clear(); + for (const c of this.culledResults) { + c.length = 0; + } + this.culledResults.length = 0; + for (const q of this.renderQueues) { + q.clear(); + } + this.renderQueues.length = 0; + this.sceneQueryIndex.clear(); + this.numCullingQueries = 0; + this.numRenderQueues = 0; + } + + buildRenderQueues (rg: RenderGraph, lg: LayoutGraphData, pplSceneData: PipelineSceneData): void { + this.layoutGraph = lg; + this.renderGraph = rg; + pSceneData = pplSceneData; + this.collectCullingQueries(rg, lg); + this.batchCulling(pplSceneData); + this.fillRenderQueues(rg, pplSceneData); + } + + private getOrCreateSceneCullingQuery (sceneData: SceneData): number { + const scene = sceneData.scene!; + let queries = this.sceneQueries.get(scene); + if (!queries) { + this.sceneQueries.set(scene, new CullingQueries()); + queries = this.sceneQueries.get(scene); + } + const castShadow = bool(sceneData.flags & SceneFlags.SHADOW_CASTER); + const key = computeCullingKey(sceneData.camera, sceneData.light.light, castShadow, sceneData.light.level); + const cullNum = queries!.culledResultIndex.get(key); + if (cullNum !== undefined) { + return cullNum; + } + const soureceID = this.numCullingQueries++; + if (this.numCullingQueries > this.culledResults.length) { + assert(this.numCullingQueries === (this.culledResults.length + 1)); + this.culledResults.push([]); + } + queries!.culledResultIndex.set(key, soureceID); + queries!.cullingKeyResult.set(key, new CullingKey(sceneData.camera, sceneData.light.light, castShadow, sceneData.light.level)); + return soureceID; + } + + private createRenderQueue (sceneFlags: SceneFlags, subpassOrPassLayoutID: number): number { + const targetID = this.numRenderQueues++; + if (this.numRenderQueues > this.renderQueues.length) { + assert(this.numRenderQueues === (this.renderQueues.length + 1)); + this.renderQueues.push(new RenderQueue()); + } + assert(targetID < this.renderQueues.length); + const rq = this.renderQueues[targetID]; + rq.sceneFlags = sceneFlags; + rq.subpassOrPassLayoutID = subpassOrPassLayoutID; + return targetID; + } + + private collectCullingQueries (rg: RenderGraph, lg: LayoutGraphData): void { + for (const v of rg.vertices()) { + if (!rg.holds(RenderGraphValue.Scene, v) || !rg.getValid(v)) { + continue; + } + const sceneData = rg.getScene(v); + if (!sceneData.scene) { + assert(!!sceneData.scene); + continue; + } + const sourceID = this.getOrCreateSceneCullingQuery(sceneData); + const layoutID = getSubpassOrPassID(v, rg, lg); + const targetID = this.createRenderQueue(sceneData.flags, layoutID); + + const lightType = sceneData.light.light ? sceneData.light.light.type : LightType.UNKNOWN; + // add render queue to query source + this.sceneQueryIndex.set(v, new RenderQueueDesc(sourceID, targetID, lightType)); + } + } + + uploadInstancing (cmdBuffer: CommandBuffer): void { + for (let queueID = 0; queueID !== this.numRenderQueues; ++queueID) { + assert(this.numRenderQueues <= this.renderQueues.length); + const queue = this.renderQueues[queueID]; + queue.opaqueInstancingQueue.uploadBuffers(cmdBuffer); + queue.transparentInstancingQueue.uploadBuffers(cmdBuffer); + } + } + + private batchCulling (pplSceneData: PipelineSceneData): void { + const skybox = pplSceneData.skybox; + const skyboxModelToSkip = skybox ? skybox.model : null; + for (const [scene, queries] of this.sceneQueries) { + assert(!!scene); + for (const [key, sourceID] of queries.culledResultIndex) { + const cullingKey = queries.cullingKeyResult.get(key)!; + assert(!!cullingKey.camera); + assert(cullingKey.camera.scene === scene); + const camera = cullingKey.camera; + const light = cullingKey.light; + const level = cullingKey.lightLevel; + const castShadow = cullingKey.castShadows; + assert(sourceID < this.culledResults.length); + const models = this.culledResults[sourceID]; + if (light) { + switch (light.type) { + case LightType.SPOT: + sceneCulling(skyboxModelToSkip, scene, camera, (light as SpotLight).frustum, castShadow, models); + break; + case LightType.DIRECTIONAL: { + const csmLayers = pplSceneData.csmLayers; + const mainLight: DirectionalLight = light as DirectionalLight; + const csmLevel = mainLight.csmLevel; + let frustum: Readonly; + const shadows = pplSceneData.shadows; + if (shadows.type === ShadowType.Planar) { + frustum = camera.frustum; + } else { + if (shadows.enabled && shadows.type === ShadowType.ShadowMap && mainLight && mainLight.node) { + // pplSceneData.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor); + csmLayers.update(pplSceneData, camera); + } + + if (mainLight.shadowFixedArea || csmLevel === CSMLevel.LEVEL_1) { + frustum = csmLayers.specialLayer.validFrustum; + } else { + frustum = csmLayers.layers[level].validFrustum; + } + } + sceneCulling(skyboxModelToSkip, scene, camera, frustum, castShadow, models); + } + break; + default: + } + } else { + sceneCulling(skyboxModelToSkip, scene, camera, camera.frustum, castShadow, models); + } + } + } + } + + private fillRenderQueues (rg: RenderGraph, pplSceneData: PipelineSceneData): void { + const skybox = pplSceneData.skybox; + for (const [sceneId, desc] of this.sceneQueryIndex) { + assert(rg.holds(RenderGraphValue.Scene, sceneId)); + const sourceId = desc.culledSource; + const targetId = desc.renderQueueTarget; + const sceneData = rg.getScene(sceneId); + const isDrawBlend = bool(sceneData.flags & SceneFlags.TRANSPARENT_OBJECT); + const isDrawOpaqueOrMask = bool(sceneData.flags & (SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT)); + const isDrawShadowCaster = bool(sceneData.flags & SceneFlags.SHADOW_CASTER); + if (!isDrawShadowCaster && !isDrawBlend && !isDrawOpaqueOrMask) { + continue; + } + // render queue info + const renderQueueId = rg.getParent(sceneId); + assert(rg.holds(RenderGraphValue.Queue, renderQueueId)); + const graphRenderQueue = rg.getQueue(renderQueueId); + const phaseLayoutId = graphRenderQueue.phaseID; + assert(phaseLayoutId !== this.layoutGraph.nullVertex()); + + // culling source + assert(sourceId < this.culledResults.length); + const sourceModels = this.culledResults[sourceId]; + + // queue target + assert(targetId < this.renderQueues.length); + const renderQueue = this.renderQueues[targetId]; + assert(renderQueue.empty()); + + // skybox + const camera = sceneData.camera; + assert(!!camera); + if (!bool(sceneData.flags & SceneFlags.SHADOW_CASTER) + && skybox && skybox.enabled + && (camera.clearFlag & SKYBOX_FLAG)) { + assert(!!skybox.model); + const model = skybox.model; + const node = model.node; + let depth = 0; + if (node) { + const tempVec3 = new Vec3(); + Vec3.subtract(tempVec3, node.worldPosition, camera.position); + depth = tempVec3.dot(camera.forward); + } + renderQueue.opaqueQueue.add(model, depth, 0, 0); + } + + // fill render queue + for (const model of sourceModels) { + addRenderObject( + phaseLayoutId, + isDrawOpaqueOrMask, + isDrawBlend, + camera, + model, + renderQueue, + ); + } + // post-processing + renderQueue.sort(); + } + } +} diff --git a/cocos/rendering/custom/web-pipeline-types.ts b/cocos/rendering/custom/web-pipeline-types.ts new file mode 100644 index 0000000000..c41128cefd --- /dev/null +++ b/cocos/rendering/custom/web-pipeline-types.ts @@ -0,0 +1,234 @@ +import { CommandBuffer, DescriptorSet, Device, PipelineState, RenderPass, deviceManager } from '../../gfx'; +import { RenderScene } from '../../render-scene'; +import { Camera, Light, LightType, Model, SubModel } from '../../render-scene/scene'; +import { SetIndex } from '../define'; +import { InstancedBuffer } from '../instanced-buffer'; +import { PipelineStateManager } from '../pipeline-state-manager'; +import { SceneFlags } from './types'; + +export class DrawInstance { + subModel: SubModel | null; + priority: number; + hash: number; + depth: number; + shaderID: number; + passIndex: number; + + constructor ( + subModel: SubModel | null = null, + priority = 0, + hash = 0, + depth = 0, + shaderID = 0, + passIndex = 0, + ) { + this.subModel = subModel; + this.priority = priority; + this.hash = hash; + this.depth = depth; + this.shaderID = shaderID; + this.passIndex = passIndex; + } +} + +export class RenderDrawQueue { + instances: Array = new Array(); + + add (model: Model, depth: number, subModelIdx: number, passIdx: number): void { + const subModel = model.subModels[subModelIdx]; + const pass = subModel.passes[passIdx]; + const passPriority = pass.priority; + const modelPriority = subModel.priority; + const shaderId = subModel.shaders[passIdx].typedID; + const hash = (0 << 30) | (passPriority as number << 16) | (modelPriority as number << 8) | passIdx; + const priority = model.priority; + + this.instances.push(new DrawInstance(subModel, priority, hash, depth, shaderId, passIdx)); + } + /** + * @en Comparison sorting function. Opaque objects are sorted by priority -> depth front to back -> shader ID. + * @zh 比较排序函数。不透明对象按优先级 -> 深度由前向后 -> Shader ID 顺序排序。 + */ + sortOpaqueOrCutout (): void { + this.instances.sort((lhs: DrawInstance, rhs: DrawInstance) => { + if (lhs.hash !== rhs.hash) { + return lhs.hash - rhs.hash; + } + if (lhs.depth !== rhs.depth) { + return lhs.depth - rhs.depth; + } + return lhs.shaderID - rhs.shaderID; + }); + } + /** + * @en Comparison sorting function. Transparent objects are sorted by priority -> depth back to front -> shader ID. + * @zh 比较排序函数。半透明对象按优先级 -> 深度由后向前 -> Shader ID 顺序排序。 + */ + sortTransparent (): void { + this.instances.sort((lhs: DrawInstance, rhs: DrawInstance) => { + if (lhs.priority !== rhs.priority) { + return lhs.priority - rhs.priority; + } + if (lhs.hash !== rhs.hash) { + return lhs.hash - rhs.hash; + } + if (lhs.depth !== rhs.depth) { + return rhs.depth - lhs.depth; // 注意此处的差值顺序,为了按照降序排列 + } + return lhs.shaderID - rhs.shaderID; + }); + } + + recordCommandBuffer ( + device: Device, + renderPass: RenderPass, + cmdBuffer: CommandBuffer, + ): void { + for (const instance of this.instances) { + const subModel = instance.subModel!; + + const passIdx = instance.passIndex; + const inputAssembler = subModel.inputAssembler; + const pass = subModel.passes[passIdx]; + const shader = subModel.shaders[passIdx]; + const pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler); + + cmdBuffer.bindPipelineState(pso); + cmdBuffer.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); + cmdBuffer.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet); + cmdBuffer.bindInputAssembler(inputAssembler); + cmdBuffer.draw(inputAssembler); + } + } +} + +export class RenderInstancingQueue { + batches: Set = new Set(); + sortedBatches: Array = new Array(); + + add (instancedBuffer: InstancedBuffer): void { + this.batches.add(instancedBuffer); + } + + sort (): void { + this.sortedBatches = Array.from(this.batches); + } + + uploadBuffers (cmdBuffer: CommandBuffer): void { + for (const instanceBuffer of this.batches) { + if (instanceBuffer.hasPendingModels) { + instanceBuffer.uploadBuffers(cmdBuffer); + } + } + } + + recordCommandBuffer ( + renderPass: RenderPass, + cmdBuffer: CommandBuffer, + ds: DescriptorSet | null = null, + offset = 0, + dynamicOffsets: number[] | null = null, + ): void { + const renderQueue = this.sortedBatches; + for (const instanceBuffer of renderQueue) { + if (!instanceBuffer.hasPendingModels) { + continue; + } + const instances = instanceBuffer.instances; + const drawPass = instanceBuffer.pass; + cmdBuffer.bindDescriptorSet(SetIndex.MATERIAL, drawPass.descriptorSet); + let lastPSO: PipelineState | null = null; + for (const instance of instances) { + if (!instance.count) { + continue; + } + const pso = PipelineStateManager.getOrCreatePipelineState( + deviceManager.gfxDevice, + drawPass, + instance.shader!, + renderPass, + instance.ia, + ); + if (lastPSO !== pso) { + cmdBuffer.bindPipelineState(pso); + lastPSO = pso; + } + if (ds) { + cmdBuffer.bindDescriptorSet(SetIndex.GLOBAL, ds, [offset]); + } + if (dynamicOffsets) { + cmdBuffer.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, dynamicOffsets); + } else { + cmdBuffer.bindDescriptorSet( + SetIndex.LOCAL, + instance.descriptorSet, + instanceBuffer.dynamicOffsets, + ); + } + cmdBuffer.bindInputAssembler(instance.ia); + cmdBuffer.draw(instance.ia); + } + } + } +} + +export class RenderQueueDesc { + culledSource: number; + renderQueueTarget: number; + lightType: LightType; + + constructor ( + culledSourceIn = 0xFFFFFFFF, + renderQueueTargetIn = 0xFFFFFFFF, + lightTypeIn: LightType = LightType.UNKNOWN, + ) { + this.culledSource = culledSourceIn; + this.renderQueueTarget = renderQueueTargetIn; + this.lightType = lightTypeIn; + } +} + +export class RenderQueue { + opaqueQueue: RenderDrawQueue = new RenderDrawQueue(); + transparentQueue: RenderDrawQueue = new RenderDrawQueue(); + opaqueInstancingQueue: RenderInstancingQueue = new RenderInstancingQueue(); + transparentInstancingQueue: RenderInstancingQueue = new RenderInstancingQueue(); + sceneFlags: SceneFlags = SceneFlags.NONE; + subpassOrPassLayoutID = 0xffffffff; + + sort (): void { + this.opaqueQueue.sortOpaqueOrCutout(); + this.transparentQueue.sortTransparent(); + this.opaqueInstancingQueue.sort(); + this.transparentInstancingQueue.sort(); + } + + private _clearInstances (instances: Set): void { + const it = instances.values(); let res = it.next(); + while (!res.done) { + res.value.clear(); + res = it.next(); + } + instances.clear(); + } + + clear (): void { + this.opaqueQueue.instances.length = 0; + this.transparentQueue.instances.length = 0; + this._clearInstances(this.opaqueInstancingQueue.batches); + this.opaqueInstancingQueue.sortedBatches.length = 0; + this._clearInstances(this.transparentInstancingQueue.batches); + this.transparentInstancingQueue.sortedBatches.length = 0; + this.sceneFlags = SceneFlags.NONE; + this.subpassOrPassLayoutID = 0xFFFFFFFF; + } + + empty (): boolean { + return this.opaqueQueue.instances.length === 0 + && this.transparentQueue.instances.length === 0 + && this.opaqueInstancingQueue.batches.size === 0 + && this.opaqueInstancingQueue.sortedBatches.length === 0 + && this.transparentInstancingQueue.batches.size === 0 + && this.transparentInstancingQueue.sortedBatches.length === 0; + } +} diff --git a/cocos/rendering/custom/web-pipeline.ts b/cocos/rendering/custom/web-pipeline.ts index c1bac8ca45..08e171ab45 100644 --- a/cocos/rendering/custom/web-pipeline.ts +++ b/cocos/rendering/custom/web-pipeline.ts @@ -304,7 +304,11 @@ function setShadowUBOLightView ( const pipeline = (director.root as Root).pipeline; const device = pipeline.device; const sceneData = pipeline.pipelineSceneData; + const shadowInfo = sceneData.shadows; + if (shadowInfo.type === ShadowType.Planar) { + return; + } const csmLayers = sceneData.csmLayers; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; const cap = pipeline.device.capabilities; @@ -758,6 +762,7 @@ function setTextureUBOView (setter: WebSetter, camera: Camera | null, cfg: Reado const skybox = cfg.skybox; const director = cclegacy.director; const root = director.root; + const pipeline = root.pipeline as WebPipeline; if (skybox.reflectionMap) { const texture = skybox.reflectionMap.getGFXTexture()!; const sampler: Sampler = root.device.getSampler(skybox.reflectionMap.getSamplerInfo()); @@ -779,18 +784,17 @@ function setTextureUBOView (setter: WebSetter, camera: Camera | null, cfg: Reado setter.setTexture('cc_diffuseMap', texture); setter.setSampler('cc_diffuseMap', sampler); } - const pointSampler: Sampler = root.device.getSampler(_samplerPointInfo); if (!setter.hasSampler('cc_shadowMap')) { - setter.setSampler('cc_shadowMap', pointSampler); + setter.setSampler('cc_shadowMap', pipeline.defaultSampler); } if (!setter.hasTexture('cc_shadowMap')) { - setter.setTexture('cc_shadowMap', builtinResMgr.get('default-texture').getGFXTexture()!); + setter.setTexture('cc_shadowMap', pipeline.defaultTexture); } if (!setter.hasSampler('cc_spotShadowMap')) { - setter.setSampler('cc_spotShadowMap', pointSampler); + setter.setSampler('cc_spotShadowMap', pipeline.defaultSampler); } if (!setter.hasTexture('cc_spotShadowMap')) { - setter.setTexture('cc_spotShadowMap', builtinResMgr.get('default-texture').getGFXTexture()!); + setter.setTexture('cc_spotShadowMap', pipeline.defaultTexture); } } @@ -989,11 +993,12 @@ export class WebRenderSubpassBuilder extends WebSetter implements RenderSubpassB throw new Error('Method not implemented.'); } addQueue (hint: QueueHint = QueueHint.RENDER_OPAQUE, layoutName = 'default'): RenderQueueBuilder { + const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); if (DEBUG) { - const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); assert(layoutId !== 0xFFFFFFFF); } const queue = new RenderQueue(hint); + queue.phaseID = layoutId; const data = new RenderData(); const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebRenderQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); @@ -1129,11 +1134,12 @@ export class WebRenderPassBuilder extends WebSetter implements BasicMultisampleR return result; } addQueue (hint: QueueHint = QueueHint.RENDER_OPAQUE, layoutName = 'default'): WebRenderQueueBuilder { + const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); if (DEBUG) { - const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); assert(layoutId !== 0xFFFFFFFF); } const queue = new RenderQueue(hint); + queue.phaseID = layoutId; const data = new RenderData(); const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebRenderQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); @@ -1283,11 +1289,12 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild throw new Error('Method not implemented.'); } addQueue (layoutName = 'default'): WebComputeQueueBuilder { + const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); if (DEBUG) { - const layoutId = this._layoutGraph.locateChild(this._layoutID, layoutName); assert(layoutId !== 0xFFFFFFFF); } const queue = new RenderQueue(); + queue.phaseID = layoutId; const data = new RenderData(); const queueID = this._renderGraph.addVertex(RenderGraphValue.Queue, queue, '', layoutName, data, false, this._vertID); return new WebComputeQueueBuilder(data, this._renderGraph, this._layoutGraph, queueID, queue, this._pipeline); @@ -1556,6 +1563,14 @@ export class WebPipeline implements BasicPipeline { return this._globalDescSetData; } + get defaultSampler (): Sampler { + return this._defaultSampler; + } + + get defaultTexture (): Texture { + return builtinResMgr.get('default-texture').getGFXTexture()!; + } + private _compileMaterial (): void { this._copyPassMat.initialize({ effectName: 'pipeline/copy-pass', @@ -1587,7 +1602,9 @@ export class WebPipeline implements BasicPipeline { // 0: SHADOWMAP_LINER_DEPTH_OFF, 1: SHADOWMAP_LINER_DEPTH_ON. const isLinear = this._device.gfxAPI === API.WEBGL ? 1 : 0; this.setMacroInt('CC_SHADOWMAP_USE_LINEAR_DEPTH', isLinear); - + const director: Director = cclegacy.director; + const root: Root = director.root!; + this._defaultSampler = root.device.getSampler(_samplerPointInfo); // 0: UNIFORM_VECTORS_LESS_EQUAL_64, 1: UNIFORM_VECTORS_GREATER_EQUAL_125. this.pipelineSceneData.csmSupported = this.device.capabilities.maxFragmentUniformVectors >= (WebPipeline.CSM_UNIFORM_VECTORS + WebPipeline.GLOBAL_UNIFORM_VECTORS); @@ -1998,6 +2015,7 @@ export class WebPipeline implements BasicPipeline { private _copyPassMat: Material = new Material(); private _device!: Device; private _globalDSManager!: GlobalDSManager; + private _defaultSampler!: Sampler; private _globalDescriptorSet: DescriptorSet | null = null; private _globalDescriptorSetInfo: DescriptorSetInfo | null = null; private _globalDescriptorSetLayout: DescriptorSetLayout | null = null; diff --git a/cocos/rendering/post-process/passes/forward-pass.ts b/cocos/rendering/post-process/passes/forward-pass.ts index ef9f478d28..e81630d80d 100644 --- a/cocos/rendering/post-process/passes/forward-pass.ts +++ b/cocos/rendering/post-process/passes/forward-pass.ts @@ -11,7 +11,7 @@ import { ShadowPass } from './shadow-pass'; export class ForwardPass extends BasePass { name = 'ForwardPass'; - outputNames = ['ForwardColor', 'ForwardDS'] + outputNames = ['ForwardColor', 'ForwardDS']; enableInAllEditorCamera = true; depthBufferShadingScale = 1; @@ -70,11 +70,21 @@ export class ForwardPass extends BasePass { } } pass.addQueue(QueueHint.RENDER_OPAQUE) - .addSceneOfCamera(camera, + .addSceneOfCamera( + camera, new LightInfo(), - SceneFlags.OPAQUE_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.CUTOUT_OBJECT - | SceneFlags.DEFAULT_LIGHTING | SceneFlags.DRAW_INSTANCING | SceneFlags.GEOMETRY); - + SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT + | SceneFlags.DEFAULT_LIGHTING | SceneFlags.GEOMETRY, + ); + if (camera.scene?.mainLight) { + pass.addQueue(QueueHint.RENDER_TRANSPARENT, 'planar-shadow') + .addSceneOfCamera( + camera, + new LightInfo(camera.scene?.mainLight), + SceneFlags.TRANSPARENT_OBJECT | SceneFlags.SHADOW_CASTER + | SceneFlags.DEFAULT_LIGHTING | SceneFlags.GEOMETRY, + ); + } passContext.forwardPass = this; } } diff --git a/cocos/rendering/post-process/passes/skin-pass.ts b/cocos/rendering/post-process/passes/skin-pass.ts index bcbc60fdc8..24bdd068a8 100644 --- a/cocos/rendering/post-process/passes/skin-pass.ts +++ b/cocos/rendering/post-process/passes/skin-pass.ts @@ -120,7 +120,7 @@ export class SSSSBlurData { const o = -range + i * step; const sign = o < 0.0 ? -1.0 : 1.0; // eslint-disable-next-line no-restricted-properties - this._kernel[i].w = range * sign * Math.abs(Math.pow(o, EXPONENT)) / Math.pow(range, EXPONENT); + this._kernel[i].w = range * sign * Math.abs(o ** EXPONENT) / range ** EXPONENT; } // Calculate the weights: @@ -185,9 +185,9 @@ export class SSSSBlurData { } export class SkinPass extends SettingPass { - name = 'SkinPass' + name = 'SkinPass'; effectName = 'pipeline/ssss-blur'; - outputNames = ['SSSSBlur', 'SSSSBlurDS'] + outputNames = ['SSSSBlur', 'SSSSBlurDS']; ssssBlurData = new SSSSBlurData(); private _activate = false; @@ -220,10 +220,12 @@ export class SkinPass extends SettingPass { this._buildSpecularPass(camera, ppl, inputRT!, inputDS); } - private _buildSSSSBlurPass (camera: Camera, + private _buildSSSSBlurPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string): void { + inputDS: string, + ): void { const cameraID = getCameraUniqueID(camera); const pipelineSceneData = ppl.pipelineSceneData; @@ -259,8 +261,12 @@ export class SkinPass extends SettingPass { passIdx = SSSS_BLUR_X_PASS_INDEX; const ssssblurXPassLayoutName = 'ssss-blurX'; const ssssblurXPassPassName = `ssss-blurX${cameraID}`; - this.material.setProperty('blurInfo', new Vec4(camera.fov, skin.blurRadius, - boundingBox, skin.sssIntensity), passIdx); + this.material.setProperty('blurInfo', new Vec4( + camera.fov, + skin.blurRadius, + boundingBox, + skin.sssIntensity, + ), passIdx); this.material.setProperty('kernel', this.ssssBlurData.kernel, passIdx); passContext.updatePassViewPort() .addRenderPass(ssssblurXPassLayoutName, ssssblurXPassPassName) @@ -276,8 +282,12 @@ export class SkinPass extends SettingPass { passIdx = SSSS_BLUR_Y_PASS_INDEX; const ssssblurYPassLayoutName = 'ssss-blurY'; const ssssblurYPassPassName = `ssss-blurY${cameraID}`; - this.material.setProperty('blurInfo', new Vec4(camera.fov, skin.blurRadius, - boundingBox, skin.sssIntensity), passIdx); + this.material.setProperty('blurInfo', new Vec4( + camera.fov, + skin.blurRadius, + boundingBox, + skin.sssIntensity, + ), passIdx); this.material.setProperty('kernel', this.ssssBlurData.kernel, passIdx); passContext.updatePassViewPort() .addRenderPass(ssssblurYPassLayoutName, ssssblurYPassPassName) @@ -290,10 +300,12 @@ export class SkinPass extends SettingPass { .version(); } - private _buildSpecularPass (camera: Camera, + private _buildSpecularPass ( + camera: Camera, ppl: BasicPipeline, inputRT: string, - inputDS: string): void { + inputDS: string, + ): void { const cameraID = getCameraUniqueID(camera); const layoutName = 'specular-pass'; const passName = `specular-pass${cameraID}`; @@ -323,13 +335,19 @@ export class SkinPass extends SettingPass { } pass.addQueue(QueueHint.RENDER_OPAQUE, 'default') - .addSceneOfCamera(camera, new LightInfo(), - SceneFlags.TRANSPARENT_OBJECT | SceneFlags.DEFAULT_LIGHTING | SceneFlags.PLANAR_SHADOW - | SceneFlags.CUTOUT_OBJECT | SceneFlags.DRAW_INSTANCING); + .addSceneOfCamera( + camera, + new LightInfo(), + SceneFlags.TRANSPARENT_OBJECT + | SceneFlags.CUTOUT_OBJECT, + ); pass.addQueue(QueueHint.RENDER_TRANSPARENT, 'forward-add') - .addSceneOfCamera(camera, new LightInfo(), - SceneFlags.TRANSPARENT_OBJECT | SceneFlags.DEFAULT_LIGHTING | SceneFlags.PLANAR_SHADOW - | SceneFlags.CUTOUT_OBJECT | SceneFlags.DRAW_INSTANCING); + .addSceneOfCamera( + camera, + new LightInfo(), + SceneFlags.TRANSPARENT_OBJECT + | SceneFlags.CUTOUT_OBJECT, + ); } slotName (camera: Camera, index = 0): string { diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index ab5c7bd810..a8a6e4b22d 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -173,9 +173,8 @@ enum class Feature : uint32_t { MULTIPLE_RENDER_TARGETS, BLEND_MINMAX, COMPUTE_SHADER, - // @deprecated - INPUT_ATTACHMENT_BENEFIT, + INPUT_ATTACHMENT_BENEFIT, // @deprecated SUBPASS_COLOR_INPUT, SUBPASS_DEPTH_STENCIL_INPUT, RASTERIZATION_ORDER_NOCOHERENT, @@ -474,11 +473,12 @@ CC_ENUM_BITWISE_OPERATORS(TextureUsageBit); enum class TextureFlagBit : uint32_t { NONE = 0, - GEN_MIPMAP = 0x1, // Generate mipmaps using bilinear filter - GENERAL_LAYOUT = 0x2, // @deprecated, For inout framebuffer attachments - EXTERNAL_OES = 0x4, // External oes texture - EXTERNAL_NORMAL = 0x8, // External normal texture - LAZILY_ALLOCATED = 0x10 // Try lazily allocated mode. + GEN_MIPMAP = 0x1, // Generate mipmaps using bilinear filter + GENERAL_LAYOUT = 0x2, // @deprecated, For inout framebuffer attachments + EXTERNAL_OES = 0x4, // External oes texture + EXTERNAL_NORMAL = 0x8, // External normal texture + LAZILY_ALLOCATED = 0x10, // Try lazily allocated mode. + MUTABLE_VIEW_FORMAT = 0x40, // texture view as different format }; using TextureFlags = TextureFlagBit; CC_ENUM_BITWISE_OPERATORS(TextureFlagBit); @@ -1089,6 +1089,8 @@ struct ALIGNAS(8) TextureViewInfo { uint32_t levelCount{1}; uint32_t baseLayer{0}; uint32_t layerCount{1}; + uint32_t basePlane{0}; + uint32_t planeCount{1}; #if CC_CPU_ARCH == CC_CPU_ARCH_32 uint32_t _padding{0}; #endif diff --git a/native/cocos/renderer/gfx-base/GFXTexture.cpp b/native/cocos/renderer/gfx-base/GFXTexture.cpp index 0f1a7c2c14..59432996a0 100644 --- a/native/cocos/renderer/gfx-base/GFXTexture.cpp +++ b/native/cocos/renderer/gfx-base/GFXTexture.cpp @@ -144,6 +144,8 @@ void Texture::updateTextureInfo(const SwapchainTextureInfo &info, Texture *out) out->_viewInfo.layerCount = out->_info.layerCount; out->_viewInfo.baseLevel = 0; out->_viewInfo.levelCount = out->_info.levelCount; + out->_viewInfo.basePlane = 0; + out->_viewInfo.planeCount = info.format == gfx::Format::DEPTH_STENCIL ? 2 : 1; } } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXTexture.h b/native/cocos/renderer/gfx-base/GFXTexture.h index b00defb4fc..0d29fcfc27 100644 --- a/native/cocos/renderer/gfx-base/GFXTexture.h +++ b/native/cocos/renderer/gfx-base/GFXTexture.h @@ -51,7 +51,7 @@ public: inline ccstd::hash_t getHash() const { return _hash; } // convenient getter for common usages - inline Format getFormat() const { return _info.format; } + inline Format getFormat() const { return _isTextureView ? _viewInfo.format : _info.format; } inline uint32_t getWidth() const { return _info.width; } inline uint32_t getHeight() const { return _info.height; } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index afddfc2d1a..231ed1d3b5 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -1375,16 +1375,21 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * auto &attachments = gpuRenderPass->colorAttachments; auto &drawBuffers = gpuRenderPass->drawBuffers; + bool hasDS = (gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN); gpuRenderPass->drawBuffers.resize(subPasses.size()); - gpuRenderPass->indices.resize(attachments.size(), INVALID_BINDING); + gpuRenderPass->indices.resize(attachments.size() + hasDS, INVALID_BINDING); for (uint32_t i = 0; i < subPasses.size(); ++i) { auto &sub = subPasses[i]; auto &drawBuffer = drawBuffers[i]; - std::vector visited(gpuRenderPass->colorAttachments.size()); + std::vector visited(gpuRenderPass->colorAttachments.size() + hasDS); for (auto &input : sub.inputs) { visited[input] = true; + if(input == gpuRenderPass->colorAttachments.size()) { + // ds input + continue; + } drawBuffer.emplace_back(gpuRenderPass->indices[input]); } @@ -1411,8 +1416,14 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * } } - gpuRenderPass->depthStencil = sub.depthStencil; - gpuRenderPass->depthStencilResolve = sub.depthStencilResolve; + + if (sub.depthStencil != gfx::INVALID_BINDING) { + gpuRenderPass->depthStencil = sub.depthStencil; + gpuRenderPass->indices.back() = gpuRenderPass->depthStencil; + } + if (sub.depthStencilResolve != gfx::INVALID_BINDING) { + gpuRenderPass->depthStencilResolve = sub.depthStencilResolve; + } } } diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 169767fe08..0005cf0c6b 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -156,6 +156,8 @@ struct GLES3GPUTextureView { Format format = Format::UNKNOWN; uint32_t baseLevel = 0U; uint32_t levelCount = 1U; + uint32_t basePlane = 0U; + uint32_t planeCount = 0U; }; using GLES3GPUTextureViewList = ccstd::vector; diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp b/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp index 067c503747..cd97b6fdf4 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp @@ -61,14 +61,20 @@ void updateGPUShaderSourceByRenderPass(GLES3GPUShader *gpuShader, GLES3GPURender } CC_ASSERT(subpassIndex < renderPass->subpasses.size()); - if (renderPass->subpasses[subpassIndex].inputs.empty()) { + if (renderPass->subpasses.size() <= 1) { return; } - auto &drawBuffers = renderPass->drawBuffers.at(subpassIndex); + bool dsInput{false}; + if (renderPass->depthStencil != INVALID_BINDING && !renderPass->subpasses[subpassIndex].inputs.empty()) { + const auto &inputs = renderPass->subpasses[subpassIndex].inputs; + // depth stencil input should always lies at the end of index list. + dsInput = inputs.back() == renderPass->depthStencil; + } + auto &drawBuffers = renderPass->drawBuffers.at(subpassIndex); ccstd::string::size_type offset = 0; for (uint32_t i = 0; i < drawBuffers.size(); ++i) { - const char* layoutPrefix = "layout(location = "; + const char *layoutPrefix = "layout(location = "; std::stringstream ss1; ss1 << layoutPrefix << i << ") out"; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp index 286ef62b78..2026ec3d01 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp @@ -95,6 +95,8 @@ void GLES3Texture::createTextureView() { _gpuTextureView->format = _viewInfo.format; _gpuTextureView->baseLevel = _viewInfo.baseLevel; _gpuTextureView->levelCount = _viewInfo.levelCount; + _gpuTextureView->basePlane = _viewInfo.basePlane; + _gpuTextureView->planeCount = _viewInfo.planeCount; } void GLES3Texture::doDestroy() { diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm index 84cd6f958e..eef51f0eef 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm @@ -219,7 +219,9 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb for (size_t i = 0; i < subpasses.size(); ++i) { for (size_t j = 0; j < subpasses[i].inputs.size(); ++j) { uint32_t input = subpasses[i].inputs[j]; - if(input >= colorAttachments.size()) { + if(input >= colorAttachments.size() || + colorAttachments[input].format == Format::DEPTH_STENCIL || + colorAttachments[input].format == Format::DEPTH) { continue; // depthStencil as input } if (visited[input]) @@ -237,7 +239,7 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb if(color >= colorAttachments.size()) { continue; // depthStencil as output } - if (subpasses[i].resolves.size() > j) { + if (!subpasses[i].resolves.empty() && subpasses[i].resolves[j] != INVALID_BINDING) { uint32_t resolve = subpasses[i].resolves[j]; auto *resolveTex = static_cast(colorTextures[resolve]); mtlRenderPassDescriptor.colorAttachments[color].resolveTexture = resolveTex->getMTLTexture(); @@ -245,6 +247,8 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb mtlRenderPassDescriptor.colorAttachments[color].resolveSlice = 0; mtlRenderPassDescriptor.colorAttachments[color].resolveDepthPlane = 0; mtlRenderPassDescriptor.colorAttachments[color].storeAction = MTLStoreActionMultisampleResolve; + } else { + mtlRenderPassDescriptor.colorAttachments[color].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[color].storeOp) : MTLStoreActionStore; } if (visited[color]) continue; @@ -261,7 +265,6 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb } else { mtlRenderPassDescriptor.colorAttachments[color].loadAction = mu::toMTLLoadAction(colorAttachments[color].loadOp); } - mtlRenderPassDescriptor.colorAttachments[color].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[color].storeOp) : MTLStoreActionStore; visited[color] = true; _colorAppearedBefore.set(color); } @@ -386,7 +389,7 @@ void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDe } if (subpass.depthStencilResolve != INVALID_BINDING) { - descriptor.depthAttachment.resolveTexture = static_cast(curFBO->getDepthStencilTexture())->getMTLTexture(); + descriptor.depthAttachment.resolveTexture = static_cast(curFBO->getDepthStencilResolveTexture())->getMTLTexture(); descriptor.depthAttachment.resolveLevel = 0; descriptor.depthAttachment.resolveSlice = 0; descriptor.depthAttachment.resolveDepthPlane = 0; diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index 186a152bcd..097d14dd0b 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -135,7 +135,7 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; _features[toNumber(Feature::COMPUTE_SHADER)] = true; _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = true; - _features[toNumber(Feature::SUBPASS_COLOR_INPUT)] = false; + _features[toNumber(Feature::SUBPASS_COLOR_INPUT)] = true; _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = false; _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; diff --git a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm index 447ca460e1..5eb009affe 100644 --- a/native/cocos/renderer/gfx-metal/MTLPipelineState.mm +++ b/native/cocos/renderer/gfx-metal/MTLPipelineState.mm @@ -304,10 +304,11 @@ bool CCMTLPipelineState::setMTLFunctionsAndFormats(MTLRenderPipelineDescriptor * depthStencilTexIndex = subpass.depthStencil; for (size_t i = 0; i < subpass.inputs.size(); ++i) { uint32_t input = subpass.inputs[i]; + if (inputs.find(input) == inputs.end()) { inputs.insert(input); - if(input >= colorAttachments.size()) { - depthStencilTexIndex = input; + if(_renderPass->getColorAttachments()[input].format == Format::DEPTH || + _renderPass->getColorAttachments()[input].format == Format::DEPTH_STENCIL) { continue; } mtlPixelFormat = mu::toMTLPixelFormat(colorAttachments[input].format); diff --git a/native/cocos/renderer/gfx-metal/MTLRenderPass.mm b/native/cocos/renderer/gfx-metal/MTLRenderPass.mm index 06c177998e..51b98ea9f3 100644 --- a/native/cocos/renderer/gfx-metal/MTLRenderPass.mm +++ b/native/cocos/renderer/gfx-metal/MTLRenderPass.mm @@ -93,7 +93,13 @@ void CCMTLRenderPass::doInit(const RenderPassInfo& info) { auto &drawBuffer = _drawBuffers[i]; for (auto &input : subPass.inputs) { - auto &index = _colorIndices[input]; + auto index = INVALID_BINDING; + if(input < _colorAttachments.size()) { + index = _colorIndices[input]; + } else { + // ds input + index = input; + } CC_ASSERT(index != INVALID_BINDING); // input should not appear before color or depthstencil. readBuffer.emplace_back(index); } diff --git a/native/cocos/renderer/gfx-metal/MTLShader.mm b/native/cocos/renderer/gfx-metal/MTLShader.mm index 3a81909b73..24b7e35b6a 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.mm +++ b/native/cocos/renderer/gfx-metal/MTLShader.mm @@ -73,9 +73,9 @@ void CCMTLShader::doInit(const ShaderInfo& info) { _specializedFragFuncs = [[NSMutableDictionary alloc] init]; // spirv-cross for input attachment needs RenderPass to build [[color(index)]], // build gpu shader only when there is no subPass input. - if (!checkInputAttachment(info)) { - gpuShader(nullptr, 0); - } +// if (!checkInputAttachment(info)) { +// gpuShader(nullptr, 0); +// } } void CCMTLShader::doDestroy() { @@ -169,7 +169,7 @@ bool CCMTLShader::createMTLFunction(const ShaderStage& stage, CCMTLRenderPass *r const auto &drawBuffer = renderPass != nullptr ? renderPass->getDrawBuffer(subPass) : emptyBuffer; const auto &readBuffer = renderPass != nullptr ? renderPass->getReadBuffer(subPass) : emptyBuffer; ccstd::string mtlShaderSrc = mu::spirv2MSL(spirv->getOutputData(), spirv->getOutputSize() / unitSize, stage.stage, - _gpuShader, drawBuffer, readBuffer); + _gpuShader, renderPass, subPass); NSString* shader = [NSString stringWithUTF8String:mtlShaderSrc.c_str()]; NSError* error = nil; diff --git a/native/cocos/renderer/gfx-metal/MTLTexture.mm b/native/cocos/renderer/gfx-metal/MTLTexture.mm index 96d7b9a1bc..2359cd9969 100644 --- a/native/cocos/renderer/gfx-metal/MTLTexture.mm +++ b/native/cocos/renderer/gfx-metal/MTLTexture.mm @@ -162,8 +162,14 @@ void CCMTLTexture::doInit(const TextureViewInfo &info) { } _convertedFormat = mu::convertGFXPixelFormat(_viewInfo.format); auto mtlTextureType = mu::toMTLTextureType(_viewInfo.type); + + MTLPixelFormat format = mu::toMTLPixelFormat(_convertedFormat); + if(_viewInfo.format == Format::DEPTH_STENCIL) { + format = _viewInfo.basePlane == 0 ? mu::toMTLPixelFormat(_viewInfo.texture->getFormat()) : MTLPixelFormatX32_Stencil8; + } + _mtlTextureView = [static_cast(_viewInfo.texture)->_mtlTexture - newTextureViewWithPixelFormat:mu::toMTLPixelFormat(_convertedFormat) + newTextureViewWithPixelFormat:format textureType:mtlTextureType levels:NSMakeRange(_viewInfo.baseLevel, _viewInfo.levelCount) slices:NSMakeRange(_viewInfo.baseLayer, _viewInfo.layerCount)]; @@ -220,6 +226,9 @@ bool CCMTLTexture::createMTLTexture() { return false; descriptor.usage = mu::toMTLTextureUsage(_info.usage); + if(hasFlag(_info.flags, TextureFlags::MUTABLE_VIEW_FORMAT)) { + descriptor.usage |= MTLTextureUsagePixelFormatView; + } descriptor.sampleCount = mu::toMTLSampleCount(_info.samples); descriptor.textureType = descriptor.sampleCount > 1 ? MTLTextureType2DMultisample : mu::toMTLTextureType(_info.type); descriptor.mipmapLevelCount = _info.levelCount; diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.h b/native/cocos/renderer/gfx-metal/MTLUtils.h index f055f6de26..18f597b3f3 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.h +++ b/native/cocos/renderer/gfx-metal/MTLUtils.h @@ -71,8 +71,7 @@ MTLSamplerAddressMode toMTLSamplerAddressMode(Address); int toMTLSamplerBorderColor(const Color &); MTLSamplerMinMagFilter toMTLSamplerMinMagFilter(Filter); MTLSamplerMipFilter toMTLSamplerMipFilter(Filter); -ccstd::string spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader, - const ccstd::vector &drawBuffer, const ccstd::vector &readBuffer); +ccstd::string spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader, RenderPass* renderpass, uint32_t subpassIndex); const uint8_t *convertRGB8ToRGBA8(const uint8_t *source, uint32_t length); const uint8_t *convertRGB32FToRGBA32F(const uint8_t *source, uint32_t length); NSUInteger highestSupportedFeatureSet(id device); diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index d2864e9b91..cf4f3fc7a8 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -35,6 +35,7 @@ #include "spirv_cross/spirv_msl.hpp" #include "TargetConditionals.h" #include "base/Log.h" +#include namespace cc { namespace gfx { @@ -918,8 +919,8 @@ bool mu::isFramebufferFetchSupported() { ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader, - const ccstd::vector &drawBuffer, - const ccstd::vector &readBuffer) { + RenderPass* renderPass, + uint32_t subpassIndex) { CCMTLDevice *device = CCMTLDevice::getInstance(); spirv_cross::CompilerMSL msl(ir, word_count); @@ -1057,18 +1058,24 @@ ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, } if (executionModel == spv::ExecutionModelFragment) { + auto* ccRenderPass = static_cast(renderPass); + const auto& readBuffer = ccRenderPass ? ccRenderPass->getReadBuffer(subpassIndex) : ccstd::vector{}; if (!resources.subpass_inputs.empty()) { - gpuShader->inputs.resize(resources.subpass_inputs.size()); +// gpuShader->inputs.resize(resources.subpass_inputs.size()); for (size_t i = 0; i < resources.subpass_inputs.size(); i++) { const auto &attachment = resources.subpass_inputs[i]; - gpuShader->inputs[i].name = attachment.name; - auto id = msl.get_decoration(attachment.id, spv::DecorationInputAttachmentIndex); - auto loc = id >= readBuffer.size() ? id : readBuffer[id]; + auto inputIndex = msl.get_decoration(attachment.id, spv::DecorationInputAttachmentIndex); + auto loc = inputIndex >= readBuffer.size() ? inputIndex : readBuffer[inputIndex]; + // depth stencil input not support in metal + CC_ASSERT(loc != renderPass->getColorAttachments().size()); + auto& input = gpuShader->inputs.emplace_back(); + input.name = attachment.name; msl.set_decoration(attachment.id, spv::DecorationInputAttachmentIndex, loc); } } gpuShader->outputs.resize(resources.stage_outputs.size()); + const auto& drawBuffer = renderPass ? ccRenderPass->getDrawBuffer(subpassIndex) : ccstd::vector{}; for (size_t i = 0; i < resources.stage_outputs.size(); i++) { const auto &stageOutput = resources.stage_outputs[i]; auto set = msl.get_decoration(stageOutput.id, spv::DecorationDescriptorSet); @@ -1096,6 +1103,7 @@ ccstd::string mu::spirv2MSL(const uint32_t *ir, size_t word_count, CC_LOG_ERROR("Compile to MSL failed."); CC_LOG_ERROR("%s", output.c_str()); } + return output; } diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index cf09829838..0468624dd5 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -196,15 +196,31 @@ void cmdFuncCCVKCreateTextureView(CCVKDevice *device, CCVKGPUTextureView *gpuTex if (!gpuTextureView->gpuTexture) return; auto createFn = [device, gpuTextureView](VkImage vkImage, VkImageView *pVkImageView) { + auto format = gpuTextureView->format; + auto mapAspect = [](CCVKGPUTextureView *gpuTextureView) { + auto aspectMask = gpuTextureView->gpuTexture->aspectMask; + if (gpuTextureView->gpuTexture->format == Format::DEPTH_STENCIL) { + uint32_t planeIndex = gpuTextureView->basePlane; + uint32_t planeCount = gpuTextureView->planeCount; + aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT << planeIndex; + CC_ASSERT(planeIndex + planeCount <= 2); + CC_ASSERT(planeCount > 0); + while (planeCount && --planeCount) { + aspectMask |= (aspectMask << 1); + } + } + return aspectMask; + }; + VkImageViewCreateInfo createInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; createInfo.image = vkImage; createInfo.viewType = mapVkImageViewType(gpuTextureView->type); - createInfo.format = mapVkFormat(gpuTextureView->format, device->gpuDevice()); - createInfo.subresourceRange.aspectMask = gpuTextureView->gpuTexture->aspectMask; + createInfo.subresourceRange.aspectMask = mapAspect(gpuTextureView); createInfo.subresourceRange.baseMipLevel = gpuTextureView->baseLevel; createInfo.subresourceRange.levelCount = gpuTextureView->levelCount; createInfo.subresourceRange.baseArrayLayer = gpuTextureView->baseLayer; createInfo.subresourceRange.layerCount = gpuTextureView->layerCount; + createInfo.format = mapVkFormat(format, device->gpuDevice()); VK_CHECK(vkCreateImageView(device->gpuDevice()->vkDevice, &createInfo, nullptr, pVkImageView)); }; @@ -444,13 +460,13 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende for (uint32_t input : subpassInfo.inputs) { bool appearsInOutput = std::find(subpassInfo.colors.begin(), subpassInfo.colors.end(), input) != subpassInfo.colors.end(); + VkImageLayout layout = appearsInOutput ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + VkImageAspectFlags aspectFlag = VK_IMAGE_ASPECT_COLOR_BIT; if (input == gpuRenderPass->colorAttachments.size()) { - VkImageLayout layout = subpassInfo.depthStencil != INVALID_BINDING ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; - attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, input, layout, VK_IMAGE_ASPECT_DEPTH_BIT}); - } else { - VkImageLayout layout = appearsInOutput ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, input, layout, VK_IMAGE_ASPECT_COLOR_BIT}); + layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; + aspectFlag = VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_DEPTH_BIT; } + attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, input, layout, aspectFlag}); } for (uint32_t color : subpassInfo.colors) { const VkAttachmentDescription2 &attachment = attachmentDescriptions[color]; @@ -518,7 +534,6 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende offset += subpassInfo.resolves.size(); } } - if (!subpassInfo.preserves.empty()) { desc.preserveAttachmentCount = utils::toUint(subpassInfo.preserves.size()); desc.pPreserveAttachments = subpassInfo.preserves.data(); diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index cb386223c6..edb7dfc6f4 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -188,6 +188,8 @@ struct CCVKGPUTextureView : public CCVKGPUDeviceObject { uint32_t levelCount = 1U; uint32_t baseLayer = 0U; uint32_t layerCount = 1U; + uint32_t basePlane = 0U; + uint32_t planeCount = 1U; ccstd::vector swapchainVkImageViews; diff --git a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp index 5f0a3e85b4..c9b74b170b 100644 --- a/native/cocos/renderer/gfx-vulkan/VKTexture.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKTexture.cpp @@ -43,6 +43,7 @@ CCVKTexture::~CCVKTexture() { void CCVKTexture::doInit(const TextureInfo & /*info*/) { createTexture(_info.width, _info.height, _size); + _viewInfo.planeCount = _info.format == Format::DEPTH_STENCIL ? 2 : 1; createTextureView(); } @@ -71,6 +72,7 @@ void CCVKTexture::createTexture(uint32_t width, uint32_t height, uint32_t size, _gpuTexture->mipLevels = _info.levelCount; _gpuTexture->samples = _info.samples; _gpuTexture->flags = _info.flags; + bool hasExternalFlag = hasFlag(_gpuTexture->flags, TextureFlagBit::EXTERNAL_NORMAL); if (hasExternalFlag) { _gpuTexture->externalVKImage = reinterpret_cast(_info.externalRes); @@ -90,6 +92,8 @@ void CCVKTexture::createTextureView(bool initGPUTextureView) { _gpuTextureView->levelCount = _viewInfo.levelCount; _gpuTextureView->baseLayer = _viewInfo.baseLayer; _gpuTextureView->layerCount = _viewInfo.layerCount; + _gpuTextureView->basePlane = _viewInfo.basePlane; + _gpuTextureView->planeCount = _viewInfo.planeCount; if (initGPUTextureView) { _gpuTextureView->init(); diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h b/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h index 4050a7fbb5..c12b37f57b 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherGraphs.h @@ -1,824 +1,962 @@ -/**************************************************************************** - Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - 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 - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -/** - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - * The following section is auto-generated. - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - */ -// clang-format off -#pragma once -#include -#include -#include "cocos/renderer/pipeline/custom/FGDispatcherTypes.h" -#include "cocos/renderer/pipeline/custom/details/GraphImpl.h" -#include "cocos/renderer/pipeline/custom/details/Overload.h" -#include "cocos/renderer/pipeline/custom/details/PathUtils.h" - -namespace cc { - -namespace render { - -// IncidenceGraph -inline ResourceAccessGraph::vertex_descriptor -source(const ResourceAccessGraph::edge_descriptor& e, const ResourceAccessGraph& /*g*/) noexcept { - return e.source; -} - -inline ResourceAccessGraph::vertex_descriptor -target(const ResourceAccessGraph::edge_descriptor& e, const ResourceAccessGraph& /*g*/) noexcept { - return e.target; -} - -inline std::pair -out_edges(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT - return std::make_pair( - ResourceAccessGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), - ResourceAccessGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); -} - -inline ResourceAccessGraph::degree_size_type -out_degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getOutEdgeList(u).size()); -} - -inline std::pair -edge(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph::vertex_descriptor v, const ResourceAccessGraph& g) noexcept { - const auto& outEdgeList = g.getOutEdgeList(u); - auto iter = std::find(outEdgeList.begin(), outEdgeList.end(), ResourceAccessGraph::OutEdge(v)); - bool hasEdge = (iter != outEdgeList.end()); - return {ResourceAccessGraph::edge_descriptor(u, v), hasEdge}; -} - -// BidirectionalGraph(Directed) -inline std::pair -in_edges(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT - return std::make_pair( - ResourceAccessGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), - ResourceAccessGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); -} - -inline ResourceAccessGraph::degree_size_type -in_degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getInEdgeList(u).size()); -} - -inline ResourceAccessGraph::degree_size_type -degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { - return in_degree(u, g) + out_degree(u, g); -} - -// AdjacencyGraph -inline std::pair -adjacent_vertices(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT - auto edges = out_edges(u, g); - return std::make_pair(ResourceAccessGraph::adjacency_iterator(edges.first, &g), ResourceAccessGraph::adjacency_iterator(edges.second, &g)); -} - -// VertexListGraph -inline std::pair -vertices(const ResourceAccessGraph& g) noexcept { - return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); -} - -inline ResourceAccessGraph::vertices_size_type -num_vertices(const ResourceAccessGraph& g) noexcept { // NOLINT - return gsl::narrow_cast(g.getVertexList().size()); -} - -// EdgeListGraph -inline std::pair -edges(const ResourceAccessGraph& g0) noexcept { - auto& g = const_cast(g0); - return std::make_pair( - ResourceAccessGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().begin(), g.getVertexList().end(), g), - ResourceAccessGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().end(), g.getVertexList().end(), g)); -} - -inline ResourceAccessGraph::edges_size_type -num_edges(const ResourceAccessGraph& g) noexcept { // NOLINT - ResourceAccessGraph::edges_size_type numEdges = 0; - - auto range = vertices(g); - for (auto iter = range.first; iter != range.second; ++iter) { - numEdges += out_degree(*iter, g); - } - return numEdges; -} - -// MutableGraph(Edge) -inline std::pair -add_edge( // NOLINT - ResourceAccessGraph::vertex_descriptor u, - ResourceAccessGraph::vertex_descriptor v, ResourceAccessGraph& g) { - auto& outEdgeList = g.getOutEdgeList(u); - outEdgeList.emplace_back(v); - - auto& inEdgeList = g.getInEdgeList(v); - inEdgeList.emplace_back(u); - - return std::make_pair(ResourceAccessGraph::edge_descriptor(u, v), true); -} - -inline void remove_edge(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph::vertex_descriptor v, ResourceAccessGraph& g) noexcept { // NOLINT - auto& s = g._vertices[u]; - auto& t = g._vertices[v]; - s.outEdges.erase(std::remove(s.outEdges.begin(), s.outEdges.end(), ResourceAccessGraph::OutEdge(v)), s.outEdges.end()); - t.inEdges.erase(std::remove(t.inEdges.begin(), t.inEdges.end(), ResourceAccessGraph::InEdge(u)), t.inEdges.end()); -} - -inline void remove_edge(ResourceAccessGraph::out_edge_iterator outIter, ResourceAccessGraph& 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(), ResourceAccessGraph::InEdge(u)); - CC_EXPECTS(inIter != t.inEdges.end()); - t.inEdges.erase(inIter); - s.outEdges.erase(outIter.base()); -} - -inline void remove_edge(ResourceAccessGraph::edge_descriptor e, ResourceAccessGraph& 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(), ResourceAccessGraph::OutEdge(v)); - CC_EXPECTS(outIter != s.outEdges.end()); - remove_edge(ResourceAccessGraph::out_edge_iterator(outIter, u), g); -} - -// MutableGraph(Vertex) -inline void clear_out_edges(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT - // Bidirectional (OutEdges) - auto& outEdgeList = g.getOutEdgeList(u); - auto outEnd = outEdgeList.end(); - for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { - auto& inEdgeList = g.getInEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); - } - outEdgeList.clear(); -} - -inline void clear_in_edges(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT - // Bidirectional (InEdges) - auto& inEdgeList = g.getInEdgeList(u); - auto inEnd = inEdgeList.end(); - for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { - auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); - } - inEdgeList.clear(); -} - -inline void clear_vertex(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT - clear_out_edges(u, g); - clear_in_edges(u, g); -} - -inline void remove_vertex(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT - { // UuidGraph - const auto& key = g.passID[u]; - auto num = g.passIndex.erase(key); - CC_ENSURES(num == 1); - for (auto&& pair : g.passIndex) { - auto& v = pair.second; - if (v > u) { - --v; - } - } - } - impl::removeVectorVertex(const_cast(g), u, ResourceAccessGraph::directed_category{}); - - // remove components - g.passID.erase(g.passID.begin() + static_cast(u)); - g.access.erase(g.access.begin() + static_cast(u)); -} - -// MutablePropertyGraph(Vertex) -template -inline ResourceAccessGraph::vertex_descriptor -addVertex(Component0&& c0, Component1&& c1, ResourceAccessGraph& g) { - auto v = gsl::narrow_cast(g._vertices.size()); - - g._vertices.emplace_back(); - - { // UuidGraph - const auto& uuid = c0; - auto res = g.passIndex.emplace(uuid, v); - CC_ENSURES(res.second); - } - g.passID.emplace_back(std::forward(c0)); - g.access.emplace_back(std::forward(c1)); - - return v; -} - -template -inline ResourceAccessGraph::vertex_descriptor -addVertex(std::piecewise_construct_t /*tag*/, Component0&& c0, Component1&& c1, ResourceAccessGraph& g) { - auto v = gsl::narrow_cast(g._vertices.size()); - - g._vertices.emplace_back(); - - { // UuidGraph - std::apply( - [&](const auto&... args) { - auto res = g.passIndex.emplace(std::piecewise_construct, std::forward_as_tuple(args...), std::forward_as_tuple(v)); - CC_ENSURES(res.second); - }, - c0); - } - - std::apply( - [&](auto&&... args) { - g.passID.emplace_back(std::forward(args)...); - }, - std::forward(c0)); - - std::apply( - [&](auto&&... args) { - g.access.emplace_back(std::forward(args)...); - }, - std::forward(c1)); - - return v; -} - -// IncidenceGraph -inline RelationGraph::vertex_descriptor -source(const RelationGraph::edge_descriptor& e, const RelationGraph& /*g*/) noexcept { - return e.source; -} - -inline RelationGraph::vertex_descriptor -target(const RelationGraph::edge_descriptor& e, const RelationGraph& /*g*/) noexcept { - return e.target; -} - -inline std::pair -out_edges(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT - return std::make_pair( - RelationGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), - RelationGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); -} - -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(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(), RelationGraph::OutEdge(v)); - bool hasEdge = (iter != outEdgeList.end()); - return {RelationGraph::edge_descriptor(u, v), hasEdge}; -} - -// BidirectionalGraph(Directed) -inline std::pair -in_edges(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT - return std::make_pair( - RelationGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), - RelationGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); -} - -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 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(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT - auto edges = out_edges(u, g); - return std::make_pair(RelationGraph::adjacency_iterator(edges.first, &g), RelationGraph::adjacency_iterator(edges.second, &g)); -} - -// VertexListGraph -inline std::pair -vertices(const RelationGraph& g) noexcept { - return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); -} - -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 RelationGraph& g0) noexcept { - auto& g = const_cast(g0); - return std::make_pair( - 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 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) { - numEdges += out_degree(*iter, g); - } - return numEdges; -} - -// MutableGraph(Edge) -inline std::pair -add_edge( // NOLINT - 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(RelationGraph::edge_descriptor(u, v), true); -} - -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(), 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(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(), RelationGraph::InEdge(u)); - CC_EXPECTS(inIter != t.inEdges.end()); - t.inEdges.erase(inIter); - s.outEdges.erase(outIter.base()); -} - -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(), RelationGraph::OutEdge(v)); - CC_EXPECTS(outIter != s.outEdges.end()); - remove_edge(RelationGraph::out_edge_iterator(outIter, u), g); -} - -// MutableGraph(Vertex) -inline void clear_out_edges(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT - // Bidirectional (OutEdges) - auto& outEdgeList = g.getOutEdgeList(u); - auto outEnd = outEdgeList.end(); - for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { - auto& inEdgeList = g.getInEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); - } - outEdgeList.clear(); -} - -inline void clear_in_edges(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT - // Bidirectional (InEdges) - auto& inEdgeList = g.getInEdgeList(u); - auto inEnd = inEdgeList.end(); - for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { - auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); - // eraseFromIncidenceList - impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { - return e.get_target() == u; - }); - } - inEdgeList.clear(); -} - -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(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() + static_cast(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 - -} // namespace cc - -namespace boost { - -// Vertex Index -template <> -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::ResourceAccessGraph, - const ccstd::pmr::vector, - cc::render::RenderGraph::vertex_descriptor, - const cc::render::RenderGraph::vertex_descriptor&>; - using type = cc::render::impl::VectorVertexComponentPropertyMap< - lvalue_property_map_tag, - cc::render::ResourceAccessGraph, - ccstd::pmr::vector, - cc::render::RenderGraph::vertex_descriptor, - cc::render::RenderGraph::vertex_descriptor&>; -}; - -// Vertex Component -template <> -struct property_map { - using const_type = cc::render::impl::VectorVertexComponentPropertyMap< - lvalue_property_map_tag, - const cc::render::ResourceAccessGraph, - const ccstd::pmr::vector, - cc::render::ResourceAccessNode, - const cc::render::ResourceAccessNode&>; - using type = cc::render::impl::VectorVertexComponentPropertyMap< - lvalue_property_map_tag, - cc::render::ResourceAccessGraph, - ccstd::pmr::vector, - cc::render::ResourceAccessNode, - cc::render::ResourceAccessNode&>; -}; - -// Vertex ComponentMember -template -struct property_map { - using const_type = cc::render::impl::VectorVertexComponentMemberPropertyMap< - lvalue_property_map_tag, - const cc::render::ResourceAccessGraph, - const ccstd::pmr::vector, - T, - const T&, - T cc::render::ResourceAccessNode::*>; - using type = cc::render::impl::VectorVertexComponentMemberPropertyMap< - lvalue_property_map_tag, - cc::render::ResourceAccessGraph, - ccstd::pmr::vector, - T, - T&, - T cc::render::ResourceAccessNode::*>; -}; - -// Vertex Index -template <> -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 { - -namespace render { - -// Vertex Index -inline boost::property_map::const_type -get(boost::vertex_index_t /*tag*/, const ResourceAccessGraph& /*g*/) noexcept { - return {}; -} - -inline boost::property_map::type -get(boost::vertex_index_t /*tag*/, ResourceAccessGraph& /*g*/) noexcept { - return {}; -} - -inline impl::ColorMap -get(ccstd::pmr::vector& colors, const ResourceAccessGraph& /*g*/) noexcept { - return {colors}; -} - -// Vertex Component -inline typename boost::property_map::const_type -get(ResourceAccessGraph::PassIDTag /*tag*/, const ResourceAccessGraph& g) noexcept { - return {g.passID}; -} - -inline typename boost::property_map::type -get(ResourceAccessGraph::PassIDTag /*tag*/, ResourceAccessGraph& g) noexcept { - return {g.passID}; -} - -// Vertex Component -inline typename boost::property_map::const_type -get(ResourceAccessGraph::AccessNodeTag /*tag*/, const ResourceAccessGraph& g) noexcept { - return {g.access}; -} - -inline typename boost::property_map::type -get(ResourceAccessGraph::AccessNodeTag /*tag*/, ResourceAccessGraph& g) noexcept { - return {g.access}; -} - -// Vertex ComponentMember -template -inline typename boost::property_map::const_type -get(T ResourceAccessNode::*memberPointer, const ResourceAccessGraph& g) noexcept { - return {g.access, memberPointer}; -} - -template -inline typename boost::property_map::type -get(T ResourceAccessNode::*memberPointer, ResourceAccessGraph& g) noexcept { - return {g.access, memberPointer}; -} - -// Vertex Constant Getter -template -inline decltype(auto) -get(Tag tag, const ResourceAccessGraph& g, ResourceAccessGraph::vertex_descriptor v) noexcept { - return get(get(tag, g), v); -} - -// Vertex Mutable Getter -template -inline decltype(auto) -get(Tag tag, ResourceAccessGraph& g, ResourceAccessGraph::vertex_descriptor v) noexcept { - return get(get(tag, g), v); -} - -// Vertex Setter -template -inline void put( - Tag tag, ResourceAccessGraph& g, - ResourceAccessGraph::vertex_descriptor v, - Args&&... args) { - put(get(tag, g), v, std::forward(args)...); -} - -// UuidGraph -inline ResourceAccessGraph::vertex_descriptor -vertex(const RenderGraph::vertex_descriptor& key, const ResourceAccessGraph& g) { - return g.passIndex.at(key); -} - -template -inline ResourceAccessGraph::vertex_descriptor -vertex(const KeyLike& key, const ResourceAccessGraph& g) { - const auto& index = g.passIndex; - auto iter = index.find(key); - if (iter == index.end()) { - throw std::out_of_range("at(key, ResourceAccessGraph) out of range"); - } - return iter->second; -} - -template -inline ResourceAccessGraph::vertex_descriptor -findVertex(const KeyLike& key, const ResourceAccessGraph& g) noexcept { - const auto& index = g.passIndex; - auto iter = index.find(key); - if (iter == index.end()) { - return ResourceAccessGraph::null_vertex(); - } - return iter->second; -} - -inline bool -contains(const RenderGraph::vertex_descriptor& key, const ResourceAccessGraph& g) noexcept { - auto iter = g.passIndex.find(key); - return iter != g.passIndex.end(); -} - -template -inline bool -contains(const KeyLike& key, const ResourceAccessGraph& g) noexcept { - auto iter = g.passIndex.find(key); - return iter != g.passIndex.end(); -} - -// MutableGraph(Vertex) -inline ResourceAccessGraph::vertex_descriptor -add_vertex(ResourceAccessGraph& g, const RenderGraph::vertex_descriptor& key) { // NOLINT - return addVertex( - std::piecewise_construct, - std::forward_as_tuple(key), // passID - std::forward_as_tuple(), // access - g); -} - -// Vertex Index -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*/, RelationGraph& /*g*/) noexcept { - return {}; -} - -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 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 - -} // namespace cc - -// clang-format on +/**************************************************************************** + Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + 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 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +/** + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + * The following section is auto-generated. + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + */ +// clang-format off +#pragma once +#include +#include +#include "cocos/renderer/pipeline/custom/FGDispatcherTypes.h" +#include "cocos/renderer/pipeline/custom/details/GraphImpl.h" +#include "cocos/renderer/pipeline/custom/details/Overload.h" +#include "cocos/renderer/pipeline/custom/details/PathUtils.h" + +namespace cc { + +namespace render { + +// IncidenceGraph +inline ResourceAccessGraph::vertex_descriptor +source(const ResourceAccessGraph::edge_descriptor& e, const ResourceAccessGraph& /*g*/) noexcept { + return e.source; +} + +inline ResourceAccessGraph::vertex_descriptor +target(const ResourceAccessGraph::edge_descriptor& e, const ResourceAccessGraph& /*g*/) noexcept { + return e.target; +} + +inline std::pair +out_edges(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT + return std::make_pair( + ResourceAccessGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), + ResourceAccessGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); +} + +inline ResourceAccessGraph::degree_size_type +out_degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getOutEdgeList(u).size()); +} + +inline std::pair +edge(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph::vertex_descriptor v, const ResourceAccessGraph& g) noexcept { + const auto& outEdgeList = g.getOutEdgeList(u); + auto iter = std::find(outEdgeList.begin(), outEdgeList.end(), ResourceAccessGraph::OutEdge(v)); + bool hasEdge = (iter != outEdgeList.end()); + return {ResourceAccessGraph::edge_descriptor(u, v), hasEdge}; +} + +// BidirectionalGraph(Directed) +inline std::pair +in_edges(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT + return std::make_pair( + ResourceAccessGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), + ResourceAccessGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); +} + +inline ResourceAccessGraph::degree_size_type +in_degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getInEdgeList(u).size()); +} + +inline ResourceAccessGraph::degree_size_type +degree(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { + return in_degree(u, g) + out_degree(u, g); +} + +// AdjacencyGraph +inline std::pair +adjacent_vertices(ResourceAccessGraph::vertex_descriptor u, const ResourceAccessGraph& g) noexcept { // NOLINT + auto edges = out_edges(u, g); + return std::make_pair(ResourceAccessGraph::adjacency_iterator(edges.first, &g), ResourceAccessGraph::adjacency_iterator(edges.second, &g)); +} + +// VertexListGraph +inline std::pair +vertices(const ResourceAccessGraph& g) noexcept { + return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); +} + +inline ResourceAccessGraph::vertices_size_type +num_vertices(const ResourceAccessGraph& g) noexcept { // NOLINT + return gsl::narrow_cast(g.getVertexList().size()); +} + +// EdgeListGraph +inline std::pair +edges(const ResourceAccessGraph& g0) noexcept { + auto& g = const_cast(g0); + return std::make_pair( + ResourceAccessGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().begin(), g.getVertexList().end(), g), + ResourceAccessGraph::edge_iterator(g.getVertexList().begin(), g.getVertexList().end(), g.getVertexList().end(), g)); +} + +inline ResourceAccessGraph::edges_size_type +num_edges(const ResourceAccessGraph& g) noexcept { // NOLINT + ResourceAccessGraph::edges_size_type numEdges = 0; + + auto range = vertices(g); + for (auto iter = range.first; iter != range.second; ++iter) { + numEdges += out_degree(*iter, g); + } + return numEdges; +} + +// MutableGraph(Edge) +inline std::pair +add_edge( // NOLINT + ResourceAccessGraph::vertex_descriptor u, + ResourceAccessGraph::vertex_descriptor v, ResourceAccessGraph& g) { + auto& outEdgeList = g.getOutEdgeList(u); + outEdgeList.emplace_back(v); + + auto& inEdgeList = g.getInEdgeList(v); + inEdgeList.emplace_back(u); + + return std::make_pair(ResourceAccessGraph::edge_descriptor(u, v), true); +} + +inline void remove_edge(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph::vertex_descriptor v, ResourceAccessGraph& g) noexcept { // NOLINT + auto& s = g._vertices[u]; + auto& t = g._vertices[v]; + s.outEdges.erase(std::remove(s.outEdges.begin(), s.outEdges.end(), ResourceAccessGraph::OutEdge(v)), s.outEdges.end()); + t.inEdges.erase(std::remove(t.inEdges.begin(), t.inEdges.end(), ResourceAccessGraph::InEdge(u)), t.inEdges.end()); +} + +inline void remove_edge(ResourceAccessGraph::out_edge_iterator outIter, ResourceAccessGraph& 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(), ResourceAccessGraph::InEdge(u)); + CC_EXPECTS(inIter != t.inEdges.end()); + t.inEdges.erase(inIter); + s.outEdges.erase(outIter.base()); +} + +inline void remove_edge(ResourceAccessGraph::edge_descriptor e, ResourceAccessGraph& 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(), ResourceAccessGraph::OutEdge(v)); + CC_EXPECTS(outIter != s.outEdges.end()); + remove_edge(ResourceAccessGraph::out_edge_iterator(outIter, u), g); +} + +// MutableGraph(Vertex) +inline void clear_out_edges(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT + // Bidirectional (OutEdges) + auto& outEdgeList = g.getOutEdgeList(u); + auto outEnd = outEdgeList.end(); + for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { + auto& inEdgeList = g.getInEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + outEdgeList.clear(); +} + +inline void clear_in_edges(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT + // Bidirectional (InEdges) + auto& inEdgeList = g.getInEdgeList(u); + auto inEnd = inEdgeList.end(); + for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { + auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + inEdgeList.clear(); +} + +inline void clear_vertex(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT + clear_out_edges(u, g); + clear_in_edges(u, g); +} + +inline void remove_vertex(ResourceAccessGraph::vertex_descriptor u, ResourceAccessGraph& g) noexcept { // NOLINT + { // UuidGraph + const auto& key = g.passID[u]; + auto num = g.passIndex.erase(key); + CC_ENSURES(num == 1); + for (auto&& pair : g.passIndex) { + auto& v = pair.second; + if (v > u) { + --v; + } + } + } + impl::removeVectorVertex(const_cast(g), u, ResourceAccessGraph::directed_category{}); + + // remove components + g.passID.erase(g.passID.begin() + static_cast(u)); + g.passResource.erase(g.passResource.begin() + static_cast(u)); + g.rpInfo.erase(g.rpInfo.begin() + static_cast(u)); + g.barrier.erase(g.barrier.begin() + static_cast(u)); +} + +// MutablePropertyGraph(Vertex) +template +inline ResourceAccessGraph::vertex_descriptor +addVertex(Component0&& c0, Component1&& c1, Component2&& c2, Component3&& c3, ResourceAccessGraph& g) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + + { // UuidGraph + const auto& uuid = c0; + auto res = g.passIndex.emplace(uuid, v); + CC_ENSURES(res.second); + } + g.passID.emplace_back(std::forward(c0)); + g.passResource.emplace_back(std::forward(c1)); + g.rpInfo.emplace_back(std::forward(c2)); + g.barrier.emplace_back(std::forward(c3)); + + return v; +} + +template +inline ResourceAccessGraph::vertex_descriptor +addVertex(std::piecewise_construct_t /*tag*/, Component0&& c0, Component1&& c1, Component2&& c2, Component3&& c3, ResourceAccessGraph& g) { + auto v = gsl::narrow_cast(g._vertices.size()); + + g._vertices.emplace_back(); + + { // UuidGraph + std::apply( + [&](const auto&... args) { + auto res = g.passIndex.emplace(std::piecewise_construct, std::forward_as_tuple(args...), std::forward_as_tuple(v)); + CC_ENSURES(res.second); + }, + c0); + } + + std::apply( + [&](auto&&... args) { + g.passID.emplace_back(std::forward(args)...); + }, + std::forward(c0)); + + std::apply( + [&](auto&&... args) { + g.passResource.emplace_back(std::forward(args)...); + }, + std::forward(c1)); + + std::apply( + [&](auto&&... args) { + g.rpInfo.emplace_back(std::forward(args)...); + }, + std::forward(c2)); + + std::apply( + [&](auto&&... args) { + g.barrier.emplace_back(std::forward(args)...); + }, + std::forward(c3)); + + return v; +} + +// IncidenceGraph +inline RelationGraph::vertex_descriptor +source(const RelationGraph::edge_descriptor& e, const RelationGraph& /*g*/) noexcept { + return e.source; +} + +inline RelationGraph::vertex_descriptor +target(const RelationGraph::edge_descriptor& e, const RelationGraph& /*g*/) noexcept { + return e.target; +} + +inline std::pair +out_edges(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT + return std::make_pair( + RelationGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).begin(), u), + RelationGraph::out_edge_iterator(const_cast(g).getOutEdgeList(u).end(), u)); +} + +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(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(), RelationGraph::OutEdge(v)); + bool hasEdge = (iter != outEdgeList.end()); + return {RelationGraph::edge_descriptor(u, v), hasEdge}; +} + +// BidirectionalGraph(Directed) +inline std::pair +in_edges(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT + return std::make_pair( + RelationGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).begin(), u), + RelationGraph::in_edge_iterator(const_cast(g).getInEdgeList(u).end(), u)); +} + +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 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(RelationGraph::vertex_descriptor u, const RelationGraph& g) noexcept { // NOLINT + auto edges = out_edges(u, g); + return std::make_pair(RelationGraph::adjacency_iterator(edges.first, &g), RelationGraph::adjacency_iterator(edges.second, &g)); +} + +// VertexListGraph +inline std::pair +vertices(const RelationGraph& g) noexcept { + return std::make_pair(const_cast(g).getVertexList().begin(), const_cast(g).getVertexList().end()); +} + +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 RelationGraph& g0) noexcept { + auto& g = const_cast(g0); + return std::make_pair( + 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 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) { + numEdges += out_degree(*iter, g); + } + return numEdges; +} + +// MutableGraph(Edge) +inline std::pair +add_edge( // NOLINT + 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(RelationGraph::edge_descriptor(u, v), true); +} + +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(), 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(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(), RelationGraph::InEdge(u)); + CC_EXPECTS(inIter != t.inEdges.end()); + t.inEdges.erase(inIter); + s.outEdges.erase(outIter.base()); +} + +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(), RelationGraph::OutEdge(v)); + CC_EXPECTS(outIter != s.outEdges.end()); + remove_edge(RelationGraph::out_edge_iterator(outIter, u), g); +} + +// MutableGraph(Vertex) +inline void clear_out_edges(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT + // Bidirectional (OutEdges) + auto& outEdgeList = g.getOutEdgeList(u); + auto outEnd = outEdgeList.end(); + for (auto iter = outEdgeList.begin(); iter != outEnd; ++iter) { + auto& inEdgeList = g.getInEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(inEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + outEdgeList.clear(); +} + +inline void clear_in_edges(RelationGraph::vertex_descriptor u, RelationGraph& g) noexcept { // NOLINT + // Bidirectional (InEdges) + auto& inEdgeList = g.getInEdgeList(u); + auto inEnd = inEdgeList.end(); + for (auto iter = inEdgeList.begin(); iter != inEnd; ++iter) { + auto& outEdgeList = g.getOutEdgeList((*iter).get_target()); + // eraseFromIncidenceList + impl::sequenceEraseIf(outEdgeList, [u](const auto& e) { + return e.get_target() == u; + }); + } + inEdgeList.clear(); +} + +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(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() + static_cast(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 + +} // namespace cc + +namespace boost { + +// Vertex Index +template <> +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::ResourceAccessGraph, + const ccstd::pmr::vector, + cc::render::RenderGraph::vertex_descriptor, + const cc::render::RenderGraph::vertex_descriptor&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + cc::render::RenderGraph::vertex_descriptor, + cc::render::RenderGraph::vertex_descriptor&>; +}; + +// Vertex Component +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + cc::render::ResourceAccessNode, + const cc::render::ResourceAccessNode&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + cc::render::ResourceAccessNode, + cc::render::ResourceAccessNode&>; +}; + +// Vertex ComponentMember +template +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + T, + const T&, + T cc::render::ResourceAccessNode::*>; + using type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + T, + T&, + T cc::render::ResourceAccessNode::*>; +}; + +// Vertex Component +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + cc::render::FGRenderPassInfo, + const cc::render::FGRenderPassInfo&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + cc::render::FGRenderPassInfo, + cc::render::FGRenderPassInfo&>; +}; + +// Vertex ComponentMember +template +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + T, + const T&, + T cc::render::FGRenderPassInfo::*>; + using type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + T, + T&, + T cc::render::FGRenderPassInfo::*>; +}; + +// Vertex Component +template <> +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + cc::render::BarrierNode, + const cc::render::BarrierNode&>; + using type = cc::render::impl::VectorVertexComponentPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + cc::render::BarrierNode, + cc::render::BarrierNode&>; +}; + +// Vertex ComponentMember +template +struct property_map { + using const_type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + const cc::render::ResourceAccessGraph, + const ccstd::pmr::vector, + T, + const T&, + T cc::render::BarrierNode::*>; + using type = cc::render::impl::VectorVertexComponentMemberPropertyMap< + lvalue_property_map_tag, + cc::render::ResourceAccessGraph, + ccstd::pmr::vector, + T, + T&, + T cc::render::BarrierNode::*>; +}; + +// Vertex Index +template <> +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 { + +namespace render { + +// Vertex Index +inline boost::property_map::const_type +get(boost::vertex_index_t /*tag*/, const ResourceAccessGraph& /*g*/) noexcept { + return {}; +} + +inline boost::property_map::type +get(boost::vertex_index_t /*tag*/, ResourceAccessGraph& /*g*/) noexcept { + return {}; +} + +inline impl::ColorMap +get(ccstd::pmr::vector& colors, const ResourceAccessGraph& /*g*/) noexcept { + return {colors}; +} + +// Vertex Component +inline typename boost::property_map::const_type +get(ResourceAccessGraph::PassIDTag /*tag*/, const ResourceAccessGraph& g) noexcept { + return {g.passID}; +} + +inline typename boost::property_map::type +get(ResourceAccessGraph::PassIDTag /*tag*/, ResourceAccessGraph& g) noexcept { + return {g.passID}; +} + +// Vertex Component +inline typename boost::property_map::const_type +get(ResourceAccessGraph::PassNodeTag /*tag*/, const ResourceAccessGraph& g) noexcept { + return {g.passResource}; +} + +inline typename boost::property_map::type +get(ResourceAccessGraph::PassNodeTag /*tag*/, ResourceAccessGraph& g) noexcept { + return {g.passResource}; +} + +// Vertex ComponentMember +template +inline typename boost::property_map::const_type +get(T ResourceAccessNode::*memberPointer, const ResourceAccessGraph& g) noexcept { + return {g.passResource, memberPointer}; +} + +template +inline typename boost::property_map::type +get(T ResourceAccessNode::*memberPointer, ResourceAccessGraph& g) noexcept { + return {g.passResource, memberPointer}; +} + +// Vertex Component +inline typename boost::property_map::const_type +get(ResourceAccessGraph::RenderPassInfoTag /*tag*/, const ResourceAccessGraph& g) noexcept { + return {g.rpInfo}; +} + +inline typename boost::property_map::type +get(ResourceAccessGraph::RenderPassInfoTag /*tag*/, ResourceAccessGraph& g) noexcept { + return {g.rpInfo}; +} + +// Vertex ComponentMember +template +inline typename boost::property_map::const_type +get(T FGRenderPassInfo::*memberPointer, const ResourceAccessGraph& g) noexcept { + return {g.rpInfo, memberPointer}; +} + +template +inline typename boost::property_map::type +get(T FGRenderPassInfo::*memberPointer, ResourceAccessGraph& g) noexcept { + return {g.rpInfo, memberPointer}; +} + +// Vertex Component +inline typename boost::property_map::const_type +get(ResourceAccessGraph::BarrierTag /*tag*/, const ResourceAccessGraph& g) noexcept { + return {g.barrier}; +} + +inline typename boost::property_map::type +get(ResourceAccessGraph::BarrierTag /*tag*/, ResourceAccessGraph& g) noexcept { + return {g.barrier}; +} + +// Vertex ComponentMember +template +inline typename boost::property_map::const_type +get(T BarrierNode::*memberPointer, const ResourceAccessGraph& g) noexcept { + return {g.barrier, memberPointer}; +} + +template +inline typename boost::property_map::type +get(T BarrierNode::*memberPointer, ResourceAccessGraph& g) noexcept { + return {g.barrier, memberPointer}; +} + +// Vertex Constant Getter +template +inline decltype(auto) +get(Tag tag, const ResourceAccessGraph& g, ResourceAccessGraph::vertex_descriptor v) noexcept { + return get(get(tag, g), v); +} + +// Vertex Mutable Getter +template +inline decltype(auto) +get(Tag tag, ResourceAccessGraph& g, ResourceAccessGraph::vertex_descriptor v) noexcept { + return get(get(tag, g), v); +} + +// Vertex Setter +template +inline void put( + Tag tag, ResourceAccessGraph& g, + ResourceAccessGraph::vertex_descriptor v, + Args&&... args) { + put(get(tag, g), v, std::forward(args)...); +} + +// UuidGraph +inline ResourceAccessGraph::vertex_descriptor +vertex(const RenderGraph::vertex_descriptor& key, const ResourceAccessGraph& g) { + return g.passIndex.at(key); +} + +template +inline ResourceAccessGraph::vertex_descriptor +vertex(const KeyLike& key, const ResourceAccessGraph& g) { + const auto& index = g.passIndex; + auto iter = index.find(key); + if (iter == index.end()) { + throw std::out_of_range("at(key, ResourceAccessGraph) out of range"); + } + return iter->second; +} + +template +inline ResourceAccessGraph::vertex_descriptor +findVertex(const KeyLike& key, const ResourceAccessGraph& g) noexcept { + const auto& index = g.passIndex; + auto iter = index.find(key); + if (iter == index.end()) { + return ResourceAccessGraph::null_vertex(); + } + return iter->second; +} + +inline bool +contains(const RenderGraph::vertex_descriptor& key, const ResourceAccessGraph& g) noexcept { + auto iter = g.passIndex.find(key); + return iter != g.passIndex.end(); +} + +template +inline bool +contains(const KeyLike& key, const ResourceAccessGraph& g) noexcept { + auto iter = g.passIndex.find(key); + return iter != g.passIndex.end(); +} + +// MutableGraph(Vertex) +inline ResourceAccessGraph::vertex_descriptor +add_vertex(ResourceAccessGraph& g, const RenderGraph::vertex_descriptor& key) { // NOLINT + return addVertex( + std::piecewise_construct, + std::forward_as_tuple(key), // passID + std::forward_as_tuple(), // passResource + std::forward_as_tuple(), // rpInfo + std::forward_as_tuple(), // barrier + g); +} + +// Vertex Index +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*/, RelationGraph& /*g*/) noexcept { + return {}; +} + +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 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 + +} // namespace cc + +// clang-format on diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp index 01ba6c84a2..1982760fd0 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.cpp @@ -1,107 +1,173 @@ -/**************************************************************************** - Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - 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 - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -/** - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - * The following section is auto-generated. - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - */ -// clang-format off -#include "FGDispatcherTypes.h" - -namespace cc { - -namespace render { - -ResourceAccessGraph::ResourceAccessGraph(const allocator_type& alloc) noexcept -: _vertices(alloc), - passID(alloc), - access(alloc), - passIndex(alloc), - resourceNames(alloc), - resourceIndex(alloc), - leafPasses(alloc), - culledPasses(alloc), - accessRecord(alloc), - resourceLifeRecord(alloc), - topologicalOrder(alloc), - rpInfos(alloc), - subpassIndex(alloc) {} - -// ContinuousContainer -void ResourceAccessGraph::reserve(vertices_size_type sz) { - _vertices.reserve(sz); - passID.reserve(sz); - access.reserve(sz); -} - -ResourceAccessGraph::Vertex::Vertex(const allocator_type& alloc) noexcept -: outEdges(alloc), - inEdges(alloc) {} - -ResourceAccessGraph::Vertex::Vertex(Vertex&& rhs, const allocator_type& alloc) -: outEdges(std::move(rhs.outEdges), alloc), - inEdges(std::move(rhs.inEdges), alloc) {} - -ResourceAccessGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) -: 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, const 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), - relationGraph(alloc) {} - -} // namespace render - -} // namespace cc - -// clang-format on +/**************************************************************************** + Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + 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 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +/** + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + * The following section is auto-generated. + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + */ +// clang-format off +#include "FGDispatcherTypes.h" + +namespace cc { + +namespace render { + +ResourceAccessNode::ResourceAccessNode(const allocator_type& alloc) noexcept +: resourceStatus(alloc) {} + +ResourceAccessNode::ResourceAccessNode(ResourceAccessNode&& rhs, const allocator_type& alloc) +: resourceStatus(std::move(rhs.resourceStatus), alloc) {} + +ResourceAccessNode::ResourceAccessNode(ResourceAccessNode const& rhs, const allocator_type& alloc) +: resourceStatus(rhs.resourceStatus, alloc) {} + +AttachmentInfo::AttachmentInfo(const allocator_type& alloc) noexcept +: parentName(alloc) {} + +AttachmentInfo::AttachmentInfo(AttachmentInfo&& rhs, const allocator_type& alloc) +: parentName(std::move(rhs.parentName), alloc), + attachmentIndex(rhs.attachmentIndex), + isResolveView(rhs.isResolveView) {} + +AttachmentInfo::AttachmentInfo(AttachmentInfo const& rhs, const allocator_type& alloc) +: parentName(rhs.parentName, alloc), + attachmentIndex(rhs.attachmentIndex), + isResolveView(rhs.isResolveView) {} + +FGRenderPassInfo::FGRenderPassInfo(const allocator_type& alloc) noexcept +: orderedViews(alloc), + viewIndex(alloc) {} + +FGRenderPassInfo::FGRenderPassInfo(FGRenderPassInfo&& rhs, const allocator_type& alloc) +: colorAccesses(std::move(rhs.colorAccesses)), + dsAccess(rhs.dsAccess), + dsResolveAccess(rhs.dsResolveAccess), + rpInfo(std::move(rhs.rpInfo)), + orderedViews(std::move(rhs.orderedViews), alloc), + viewIndex(std::move(rhs.viewIndex), alloc), + resolveCount(rhs.resolveCount), + uniqueRasterViewCount(rhs.uniqueRasterViewCount) {} + +FGRenderPassInfo::FGRenderPassInfo(FGRenderPassInfo const& rhs, const allocator_type& alloc) +: colorAccesses(rhs.colorAccesses), + dsAccess(rhs.dsAccess), + dsResolveAccess(rhs.dsResolveAccess), + rpInfo(rhs.rpInfo), + orderedViews(rhs.orderedViews, alloc), + viewIndex(rhs.viewIndex, alloc), + resolveCount(rhs.resolveCount), + uniqueRasterViewCount(rhs.uniqueRasterViewCount) {} + +ResourceAccessGraph::ResourceAccessGraph(const allocator_type& alloc) noexcept +: _vertices(alloc), + passID(alloc), + passResource(alloc), + rpInfo(alloc), + barrier(alloc), + passIndex(alloc), + resourceNames(alloc), + resourceIndex(alloc), + leafPasses(alloc), + culledPasses(alloc), + resourceLifeRecord(alloc), + topologicalOrder(alloc), + resourceAccess(alloc), + movedTarget(alloc), + movedSourceStatus(alloc) {} + +// ContinuousContainer +void ResourceAccessGraph::reserve(vertices_size_type sz) { + _vertices.reserve(sz); + passID.reserve(sz); + passResource.reserve(sz); + rpInfo.reserve(sz); + barrier.reserve(sz); +} + +ResourceAccessGraph::Vertex::Vertex(const allocator_type& alloc) noexcept +: outEdges(alloc), + inEdges(alloc) {} + +ResourceAccessGraph::Vertex::Vertex(Vertex&& rhs, const allocator_type& alloc) +: outEdges(std::move(rhs.outEdges), alloc), + inEdges(std::move(rhs.inEdges), alloc) {} + +ResourceAccessGraph::Vertex::Vertex(Vertex const& rhs, const allocator_type& alloc) +: 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) {} + +RenderingInfo::RenderingInfo(const allocator_type& alloc) noexcept +: clearColors(alloc) {} + +RenderingInfo::RenderingInfo(RenderingInfo&& rhs, const allocator_type& alloc) +: renderpassInfo(std::move(rhs.renderpassInfo)), + framebufferInfo(std::move(rhs.framebufferInfo)), + clearColors(std::move(rhs.clearColors), alloc), + clearDepth(rhs.clearDepth), + clearStencil(rhs.clearStencil) {} + +RenderingInfo::RenderingInfo(RenderingInfo const& rhs, const allocator_type& alloc) +: renderpassInfo(rhs.renderpassInfo), + framebufferInfo(rhs.framebufferInfo), + clearColors(rhs.clearColors, alloc), + clearDepth(rhs.clearDepth), + clearStencil(rhs.clearStencil) {} + +FrameGraphDispatcher::FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& renderGraphIn, const LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept +: resourceAccessGraph(alloc), + resourceGraph(resourceGraphIn), + renderGraph(renderGraphIn), + layoutGraph(layoutGraphIn), + scratch(scratchIn), + relationGraph(alloc) {} + +} // namespace render + +} // namespace cc + +// clang-format on diff --git a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h index 0ac3830c64..25816eaf81 100644 --- a/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h +++ b/native/cocos/renderer/pipeline/custom/FGDispatcherTypes.h @@ -1,451 +1,502 @@ -/**************************************************************************** - Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - 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 - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -/** - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - * The following section is auto-generated. - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - */ -// clang-format off -#pragma once -#include -#include -#include -#include -#include -#include "cocos/base/std/container/string.h" -#include "cocos/base/std/container/vector.h" -#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" -#include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" -#include "cocos/renderer/pipeline/custom/details/GraphTypes.h" -#include "cocos/renderer/pipeline/custom/details/Map.h" -#include "cocos/renderer/pipeline/custom/details/Set.h" -#include "gfx-base/GFXDef-common.h" - -namespace cc { - -namespace render { - -struct NullTag { -}; - -struct ResourceLifeRecord { - uint32_t start{0}; - uint32_t end{0}; -}; - -struct LeafStatus { - bool isExternal{false}; - bool needCulling{false}; -}; - -struct BufferRange { - uint32_t offset{0}; - uint32_t size{0}; -}; - -inline bool operator<(const BufferRange& lhs, const BufferRange& rhs) noexcept { - return std::forward_as_tuple(lhs.offset, lhs.size) < - std::forward_as_tuple(rhs.offset, rhs.size); -} - -struct TextureRange { - uint32_t firstSlice{0}; - uint32_t numSlices{1}; - uint32_t mipLevel{0}; - uint32_t levelCount{1}; -}; - -inline bool operator<(const TextureRange& lhs, const TextureRange& rhs) noexcept { - return std::forward_as_tuple(lhs.firstSlice, lhs.numSlices, lhs.mipLevel, lhs.levelCount) < - std::forward_as_tuple(rhs.firstSlice, rhs.numSlices, rhs.mipLevel, rhs.levelCount); -} - -using Range = ccstd::variant; - -using ResourceUsage = ccstd::variant; - -struct AccessStatus { - uint32_t vertID{0xFFFFFFFF}; - 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; -}; - -struct ResourceTransition { - AccessStatus lastStatus; - AccessStatus currStatus; -}; - -struct ResourceAccessNode { - std::vector attachmentStatus; - struct ResourceAccessNode* nextSubpass{nullptr}; -}; - -struct LayoutAccess { - gfx::AccessFlagBit prevAccess{gfx::AccessFlagBit::NONE}; - gfx::AccessFlagBit nextAccess{gfx::AccessFlagBit::NONE}; -}; - -struct FGRenderPassInfo { - std::vector colorAccesses; - LayoutAccess dsAccess; - LayoutAccess dsResolveAccess; - gfx::RenderPassInfo rpInfo; - std::vector orderedViews; - bool needResolve{false}; -}; - -struct ResourceAccessGraph { - 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(); - } - - ResourceAccessGraph(const allocator_type& alloc) noexcept; // NOLINT - ResourceAccessGraph(ResourceAccessGraph&& rhs) = delete; - ResourceAccessGraph(ResourceAccessGraph const& rhs) = delete; - ResourceAccessGraph& operator=(ResourceAccessGraph&& rhs) = delete; - ResourceAccessGraph& operator=(ResourceAccessGraph const& rhs) = delete; - - // Graph - using directed_category = boost::bidirectional_tag; - using vertex_descriptor = uint32_t; - using edge_descriptor = impl::EdgeDescriptor; - using edge_parallel_category = boost::allow_parallel_edge_tag; - struct traversal_category // NOLINT - : virtual boost::incidence_graph_tag, - virtual boost::bidirectional_graph_tag, - virtual boost::adjacency_graph_tag, - virtual boost::vertex_list_graph_tag, - virtual boost::edge_list_graph_tag {}; - - constexpr static vertex_descriptor null_vertex() noexcept { // NOLINT - return std::numeric_limits::max(); - } - - // IncidenceGraph - using OutEdge = impl::StoredEdge; - using out_edge_iterator = impl::OutEdgeIter< - 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< - ccstd::pmr::vector::iterator, - vertex_descriptor, edge_descriptor, int32_t>; - - // AdjacencyGraph - using adjacency_iterator = boost::adjacency_iterator_generator< - ResourceAccessGraph, vertex_descriptor, out_edge_iterator>::type; - - // VertexListGraph - using vertex_iterator = boost::integer_range::iterator; - using vertices_size_type = uint32_t; - - // VertexList help functions - inline ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) noexcept { - return _vertices[v].outEdges; - } - inline const ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) const noexcept { - return _vertices[v].outEdges; - } - - inline ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) noexcept { - return _vertices[v].inEdges; - } - inline const ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) const noexcept { - return _vertices[v].inEdges; - } - - inline boost::integer_range getVertexList() const noexcept { - return {0, static_cast(_vertices.size())}; - } - - inline vertex_descriptor getCurrentID() const noexcept { - return static_cast(_vertices.size()); - } - - inline ccstd::pmr::vector colors(boost::container::pmr::memory_resource* mr) const { - return ccstd::pmr::vector(_vertices.size(), mr); - } - - // EdgeListGraph - using edge_iterator = impl::DirectedEdgeIterator; - using edges_size_type = uint32_t; - - ~ResourceAccessGraph() { - for (auto& node : access) { - auto* resNode = node.nextSubpass; - node.nextSubpass = nullptr; - while(resNode) { - auto* oldResNode = resNode; - resNode = resNode->nextSubpass; - oldResNode->nextSubpass = nullptr; - delete oldResNode; - } - } - } - - - // ContinuousContainer - void reserve(vertices_size_type sz); - - // Members - struct Vertex { - 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 PassIDTag {}; - struct AccessNodeTag {}; - - // Vertices - ccstd::pmr::vector _vertices; - // Components - ccstd::pmr::vector passID; - ccstd::pmr::vector access; - // UuidGraph - PmrUnorderedMap passIndex; - // Members - ccstd::pmr::vector resourceNames; - PmrUnorderedStringMap resourceIndex; - vertex_descriptor presentPassID{0xFFFFFFFF}; - PmrFlatMap leafPasses; - PmrFlatSet culledPasses; - PmrFlatMap accessRecord; - PmrFlatMap resourceLifeRecord; - ccstd::pmr::vector topologicalOrder; - PmrFlatMap rpInfos; - PmrFlatMap subpassIndex; -}; - -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; - using vertex_descriptor = uint32_t; - using edge_descriptor = impl::EdgeDescriptor; - using edge_parallel_category = boost::allow_parallel_edge_tag; - struct traversal_category // NOLINT - : virtual boost::incidence_graph_tag, - virtual boost::bidirectional_graph_tag, - virtual boost::adjacency_graph_tag, - virtual boost::vertex_list_graph_tag, - virtual boost::edge_list_graph_tag {}; - - constexpr static vertex_descriptor null_vertex() noexcept { // NOLINT - return std::numeric_limits::max(); - } - - // IncidenceGraph - using OutEdge = impl::StoredEdge; - using out_edge_iterator = impl::OutEdgeIter< - 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< - ccstd::pmr::vector::iterator, - vertex_descriptor, edge_descriptor, int32_t>; - - // AdjacencyGraph - using adjacency_iterator = boost::adjacency_iterator_generator< - 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 ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) noexcept { - return _vertices[v].outEdges; - } - inline const ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) const noexcept { - return _vertices[v].outEdges; - } - - inline ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) noexcept { - return _vertices[v].inEdges; - } - inline const ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) const noexcept { - return _vertices[v].inEdges; - } - - inline boost::integer_range getVertexList() const noexcept { - return {0, static_cast(_vertices.size())}; - } - - inline vertex_descriptor getCurrentID() const noexcept { - return static_cast(_vertices.size()); - } - - inline ccstd::pmr::vector colors(boost::container::pmr::memory_resource* mr) const { - return ccstd::pmr::vector(_vertices.size(), mr); - } - - // EdgeListGraph - using edge_iterator = impl::DirectedEdgeIterator; - using edges_size_type = uint32_t; - - // ContinuousContainer - void reserve(vertices_size_type sz); - - // Members - struct Vertex { - 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 {}; - - // Vertices - ccstd::pmr::vector _vertices; - // Components - ccstd::pmr::vector descID; - // UuidGraph - PmrUnorderedMap vertexMap; -}; - -struct Barrier { - ResourceGraph::vertex_descriptor resourceID{0xFFFFFFFF}; - gfx::BarrierType type{gfx::BarrierType::FULL}; - gfx::GFXObject* barrier{nullptr}; - AccessStatus beginStatus; - AccessStatus endStatus; -}; - -struct BarrierPair { - std::vector frontBarriers; - std::vector rearBarriers; -}; - -struct BarrierNode { - BarrierPair blockBarrier; - std::vector subpassBarriers; -}; - -struct FrameGraphDispatcher { - using allocator_type = boost::container::pmr::polymorphic_allocator; - allocator_type get_allocator() const noexcept { // NOLINT - return {resourceAccessGraph.get_allocator().resource()}; - } - - FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& graphIn, const LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept; - FrameGraphDispatcher(FrameGraphDispatcher&& rhs) = delete; - FrameGraphDispatcher(FrameGraphDispatcher const& rhs) = delete; - FrameGraphDispatcher& operator=(FrameGraphDispatcher&& rhs) = delete; - FrameGraphDispatcher& operator=(FrameGraphDispatcher const& rhs) = delete; - - using BarrierMap = PmrMap; - - void enablePassReorder(bool enable); - - // how much paralell-execution weights during pass reorder, - // eg:0.3 means 30% of effort aim to paralellize execution, other 70% aim to decrease memory using. - // 0 by default - void setParalellWeight(float paralellExecWeight); - - void enableMemoryAliasing(bool enable); - - void run(); - - const ResourceAccessNode& getAttachmentStatus(RenderGraph::vertex_descriptor renderGraphVertID) const; - - inline const BarrierMap& getBarriers() const { return barrierMap; } - - BarrierMap barrierMap; - - ResourceAccessGraph resourceAccessGraph; - ResourceGraph& resourceGraph; - const RenderGraph& graph; - const LayoutGraphData& layoutGraph; - boost::container::pmr::memory_resource* scratch{nullptr}; - PmrFlatMap externalResMap; - RelationGraph relationGraph; - bool _enablePassReorder{false}; - bool _enableAutoBarrier{true}; - bool _enableMemoryAliasing{false}; - bool _accessGraphBuilt{false}; - float _paralellExecWeight{0.0F}; -}; - -} // namespace render - -} // namespace cc - -// clang-format on +/**************************************************************************** + Copyright (c) 2021-2023 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 documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + 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 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +/** + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + * The following section is auto-generated. + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + */ +// clang-format off +#pragma once +#include +#include +#include +#include +#include +#include "cocos/base/std/container/string.h" +#include "cocos/base/std/container/vector.h" +#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" +#include "cocos/renderer/pipeline/custom/RenderGraphTypes.h" +#include "cocos/renderer/pipeline/custom/details/GraphTypes.h" +#include "cocos/renderer/pipeline/custom/details/Map.h" +#include "cocos/renderer/pipeline/custom/details/Set.h" +#include "gfx-base/GFXDef-common.h" + +namespace cc { + +namespace render { + +struct NullTag { +}; + +struct ResourceLifeRecord { + uint32_t start{0}; + uint32_t end{0}; +}; + +struct LeafStatus { + bool isExternal{false}; + bool needCulling{false}; +}; + +struct ResourceRange { + uint32_t width{0}; + uint32_t height{0}; + uint32_t depthOrArraySize{0}; + uint32_t firstSlice{0}; + uint32_t numSlices{0}; + uint32_t mipLevel{0}; + uint32_t levelCount{0}; + uint32_t basePlane{0}; + uint32_t planeCount{0}; +}; + +struct AccessStatus { + gfx::AccessFlagBit accessFlag{gfx::AccessFlagBit::NONE}; + ResourceRange range; +}; + +struct ResourceAccessNode { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {resourceStatus.get_allocator().resource()}; + } + + ResourceAccessNode(const allocator_type& alloc) noexcept; // NOLINT + ResourceAccessNode(ResourceAccessNode&& rhs, const allocator_type& alloc); + ResourceAccessNode(ResourceAccessNode const& rhs, const allocator_type& alloc); + + ResourceAccessNode(ResourceAccessNode&& rhs) noexcept = default; + ResourceAccessNode(ResourceAccessNode const& rhs) = delete; + ResourceAccessNode& operator=(ResourceAccessNode&& rhs) = default; + ResourceAccessNode& operator=(ResourceAccessNode const& rhs) = default; + + PmrFlatMap resourceStatus; +}; + +struct LayoutAccess { + gfx::AccessFlagBit prevAccess{gfx::AccessFlagBit::NONE}; + gfx::AccessFlagBit nextAccess{gfx::AccessFlagBit::NONE}; +}; + +struct AttachmentInfo { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {parentName.get_allocator().resource()}; + } + + AttachmentInfo(const allocator_type& alloc) noexcept; // NOLINT + AttachmentInfo(AttachmentInfo&& rhs, const allocator_type& alloc); + AttachmentInfo(AttachmentInfo const& rhs, const allocator_type& alloc); + + AttachmentInfo(AttachmentInfo&& rhs) noexcept = default; + AttachmentInfo(AttachmentInfo const& rhs) = delete; + AttachmentInfo& operator=(AttachmentInfo&& rhs) = default; + AttachmentInfo& operator=(AttachmentInfo const& rhs) = default; + + ccstd::pmr::string parentName; + uint32_t attachmentIndex{0}; + uint32_t isResolveView{0}; +}; + +struct FGRenderPassInfo { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {orderedViews.get_allocator().resource()}; + } + + FGRenderPassInfo(const allocator_type& alloc) noexcept; // NOLINT + FGRenderPassInfo(FGRenderPassInfo&& rhs, const allocator_type& alloc); + FGRenderPassInfo(FGRenderPassInfo const& rhs, const allocator_type& alloc); + + FGRenderPassInfo(FGRenderPassInfo&& rhs) noexcept = default; + FGRenderPassInfo(FGRenderPassInfo const& rhs) = delete; + FGRenderPassInfo& operator=(FGRenderPassInfo&& rhs) = default; + FGRenderPassInfo& operator=(FGRenderPassInfo const& rhs) = default; + + std::vector colorAccesses; + LayoutAccess dsAccess; + LayoutAccess dsResolveAccess; + gfx::RenderPassInfo rpInfo; + ccstd::pmr::vector orderedViews; + PmrTransparentMap viewIndex; + uint32_t resolveCount{0}; + uint32_t uniqueRasterViewCount{0}; +}; + +struct Barrier { + ResourceGraph::vertex_descriptor resourceID{0xFFFFFFFF}; + gfx::BarrierType type{gfx::BarrierType::FULL}; + gfx::GFXObject* barrier{nullptr}; + RenderGraph::vertex_descriptor beginVert{0xFFFFFFFF}; + RenderGraph::vertex_descriptor endVert{0xFFFFFFFF}; + AccessStatus beginStatus; + AccessStatus endStatus; +}; + +struct BarrierNode { + std::vector frontBarriers; + std::vector rearBarriers; +}; + +struct ResourceAccessGraph { + 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(); + } + + ResourceAccessGraph(const allocator_type& alloc) noexcept; // NOLINT + ResourceAccessGraph(ResourceAccessGraph&& rhs) = delete; + ResourceAccessGraph(ResourceAccessGraph const& rhs) = delete; + ResourceAccessGraph& operator=(ResourceAccessGraph&& rhs) = delete; + ResourceAccessGraph& operator=(ResourceAccessGraph const& rhs) = delete; + + // Graph + using directed_category = boost::bidirectional_tag; + using vertex_descriptor = uint32_t; + using edge_descriptor = impl::EdgeDescriptor; + using edge_parallel_category = boost::allow_parallel_edge_tag; + struct traversal_category // NOLINT + : virtual boost::incidence_graph_tag, + virtual boost::bidirectional_graph_tag, + virtual boost::adjacency_graph_tag, + virtual boost::vertex_list_graph_tag, + virtual boost::edge_list_graph_tag {}; + + constexpr static vertex_descriptor null_vertex() noexcept { // NOLINT + return std::numeric_limits::max(); + } + + // IncidenceGraph + using OutEdge = impl::StoredEdge; + using out_edge_iterator = impl::OutEdgeIter< + 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< + ccstd::pmr::vector::iterator, + vertex_descriptor, edge_descriptor, int32_t>; + + // AdjacencyGraph + using adjacency_iterator = boost::adjacency_iterator_generator< + ResourceAccessGraph, vertex_descriptor, out_edge_iterator>::type; + + // VertexListGraph + using vertex_iterator = boost::integer_range::iterator; + using vertices_size_type = uint32_t; + + // VertexList help functions + inline ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) noexcept { + return _vertices[v].outEdges; + } + inline const ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) const noexcept { + return _vertices[v].outEdges; + } + + inline ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) noexcept { + return _vertices[v].inEdges; + } + inline const ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) const noexcept { + return _vertices[v].inEdges; + } + + inline boost::integer_range getVertexList() const noexcept { + return {0, static_cast(_vertices.size())}; + } + + inline vertex_descriptor getCurrentID() const noexcept { + return static_cast(_vertices.size()); + } + + inline ccstd::pmr::vector colors(boost::container::pmr::memory_resource* mr) const { + return ccstd::pmr::vector(_vertices.size(), mr); + } + + // EdgeListGraph + using edge_iterator = impl::DirectedEdgeIterator; + using edges_size_type = uint32_t; + + LayoutAccess getAccess(ccstd::pmr::string, RenderGraph::vertex_descriptor vertID); + + + // ContinuousContainer + void reserve(vertices_size_type sz); + + // Members + struct Vertex { + 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 PassIDTag {}; + struct PassNodeTag {}; + struct RenderPassInfoTag {}; + struct BarrierTag {}; + + // Vertices + ccstd::pmr::vector _vertices; + // Components + ccstd::pmr::vector passID; + ccstd::pmr::vector passResource; + ccstd::pmr::vector rpInfo; + ccstd::pmr::vector barrier; + // UuidGraph + PmrUnorderedMap passIndex; + // Members + ccstd::pmr::vector resourceNames; + PmrUnorderedStringMap resourceIndex; + vertex_descriptor presentPassID{0xFFFFFFFF}; + PmrFlatMap leafPasses; + PmrFlatSet culledPasses; + PmrFlatMap resourceLifeRecord; + ccstd::pmr::vector topologicalOrder; + PmrTransparentMap> resourceAccess; + PmrFlatMap> movedTarget; + PmrFlatMap movedSourceStatus; +}; + +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; + using vertex_descriptor = uint32_t; + using edge_descriptor = impl::EdgeDescriptor; + using edge_parallel_category = boost::allow_parallel_edge_tag; + struct traversal_category // NOLINT + : virtual boost::incidence_graph_tag, + virtual boost::bidirectional_graph_tag, + virtual boost::adjacency_graph_tag, + virtual boost::vertex_list_graph_tag, + virtual boost::edge_list_graph_tag {}; + + constexpr static vertex_descriptor null_vertex() noexcept { // NOLINT + return std::numeric_limits::max(); + } + + // IncidenceGraph + using OutEdge = impl::StoredEdge; + using out_edge_iterator = impl::OutEdgeIter< + 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< + ccstd::pmr::vector::iterator, + vertex_descriptor, edge_descriptor, int32_t>; + + // AdjacencyGraph + using adjacency_iterator = boost::adjacency_iterator_generator< + 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 ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) noexcept { + return _vertices[v].outEdges; + } + inline const ccstd::pmr::vector& getOutEdgeList(vertex_descriptor v) const noexcept { + return _vertices[v].outEdges; + } + + inline ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) noexcept { + return _vertices[v].inEdges; + } + inline const ccstd::pmr::vector& getInEdgeList(vertex_descriptor v) const noexcept { + return _vertices[v].inEdges; + } + + inline boost::integer_range getVertexList() const noexcept { + return {0, static_cast(_vertices.size())}; + } + + inline vertex_descriptor getCurrentID() const noexcept { + return static_cast(_vertices.size()); + } + + inline ccstd::pmr::vector colors(boost::container::pmr::memory_resource* mr) const { + return ccstd::pmr::vector(_vertices.size(), mr); + } + + // EdgeListGraph + using edge_iterator = impl::DirectedEdgeIterator; + using edges_size_type = uint32_t; + + // ContinuousContainer + void reserve(vertices_size_type sz); + + // Members + struct Vertex { + 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 {}; + + // Vertices + ccstd::pmr::vector _vertices; + // Components + ccstd::pmr::vector descID; + // UuidGraph + PmrUnorderedMap vertexMap; +}; + +struct RenderingInfo { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {clearColors.get_allocator().resource()}; + } + + RenderingInfo(const allocator_type& alloc) noexcept; // NOLINT + RenderingInfo(RenderingInfo&& rhs, const allocator_type& alloc); + RenderingInfo(RenderingInfo const& rhs, const allocator_type& alloc); + + RenderingInfo(RenderingInfo&& rhs) noexcept = default; + RenderingInfo(RenderingInfo const& rhs) = delete; + RenderingInfo& operator=(RenderingInfo&& rhs) = default; + RenderingInfo& operator=(RenderingInfo const& rhs) = default; + + gfx::RenderPassInfo renderpassInfo; + gfx::FramebufferInfo framebufferInfo; + ccstd::pmr::vector clearColors; + float clearDepth{0}; + uint8_t clearStencil{0}; +}; + +struct FrameGraphDispatcher { + using allocator_type = boost::container::pmr::polymorphic_allocator; + allocator_type get_allocator() const noexcept { // NOLINT + return {resourceAccessGraph.get_allocator().resource()}; + } + + FrameGraphDispatcher(ResourceGraph& resourceGraphIn, const RenderGraph& renderGraphIn, const LayoutGraphData& layoutGraphIn, boost::container::pmr::memory_resource* scratchIn, const allocator_type& alloc) noexcept; + FrameGraphDispatcher(FrameGraphDispatcher&& rhs) = delete; + FrameGraphDispatcher(FrameGraphDispatcher const& rhs) = delete; + FrameGraphDispatcher& operator=(FrameGraphDispatcher&& rhs) = delete; + FrameGraphDispatcher& operator=(FrameGraphDispatcher const& rhs) = delete; + + + void enablePassReorder(bool enable); + + // how much paralell-execution weights during pass reorder, + // eg:0.3 means 30% of effort aim to paralellize execution, other 70% aim to decrease memory using. + // 0 by default + void setParalellWeight(float paralellExecWeight); + + void enableMemoryAliasing(bool enable); + + void run(); + + const BarrierNode& getBarrier(RenderGraph::vertex_descriptor u) const; + + const ResourceAccessNode& getAccessNode(RenderGraph::vertex_descriptor u) const; + + const gfx::RenderPassInfo& getRenderPassInfo(RenderGraph::vertex_descriptor u) const; + + RenderingInfo getRenderPassAndFrameBuffer(RenderGraph::vertex_descriptor u, const ResourceGraph& resg) const; + + LayoutAccess getResourceAccess(ResourceGraph::vertex_descriptor r, RenderGraph::vertex_descriptor p) const; + + // those resource been moved point to another resID + ResourceGraph::vertex_descriptor realResourceID(const ccstd::pmr::string& name) const; + + PmrFlatMap buildDescriptorIndex( + const PmrTransparentMap>&computeViews, + const PmrTransparentMap& rasterViews, + boost::container::pmr::memory_resource* scratch) const; + + PmrFlatMap buildDescriptorIndex( + const PmrTransparentMap>&computeViews, + boost::container::pmr::memory_resource* scratch) const; + + ResourceAccessGraph resourceAccessGraph; + ResourceGraph& resourceGraph; + const RenderGraph& renderGraph; + const LayoutGraphData& layoutGraph; + boost::container::pmr::memory_resource* scratch{nullptr}; + RelationGraph relationGraph; + bool _enablePassReorder{false}; + bool _enableAutoBarrier{true}; + bool _enableMemoryAliasing{false}; + bool _accessGraphBuilt{false}; + float _paralellExecWeight{0.0F}; +}; + +} // namespace render + +} // namespace cc + +// clang-format on diff --git a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp index 1a2cffac76..6cdd864a2b 100644 --- a/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp +++ b/native/cocos/renderer/pipeline/custom/FrameGraphDispatcher.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -43,6 +44,7 @@ #include "boost/graph/hawick_circuits.hpp" #include "boost/graph/visitors.hpp" #include "boost/lexical_cast.hpp" +#include "details/GraphView.h" #include "details/Range.h" #include "gfx-base/GFXBarrier.h" #include "gfx-base/GFXDef-common.h" @@ -54,11 +56,20 @@ #include "pipeline/custom/RenderCommonFwd.h" #include "pipeline/custom/RenderGraphTypes.h" #include "pipeline/custom/details/GslUtils.h" +#include "NativeRenderGraphUtils.h" #ifndef BRANCH_CULLING #define BRANCH_CULLING 0 #endif +#define ENABLE_FGD_WARNNING 1 + +#ifdef ENABLE_FGD_WARNNING + #define FGD_WARNING(...) printf(##__VA_ARGS__) +#else + #define FGD_WARNING(...) +#endif + namespace cc { namespace render { @@ -91,35 +102,219 @@ void FrameGraphDispatcher::setParalellWeight(float paralellExecWeight) { _paralellExecWeight = clampf(paralellExecWeight, 0.0F, 1.0F); } -const ResourceAccessNode &FrameGraphDispatcher::getAttachmentStatus(RenderGraph::vertex_descriptor renderGraphVertID) const { - auto iter = resourceAccessGraph.subpassIndex.find(renderGraphVertID); - auto ragVertID = resourceAccessGraph.passIndex.at(renderGraphVertID); - const ResourceAccessNode *accessNode = &resourceAccessGraph.access.at(ragVertID); - if (iter != resourceAccessGraph.subpassIndex.end()) { - auto subpassIndex = iter->second; - accessNode = accessNode->nextSubpass; - CC_ASSERT(accessNode); - while (subpassIndex) { - accessNode = accessNode->nextSubpass; - --subpassIndex; - CC_ASSERT(accessNode); +const BarrierNode &FrameGraphDispatcher::getBarrier(RenderGraph::vertex_descriptor u) const { + auto ragVertID = resourceAccessGraph.passIndex.at(u); + return get(ResourceAccessGraph::BarrierTag{}, resourceAccessGraph, ragVertID); +} + +const ResourceAccessNode &FrameGraphDispatcher::getAccessNode(RenderGraph::vertex_descriptor u) const { + auto ragVertID = resourceAccessGraph.passIndex.at(u); + return get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, ragVertID); +} + +const gfx::RenderPassInfo &FrameGraphDispatcher::getRenderPassInfo(RenderGraph::vertex_descriptor u) const { + CC_EXPECTS(holds(u, renderGraph)); + auto ragVertID = resourceAccessGraph.passIndex.at(u); + return get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, ragVertID).rpInfo; +} + +ResourceGraph::vertex_descriptor FrameGraphDispatcher::realResourceID(const ccstd::pmr::string &name) const { + return resourceAccessGraph.resourceIndex.at(name); +} + +ResourceGraph::vertex_descriptor locateSubres(ResourceGraph::vertex_descriptor resID, const ResourceGraph &resg, std::string_view name) { + auto resName = get(ResourceGraph::NameTag{}, resg, resID); + resName += "/"; + resName += name; + return findVertex(resName, resg); +} + +ResourceGraph::vertex_descriptor locateSubres(ResourceGraph::vertex_descriptor resID, + const ResourceGraph &resg, + uint32_t basePlane) { + auto ret = resID; + const auto &desc = get(ResourceGraph::DescTag{}, resg, resID); + if (desc.format == gfx::Format::DEPTH_STENCIL) { + ret = basePlane == 0 ? locateSubres(resID, resg, DEPTH_PLANE_NAME) : locateSubres(resID, resg, STENCIL_PLANE_NAME); + } + return ret; +} + +PmrFlatMap FrameGraphDispatcher::buildDescriptorIndex( + const PmrTransparentMap> &computeViews, + boost::container::pmr::memory_resource *scratch) const { + PmrFlatMap resourceIndex(scratch); + resourceIndex.reserve(computeViews.size() * 2); + if (!computeViews.empty()) { + for (const auto &[resName, computeViews] : computeViews) { + auto resID = realResourceID(resName); + for (const auto &computeView : computeViews) { + const auto &name = computeView.name; + CC_EXPECTS(!name.empty()); + const auto nameID = layoutGraph.attributeIndex.at(name); + auto subresID = locateSubres(resID, resourceGraph, computeView.plane); + resourceIndex.emplace(nameID, subresID); + } } } - return *accessNode; + return resourceIndex; +} + +PmrFlatMap FrameGraphDispatcher::buildDescriptorIndex( + const PmrTransparentMap> &computeViews, + const PmrTransparentMap &rasterViews, + boost::container::pmr::memory_resource *scratch) const { + + auto resourceIndex = buildDescriptorIndex(computeViews, scratch); + if (!rasterViews.empty()) { + NameLocalID unused{128}; + // input sort by slot name + ccstd::pmr::map> inputs(scratch); + for (const auto &[resourceName, rasterView] : rasterViews) { + if (rasterView.accessType != AccessType::WRITE) { + if (!defaultAttachment(rasterView.slotName)) { + std::string_view suffix = rasterView.attachmentType == AttachmentType::DEPTH_STENCIL ? DEPTH_PLANE_NAME : ""; + inputs.emplace(std::piecewise_construct, + std::forward_as_tuple(rasterView.slotName), + std::forward_as_tuple(resourceName, suffix)); + } + if (!defaultAttachment(rasterView.slotName1)) { + CC_EXPECTS(rasterView.attachmentType == AttachmentType::DEPTH_STENCIL); + std::string_view suffix = STENCIL_PLANE_NAME; + inputs.emplace(std::piecewise_construct, + std::forward_as_tuple(rasterView.slotName1), + std::forward_as_tuple(resourceName, suffix)); + } + } + } + // build pass resources + for (const auto &[slotName, nameInfo] : inputs) { + auto resID = realResourceID(nameInfo.first.data()); + if (!nameInfo.second.empty()) { + resID = locateSubres(resID, resourceGraph, nameInfo.second); + } + resourceIndex.emplace(unused, resID); + unused.value++; + } + } + + return resourceIndex; +} + +RenderingInfo FrameGraphDispatcher::getRenderPassAndFrameBuffer(RenderGraph::vertex_descriptor u, const ResourceGraph &resg) const { + auto ragVertID = resourceAccessGraph.passIndex.at(u); + const auto &fgRenderPassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, ragVertID); + const auto &orderedViews = fgRenderPassInfo.orderedViews; + const auto &viewIndex = fgRenderPassInfo.viewIndex; + + RenderingInfo renderingInfo(scratch); + renderingInfo.renderpassInfo = getRenderPassInfo(u); + gfx::FramebufferInfo fbInfo{ + nullptr, + }; + + CC_ENSURES(holds(u, renderGraph)); + const RasterPass &pass = get(RasterPassTag{}, u, renderGraph); + + for (const auto &viewName : orderedViews) { + const auto &info = viewIndex.at(viewName); + auto attachmentIndex = info.attachmentIndex; + gfx::Color clearColor{}; + if (!info.isResolveView) { + const auto &rasterView = pass.rasterViews.at(viewName); + clearColor = rasterView.clearColor; + } + if (info.attachmentIndex != gfx::INVALID_BINDING) { + // colorLike + renderingInfo.clearColors.emplace_back(clearColor); + + auto resID = resourceAccessGraph.resourceIndex.at(viewName); + visitObject( + resID, resg, + [&](const ManagedResource &res) { + std::ignore = res; + CC_EXPECTS(false); + }, + [&](const ManagedBuffer &res) { + std::ignore = res; + CC_EXPECTS(false); + }, + [&](const ManagedTexture &tex) { + CC_EXPECTS(tex.texture); + fbInfo.colorTextures.emplace_back(tex.texture); + }, + [&](const IntrusivePtr &res) { + std::ignore = res; + CC_EXPECTS(false); + }, + [&](const IntrusivePtr &tex) { + fbInfo.colorTextures.emplace_back(tex); + }, + [&](const IntrusivePtr &fb) { + CC_EXPECTS(fb->getColorTextures().size() == 1); + CC_EXPECTS(fb->getColorTextures().at(0)); + // render window attaches a depthStencil by default, which may differs from renderpassInfo here. + // data.framebuffer = fb; + }, + [&](const RenderSwapchain &sc) { + fbInfo.colorTextures.emplace_back(sc.swapchain->getColorTexture()); + }, + [&](const FormatView &view) { + // TODO(zhouzhenglong): add ImageView support + std::ignore = view; + CC_EXPECTS(false); + }, + [&](const SubresourceView &view) { + fbInfo.colorTextures.emplace_back(view.textureView); + }); + } else { + // ds or ds resolve + if (!info.isResolveView) { + renderingInfo.clearDepth = clearColor.x; + renderingInfo.clearStencil = static_cast(clearColor.y); + } + + auto &dsAttachment = info.isResolveView ? fbInfo.depthStencilResolveTexture : fbInfo.depthStencilTexture; + + auto resID = resourceAccessGraph.resourceIndex.at(viewName); + visitObject( + resID, resg, + [&](const ManagedTexture &tex) { + CC_EXPECTS(tex.texture); + dsAttachment = tex.texture.get(); + }, + [&](const IntrusivePtr &tex) { + dsAttachment = tex.get(); + }, + [&](const FormatView &view) { + std::ignore = view; + CC_EXPECTS(false); + }, + [&](const SubresourceView &view) { + std::ignore = view; + CC_EXPECTS(false); + }, + [](const auto & /*unused*/) { + CC_EXPECTS(false); + }); + } + } + renderingInfo.framebufferInfo = fbInfo; + + return renderingInfo; +} + +LayoutAccess FrameGraphDispatcher::getResourceAccess(ResourceGraph::vertex_descriptor r, RenderGraph::vertex_descriptor p) const { + auto ragVertID = resourceAccessGraph.passIndex.at(p); + const auto &resName = get(ResourceGraph::NameTag{}, resourceGraph, r); + auto range = resourceAccessGraph.resourceAccess.at(resName).equal_range(ragVertID); + return {range.first->second.accessFlag, range.second->second.accessFlag}; } /////////////////////////////////////////////////////////////////////////////////////INTERNAL⚡IMPLEMENTATION///////////////////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------predefine------------------------------------------------------------------ using PmrString = ccstd::pmr::string; -using RAG = ResourceAccessGraph; -using LGD = LayoutGraphData; -using gfx::PassType; -using BarrierMap = FrameGraphDispatcher::BarrierMap; -using AccessVertex = ResourceAccessGraph::vertex_descriptor; -using InputStatusTuple = std::tuple; -using ResourceHandle = ResourceGraph::vertex_descriptor; -using ResourceNames = PmrFlatSet; using EdgeList = std::pair; using CloseCircuit = std::pair; using CloseCircuits = std::vector; @@ -134,30 +329,23 @@ using ResourceLifeRecordMap = PmrFlatMap; struct Graphs { const RenderGraph &renderGraph; - ResourceGraph &resourceGraph; const LayoutGraphData &layoutGraphData; + ResourceGraph &resourceGraph; ResourceAccessGraph &resourceAccessGraph; RelationGraph &relationGraph; }; struct ViewStatus { - PmrString name; - const PassType passType; + const ccstd::pmr::string &name; + const AccessType access; const gfx::ShaderStageFlagBit visibility; - const gfx::MemoryAccessBit access; const gfx::AccessFlags accessFlag; - const ResourceUsage usage; + const ResourceRange ⦥ }; -auto defaultAccess = gfx::MemoryAccessBit::NONE; -auto defaultVisibility = gfx::ShaderStageFlagBit::NONE; - constexpr uint32_t EXPECT_START_ID = 0; constexpr uint32_t INVALID_ID = 0xFFFFFFFF; -using AccessTable = PmrFlatMap; -using ExternalResMap = PmrFlatMap; - // for scoped enum only template class GfxTypeConverter { @@ -168,39 +356,11 @@ public: } }; -// static auto toGfxAccess = GfxTypeConverter(); -gfx::MemoryAccessBit toGfxAccess(AccessType type) { - switch (type) { - case AccessType::READ: - return gfx::MemoryAccessBit::READ_ONLY; - case AccessType::WRITE: - return gfx::MemoryAccessBit::WRITE_ONLY; - case AccessType::READ_WRITE: - return gfx::MemoryAccessBit::READ_WRITE; - default: - return gfx::MemoryAccessBit::NONE; - } -}; - // TODO(Zeqiang): remove barrier in renderpassinfo gfx::GeneralBarrier *getGeneralBarrier(gfx::Device *device, gfx::AccessFlagBit prevAccess, gfx::AccessFlagBit nextAccess) { return device->getGeneralBarrier({prevAccess, nextAccess}); } -// AccessStatus.vertID : in resourceNode it's resource ID; in barrierNode it's pass ID. -AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ResourceGraph &rg, const ViewStatus &status); -gfx::ShaderStageFlagBit getVisibilityByDescName(const RenderGraph &renderGraph, const LGD &lgd, uint32_t passID, const PmrString &resName); - -PmrString addAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status); -void addCopyAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status, const Range &range); -void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass &pass); -void processComputePass(const Graphs &graphs, uint32_t passID, const ComputePass &pass); -void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSubpass &pass); -void processComputeSubpass(const Graphs &graphs, uint32_t passID, const ComputeSubpass &pass); -void processCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass); -void processRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePass &pass); -auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAccess memAccess, gfx::ShaderStageFlags visibility, const ResourceGraph &resourceGraph, bool rasterized); - // execution order BUT NOT LOGICALLY bool isPassExecAdjecent(uint32_t passLID, uint32_t passRID) { return std::abs(static_cast(passLID) - static_cast(passRID)) <= 1; @@ -235,11 +395,21 @@ inline bool isAttachmentAccess(gfx::AccessFlagBit flag) { gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE); } +// SHADING_RATE may be ambiguos inline bool isReadOnlyAccess(gfx::AccessFlagBit flag) { - return flag < gfx::AccessFlagBit::PRESENT || flag == gfx::AccessFlagBit::SHADING_RATE; + return static_cast(flag) < static_cast(gfx::AccessFlagBit::PRESENT) || flag == gfx::AccessFlagBit::SHADING_RATE; +} + +bool accessDependent(const gfx::AccessFlagBit lhs, const gfx::AccessFlagBit &rhs, bool buffer) { + bool dep{false}; + if (buffer) { + dep = !isReadOnlyAccess(lhs) || !isReadOnlyAccess(rhs); + } else { + dep = (!isReadOnlyAccess(lhs) || !isReadOnlyAccess(rhs)) || (lhs != rhs); + } + return dep; } -bool isTransitionStatusDependent(const AccessStatus &lhs, const AccessStatus &rhs); template bool tryAddEdge(uint32_t srcVertex, uint32_t dstVertex, Graph &graph); @@ -249,6 +419,1135 @@ inline RelationGraph::vertex_descriptor add_vertex(RelationGraph &g) { // NOLINT return add_vertex(g, count++); } +bool isResourceView(const ResourceGraph::vertex_descriptor v, const ResourceGraph &resg) { + return resg.isTextureView(v); // || isBufferView +} + +ResourceRange getResourceRange(const ResourceGraph::vertex_descriptor v, + const ResourceGraph &resg) { + const auto &desc = get(ResourceGraph::DescTag{}, resg, v); + ResourceRange range{ + desc.width, + desc.height, + desc.depthOrArraySize, + }; + + if (isResourceView(v, resg)) { + const auto *const subResView = get_if(v, &resg); + range.firstSlice = subResView->firstArraySlice; + range.numSlices = subResView->numArraySlices; + range.mipLevel = subResView->indexOrFirstMipLevel; + range.levelCount = subResView->numMipLevels; + range.basePlane = subResView->firstPlane; + range.planeCount = subResView->numPlanes; + } else { + range.numSlices = desc.depthOrArraySize; + range.levelCount = desc.mipLevels; + } + + return range; +} + +ResourceGraph::vertex_descriptor realID(const ccstd::pmr::string &name, const ResourceGraph &resg) { + auto resID = vertex(name, resg); + while (parent(resID, resg) != ResourceGraph::null_vertex()) { + resID = parent(resID, resg); + } + return resID; +} + +bool depthStencil(gfx::Format format) { + return format == gfx::Format::DEPTH_STENCIL || format == gfx::Format::DEPTH; +} + +void subResourceFeedback(ResourceGraph &resg, ResourceGraph::vertex_descriptor parentID, gfx::Format subFormat) { + auto &parentDesc = get(ResourceGraph::DescTag{}, resg, parentID); + if (depthStencil(subFormat) || parentDesc.format != subFormat) { + parentDesc.textureFlags |= gfx::TextureFlagBit::MUTABLE_VIEW_FORMAT; + } +} + +auto dependencyCheck(ResourceAccessGraph &rag, ResourceAccessGraph::vertex_descriptor curVertID, ResourceGraph &resourceGraph, const ViewStatus &viewStatus) { + auto &accessRecord = rag.resourceAccess; + const auto &[name, access, visibility, accessFlag, originRange] = viewStatus; + auto resourceID = rag.resourceIndex.at(name); + const auto &states = get(ResourceGraph::StatesTag{}, resourceGraph, resourceID); + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resourceID); + + auto range = originRange; + if (rag.movedSourceStatus.find(name) != rag.movedSourceStatus.end()) { + range = rag.movedSourceStatus.at(name).range; + } + + bool isExternalPass = get(get(ResourceGraph::TraitsTag{}, resourceGraph), resourceID).hasSideEffects(); + auto iter = accessRecord.find(name); + ResourceAccessGraph::vertex_descriptor lastVertID{EXPECT_START_ID}; + gfx::AccessFlagBit lastAccess{gfx::AccessFlagBit::NONE}; + + if (iter == accessRecord.end()) { + accessRecord[name].emplace(curVertID, AccessStatus{accessFlag, range}); + if (isExternalPass) { + rag.leafPasses[curVertID] = LeafStatus{true, isReadOnlyAccess(accessFlag)}; + lastAccess = states.states; + } + + // update parent + auto parentID = realID(name, resourceGraph); + if (parentID != resourceID) { + const auto &realName = get(ResourceGraph::NameTag{}, resourceGraph, parentID); + auto lastIter = accessRecord[realName].rbegin(); + if (lastIter->first == curVertID) { + // in case more than 1 view of same resource in a renderpass + ++lastIter; + } + accessRecord[name].emplace(*lastIter); + accessRecord[realName][curVertID] = AccessStatus{accessFlag, range}; + subResourceFeedback(resourceGraph, parentID, desc.format); + } else { + accessRecord[name].emplace(0, AccessStatus{lastAccess, range}); + } + } else { + auto &transMap = iter->second; + CC_ASSERT(!transMap.empty()); + + const auto lastRecordIter = (--transMap.end()); + const auto &lastStatus = lastRecordIter->second; + lastAccess = lastStatus.accessFlag; + bool isBuffer = desc.dimension == ResourceDimension::BUFFER; + bool dependent = accessDependent(lastAccess, accessFlag, isBuffer); + + if (!dependent) { + for (auto recordIter = transMap.rbegin(); recordIter != transMap.rend(); ++recordIter) { + if (accessDependent(recordIter->second.accessFlag, accessFlag, isBuffer)) { + lastVertID = recordIter->first; + break; + } + } + if (isExternalPass) { + // only external res will be manually record here, leaf pass with transient resource will be culled by default, + // those leaf passes with ALL read access on external(or with transients) res can be culled. + rag.leafPasses[curVertID].needCulling &= (access == AccessType::READ); + lastAccess = states.states; + } + transMap[curVertID] = {accessFlag, range}; + } else { + lastVertID = lastRecordIter->first; + transMap[curVertID] = {accessFlag, range}; + + if (rag.leafPasses.find(curVertID) != rag.leafPasses.end()) { + // only write into externalRes counts + if (isExternalPass) { + rag.leafPasses[curVertID].needCulling &= (access == AccessType::READ); + } + } + } + + if (rag.leafPasses.find(lastVertID) != rag.leafPasses.end()) { + rag.leafPasses.erase(lastVertID); + } + + if(viewStatus.access != AccessType::WRITE) { + subResourceFeedback(resourceGraph, resourceID, desc.format); + } + } + auto lastDependentVert = lastVertID; // last dependent vert, WAW/WAR/RAW + auto nearestAccess = lastAccess; // last access, maybe RAR + return std::make_tuple(lastDependentVert, nearestAccess); +} + +ResourceGraph::vertex_descriptor parentResource(ResourceGraph::vertex_descriptor vert, const ResourceGraph &resg) { + const auto &desc = get(ResourceGraph::DescTag{}, resg, vert); + auto ret = vert; + if (desc.dimension == ResourceDimension::BUFFER) { + // TODO(Zeqaing): bufferview + } else { + auto srcParentID = vert; + while (resg.isTextureView(srcParentID)) { + srcParentID = parent(srcParentID, resg); + } + ret = srcParentID; + } + return ret; +} + +gfx::ShaderStageFlagBit getVisibility(const RenderGraph &renderGraph, const LayoutGraphData &lgd, uint32_t passID, const PmrString &resName) { // NOLINT + auto iter = lgd.attributeIndex.find(resName); + if (iter == lgd.attributeIndex.end()) { + iter = lgd.constantIndex.find(resName); + if (iter == lgd.constantIndex.end()) { + // resource not in descriptor: eg. input or output attachment. + return gfx::ShaderStageFlagBit::NONE; + } + } + auto slotID = iter->second; + + auto layoutName = get(RenderGraph::LayoutTag{}, renderGraph, passID); + auto layoutID = locate(LayoutGraphData::null_vertex(), layoutName, lgd); + const auto &layout = get(LayoutGraphData::LayoutTag{}, lgd, layoutID); + for (const auto &pair : layout.descriptorSets) { + for (const auto &block : pair.second.descriptorSetLayoutData.descriptorBlocks) { + for (const auto &descriptor : block.descriptors) { + if (descriptor.descriptorID.value == slotID.value) { + return block.visibility; + } + } + } + } + // unreachable + CC_EXPECTS(false); + + return gfx::ShaderStageFlagBit::NONE; +}; + +gfx::MemoryAccessBit toGfxAccess(AccessType type) { + switch (type) { + case AccessType::READ: + return gfx::MemoryAccessBit::READ_ONLY; + case AccessType::WRITE: + return gfx::MemoryAccessBit::WRITE_ONLY; + case AccessType::READ_WRITE: + return gfx::MemoryAccessBit::READ_WRITE; + default: + return gfx::MemoryAccessBit::NONE; + } +}; + +auto mapTextureFlags(ResourceFlags flags) { + gfx::TextureUsage usage = gfx::TextureUsage::NONE; + if ((flags & ResourceFlags::SAMPLED) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::SAMPLED; + } + if ((flags & ResourceFlags::STORAGE) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::STORAGE; + } + if ((flags & ResourceFlags::SHADING_RATE) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::SHADING_RATE; + } + if ((flags & ResourceFlags::COLOR_ATTACHMENT) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::COLOR_ATTACHMENT; + } + if ((flags & ResourceFlags::DEPTH_STENCIL_ATTACHMENT) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT; + } + if ((flags & ResourceFlags::INPUT_ATTACHMENT) != ResourceFlags::NONE) { + usage |= gfx::TextureUsage::INPUT_ATTACHMENT; + } + return usage; +} + +auto getTextureStatus(std::string_view name, AccessType access, gfx::ShaderStageFlags visibility, const ResourceGraph &resourceGraph, bool rasterized) { + gfx::ShaderStageFlags vis{visibility}; + if (vis == gfx::ShaderStageFlags::NONE) { + // attachment + vis = gfx::ShaderStageFlagBit::FRAGMENT; + } + gfx::AccessFlags accesFlag; + auto vertex = resourceGraph.valueIndex.at(name.data()); + + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, vertex); + + // can't find this resource in layoutdata, should be output attachment. + gfx::TextureUsage texUsage = gfx::TextureUsage::NONE; + if (access != AccessType::WRITE) { + if ((desc.flags & ResourceFlags::INPUT_ATTACHMENT) != ResourceFlags::NONE && rasterized) { + texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::INPUT_ATTACHMENT)); + } else { + texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::SAMPLED | gfx::TextureUsage::STORAGE | gfx::TextureUsage::SHADING_RATE | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT)); + } + } + + if (access != AccessType::READ) { + texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::STORAGE)); + } + accesFlag = gfx::getAccessFlags(texUsage, toGfxAccess(access), vis); + + return std::make_tuple(vis, accesFlag); +}; + +auto getBufferStatus(const PmrString &name, AccessType access, gfx::ShaderStageFlags visibility, const ResourceGraph &resourceGraph) { + gfx::AccessFlags accesFlag; + auto vertex = resourceGraph.valueIndex.at(name); + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, vertex); + + gfx::BufferUsage bufferUsage{gfx::BufferUsage::NONE}; + // copy is not included in this logic because copy can be set TRANSFER_xxx directly. + if (access != AccessType::READ) { + bufferUsage = gfx::BufferUsage::STORAGE; + } + + if (access != AccessType::WRITE) { + 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 + bufferUsage = uniformFlag ? gfx::BufferUsage::UNIFORM : gfx::BufferUsage::STORAGE; + } + + // those buffers not found in descriptorlayout but appear here, + // can and only can be VERTEX/INDEX/INDIRECT BUFFER, + // only copy pass is allowed. + + auto memAccess = toGfxAccess(access); + accesFlag = gfx::getAccessFlags(bufferUsage, gfx::MemoryUsage::DEVICE, memAccess, visibility); + return std::make_tuple(visibility, accesFlag); +}; + +void addAccessStatus(ResourceAccessGraph &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status) { + const auto &[name, access, visibility, accessFlag, range] = status; + uint32_t rescID = rg.valueIndex.at(name); + const auto &resourceDesc = get(ResourceGraph::DescTag{}, rg, rescID); + const auto &traits = get(ResourceGraph::TraitsTag{}, rg, rescID); + + CC_EXPECTS(rg.valueIndex.find(name) != rg.valueIndex.end()); + if (std::find(rag.resourceNames.begin(), rag.resourceNames.end(), name) == rag.resourceNames.end()) { + rag.resourceIndex.emplace(name, rescID); + rag.resourceNames.emplace_back(name); + } + + node.resourceStatus.emplace(name, AccessStatus{ + accessFlag, + range, + }); +} + +namespace { +const uint32_t ATTACHMENT_TYPE_WEIGHT[] = {0, 2, 1}; + +struct AttachmentSortKey { + gfx::SampleCount samples; + AccessType accessType; + uint32_t attachmentWeight; + const ccstd::pmr::string name; +}; + +struct AttachmentComparator { + bool operator()(const AttachmentSortKey &lhs, const AttachmentSortKey &rhs) const { + return std::tie(rhs.samples, lhs.accessType, lhs.attachmentWeight, lhs.name) < std::tie(lhs.samples, rhs.accessType, rhs.attachmentWeight, rhs.name); + } +}; + +struct ViewInfo { + gfx::Format format{gfx::Format::UNKNOWN}; + LayoutAccess access; + gfx::LoadOp loadOp; + gfx::StoreOp storeOp; + AttachmentType attachmentType; +}; + +using AttachmentMap = ccstd::pmr::map; +} // namespace + +void fillRenderPassInfo(const AttachmentMap &colorMap, + FGRenderPassInfo &fgRenderpassInfo, + const ResourceGraph &resg) { + for (const auto &pair : colorMap) { + const auto &key = pair.first; + const auto &viewInfo = pair.second; + if (viewInfo.attachmentType == AttachmentType::DEPTH_STENCIL) { + // put ds[sample > 1] to ds, ds[sample == 1] to dsResolve, swap them if not a ms pass in endRenderPass. + bool ms = key.samples != gfx::SampleCount::X1; + auto &ds = ms ? fgRenderpassInfo.rpInfo.depthStencilAttachment + : fgRenderpassInfo.rpInfo.depthStencilResolveAttachment; + auto &dsAccess = ms ? fgRenderpassInfo.dsAccess : fgRenderpassInfo.dsResolveAccess; + if (ds.format == gfx::Format::UNKNOWN) { + ds.depthLoadOp = viewInfo.loadOp; + ds.stencilLoadOp = viewInfo.loadOp; + ds.sampleCount = key.samples; + ds.format = viewInfo.format; + dsAccess.prevAccess = viewInfo.access.prevAccess; + } + ds.depthStoreOp = viewInfo.storeOp; + ds.stencilStoreOp = viewInfo.storeOp; + dsAccess.nextAccess = viewInfo.access.nextAccess; + + auto iter = fgRenderpassInfo.viewIndex.find(key.name.c_str()); + if (iter == fgRenderpassInfo.viewIndex.end()) { + auto parentID = realID(key.name, resg); + const auto &parentName = get(ResourceGraph::NameTag{}, resg, parentID); + AttachmentInfo attachmentInfo(fgRenderpassInfo.get_allocator()); + attachmentInfo.parentName = parentName; + attachmentInfo.attachmentIndex = gfx::INVALID_BINDING; + attachmentInfo.isResolveView = fgRenderpassInfo.resolveCount && key.samples == gfx::SampleCount::X1; + fgRenderpassInfo.viewIndex.emplace(key.name, attachmentInfo); + } + } else { + auto iter = fgRenderpassInfo.viewIndex.find(key.name.c_str()); + auto &colors = fgRenderpassInfo.rpInfo.colorAttachments; + if (iter == fgRenderpassInfo.viewIndex.end()) { + auto colorIndex = fgRenderpassInfo.orderedViews.size(); + auto &color = colors.emplace_back(); + color.format = viewInfo.format; + color.sampleCount = key.samples; + color.storeOp = viewInfo.storeOp; + color.loadOp = viewInfo.loadOp; + fgRenderpassInfo.colorAccesses.emplace_back(LayoutAccess{viewInfo.access.prevAccess, viewInfo.access.nextAccess}); + fgRenderpassInfo.colorAccesses[colorIndex].nextAccess = viewInfo.access.nextAccess; + + auto parentID = realID(key.name, resg); + const auto &parentName = get(ResourceGraph::NameTag{}, resg, parentID); + AttachmentInfo attachmentInfo(fgRenderpassInfo.get_allocator()); + attachmentInfo.parentName = parentName; + attachmentInfo.attachmentIndex = static_cast(fgRenderpassInfo.orderedViews.size()); + attachmentInfo.isResolveView = fgRenderpassInfo.resolveCount && key.samples == gfx::SampleCount::X1; + + fgRenderpassInfo.viewIndex.emplace(key.name, attachmentInfo); + fgRenderpassInfo.orderedViews.emplace_back(key.name); + } else { + const auto &attachmentInfo = fgRenderpassInfo.viewIndex.at(key.name); + auto cIndex = attachmentInfo.attachmentIndex; + if (cIndex == gfx::INVALID_BINDING) { + bool ms = key.samples == gfx::SampleCount::X1; + auto &ds = ms ? fgRenderpassInfo.rpInfo.depthStencilAttachment : fgRenderpassInfo.rpInfo.depthStencilResolveAttachment; + ds.depthStoreOp = viewInfo.storeOp; + ds.stencilStoreOp = viewInfo.storeOp; + auto &access = ms ? fgRenderpassInfo.dsAccess : fgRenderpassInfo.dsResolveAccess; + access.nextAccess = viewInfo.access.nextAccess; + } else { + auto &color = fgRenderpassInfo.rpInfo.colorAttachments[cIndex]; + color.storeOp = viewInfo.storeOp; + fgRenderpassInfo.colorAccesses[cIndex].nextAccess = viewInfo.access.nextAccess; + } + } + } + } +}; + +[[nodiscard("concat")]] ccstd::pmr::string concatResName( + std::string_view name0, + std::string_view name1, + boost::container::pmr::memory_resource *scratch) { + ccstd::pmr::string name(name0, scratch); + name += "/"; + name += name1; + return name; +} + +void extractNames(const ccstd::pmr::string &resName, + const RasterView &view, + ccstd::pmr::vector> &names) { + // depth_stencil + if (view.attachmentType == AttachmentType::DEPTH_STENCIL) { + if (!defaultAttachment(view.slotName)) { + if (strstr(resName.c_str(), "/")) { + names.emplace_back(resName, 0); + } else { + auto &subresName = names.emplace_back(); + subresName.first = concatResName(resName, DEPTH_PLANE_NAME, names.get_allocator().resource()); + subresName.second = 0; + } + } + if (!defaultAttachment(view.slotName1)) { + if (strstr(resName.c_str(), "/")) { + names.emplace_back(resName, 1); + } else { + auto &subresName = names.emplace_back(); + subresName.first = concatResName(resName, STENCIL_PLANE_NAME, names.get_allocator().resource()); + subresName.second = 1; + } + } + } + + // cube + + // array + + if (names.empty()) { + names.emplace_back(resName, 0); + } +} + +[[nodiscard("subresName")]] ccstd::pmr::string getSubresName(const ccstd::pmr::string &resName, + uint32_t planeID, const ResourceGraph& resg, + boost::container::pmr::memory_resource* scratch) { + const auto& desc = get(ResourceGraph::DescTag{}, resg, vertex(resName, resg)); + if(desc.format == gfx::Format::DEPTH_STENCIL) { + auto nameView = planeID == 0 ? DEPTH_PLANE_NAME : STENCIL_PLANE_NAME; + const auto &subresName = concatResName(resName, nameView, scratch); + return subresName; + } + + + // cube + + // array + + // UNREACHABLE + CC_ASSERT(false); + return ""; +} + +auto checkRasterViews(const Graphs &graphs, + ResourceAccessGraph::vertex_descriptor ragVertID, + ResourceAccessNode &node, + const RasterViewsMap &rasterViews, + AttachmentMap &colorMap) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + const auto passID = get(ResourceAccessGraph::PassIDTag{}, resourceAccessGraph, ragVertID); + bool dependent = false; + bool hasDS = false; + + auto explicitVis = gfx::ShaderStageFlagBit::NONE; + if (holds(passID, renderGraph)) { + explicitVis |= gfx::ShaderStageFlagBit::COMPUTE; + } + + for (const auto &pair : rasterViews) { + const auto &rasterView = pair.second; + const auto &resName = pair.first; + const auto resID = vertex(resName, resourceGraph); + auto access = rasterView.accessType; + gfx::ShaderStageFlagBit originVis = getVisibility(renderGraph, layoutGraphData, passID, pair.second.slotName) | explicitVis | pair.second.shaderStageFlags; + const auto &[vis, accessFlag] = getTextureStatus(resName.data(), access, originVis, resourceGraph, true); + auto range = getResourceRange(resID, resourceGraph); + + ViewStatus viewStatus{resName, access, vis, accessFlag, range}; + addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); + + const auto &[lastVertId, lastAccess] = dependencyCheck(resourceAccessGraph, ragVertID, resourceGraph, viewStatus); + tryAddEdge(lastVertId, ragVertID, resourceAccessGraph); + tryAddEdge(lastVertId, ragVertID, relationGraph); + dependent |= (lastVertId != EXPECT_START_ID); + + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + colorMap.emplace(AttachmentSortKey{desc.sampleCount, + rasterView.accessType, + ATTACHMENT_TYPE_WEIGHT[static_cast(rasterView.attachmentType)], + resName}, + ViewInfo{desc.format, + LayoutAccess{lastAccess, accessFlag}, + rasterView.loadOp, + rasterView.storeOp, + rasterView.attachmentType}); + hasDS |= rasterView.attachmentType == AttachmentType::DEPTH_STENCIL; + + ccstd::pmr::vector> names(resourceAccessGraph.get_allocator()); + extractNames(resName, rasterView, names); + for (const auto& [subresFullName, plane] : names) { + resourceAccessGraph.resourceIndex.emplace(subresFullName, vertex(subresFullName, resourceGraph)); + } + } + return std::make_tuple(dependent, hasDS); +} + +bool checkComputeViews(const Graphs &graphs, ResourceAccessGraph::vertex_descriptor ragVertID, ResourceAccessNode &node, const ComputeViewsMap &computeViews) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + const auto passID = get(ResourceAccessGraph::PassIDTag{}, resourceAccessGraph, ragVertID); + bool dependent = false; + + for (const auto &pair : computeViews) { + const auto &values = pair.second; + const auto &resName = pair.first; + const auto resID = vertex(resName, resourceGraph); + auto range = getResourceRange(vertex(resName, resourceGraph), resourceGraph); + for (const auto &computeView : values) { + gfx::ShaderStageFlagBit vis = gfx::ShaderStageFlagBit::NONE; + for (const auto &view : pair.second) { + vis |= getVisibility(renderGraph, layoutGraphData, passID, view.name); + vis |= view.shaderStageFlags; + } + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + gfx::AccessFlagBit accessFlag{gfx::AccessFlagBit::NONE}; + if (desc.dimension == ResourceDimension::BUFFER) { + const auto &[ignore0, access] = getBufferStatus(pair.first, computeView.accessType, vis, resourceGraph); + accessFlag = access; + } else { + const auto &[ignore0, access] = getTextureStatus(pair.first, computeView.accessType, vis, resourceGraph, false); + accessFlag = access; + } + range.firstSlice = computeView.plane; + range.numSlices = 1; + ViewStatus viewStatus{pair.first, computeView.accessType, vis, accessFlag, range}; + addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); + auto [lastVertId, neareastAccess] = dependencyCheck(resourceAccessGraph, ragVertID, resourceGraph, viewStatus); + + tryAddEdge(lastVertId, ragVertID, resourceAccessGraph); + tryAddEdge(lastVertId, ragVertID, relationGraph); + dependent = lastVertId != EXPECT_START_ID; + + if(out_degree(resID, resourceGraph)) { + const auto& subresFullName = getSubresName(resName, computeView.plane, resourceGraph, resourceAccessGraph.resource()); + resourceAccessGraph.resourceIndex.emplace(subresFullName, vertex(subresFullName, resourceGraph)); + } + } + } + + return dependent; +} + +bool checkResolveResource(const Graphs &graphs, + uint32_t ragVertID, + ResourceAccessNode &node, + const ccstd::pmr::vector &resolves, + AttachmentMap &colorMap) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + const auto passID = get(ResourceAccessGraph::PassIDTag{}, resourceAccessGraph, ragVertID); + bool dependent = false; + + for (const auto &pair : resolves) { + const auto &resolveTargetName = pair.target; + + const auto &resID = vertex(resolveTargetName, resourceGraph); + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + + bool isDS = desc.format == gfx::Format::DEPTH_STENCIL; + auto accessFlag = isDS ? gfx::AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE : gfx::AccessFlagBit::COLOR_ATTACHMENT_WRITE; + + gfx::ShaderStageFlagBit vis = gfx::ShaderStageFlagBit::FRAGMENT; + auto range = getResourceRange(resID, resourceGraph); + + ViewStatus viewStatus{resolveTargetName, AccessType::WRITE, vis, accessFlag, range}; + addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); + + const auto &[lastVertId, lastAccess] = dependencyCheck(resourceAccessGraph, ragVertID, resourceGraph, viewStatus); + tryAddEdge(lastVertId, ragVertID, resourceAccessGraph); + tryAddEdge(lastVertId, ragVertID, relationGraph); + dependent = lastVertId != EXPECT_START_ID; + + AttachmentType attachmentType = isDS ? AttachmentType::DEPTH_STENCIL : AttachmentType::RENDER_TARGET; + colorMap.emplace(AttachmentSortKey{desc.sampleCount, + AccessType::WRITE, + ATTACHMENT_TYPE_WEIGHT[static_cast(attachmentType)], + resolveTargetName}, + ViewInfo{desc.format, + LayoutAccess{lastAccess, accessFlag}, + gfx::LoadOp::DISCARD, + gfx::StoreOp::STORE, + attachmentType}); + } + return dependent; +} + +uint32_t record(uint32_t index) { + uint32_t res = 1 << index; + return res; +} + +uint32_t record(const ccstd::vector &indices) { + uint32_t res = 0; + for (auto attachmentIndex : indices) { + res |= 1 << attachmentIndex; + } + return res; +} + +void extract(uint32_t val, ccstd::vector &preserves) { + uint32_t index = 0; + while (val) { + if (val & 0x1) { + preserves.emplace_back(index); + } + val = val >> 1; + ++index; + } +} + +void getPreserves(gfx::RenderPassInfo &rpInfo) { + std::stack stack; + for (auto &info : rpInfo.subpasses) { + stack.push(&info); + } + + auto dsIndex = record(rpInfo.colorAttachments.size()); + auto dsMask = record(rpInfo.colorAttachments.size()) | record(rpInfo.colorAttachments.size() + 1); + + uint32_t laterRead{0}; + while (!stack.empty()) { + auto *tail = stack.top(); + stack.pop(); + + auto readRecord = record(tail->inputs); + auto writeRecord = record(tail->colors); + auto resolveRecord = record(tail->resolves); + + uint32_t dsRecord = 0; + if (tail->depthStencil != INVALID_ID) { + dsRecord |= record(tail->depthStencil); + } + if (tail->depthStencilResolve != INVALID_ID) { + dsRecord |= record(tail->depthStencilResolve); + } + auto shown = readRecord | writeRecord | resolveRecord | dsRecord; + auto needPreserve = (shown | laterRead) ^ shown; + needPreserve = (needPreserve & dsMask) == dsMask ? (needPreserve & ~dsMask) | dsIndex : (needPreserve & ~dsMask); + extract(needPreserve, tail->preserves); + laterRead |= readRecord; + } +} + +uint32_t getDepthStencilSlot(uint32_t uniqueResourceCount, uint32_t resolveCount, bool hasDS) { + auto dsSlot = uniqueResourceCount - hasDS + resolveCount; + return dsSlot; +} + +void startRenderPass(const Graphs &graphs, uint32_t passID, const RasterPass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + + auto &fgRenderPassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, vertID); + if (pass.subpassGraph.subpasses.empty()) { + AttachmentMap colorMap(resourceAccessGraph.get_allocator()); + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, vertID); + std::ignore = checkRasterViews(graphs, rlgVertID, accessNode, pass.rasterViews, colorMap); + std::ignore = checkComputeViews(graphs, rlgVertID, accessNode, pass.computeViews); + fillRenderPassInfo(colorMap, fgRenderPassInfo, resourceGraph); + } else { + const auto &subpasses = pass.subpassGraph.subpasses; + uint32_t initVal{0}; + fgRenderPassInfo.resolveCount = std::accumulate(subpasses.begin(), subpasses.end(), initVal, [](uint32_t ct, const Subpass &subpass) { + return ct + subpass.resolvePairs.size(); + }); + } + + const auto &subpasses = pass.subpassGraph.subpasses; + uint32_t initVal{0}; + ccstd::pmr::set resSet{resourceAccessGraph.get_allocator()}; + for (const auto &subpass : subpasses) { + for (const auto &view : subpass.rasterViews) { + resSet.emplace(realID(view.first, resourceGraph)); + } + auto &dsResolveAttachment = fgRenderPassInfo.rpInfo.depthStencilResolveAttachment; + if (dsResolveAttachment.format != gfx::Format::UNKNOWN) { + const auto &dsAccess = fgRenderPassInfo.dsResolveAccess; + dsResolveAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), dsAccess.prevAccess, dsAccess.nextAccess); + } + } + fgRenderPassInfo.uniqueRasterViewCount = resSet.size(); +} + +void endRenderPass(const Graphs &graphs, uint32_t passID, const RasterPass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + + auto vertID = resourceAccessGraph.passIndex.at(passID); + auto rlgVertID = relationGraph.vertexMap.at(vertID); + + auto &node = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, vertID); + auto &fgRenderpassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, vertID); + + bool filledDS{fgRenderpassInfo.dsAccess.nextAccess != gfx::AccessFlags::NONE}; + bool filledDSResolve{fgRenderpassInfo.dsResolveAccess.nextAccess != gfx::AccessFlags::NONE}; + if (filledDSResolve && !filledDS) { + CC_ASSERT(fgRenderpassInfo.rpInfo.depthStencilAttachment.format == gfx::Format::UNKNOWN); + std::swap(fgRenderpassInfo.rpInfo.depthStencilAttachment, fgRenderpassInfo.rpInfo.depthStencilResolveAttachment); + std::swap(fgRenderpassInfo.dsAccess, fgRenderpassInfo.dsResolveAccess); + } + + auto colorSize = fgRenderpassInfo.orderedViews.size(); + for (auto dsIter = fgRenderpassInfo.viewIndex.begin(); dsIter != fgRenderpassInfo.viewIndex.end(); ++dsIter) { + const auto &resName = dsIter->first; + const auto &parentName = dsIter->second.parentName; + if ((dsIter->second.attachmentIndex == gfx::INVALID_BINDING) && (resName == parentName)) { + fgRenderpassInfo.orderedViews.emplace_back(dsIter->first); + } + } + + if (!pass.subpassGraph.subpasses.empty()) { + // for (auto &subpassInfo : fgRenderpassInfo.rpInfo.subpasses) { + // if (subpassInfo.depthStencil != gfx::INVALID_BINDING) { + // if (subpassInfo.depthStencil != gfx::INVALID_BINDING) { + // subpassInfo.depthStencil = colorSize; + // } + // if (subpassInfo.depthStencilResolve != gfx::INVALID_BINDING) { + // subpassInfo.depthStencilResolve = colorSize + 1; + // } + // } + // } + getPreserves(fgRenderpassInfo.rpInfo); + } +} + +void startRenderSubpass(const Graphs &graphs, uint32_t passID, const RasterSubpass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, rlgVertID); + + auto parentID = parent(passID, renderGraph); + auto parentRagVertID = resourceAccessGraph.passIndex.at(parentID); + auto &fgRenderpassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, parentRagVertID); + AttachmentMap colorMap(resourceAccessGraph.get_allocator()); + + auto [hasDep, hasDS] = checkRasterViews(graphs, rlgVertID, accessNode, pass.rasterViews, colorMap); + hasDep |= checkComputeViews(graphs, rlgVertID, accessNode, pass.computeViews); + hasDep |= checkResolveResource(graphs, rlgVertID, accessNode, pass.resolvePairs, colorMap); + fillRenderPassInfo(colorMap, fgRenderpassInfo, resourceGraph); + + auto &subpassInfo = fgRenderpassInfo.rpInfo.subpasses.emplace_back(); + auto &dependencies = fgRenderpassInfo.rpInfo.dependencies; + + // subpass info & subpass dependencies + for (const auto &pair : colorMap) { + const auto &sortKey = pair.first; + const std::string_view name = sortKey.name; + auto resID = vertex(sortKey.name, resourceGraph); + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + const auto &[ignored, cIndex, isResolveView] = fgRenderpassInfo.viewIndex.at(name.data()); + if (isResolveView) { + auto resolveIter = std::find_if(pass.resolvePairs.begin(), pass.resolvePairs.end(), [&name](const ResolvePair &resolve) { + return strcmp(resolve.target.c_str(), name.data()) == 0; + }); + if (desc.format == gfx::Format::DEPTH_STENCIL) { + subpassInfo.depthStencilResolve = getDepthStencilSlot(fgRenderpassInfo.uniqueRasterViewCount, fgRenderpassInfo.resolveCount, hasDS) + 1; + if (resolveIter->mode != gfx::ResolveMode::NONE) { + subpassInfo.depthResolveMode = resolveIter->mode; + } + if (resolveIter->mode1 != gfx::ResolveMode::NONE) { + subpassInfo.stencilResolveMode = resolveIter->mode1; + } + } else { + if (subpassInfo.resolves.empty()) { + subpassInfo.resolves.resize(pass.rasterViews.size() - hasDS, gfx::INVALID_BINDING); + } + const auto &resolveSrc = resolveIter->source; + const auto &resourceSrcInfo = fgRenderpassInfo.viewIndex.at(resolveSrc); + subpassInfo.resolves[resourceSrcInfo.attachmentIndex] = cIndex; + } + } else { + if (desc.format == gfx::Format::DEPTH_STENCIL) { + auto dsSlot = getDepthStencilSlot(fgRenderpassInfo.uniqueRasterViewCount, fgRenderpassInfo.resolveCount, hasDS); + if (sortKey.accessType != AccessType::WRITE) { + subpassInfo.inputs.emplace_back(dsSlot); + } + if (sortKey.accessType != AccessType::READ) { + subpassInfo.depthStencil = dsSlot; + } + } else { + if (sortKey.accessType != AccessType::WRITE) { + subpassInfo.inputs.emplace_back(cIndex); + } + if (sortKey.accessType != AccessType::READ) { + subpassInfo.colors.emplace_back(cIndex); + } + + if (sortKey.accessType == AccessType::READ_WRITE) { + auto &selfDependency = dependencies.emplace_back(); + selfDependency.srcSubpass = pass.subpassID; + selfDependency.dstSubpass = pass.subpassID; + selfDependency.prevAccesses = pair.second.access.nextAccess; + selfDependency.nextAccesses = pair.second.access.nextAccess; + } + } + } + + if (hasDep) { + auto &dependency = dependencies.emplace_back(); + auto lastIter = ++resourceAccessGraph.resourceAccess[name.data()].rbegin(); + bool isBuffer = desc.dimension == ResourceDimension::BUFFER; + if (accessDependent(lastIter->second.accessFlag, accessNode.resourceStatus.at(name.data()).accessFlag, isBuffer) && lastIter->second.accessFlag != gfx::AccessFlagBit::NONE) { + auto lastVert = lastIter->first; + auto lastPassID = get(ResourceAccessGraph::PassIDTag{}, resourceAccessGraph, lastVert); + auto lastPassIndex = INVALID_ID; + if (holds(lastPassID, renderGraph) && (parent(lastPassID, renderGraph) == parentID)) { + const auto *lastPass = get_if(lastPassID, &renderGraph); + lastPassIndex = lastPass->subpassID; + } + + auto &dependency = dependencies.emplace_back(); + dependency.srcSubpass = lastPassIndex; + dependency.dstSubpass = pass.subpassID; + dependency.prevAccesses = lastIter->second.accessFlag; + dependency.nextAccesses = pair.second.access.nextAccess; + } + } + } +} + +void startComputeSubpass(const Graphs &graphs, uint32_t passID, const ComputeSubpass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, rlgVertID); + AttachmentMap colorMap(resourceAccessGraph.get_allocator()); + + auto parentID = parent(passID, renderGraph); + auto parentRagVertID = resourceAccessGraph.passIndex.at(parentID); + auto &fgRenderpassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, resourceAccessGraph, parentRagVertID); + + std::ignore = checkRasterViews(graphs, rlgVertID, accessNode, pass.rasterViews, colorMap); + std::ignore = checkComputeViews(graphs, rlgVertID, accessNode, pass.computeViews); + + fillRenderPassInfo(colorMap, fgRenderpassInfo, resourceGraph); +} + +void startComputePass(const Graphs &graphs, uint32_t passID, const ComputePass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, rlgVertID); + std::ignore = checkComputeViews(graphs, rlgVertID, accessNode, pass.computeViews); +} + +void startCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, rlgVertID); + + auto &resg = resourceGraph; + auto &rag = resourceAccessGraph; + auto &rlg = relationGraph; + auto checkCopy = [&](const ccstd::pmr::string &resName, + uint32_t firstSlice, + uint32_t firstMip, + uint32_t firstPlane, + uint32_t sliceCount, + uint32_t mipCount, + bool read) { + auto srcID = vertex(resName, resg); + auto srcRange = getResourceRange(srcID, resg); + srcRange.firstSlice = firstSlice; + srcRange.mipLevel = firstMip; + srcRange.basePlane = firstPlane; + srcRange.numSlices = sliceCount; + srcRange.levelCount = mipCount; + + AccessType access = read ? AccessType::READ : AccessType::WRITE; + gfx::AccessFlags accessFlag = read ? gfx::AccessFlags::TRANSFER_READ : gfx::AccessFlags::TRANSFER_WRITE; + ViewStatus srcViewStatus{resName, access, gfx::ShaderStageFlagBit::NONE, accessFlag, srcRange}; + addAccessStatus(rag, resg, accessNode, srcViewStatus); + const auto &[lastVertSrc, ignore1] = dependencyCheck(rag, vertID, resg, srcViewStatus); + tryAddEdge(lastVertSrc, vertID, rag); + tryAddEdge(lastVertSrc, rlgVertID, rlg); + }; + + for (const auto © : pass.copyPairs) { + checkCopy(copy.source, + copy.sourceFirstSlice, copy.sourceMostDetailedMip, copy.sourcePlaneSlice, + copy.numSlices, copy.mipLevels, true); + + checkCopy(copy.target, + copy.targetFirstSlice, copy.targetMostDetailedMip, copy.targetPlaneSlice, + copy.numSlices, copy.mipLevels, false); + } + + for (const auto &upload : pass.uploadPairs) { + checkCopy(upload.target, + upload.targetFirstSlice, upload.targetMostDetailedMip, upload.targetPlaneSlice, + upload.numSlices, upload.mipLevels, false); + } +} + +void startRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + + auto vertID = add_vertex(resourceAccessGraph, passID); + auto rlgVertID = add_vertex(relationGraph, vertID); + CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); + + auto &accessNode = get(ResourceAccessGraph::PassNodeTag{}, resourceAccessGraph, rlgVertID); + std::ignore = checkComputeViews(graphs, rlgVertID, accessNode, pass.computeViews); +} + +namespace { +struct SliceNode { + bool full{false}; + ccstd::pmr::vector mips; +}; + +struct TextureNode { + bool full{false}; + ccstd::pmr::vector slices; +}; + +struct ResourceNode { + ccstd::pmr::vector planes; +}; +} // namespace + +bool rangeCheck(ccstd::pmr::map &status, + const ResourceDesc &desc, + const PmrString &targetName, + uint32_t firstSlice, uint32_t numSlices, + uint32_t firstMip, uint32_t mipLevels, + uint32_t planeIndex) { + if (status.find(targetName) == status.end()) { + status.emplace(targetName, ResourceNode{}); + } + + if (planeIndex >= status[targetName].planes.size()) { + status[targetName].planes.resize(planeIndex + 1); + status[targetName].planes[planeIndex].slices.resize(desc.depthOrArraySize); + for (auto &slice : status[targetName].planes[planeIndex].slices) { + slice.mips.resize(desc.mipLevels, std::numeric_limits::max()); + } + } + + // no spare space in target + bool check = !status[targetName].planes[planeIndex].full; + for (auto slice = firstSlice; slice < firstSlice + numSlices; ++slice) { + auto &slices = status[targetName].planes[planeIndex].slices; + // no spare space in this slice + check &= !slices[slice].full; + for (auto mip = firstMip; mip < firstMip + mipLevels; ++mip) { + auto &mips = slices[slice].mips; + // this mip has been taken + check &= mips[mip] == std::numeric_limits::max(); + mips[mip] = mip; + auto maxIter = std::max_element(mips.begin(), mips.end()); + if ((*maxIter) != std::numeric_limits::max()) { + // linear increasing + check &= (*maxIter) == mips.size() - 1; + slices[slice].full = true; + } + } + if (std::all_of(slices.begin(), slices.end(), [](const SliceNode &sliceNode) { return sliceNode.full; })) { + status[targetName].planes[planeIndex].full = true; + } + } + return check; +} + +bool moveValidation(const MovePass& pass, ResourceAccessGraph& rag, const ResourceGraph& resourceGraph) { + bool check = true; + // ccstd::pmr::map sourceCheck; + ccstd::pmr::map targetCheck; + for (const auto &movePair : pass.movePairs) { + const auto &fromResName = movePair.source; + const auto fromResID = resourceGraph.valueIndex.at(fromResName); + const auto &fromResDesc = get(ResourceGraph::DescTag{}, resourceGraph, fromResID); + + const auto &toResName = movePair.target; + const auto toResID = resourceGraph.valueIndex.at(toResName); + const auto &toResDesc = get(ResourceGraph::DescTag{}, resourceGraph, toResID); + + const auto &fromResTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, fromResID); + const auto &toResTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, toResID); + auto commonUsage = fromResDesc.flags | toResDesc.flags; + + // bool sourceRangeValid = rangeCheck(targetCheck, toResDesc, fromResName, movePair.targetFirstSlice, movePair.numSlices, movePair.targetMostDetailedMip, movePair.mipLevels, movePair.targetPlaneSlice); + bool targetRangeValid = rangeCheck(targetCheck, toResDesc, toResName, movePair.targetFirstSlice, movePair.numSlices, movePair.targetMostDetailedMip, movePair.mipLevels, movePair.targetPlaneSlice); + + uint32_t validConditions[] = { + !fromResTraits.hasSideEffects(), + rag.movedSourceStatus.find(toResName) == rag.movedSourceStatus.end(), + rag.movedSourceStatus.find(fromResName) == rag.movedSourceStatus.end(), + targetRangeValid, + fromResTraits.residency != ResourceResidency::MEMORYLESS && toResTraits.residency != ResourceResidency::MEMORYLESS, + fromResDesc.dimension == toResDesc.dimension, + fromResDesc.width == toResDesc.width, + fromResDesc.height == toResDesc.height, + fromResDesc.format == toResDesc.format, + fromResDesc.sampleCount == toResDesc.sampleCount, + (fromResDesc.depthOrArraySize == toResDesc.depthOrArraySize) || (toResDesc.dimension != ResourceDimension::BUFFER), // full move if resource is buffer + }; + bool val = std::min_element(std::begin(validConditions), std::end(validConditions)); + check &= val; + } + + // full destination + check &= std::all_of(targetCheck.begin(), targetCheck.end(), [](const auto &pair) { + const ResourceNode &resNode = pair.second; + return std::all_of(resNode.planes.begin(), resNode.planes.end(), [](const auto &textureNode) { + return textureNode.full; + }); + }); + + return check; + } + +void startMovePass(const Graphs &graphs, uint32_t passID, const MovePass &pass) { + const auto &[renderGraph, layoutGraphData, resourceGraph, resourceAccessGraph, relationGraph] = graphs; + + if(moveValidation(pass, resourceAccessGraph, resourceGraph)) { + for(const auto& pair : pass.movePairs) { + auto srcResourceRange = getResourceRange(vertex(pair.source, resourceGraph), resourceGraph); + srcResourceRange.firstSlice = pair.targetFirstSlice; + srcResourceRange.mipLevel = pair.targetMostDetailedMip; + srcResourceRange.basePlane = pair.targetPlaneSlice; + + auto lastStatusIter = resourceAccessGraph.resourceAccess.at(pair.source).rbegin(); + resourceAccessGraph.movedSourceStatus.emplace(pair.source, AccessStatus{lastStatusIter->second.accessFlag, srcResourceRange}); + resourceAccessGraph.movedTarget[pair.target].emplace_back(pair.source); + resourceAccessGraph.resourceAccess[pair.target] = resourceAccessGraph.resourceAccess[pair.source]; + + auto targetResID = findVertex(pair.target, resourceGraph); + resourceAccessGraph.resourceIndex[pair.target] = targetResID; + + auto &rag = resourceAccessGraph; + std::function feedBack = [&](const ccstd::pmr::string &source, ResourceGraph::vertex_descriptor v) { + rag.resourceIndex[source] = v; + if (rag.movedTarget.find(source) != rag.movedTarget.end()) { + for (const auto &prt : rag.movedTarget[source]) { + feedBack(prt, v); + } + } + }; + feedBack(pair.source, targetResID); + } + } else { + for(const auto& pair : pass.movePairs) { + CopyPass copyPass(resourceAccessGraph.get_allocator()); + copyPass.copyPairs.emplace_back(CopyPair( + pair.source, + pair.target, + pair.mipLevels, pair.numSlices, + 0, 0, 0, + pair.targetMostDetailedMip, pair.targetFirstSlice, pair.targetPlaneSlice)); + startCopyPass(graphs, passID, copyPass); + } + } +} + +struct DependencyVisitor : boost::dfs_visitor<> { + void discover_vertex(RenderGraph::vertex_descriptor passID, + const AddressableView &gv) const { + visitObject( + passID, gv.mGraph, + [&](const RasterPass &pass) { + startRenderPass(graphs, passID, pass); + }, + [&](const RasterSubpass &pass) { + startRenderSubpass(graphs, passID, pass); + }, + [&](const ComputeSubpass &pass) { + startComputeSubpass(graphs, passID, pass); + }, + [&](const ComputePass &pass) { + startComputePass(graphs, passID, pass); + }, + [&](const CopyPass &pass) { + startCopyPass(graphs, passID, pass); + }, + [&](const MovePass &pass) { + startMovePass(graphs, passID, pass); + }, + [&](const RaytracePass &pass) { + startRaytracePass(graphs, passID, pass); + }, + [&](const auto & /*pass*/) { + // do nothing + }); + } + + void finish_vertex(RenderGraph::vertex_descriptor passID, + const AddressableView &gv) const { + visitObject( + passID, gv.mGraph, + [&](const RasterPass &pass) { + endRenderPass(graphs, passID, pass); + }, + [&](const auto & /*pass*/) { + // do nothing + }); + } + + const Graphs &graphs; +}; + // status of resource access void buildAccessGraph(const Graphs &graphs) { // what we need: @@ -293,30 +1592,13 @@ void buildAccessGraph(const Graphs &graphs) { add_vertex(relationGraph, startID); - for (const auto passID : makeRange(vertices(renderGraph))) { - visitObject( - passID, renderGraph, - [&](const RasterPass &pass) { - processRasterPass(graphs, passID, pass); - }, - [&](const RasterSubpass &pass) { - processRasterSubpass(graphs, passID, pass); - }, - [&](const ComputeSubpass &pass) { - processComputeSubpass(graphs, passID, pass); - }, - [&](const ComputePass &pass) { - processComputePass(graphs, passID, pass); - }, - [&](const CopyPass &pass) { - processCopyPass(graphs, passID, pass); - }, - [&](const RaytracePass &pass) { - processRaytracePass(graphs, passID, pass); - }, - [&](const auto & /*pass*/) { - // do nothing - }); + DependencyVisitor visitor{{}, graphs}; + auto colors = renderGraph.colors(renderGraph.resource()); + AddressableView gv{renderGraph}; + for (const auto passID : renderGraph.sortedVertices) { + if (!holds(passID, renderGraph) && !holds(passID, renderGraph)) { + boost::depth_first_visit(gv, passID, visitor, get(colors, renderGraph)); + } } auto &rag = resourceAccessGraph; @@ -325,12 +1607,8 @@ void buildAccessGraph(const Graphs &graphs) { using FuncType = void (*)(ResourceAccessGraph::vertex_descriptor, ResourceAccessGraph &); static FuncType leafCulling = [](ResourceAccessGraph::vertex_descriptor vertex, ResourceAccessGraph &rag) { rag.culledPasses.emplace(vertex); - auto &attachments = get(ResourceAccessGraph::AccessNodeTag{}, rag, vertex); - attachments.attachmentStatus.clear(); - if (attachments.nextSubpass) { - delete attachments.nextSubpass; - attachments.nextSubpass = nullptr; - } + auto &attachments = get(ResourceAccessGraph::PassNodeTag{}, rag, vertex); + attachments.resourceStatus.clear(); auto inEdges = in_edges(vertex, rag); for (auto iter = inEdges.first; iter < inEdges.second;) { auto inEdge = *iter; @@ -391,852 +1669,195 @@ void buildAccessGraph(const Graphs &graphs) { } #pragma region BUILD_BARRIERS -struct BarrierVisitor : public boost::bfs_visitor<> { - using Vertex = ResourceAccessGraph::vertex_descriptor; - using Edge = ResourceAccessGraph::edge_descriptor; - using Graph = ResourceAccessGraph; - - explicit BarrierVisitor( - const ResourceGraph &rg, - BarrierMap &barriers, // what we get - ExternalResMap &extMap, // record external res between frames - ResourceNames &resourceNamesIn, // for resource record - const AccessTable &accessRecordIn, // resource last meet - ResourceLifeRecordMap &rescLifeRecord, // resource lifetime - PmrFlatMap &rpInfosIn) - : barrierMap(barriers), resourceGraph(rg), externalMap(extMap), resourceNames(resourceNamesIn), accessRecord(accessRecordIn), resourceLifeRecord(rescLifeRecord), rpInfos(rpInfosIn) {} - - void updateResourceLifeTime(const ResourceAccessNode &node, ResourceAccessGraph::vertex_descriptor u) { - for (const auto &access : node.attachmentStatus) { - auto name = get(ResourceGraph::NameTag{}, resourceGraph, access.vertID); - if (resourceLifeRecord.find(name) == resourceLifeRecord.end()) { - resourceLifeRecord.emplace(name, ResourceLifeRecord{u, u}); - } else { - resourceLifeRecord.at(name).end = u; - } - } - } - - struct AccessNodeInfo { - const std::vector &status; - std::vector &edgeBarriers; // need to barrier front or back - const Vertex &vertID; - uint32_t subpassIndex{INVALID_ID}; - }; - - 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::AccessNodeTag{}, g, u); - updateResourceLifeTime(access, u); - - if (barrierMap.find(u) == barrierMap.end()) { - barrierMap.emplace(u, BarrierNode{{}, {}}); - } - - const auto *srcAccess = &access; - - auto *dstAccess = access.nextSubpass; - auto &blockBarrier = barrierMap[u].blockBarrier; - auto &barriers = barrierMap[u].subpassBarriers; - - uint32_t srcSubpass = 0; - uint32_t dstSubpass = 1; - bool isAdjacent = true; // subpass always adjacent to each other - if (dstAccess) { - if (!dstAccess->nextSubpass) { - return; - } - // subpass at least two passes inside. - // the very first pass becomes attachment status collection of all subpass - CC_ASSERT(dstAccess->nextSubpass); - srcAccess = dstAccess; - dstAccess = dstAccess->nextSubpass; - } - while (srcAccess) { - while (dstAccess) { - // 2 barriers at least when subpass exist - std::vector &srcRearBarriers = barriers[srcSubpass].rearBarriers; - std::vector &dstFrontBarriers = barriers[dstSubpass].frontBarriers; - - AccessNodeInfo from = {srcAccess->attachmentStatus, srcRearBarriers, u, srcSubpass}; - AccessNodeInfo to = {dstAccess->attachmentStatus, dstFrontBarriers, u, dstSubpass}; - std::set noUseSet; - fillBarrier(from, to, isAdjacent, noUseSet); - - dstAccess = dstAccess->nextSubpass; - ++dstSubpass; - } - srcAccess = srcAccess->nextSubpass; - if (srcAccess) { - dstAccess = srcAccess->nextSubpass; - ++srcSubpass; - dstSubpass = srcSubpass + 1; - } - } - } - - void discover_vertex(Vertex u, const Graph &g) { - processVertex(u, g); - } - - void finish_vertex(Vertex u, const Graph &g) { - auto &rearBarriers = barrierMap[u].blockBarrier.rearBarriers; - auto &frontBarriers = barrierMap[u].blockBarrier.frontBarriers; - Barrier *lastSubpassBarrier = nullptr; - uint32_t subpassIdx{0}; - for (const auto &barriers : barrierMap[u].subpassBarriers) { - if (!barriers.frontBarriers.empty()) { - auto &subpassDependencies = rpInfos.at(u).rpInfo.dependencies; - auto dependency = gfx::SubpassDependency{}; - dependency.srcSubpass = INVALID_ID; - dependency.dstSubpass = subpassIdx; - for (const auto &barrier : barriers.frontBarriers) { - if (barrier.beginStatus.accessFlag == gfx::AccessFlagBit::NONE) { - continue; - } - auto resID = barrier.resourceID; - auto findBarrierByResID = [resID](const Barrier &barrier) { - return barrier.resourceID == resID; - }; - auto resFinalPassID = accessRecord.at(resID).currStatus.vertID; - auto firstMeetIter = std::find_if(frontBarriers.begin(), frontBarriers.end(), findBarrierByResID); - auto innerResIter = std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID); - - if (firstMeetIter == frontBarriers.end() && innerResIter == rearBarriers.end() && resFinalPassID >= u) { - auto &collect = frontBarriers.emplace_back(barrier); - collect.beginStatus.vertID = collect.endStatus.vertID = u; - } - if ((barrier.beginStatus.vertID > dependency.srcSubpass) && (barrier.beginStatus.vertID != INVALID_ID)) { - dependency.srcSubpass = barrier.beginStatus.vertID; - } - - const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); - if (desc.format == gfx::Format::DEPTH_STENCIL || desc.format == gfx::Format::DEPTH) { - if (g.access.at(u).attachmentStatus.size() > 1) { - auto &dsDep = subpassDependencies.emplace_back(); - dsDep.srcSubpass = dependency.srcSubpass; - dsDep.dstSubpass = dependency.dstSubpass; - dsDep.prevAccesses |= barrier.beginStatus.accessFlag; - dsDep.nextAccesses |= barrier.endStatus.accessFlag; - } - } else { - bool isWriteAccess = !isReadOnlyAccess(barrier.endStatus.accessFlag); - if (isWriteAccess) { - auto &dep = subpassDependencies.emplace_back(); - dep.srcSubpass = dependency.srcSubpass; - dep.dstSubpass = dependency.dstSubpass; - dep.prevAccesses |= barrier.beginStatus.accessFlag; - dep.nextAccesses |= barrier.endStatus.accessFlag; - if (hasReadAccess(barrier.endStatus.accessFlag)) { - auto &selfDep = subpassDependencies.emplace_back(); - selfDep.srcSubpass = dependency.dstSubpass; - selfDep.dstSubpass = dependency.dstSubpass; - selfDep.prevAccesses |= barrier.endStatus.accessFlag; - selfDep.nextAccesses |= barrier.endStatus.accessFlag; - } - } else { - dependency.prevAccesses |= barrier.beginStatus.accessFlag; - dependency.nextAccesses |= barrier.endStatus.accessFlag; - } - } - } - if (dependency.prevAccesses != gfx::AccessFlagBit::NONE) { - subpassDependencies.emplace_back(dependency); - } - } - - if (!barriers.rearBarriers.empty()) { - auto &subpassDependencies = rpInfos.at(u).rpInfo.dependencies; - auto dependency = gfx::SubpassDependency{}; - dependency.srcSubpass = subpassIdx; - dependency.dstSubpass = INVALID_ID; - for (const auto &barrier : barriers.rearBarriers) { - if (barrier.endStatus.vertID < dependency.dstSubpass) { - dependency.dstSubpass = barrier.endStatus.vertID; - } - - auto resID = barrier.resourceID; - const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); - if (desc.format == gfx::Format::DEPTH_STENCIL || desc.format == gfx::Format::DEPTH) { - if (g.access.at(u).attachmentStatus.size() > 1) { - auto &dsDep = subpassDependencies.emplace_back(); - dsDep.srcSubpass = dependency.srcSubpass; - dsDep.dstSubpass = dependency.dstSubpass; - dsDep.prevAccesses |= barrier.beginStatus.accessFlag; - dsDep.nextAccesses |= barrier.endStatus.accessFlag; - } - } else { - bool isWriteAccess = !isReadOnlyAccess(barrier.endStatus.accessFlag); - if (isWriteAccess) { - auto &dep = subpassDependencies.emplace_back(); - dep.srcSubpass = dependency.srcSubpass; - dep.dstSubpass = dependency.dstSubpass; - dep.prevAccesses |= barrier.beginStatus.accessFlag; - dep.nextAccesses |= barrier.endStatus.accessFlag; - if (hasReadAccess(barrier.endStatus.accessFlag)) { - auto &selfDep = subpassDependencies.emplace_back(); - selfDep.srcSubpass = dependency.dstSubpass; - selfDep.dstSubpass = dependency.dstSubpass; - selfDep.prevAccesses |= barrier.endStatus.accessFlag; - selfDep.nextAccesses |= barrier.endStatus.accessFlag; - } - } else { - dependency.prevAccesses |= barrier.beginStatus.accessFlag; - dependency.nextAccesses |= barrier.endStatus.accessFlag; - } - } - } - if (dependency.prevAccesses != gfx::AccessFlagBit::NONE) { - subpassDependencies.emplace_back(dependency); - } - } - ++subpassIdx; - } - } - - void fillBarrier(const AccessNodeInfo &from, const AccessNodeInfo &to, bool isAdjacent, std::set &subpassResourceSet) { - const auto &[srcStatus, srcRearBarriers, srcPassVert, srcHasSubpass] = from; - const auto &[dstStatus, dstFrontBarriers, dstPassVert, dstHasSubpass] = to; - auto srcVert = srcPassVert; - auto dstVert = dstPassVert; - bool subToSubDeps = false; - if (srcPassVert == dstPassVert) { - srcVert = srcHasSubpass; - dstVert = dstHasSubpass; - subToSubDeps = true; - } - - bool dstExternalDeps = (srcHasSubpass != INVALID_ID) && (dstHasSubpass == INVALID_ID); - bool srcExternalDeps = (srcHasSubpass == INVALID_ID) && (dstHasSubpass != INVALID_ID); - - std::vector commonResources; - std::set_intersection(srcStatus.begin(), srcStatus.end(), - dstStatus.begin(), dstStatus.end(), - std::back_inserter(commonResources), - [](const AccessStatus &lhs, const AccessStatus &rhs) { - return lhs.vertID < rhs.vertID; - }); - if (!commonResources.empty()) { - // this edge is a logic edge added during pass reorder, - // no real dependency between this two vertices. - - // NOLINTNEXTLINE - for (uint32_t i = 0; i < commonResources.size(); ++i) { - uint32_t resourceID = commonResources[i].vertID; - if (subpassResourceSet.find(resourceID) != subpassResourceSet.end()) { - continue; - } - subpassResourceSet.emplace(resourceID); - auto findAccessByID = [resourceID](const AccessStatus &resAccess) { return resAccess.vertID == resourceID; }; - auto fromIter = std::find_if(srcStatus.begin(), srcStatus.end(), findAccessByID); - auto toIter = std::find_if(dstStatus.begin(), dstStatus.end(), findAccessByID); - - // can't happen - CC_ASSERT(fromIter != srcStatus.end()); - CC_ASSERT(toIter != dstStatus.end()); - - if (!isTransitionStatusDependent(*fromIter, *toIter)) { - continue; - } - - auto findBarrierNodeByResID = [resourceID](const Barrier &barrier) { return resourceID == barrier.resourceID; }; - - auto srcBarrierIter = srcRearBarriers.empty() ? srcRearBarriers.end() : std::find_if(srcRearBarriers.begin(), srcRearBarriers.end(), findBarrierNodeByResID); - auto dstBarrierIter = dstFrontBarriers.empty() ? dstFrontBarriers.end() : std::find_if(dstFrontBarriers.begin(), dstFrontBarriers.end(), findBarrierNodeByResID); - - auto dstVertDistribute = [&](uint32_t &vertID, bool depends) { - if (depends) { - vertID = INVALID_ID; - } else if (subToSubDeps) { - vertID = dstVert; - } else { - vertID = isAdjacent ? srcVert : dstVert; - } - }; - if (srcBarrierIter == srcRearBarriers.end()) { - auto srcAccess = (*fromIter); - srcAccess.vertID = dstExternalDeps ? INVALID_ID : srcVert; - auto dstAccess = (*toIter); - dstVertDistribute(dstAccess.vertID, dstExternalDeps); - - srcRearBarriers.emplace_back(Barrier{ - resourceID, - isAdjacent ? gfx::BarrierType::FULL : gfx::BarrierType::SPLIT_BEGIN, - nullptr, // generate later - srcAccess, - dstAccess, - }); - srcBarrierIter = std::prev(srcRearBarriers.end()); - } else { - if (isAdjacent) { - srcBarrierIter->type = gfx::BarrierType::FULL; - auto srcAccess = (*fromIter); - srcAccess.vertID = dstExternalDeps ? INVALID_ID : srcVert; - srcBarrierIter->beginStatus = srcAccess; - auto dstAccess = (*toIter); - dstVertDistribute(dstAccess.vertID, dstExternalDeps); - srcBarrierIter->endStatus = dstAccess; - } else { - auto &blockBarrier = barrierMap.at(srcPassVert).blockBarrier; - auto lastVert = srcBarrierIter->beginStatus.vertID; - auto blockIter = blockBarrier.rearBarriers.end(); - if (subToSubDeps) { - blockIter = std::find_if(blockBarrier.rearBarriers.begin(), blockBarrier.rearBarriers.end(), findBarrierNodeByResID); - lastVert = blockIter->beginStatus.vertID; - } - if (srcVert >= lastVert) { - auto srcAccess = (*fromIter); - srcAccess.vertID = srcVert; - if (blockIter != blockBarrier.rearBarriers.end()) { - blockIter->beginStatus = srcAccess; - } - - uint32_t siblingPass = lastVert; - if (srcVert > lastVert) { - auto &siblingPassBarrier = barrierMap[siblingPass].blockBarrier.rearBarriers; - auto siblingIter = std::find_if(siblingPassBarrier.begin(), siblingPassBarrier.end(), - [resourceID](const Barrier &barrier) { - return resourceID == barrier.resourceID; - }); - CC_ASSERT(siblingIter != siblingPassBarrier.end()); - siblingPassBarrier.erase(siblingIter); - } - } - } - } - - if (srcBarrierIter->type == gfx::BarrierType::SPLIT_BEGIN) { - auto srcAccess = (*fromIter); - srcAccess.vertID = srcExternalDeps ? INVALID_ID : srcVert; - auto dstAccess = (*toIter); - dstVertDistribute(dstAccess.vertID, dstExternalDeps); - if (dstBarrierIter == dstFrontBarriers.end()) { - // if isAdjacent, full barrier already in src rear barriers. - if (!isAdjacent) { - dstFrontBarriers.emplace_back(Barrier{ - resourceID, - gfx::BarrierType::SPLIT_END, - nullptr, - srcAccess, - dstAccess, - }); - } - } else { - if (isAdjacent) { - // adjacent, barrier should be commit at fromPass, and remove this iter from dstBarriers - srcBarrierIter->type = gfx::BarrierType::FULL; - srcBarrierIter->beginStatus = srcAccess; - srcBarrierIter->endStatus = dstAccess; - dstFrontBarriers.erase(dstBarrierIter); - } else { - // logic but not exec adjacent - // and more adjacent(distance from src) than another pass which hold a use of resourceID - // replace previous one - - // 1 --> 2 --> 3 - // ↓ - // 4 --> 5 --> 6 - - // [if] real pass order: 1 - 2 - 4 - 5 - 3 - 6 - - // 2 and 5 read from ResA, 6 writes to ResA - // 5 and 6 logically adjacent but not adjacent in execution order. - // barrier for ResA between 2 - 6 can be totally replaced by 5 - 6 - auto &blockBarrier = barrierMap.at(dstPassVert).blockBarrier; - auto blockIter = blockBarrier.frontBarriers.end(); - auto lastVert = dstBarrierIter->endStatus.vertID; - if (subToSubDeps) { - blockIter = std::find_if(blockBarrier.frontBarriers.begin(), blockBarrier.frontBarriers.end(), findBarrierNodeByResID); - lastVert = blockIter->endStatus.vertID; - } - if (dstVert <= lastVert) { - uint32_t siblingPass = lastVert; - dstBarrierIter->endStatus = dstAccess; - - // remove the further redundant barrier - auto &siblingPassBarrier = barrierMap[siblingPass].blockBarrier.frontBarriers; - auto siblingIter = std::find_if(siblingPassBarrier.begin(), siblingPassBarrier.end(), - [resourceID](const Barrier &barrier) { - return resourceID == barrier.resourceID; - }); - CC_ASSERT(siblingIter != siblingPassBarrier.end()); - siblingPassBarrier.erase(siblingIter); - } - } - } - } - } - } - - //----------------------------------------------check external---------------------------------------------- - auto barrierExternalRes = [&](const AccessStatus &resourcecAccess, Vertex vert) { - uint32_t rescID = resourcecAccess.vertID; - const auto &states = get(ResourceGraph::StatesTag{}, resourceGraph, rescID); - const auto &traits = get(ResourceGraph::TraitsTag{}, resourceGraph, rescID); - const PmrString &resName = get(ResourceGraph::NameTag{}, resourceGraph, rescID); - auto resIter = externalMap.find(resName); - if (traits.hasSideEffects()) { - // first meet in this frame - if (resIter == externalMap.end()) { - // first meet in this program - if (states.states == gfx::AccessFlagBit::NONE) { - auto lastRescAccess = AccessStatus{ - vert, - gfx::ShaderStageFlagBit::NONE, - gfx::MemoryAccessBit::NONE, - gfx::PassType::RASTER, - gfx::AccessFlagBit::NONE, - gfx::TextureUsageBit::NONE, - TextureRange{}, - }; - auto currRescAccess = resourcecAccess; - - // resource id in access -> pass id in barrier - currRescAccess.vertID = vert; - - lastRescAccess.accessFlag = gfx::AccessFlagBit::NONE; - - externalMap.insert({resName, - ResourceTransition{ - lastRescAccess, - currRescAccess, - }}); - } else { - externalMap[resName].lastStatus = {}; - externalMap[resName].lastStatus.vertID = INVALID_ID; - externalMap[resName].lastStatus.accessFlag = states.states; - // deprecated - externalMap[resName].lastStatus.usage = gfx::TextureUsageBit::NONE; - externalMap[resName].lastStatus.range = TextureRange{}; - - externalMap[resName].currStatus = resourcecAccess; - externalMap[resName].currStatus.vertID = vert; - - const auto &traits = get(ResourceGraph::TraitsTag{}, resourceGraph, rescID); - if (isTransitionStatusDependent(externalMap[resName].lastStatus, externalMap[resName].currStatus)) { - resourceNames.emplace(resName); - } - } - } else { - if (resIter->second.currStatus.vertID < vert) { - //[pass: vert] is later access than in iter. - externalMap[resName].currStatus = resourcecAccess; - externalMap[resName].currStatus.vertID = vert; - if (!isReadOnlyAccess(resourcecAccess.accessFlag)) { - resourceNames.emplace(resName); - } - } - } - } - }; - - for (const AccessStatus &rescAccess : srcStatus) { - barrierExternalRes(rescAccess, from.vertID); - } - - for (const AccessStatus &rescAccess : dstStatus) { - barrierExternalRes(rescAccess, to.vertID); - } - //--------------------------------------------------------------------------------------------------------- - } - - void examine_edge(Edge e, const Graph &g) { - Vertex from = source(e, g); - Vertex to = target(e, g); - - // hasSubpass ? fromAccess is a single node with all attachment status stored in 'attachmentStatus' - // : fromAccess is head of chain of subpasses, which stores all attachment status in 'attachmentStatus' - const ResourceAccessNode &fromAccess = get(ResourceAccessGraph::AccessNodeTag{}, g, from); - const ResourceAccessNode &toAccess = get(ResourceAccessGraph::AccessNodeTag{}, g, to); - - bool isAdjacent = isPassExecAdjecent(from, to); - std::vector commonResources; - - const auto *srcHead = &fromAccess; - const auto *dstHead = &toAccess; - - bool srcHasSubpass = srcHead->nextSubpass; - bool dstHasSubpass = dstHead->nextSubpass; - srcHead = srcHasSubpass ? srcHead->nextSubpass : srcHead; - - std::stack reverseSubpassQ; - while (srcHead) { - reverseSubpassQ.push(srcHead); - srcHead = srcHead->nextSubpass; - } - ccstd::set subpassResourceSet; - while (!reverseSubpassQ.empty()) { - uint32_t srcSubpassIndex = reverseSubpassQ.size() - 1; - srcHead = reverseSubpassQ.top(); - reverseSubpassQ.pop(); - const std::vector &fromStatus = srcHead->attachmentStatus; - std::vector &srcRearBarriers = srcHasSubpass ? barrierMap[from].subpassBarriers[srcSubpassIndex].rearBarriers : barrierMap[from].blockBarrier.rearBarriers; - uint32_t dstSubpassIndex = 0; - dstHead = &toAccess; - bool dstHasSubpass = dstHead->nextSubpass; - dstHead = dstHasSubpass ? toAccess.nextSubpass : &toAccess; - while (dstHead) { - const std::vector &toStatus = dstHead->attachmentStatus; - std::vector &dstFrontBarriers = dstHasSubpass ? barrierMap[to].subpassBarriers[dstSubpassIndex].frontBarriers : barrierMap[to].blockBarrier.frontBarriers; - AccessNodeInfo fromInfo = {fromStatus, srcRearBarriers, from, srcHasSubpass ? static_cast(reverseSubpassQ.size()) : INVALID_ID}; - AccessNodeInfo toInfo = {toStatus, dstFrontBarriers, to, dstHasSubpass ? dstSubpassIndex : INVALID_ID}; - bool isExecAdjacent = isAdjacent && (!srcHead->nextSubpass && !dstSubpassIndex); - fillBarrier(fromInfo, toInfo, isAdjacent, subpassResourceSet); - dstHead = dstHead->nextSubpass; - ++dstSubpassIndex; - } - } - - auto &rearBarriers = barrierMap[from].blockBarrier.rearBarriers; - auto &frontBarriers = barrierMap[from].blockBarrier.frontBarriers; - - uint32_t subpassIdx = 0; - for (const auto &barriers : barrierMap[from].subpassBarriers) { - for (const auto &barrier : barriers.rearBarriers) { - auto resID = barrier.resourceID; - auto findBarrierByResID = [resID](const Barrier &barrier) { - return barrier.resourceID == resID; - }; - auto iter = std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID); - auto resFinalPassID = accessRecord.at(resID).currStatus.vertID; - - if (resFinalPassID > from) { - const auto *dstHead = dstHasSubpass ? toAccess.nextSubpass : &toAccess; - const AccessStatus *dstAccess{nullptr}; - while (dstHead) { - auto iter = std::find_if(dstHead->attachmentStatus.begin(), dstHead->attachmentStatus.end(), [resID](const AccessStatus &access) { - return access.vertID == resID; - }); - if (iter != dstHead->attachmentStatus.end()) { - dstAccess = &(*iter); - break; - } - dstHead = dstHead->nextSubpass; - } - - if (!dstAccess) { - continue; - } - - const auto *srcHead = srcHasSubpass ? fromAccess.nextSubpass : &fromAccess; - uint32_t step = 0; - while (step <= subpassIdx) { - srcHead = srcHead->nextSubpass; - ++step; - } - - bool laterUse = false; - while (srcHead) { - const auto &attachments = srcHead->attachmentStatus; - laterUse |= std::any_of(attachments.begin(), attachments.end(), [resID](const AccessStatus &access) { - return access.vertID == resID; - }); - srcHead = srcHead->nextSubpass; - } - - // laterUse: in case it's a split begin/end. - const auto &srcAccess = laterUse ? barrier.endStatus : barrier.beginStatus; - if (isTransitionStatusDependent(srcAccess, *dstAccess)) { - if (iter == rearBarriers.end()) { - auto &collect = rearBarriers.emplace_back(barrier); - collect.beginStatus.vertID = from; - collect.endStatus.vertID = isAdjacent ? from : to; - } else if (iter->endStatus.vertID >= to) { - (*iter) = barrier; - iter->beginStatus.vertID = from; - iter->endStatus.vertID = isAdjacent ? from : to; - } - } - } - } - - for (const auto &barrier : barriers.frontBarriers) { - auto resID = barrier.resourceID; - auto findBarrierByResID = [resID](const Barrier &barrier) { - return barrier.resourceID == resID; - }; - auto resFinalPassID = accessRecord.at(resID).currStatus.vertID; - auto firstMeetIter = std::find_if(frontBarriers.begin(), frontBarriers.end(), findBarrierByResID); - auto innerResIter = std::find_if(rearBarriers.begin(), rearBarriers.end(), findBarrierByResID); - - if (firstMeetIter == frontBarriers.end() && innerResIter == rearBarriers.end() && resFinalPassID > from) { - frontBarriers.emplace_back(barrier); - } - } - } - subpassIdx++; - } - - const AccessTable &accessRecord; - BarrierMap &barrierMap; - const ResourceGraph &resourceGraph; - ExternalResMap &externalMap; // last frame to curr frame status transition - ResourceNames &resourceNames; // record those which been written - ResourceLifeRecordMap &resourceLifeRecord; - PmrFlatMap &rpInfos; -}; - void buildBarriers(FrameGraphDispatcher &fgDispatcher) { auto *scratch = fgDispatcher.scratch; - const auto &renderGraph = fgDispatcher.graph; + const auto &renderGraph = fgDispatcher.renderGraph; const auto &layoutGraph = fgDispatcher.layoutGraph; 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{renderGraph, resourceGraph, layoutGraph, rag, relationGraph}; + const Graphs graphs{renderGraph, layoutGraph, resourceGraph, rag, relationGraph}; buildAccessGraph(graphs); fgDispatcher._accessGraphBuilt = true; } + auto getGFXBarrier = [&resourceGraph](const Barrier &barrier) { + gfx::GFXObject *gfxBarrier{nullptr}; + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, barrier.resourceID); + if (desc.dimension == ResourceDimension::BUFFER) { + gfx::BufferBarrierInfo info; + info.prevAccesses = barrier.beginStatus.accessFlag; + info.nextAccesses = barrier.endStatus.accessFlag; + const auto &range = barrier.endStatus.range; + info.offset = 0; + info.size = range.depthOrArraySize; + info.type = barrier.type; + gfxBarrier = gfx::Device::getInstance()->getBufferBarrier(info); + } else { + gfx::TextureBarrierInfo info; + info.prevAccesses = barrier.beginStatus.accessFlag; + info.nextAccesses = barrier.endStatus.accessFlag; + const auto &range = barrier.beginStatus.range; + info.baseMipLevel = range.mipLevel; + info.levelCount = range.levelCount; + info.baseSlice = range.firstSlice; + info.sliceCount = range.numSlices; + info.type = barrier.type; + gfxBarrier = gfx::Device::getInstance()->getTextureBarrier(info); + } + return gfxBarrier; + }; + // found pass id in this map ? barriers you should commit when run into this pass // : or no extra barrier needed. - BarrierMap &batchedBarriers = fgDispatcher.barrierMap; - - { - // barrier first meet - // O(N) actually - ccstd::set firstMeet; - for (size_t i = 0; i < rag.access.size(); ++i) { - const auto *status = &rag.access[i]; - for (const auto &attachment : status->attachmentStatus) { - AccessStatus lastStatus{ - static_cast(i), - gfx::ShaderStageFlagBit::NONE, - gfx::MemoryAccessBit::NONE, - gfx::PassType::RASTER, - gfx::AccessFlagBit::NONE, - gfx::TextureUsageBit::NONE, - TextureRange{}, - }; - - AccessStatus currStatus = attachment; - currStatus.vertID = static_cast(i); - - gfx::BarrierType bType = gfx::BarrierType::FULL; - const auto &traits = get(ResourceGraph::TraitsTag{}, resourceGraph, attachment.vertID); - if (traits.hasSideEffects()) { - const auto &accessFlag = get(ResourceGraph::StatesTag{}, resourceGraph, attachment.vertID).states; - if (accessFlag != gfx::AccessFlagBit::NONE) { - lastStatus.accessFlag = accessFlag; - bType = traits.residency == ResourceResidency::BACKBUFFER ? gfx::BarrierType::FULL : gfx::BarrierType::SPLIT_END; - } - if (!isTransitionStatusDependent(lastStatus, currStatus)) { - continue; - } - } - if (firstMeet.find(attachment.vertID) == firstMeet.end()) { - firstMeet.emplace(attachment.vertID); - - if (batchedBarriers.find(i) == batchedBarriers.end()) { - batchedBarriers.emplace(i, BarrierNode{}); - auto &rpInfo = rag.rpInfos[i].rpInfo; - // NOLINTNEXTLINE (readability-container-size-empty) - if (rpInfo.subpasses.size() >= 1) { - batchedBarriers[i].subpassBarriers.resize(rpInfo.subpasses.size()); - } - } - - auto &blockFrontBarrier = batchedBarriers.at(i).blockBarrier.frontBarriers; - auto resIter = std::find_if(blockFrontBarrier.begin(), blockFrontBarrier.end(), [&attachment](const Barrier &barrier) { return barrier.resourceID == attachment.vertID; }); - if (resIter == blockFrontBarrier.end()) { - Barrier firstMeetBarrier{ - attachment.vertID, - bType, - nullptr, - lastStatus, - currStatus, - }; - blockFrontBarrier.emplace_back(firstMeetBarrier); - } - auto *nextStatus = status->nextSubpass; - uint32_t index = 0; - while (nextStatus) { - const auto &subpassStatus = nextStatus->attachmentStatus; - auto &subpassBarriers = batchedBarriers.at(i).subpassBarriers; - auto &frontBarriers = subpassBarriers[index].frontBarriers; - auto iter = std::find_if(subpassStatus.begin(), subpassStatus.end(), [&attachment](const AccessStatus &access) { return access.vertID == attachment.vertID; }); - if (iter != subpassStatus.end()) { - lastStatus.vertID = 0xFFFFFFFF; - currStatus.vertID = index; - currStatus.accessFlag = iter->accessFlag; - Barrier firstMeetBarrier{ - attachment.vertID, - bType, - nullptr, - lastStatus, - currStatus, - }; - frontBarriers.emplace_back(firstMeetBarrier); - break; - } - nextStatus = nextStatus->nextSubpass; - index++; - } - } - } - } - } - - ResourceNames namesSet; - { - // barrier between passes - BarrierVisitor visitor(resourceGraph, batchedBarriers, externalResMap, namesSet, rag.accessRecord, rag.resourceLifeRecord, rag.rpInfos); - auto colors = rag.colors(scratch); - boost::queue q; - - 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 &resName = externalPair.first; - const auto &transition = externalPair.second; - auto resID = resourceGraph.valueIndex.at(resName); - const auto &resTraits = get(ResourceGraph::TraitsTag{}, resourceGraph, resID); - auto &rescStates = get(ResourceGraph::StatesTag{}, resourceGraph, resID); - - bool backBuffer = resTraits.residency == ResourceResidency::BACKBUFFER; - // when to dispatch a barrier on persistent: - // 1. resource been written in this frame; - // 2. first meet in this frame (no idea if any writes in next frame) - // 3. backbuffer present - bool needNextBarrier = (namesSet.find(resName) != namesSet.end()) || (rescStates.states == gfx::AccessFlagBit::NONE); - - // persistant resource states cached here - rescStates.states = transition.currStatus.accessFlag; - - if (!backBuffer && !needNextBarrier) { + for (auto &accessPair : rag.resourceAccess) { + const auto &resName = accessPair.first; + if (rag.movedSourceStatus.find(resName) != rag.movedSourceStatus.end()) { + // moved, history of this resource access will be copied to moved target. continue; } - auto passID = transition.currStatus.vertID; - if (batchedBarriers.find(passID) == batchedBarriers.end()) { - batchedBarriers.emplace(passID, BarrierNode{}); - } + const auto &resID = findVertex(resName, resourceGraph); + const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resID); + bool isBuffer = desc.dimension == ResourceDimension::BUFFER; - Barrier nextFrameResBarrier{ - resID, - gfx::BarrierType::SPLIT_BEGIN, - nullptr, - externalResMap[externalPair.first].currStatus, - {}}; + const auto &accessRecord = accessPair.second; + auto iter = accessRecord.begin(); + auto nextIter = iter; + std::advance(nextIter, 1); + for (; nextIter != accessRecord.end(); ++iter, ++nextIter) { + auto srcRagVertID = iter->first; + auto dstRagVertID = nextIter->first; + auto srcPassID = get(ResourceAccessGraph::PassIDTag{}, rag, srcRagVertID); + auto dstPassID = get(ResourceAccessGraph::PassIDTag{}, rag, dstRagVertID); - if (backBuffer) { - nextFrameResBarrier.endStatus = { - INVALID_ID, - gfx::ShaderStageFlagBit::NONE, - gfx::MemoryAccessBit::NONE, - gfx::PassType::PRESENT, - gfx::AccessFlagBit::PRESENT, - gfx::TextureUsageBit::NONE, - TextureRange{}, - }; - nextFrameResBarrier.type = gfx::BarrierType::FULL; - rescStates.states = gfx::AccessFlagBit::PRESENT; - } - - bool hasSubpass = !(batchedBarriers[passID].subpassBarriers.size() <= 1); - if (hasSubpass) { - // rpinfo instead - auto &fgRenderPassInfo = rag.rpInfos.at(passID); - auto iter = std::find(fgRenderPassInfo.orderedViews.begin(), fgRenderPassInfo.orderedViews.end(), resName.c_str()); - CC_ASSERT(iter != fgRenderPassInfo.orderedViews.end()); - auto index = std::distance(fgRenderPassInfo.orderedViews.begin(), iter); - index -= fgRenderPassInfo.rpInfo.depthStencilAttachment.format != gfx::Format::UNKNOWN; - fgRenderPassInfo.colorAccesses[index].nextAccess = nextFrameResBarrier.endStatus.accessFlag; - } else { - auto &rearBarriers = batchedBarriers[passID].blockBarrier.rearBarriers; - rearBarriers.emplace_back(nextFrameResBarrier); - } - } - - { - const auto &resDescs = get(ResourceGraph::DescTag{}, 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.endStatus.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); + if (holds(dstPassID, renderGraph) || holds(dstPassID, renderGraph)) { + const auto &fgRenderPassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, rag, dstRagVertID); + if (fgRenderPassInfo.viewIndex.find(resName) != fgRenderPassInfo.viewIndex.end()) { + // renderpass info instead + continue; } } - }; - constexpr static bool USING_RENDERPASS_DEP_INSTEAD_OF_BARRIER{true}; - if constexpr (USING_RENDERPASS_DEP_INSTEAD_OF_BARRIER) { - auto prune = [&rag, &renderGraph, &resourceGraph](std::vector &barriers) { - barriers.erase(std::remove_if(barriers.begin(), barriers.end(), [&rag, &renderGraph, &resourceGraph](Barrier &barrier) { - bool fromAttachment = isAttachmentAccess(barrier.beginStatus.accessFlag) || barrier.beginStatus.accessFlag == gfx::AccessFlagBit::NONE; - bool toAttachment = isAttachmentAccess(barrier.endStatus.accessFlag); - return toAttachment; - }), - barriers.end()); - }; - for (auto &passBarrierInfo : batchedBarriers) { - auto &passBarrierNode = passBarrierInfo.second; - prune(passBarrierNode.blockBarrier.frontBarriers); - prune(passBarrierNode.blockBarrier.rearBarriers); + // subpass layout transition + if ((srcRagVertID != 0) && (holds(srcPassID, renderGraph) || holds(srcPassID, renderGraph))) { + auto ragVertID = srcRagVertID; + if (holds(srcPassID, renderGraph)) { + auto parentID = parent(srcPassID, renderGraph); + ragVertID = rag.passIndex.at(parentID); + } + // RenderPass Info + auto &fgRenderPassInfo = get(ResourceAccessGraph::RenderPassInfoTag{}, rag, ragVertID); + std::string_view resName = get(ResourceGraph::NameTag{}, resourceGraph, resID); + auto colorIter = std::find(fgRenderPassInfo.orderedViews.begin(), fgRenderPassInfo.orderedViews.end(), resName); + auto colorIndex = std::distance(fgRenderPassInfo.orderedViews.begin(), colorIter); + if (colorIndex < fgRenderPassInfo.colorAccesses.size()) { + fgRenderPassInfo.colorAccesses[colorIndex].nextAccess = nextIter->second.accessFlag; + } else if (colorIndex == fgRenderPassInfo.colorAccesses.size()) { + fgRenderPassInfo.dsAccess.nextAccess = nextIter->second.accessFlag; + } else if (colorIndex == fgRenderPassInfo.colorAccesses.size() + 1) { + fgRenderPassInfo.dsResolveAccess.nextAccess = nextIter->second.accessFlag; + } + + if (holds(srcPassID, renderGraph) && + accessDependent(iter->second.accessFlag, nextIter->second.accessFlag, isBuffer)) { + const auto *subpass = get_if(srcPassID, &renderGraph); + CC_ASSERT(subpass); + auto subpassID = subpass->subpassID; + auto &dependency = fgRenderPassInfo.rpInfo.dependencies.emplace_back(); + dependency.srcSubpass = subpass->subpassID; + dependency.dstSubpass = INVALID_ID; + dependency.prevAccesses = iter->second.accessFlag; + dependency.nextAccesses = nextIter->second.accessFlag; + } + continue; + } + + // undefined access + if (iter == accessRecord.begin()) { + auto &dstBarrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, dstRagVertID); + auto &firstMeetBarrier = dstBarrierNode.frontBarriers.emplace_back(); + firstMeetBarrier.resourceID = resID; + firstMeetBarrier.type = gfx::BarrierType::FULL; + firstMeetBarrier.beginVert = dstPassID; + firstMeetBarrier.endVert = dstPassID; + firstMeetBarrier.beginStatus = iter->second; + firstMeetBarrier.endStatus = nextIter->second; + firstMeetBarrier.barrier = getGFXBarrier(firstMeetBarrier); + } else if (accessDependent(iter->second.accessFlag, nextIter->second.accessFlag, isBuffer)) { + auto &srcBarrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, srcRagVertID); + auto &beginBarrier = srcBarrierNode.rearBarriers.emplace_back(); + beginBarrier.resourceID = resID; + beginBarrier.beginVert = srcPassID; + beginBarrier.endVert = dstPassID; + beginBarrier.beginStatus = iter->second; + beginBarrier.endStatus = nextIter->second; + if (isPassExecAdjecent(iter->first, nextIter->first)) { + beginBarrier.type = gfx::BarrierType::FULL; + } else { + beginBarrier.type = gfx::BarrierType::SPLIT_BEGIN; + + auto &dstBarrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, dstRagVertID); + auto &endBarrier = dstBarrierNode.frontBarriers.emplace_back(); + endBarrier.resourceID = resID; + endBarrier.type = gfx::BarrierType::SPLIT_END; + endBarrier.beginVert = srcPassID; + endBarrier.endVert = dstPassID; + endBarrier.beginStatus = iter->second; + endBarrier.endStatus = nextIter->second; + endBarrier.barrier = getGFXBarrier(endBarrier); + } + beginBarrier.barrier = getGFXBarrier(beginBarrier); } } + const auto &traits = get(ResourceGraph::TraitsTag{}, resourceGraph, resID); + auto &states = get(ResourceGraph::StatesTag{}, resourceGraph, resID); + if (traits.hasSideEffects()) { + states.states = iter->second.accessFlag; + if (traits.residency == ResourceResidency::BACKBUFFER) { + auto lastAccessPassID = get(ResourceAccessGraph::PassIDTag{}, rag, iter->first); + auto &barrierNode = get(ResourceAccessGraph::BarrierTag{}, rag, iter->first); + auto &presentBarrier = barrierNode.rearBarriers.emplace_back(); + presentBarrier.resourceID = resID; + presentBarrier.type = gfx::BarrierType::FULL; + presentBarrier.beginVert = lastAccessPassID; + presentBarrier.endVert = lastAccessPassID; + presentBarrier.beginStatus = iter->second; + presentBarrier.endStatus = {gfx::AccessFlagBit::PRESENT, iter->second.range}; + presentBarrier.barrier = getGFXBarrier(presentBarrier); - // generate gfx barrier - 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); + states.states = gfx::AccessFlagBit::NONE; } } } { - for (auto &[vert, fgRenderpassInfo] : rag.rpInfos) { + for (auto &fgRenderpassInfo : rag.rpInfo) { auto &colorAttachments = fgRenderpassInfo.rpInfo.colorAttachments; - for (uint32_t i = 0; i < colorAttachments.size(); ++i) { - const auto &colorAccess = fgRenderpassInfo.colorAccesses[i]; - colorAttachments[i].barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), colorAccess.prevAccess, colorAccess.nextAccess); + uint32_t count{0}; + for (auto &color : colorAttachments) { + const auto &colorAccess = fgRenderpassInfo.colorAccesses[count]; + color.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), + colorAccess.prevAccess, + colorAccess.nextAccess); + ++count; } auto &dsAttachment = fgRenderpassInfo.rpInfo.depthStencilAttachment; if (dsAttachment.format != gfx::Format::UNKNOWN) { const auto &dsAccess = fgRenderpassInfo.dsAccess; - dsAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), dsAccess.prevAccess, dsAccess.nextAccess); + dsAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), + dsAccess.prevAccess, + dsAccess.nextAccess); } auto &dsResolveAttachment = fgRenderpassInfo.rpInfo.depthStencilResolveAttachment; if (dsResolveAttachment.format != gfx::Format::UNKNOWN) { - const auto &dsAccess = fgRenderpassInfo.dsResolveAccess; - dsResolveAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), dsAccess.prevAccess, dsAccess.nextAccess); + const auto &dsResolveAccess = fgRenderpassInfo.dsResolveAccess; + dsResolveAttachment.barrier = getGeneralBarrier(cc::gfx::Device::getInstance(), + dsResolveAccess.prevAccess, + dsResolveAccess.nextAccess); } } } @@ -1349,18 +1970,18 @@ private: // 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, ResourceAccessGraph::vertex_descriptor vert, bool forward) { - const ResourceAccessNode &accessNode = get(RAG::AccessNodeTag{}, rag, vert); +auto evaluateHeaviness(const ResourceAccessGraph &rag, const ResourceGraph &rescGraph, ResourceAccessGraph::vertex_descriptor vert, bool forward) { + const ResourceAccessNode &accessNode = get(ResourceAccessGraph::PassNodeTag{}, rag, vert); int64_t score = 0; bool forceAdjacent = false; - for (const auto &resc : accessNode.attachmentStatus) { + for (const auto &pair : accessNode.resourceStatus) { int64_t eval = 0; - auto rescID = resc.vertID; + auto rescID = rag.resourceIndex.at(pair.first); const ResourceDesc &desc = get(ResourceGraph::DescTag{}, rescGraph, rescID); const ResourceTraits &traits = get(ResourceGraph::TraitsTag{}, rescGraph, rescID); - gfx::MemoryAccessBit substractFilter = forward ? gfx::MemoryAccessBit::READ_ONLY : gfx::MemoryAccessBit::WRITE_ONLY; - if (resc.access == substractFilter) { + const auto &resc = pair.second; + if (!(isReadOnlyAccess(resc.accessFlag) ^ forward)) { // forward calculate write(s), backward calculate read(s). continue; } @@ -1385,7 +2006,7 @@ auto evaluateHeaviness(const RAG &rag, const ResourceGraph &rescGraph, ResourceA return std::make_tuple(forceAdjacent, score); }; -void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, RelationGraph &relationGraph, const RelationGraph &relationGraphTc, const RelationVerts &lhsVerts, const RelationVerts &rhsVerts) { +void evaluateAndTryMerge(const ResourceAccessGraph &rag, const ResourceGraph &rescGraph, RelationGraph &relationGraph, const RelationGraph &relationGraphTc, const RelationVerts &lhsVerts, const RelationVerts &rhsVerts) { assert(lhsVerts.size() >= 2); assert(rhsVerts.size() >= 2); @@ -1545,7 +2166,7 @@ void evaluateAndTryMerge(const RAG &rag, const ResourceGraph &rescGraph, Relatio } // return : can be further reduced? -bool reduce(const RAG &rag, const ResourceGraph &rescGraph, RelationGraph &relationGraph, RelationGraph &relationGraphTc, const CloseCircuit &circuit) { +bool reduce(const ResourceAccessGraph &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()) { @@ -1647,14 +2268,14 @@ void applyRelation(RelationGraph &relationGraph, const TargetGraph &targetGraph) void passReorder(FrameGraphDispatcher &fgDispatcher) { auto *scratch = fgDispatcher.scratch; - const auto &renderGraph = fgDispatcher.graph; + const auto &renderGraph = fgDispatcher.renderGraph; const auto &layoutGraph = fgDispatcher.layoutGraph; auto &resourceGraph = fgDispatcher.resourceGraph; auto &relationGraph = fgDispatcher.relationGraph; auto &rag = fgDispatcher.resourceAccessGraph; if (!fgDispatcher._accessGraphBuilt) { - const Graphs graphs{renderGraph, resourceGraph, layoutGraph, rag, relationGraph}; + const Graphs graphs{renderGraph, layoutGraph, resourceGraph, rag, relationGraph}; buildAccessGraph(graphs); fgDispatcher._accessGraphBuilt = true; } @@ -1665,7 +2286,7 @@ void passReorder(FrameGraphDispatcher &fgDispatcher) { boost::transitive_closure(relationGraph, relationGraphTc); CloseCircuits circuits; - std::vector crossEdges; + std::vector crossEdges; PassVisitor visitor(relationGraphTc, circuits); auto colors = relationGraph.colors(scratch); boost::depth_first_search(relationGraph, visitor, get(colors, relationGraph)); @@ -1800,813 +2421,6 @@ bool isTransitionStatusDependent(const AccessStatus &lhs, const AccessStatus &rh return !(isReadOnlyAccess(lhs.accessFlag) && isReadOnlyAccess(rhs.accessFlag)); } -auto mapTextureFlags(ResourceFlags flags) { - gfx::TextureUsage usage = gfx::TextureUsage::NONE; - if ((flags & ResourceFlags::SAMPLED) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::SAMPLED; - } - if ((flags & ResourceFlags::STORAGE) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::STORAGE; - } - if ((flags & ResourceFlags::SHADING_RATE) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::SHADING_RATE; - } - if ((flags & ResourceFlags::COLOR_ATTACHMENT) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::COLOR_ATTACHMENT; - } - if ((flags & ResourceFlags::DEPTH_STENCIL_ATTACHMENT) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT; - } - if ((flags & ResourceFlags::INPUT_ATTACHMENT) != ResourceFlags::NONE) { - usage |= gfx::TextureUsage::INPUT_ATTACHMENT; - } - return usage; -} - -auto getResourceStatus(PassType passType, const PmrString &name, gfx::MemoryAccess memAccess, gfx::ShaderStageFlags visibility, const ResourceGraph &resourceGraph, bool rasterized) { - ResourceUsage usage; - gfx::ShaderStageFlags vis{gfx::ShaderStageFlags::NONE}; - vis |= visibility; - gfx::AccessFlags accesFlag; - auto vertex = resourceGraph.valueIndex.at(name); - const auto &desc = get(ResourceGraph::DescTag{}, 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)) { - bufferUsage = gfx::BufferUsage::STORAGE; - } - - 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 - bufferUsage = uniformFlag ? gfx::BufferUsage::UNIFORM : gfx::BufferUsage::STORAGE; - } - - if (passType == PassType::COMPUTE) { - vis |= gfx::ShaderStageFlagBit::COMPUTE; - } - - // those buffers not found in descriptorlayout but appear here, - // can and only can be VERTEX/INDEX/INDIRECT BUFFER, - // only copy pass is allowed. - 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. - gfx::TextureUsage texUsage = gfx::TextureUsage::NONE; - - // TODO(Zeqiang): visbility of slot name "_" not found - if (hasFlag(memAccess, gfx::MemoryAccess::READ_ONLY)) { - if ((desc.flags & ResourceFlags::INPUT_ATTACHMENT) != ResourceFlags::NONE && rasterized) { - texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::INPUT_ATTACHMENT)); - } else { - texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::SAMPLED | gfx::TextureUsage::STORAGE | gfx::TextureUsage::SHADING_RATE | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT)); - } - } - - if (hasFlag(memAccess, gfx::MemoryAccess::WRITE_ONLY)) { - texUsage |= (mapTextureFlags(desc.flags) & (gfx::TextureUsage::COLOR_ATTACHMENT | gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT | gfx::TextureUsage::STORAGE)); - } - - if (vis == gfx::ShaderStageFlags::NONE) { - vis = passType == gfx::PassType::RASTER ? gfx::ShaderStageFlags::FRAGMENT : gfx::ShaderStageFlags::COMPUTE; - } - - usage = texUsage; - accesFlag = gfx::getAccessFlags(texUsage, memAccess, vis); - } - - return std::make_tuple(vis, usage, accesFlag); -} - -void addCopyAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status, const Range &range) { - 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); - - CC_EXPECTS(rg.valueIndex.find(name) != rg.valueIndex.end()); - if (std::find(rag.resourceNames.begin(), rag.resourceNames.end(), name) == rag.resourceNames.end()) { - rag.resourceIndex.emplace(name, rescID); - rag.resourceNames.emplace_back(name); - } - - node.attachmentStatus.emplace_back(AccessStatus{ - rescID, - visibility, - access, - passType, - accessFlag, - usage, - range, - }); -} - -PmrString addAccessStatus(RAG &rag, const ResourceGraph &rg, ResourceAccessNode &node, const ViewStatus &status) { - const auto &[name, passType, visibility, access, accessFlag, usage] = status; - uint32_t rescID = rg.valueIndex.at(name); - const auto &resourceDesc = get(ResourceGraph::DescTag{}, rg, rescID); - const auto &traits = get(ResourceGraph::TraitsTag{}, rg, rescID); - // const PmrString *resName = &name; - - Range range; - if (resourceDesc.dimension == ResourceDimension::BUFFER) { - range = BufferRange{0, resourceDesc.width}; - } else { - range = TextureRange{0, 1, 0, resourceDesc.mipLevels}; - } - - CC_EXPECTS(rg.valueIndex.find(name) != rg.valueIndex.end()); - if (std::find(rag.resourceNames.begin(), rag.resourceNames.end(), name) == rag.resourceNames.end()) { - rag.resourceIndex.emplace(name, rescID); - rag.resourceNames.emplace_back(name); - } - - node.attachmentStatus.emplace_back(AccessStatus{ - rescID, - visibility, - access, - passType, - accessFlag, - usage, - range, - }); - return name; -} - -AccessVertex dependencyCheck(RAG &rag, AccessVertex curVertID, const ResourceGraph &rg, const ViewStatus &viewStatus) { - const auto &[name, passType, visibility, access, accessFlag, usage] = viewStatus; - auto &accessRecord = rag.accessRecord; - - bool readOnly = isReadOnlyAccess(accessFlag); - - AccessVertex lastVertID = INVALID_ID; - CC_EXPECTS(rag.resourceIndex.find(name) != rag.resourceIndex.end()); - auto resourceID = rag.resourceIndex[name]; - bool isExternalPass = get(get(ResourceGraph::TraitsTag{}, rg), resourceID).hasSideEffects(); - auto iter = accessRecord.find(resourceID); - if (iter == accessRecord.end()) { - accessRecord.emplace( - resourceID, - ResourceTransition{ - {}, - {curVertID, visibility, access, passType, accessFlag, usage, Range{}}}); - if (isExternalPass) { - rag.leafPasses[curVertID] = LeafStatus{true, access == gfx::MemoryAccessBit::READ_ONLY}; - } - } else { - ResourceTransition &trans = iter->second; - auto &currAccessStatus = trans.currStatus; - auto lastReadOnly = isReadOnlyAccess(currAccessStatus.accessFlag) && (currAccessStatus.access == gfx::MemoryAccessBit::READ_ONLY); - if (readOnly && lastReadOnly) { - if (isExternalPass) { - // only external res will be manually record here, leaf pass with transient resource will be culled by default, - // those leaf passes with ALL read access on external(or with transients) res can be culled. - rag.leafPasses[curVertID].needCulling &= (access == gfx::MemoryAccessBit::READ_ONLY); - - // current READ, no WRITE before in this frame, it's expected to be external. - bool dirtyExternalRes = trans.lastStatus.vertID == INVALID_ID; - if (!dirtyExternalRes) { - tryAddEdge(EXPECT_START_ID, curVertID, rag); - if (rag.leafPasses.find(EXPECT_START_ID) != rag.leafPasses.end()) { - rag.leafPasses.erase(EXPECT_START_ID); - } - } - } else { - tryAddEdge(trans.lastStatus.vertID, curVertID, rag); - if (rag.leafPasses.find(trans.lastStatus.vertID) != rag.leafPasses.end()) { - rag.leafPasses.erase(trans.lastStatus.vertID); - } - } - 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, accessFlag, usage, Range{}}; - if (rag.leafPasses.find(trans.lastStatus.vertID) != rag.leafPasses.end()) { - rag.leafPasses.erase(trans.lastStatus.vertID); - } - if (rag.leafPasses.find(curVertID) != rag.leafPasses.end()) { - // only write into externalRes counts - if (isExternalPass) { - // same as above - rag.leafPasses[curVertID].needCulling &= (access == gfx::MemoryAccessBit::READ_ONLY); - } - } - } else { - trans.currStatus = {curVertID, visibility, trans.currStatus.access | access, passType, accessFlag, usage, Range{}}; - } - } - } - return lastVertID; -} - -gfx::ShaderStageFlagBit getVisibilityByDescName(const RenderGraph &renderGraph, const LGD &lgd, uint32_t passID, const PmrString &resName) { - auto iter = lgd.attributeIndex.find(resName); - if (iter == lgd.attributeIndex.end()) { - iter = lgd.constantIndex.find(resName); - if (iter == lgd.constantIndex.end()) { - // resource not in descriptor: eg. input or output attachment. - return gfx::ShaderStageFlagBit::NONE; - } - } - auto slotID = iter->second; - - auto layoutName = get(RenderGraph::LayoutTag{}, renderGraph, passID); - auto layoutID = locate(LayoutGraphData::null_vertex(), layoutName, lgd); - const auto &layout = get(LayoutGraphData::LayoutTag{}, lgd, layoutID); - for (const auto &pair : layout.descriptorSets) { - for (const auto &block : pair.second.descriptorSetLayoutData.descriptorBlocks) { - for (const auto &descriptor : block.descriptors) { - if (descriptor.descriptorID.value == slotID.value) { - return block.visibility; - } - } - } - } - - // unreachable - CC_EXPECTS(false); - return gfx::ShaderStageFlagBit::NONE; -}; - -bool checkRasterViews(const Graphs &graphs, uint32_t vertID, uint32_t passID, PassType passType, ResourceAccessNode &node, const RasterViewsMap &rasterViews) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - bool dependent = false; - - for (const auto &pair : rasterViews) { - const auto &rasterView = pair.second; - auto access = toGfxAccess(rasterView.accessType); - gfx::ShaderStageFlagBit tryGotVis = getVisibilityByDescName(renderGraph, layoutGraphData, passID, pair.second.slotName); - tryGotVis |= pair.second.shaderStageFlags; - const auto &[vis, usage, accessFlag] = getResourceStatus(passType, pair.first, access, tryGotVis, resourceGraph, true); - 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) { - tryAddEdge(lastVertId, vertID, resourceAccessGraph); - tryAddEdge(lastVertId, vertID, relationGraph); - dependent = true; - } - } - - // sort for vector intersection - std::sort(node.attachmentStatus.begin(), node.attachmentStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); - - return dependent; -} - -bool checkComputeViews(const Graphs &graphs, uint32_t vertID, uint32_t passID, PassType passType, ResourceAccessNode &node, const ComputeViewsMap &computeViews) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - bool dependent = false; - - for (const auto &pair : computeViews) { - const auto &values = pair.second; - for (const auto &computeView : values) { - auto access = toGfxAccess(computeView.accessType); - gfx::ShaderStageFlagBit tryGotVis = gfx::ShaderStageFlagBit::NONE; - for (const auto &view : pair.second) { - tryGotVis |= getVisibilityByDescName(renderGraph, layoutGraphData, passID, view.name); - tryGotVis |= view.shaderStageFlags; - } - const auto &[vis, usage, accessFlag] = getResourceStatus(passType, pair.first, access, tryGotVis, resourceGraph, false); - 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) { - tryAddEdge(lastVertId, vertID, resourceAccessGraph); - tryAddEdge(lastVertId, vertID, relationGraph); - dependent = true; - } - } - } - - // sort for vector intersection - std::sort(node.attachmentStatus.begin(), node.attachmentStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); - - return dependent; -} - -bool checkResolveResource(const Graphs &graphs, uint32_t vertID, uint32_t /*passID*/, ResourceAccessNode &node, const ccstd::pmr::vector &resolves) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - bool dependent = false; - for (const auto &pair : resolves) { - const auto &resolveTargetName = pair.target; - const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, vertex(resolveTargetName, resourceGraph)); - gfx::AccessFlags accessFlag = gfx::AccessFlags::COLOR_ATTACHMENT_WRITE; - gfx::TextureUsage usage = gfx::TextureUsage::COLOR_ATTACHMENT; - if (desc.format == gfx::Format::DEPTH_STENCIL) { - accessFlag = gfx::AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE; - usage = gfx::TextureUsage::DEPTH_STENCIL_ATTACHMENT; - } - ViewStatus viewStatus{resolveTargetName, - PassType::RASTER, - gfx::ShaderStageFlags::FRAGMENT, - gfx::MemoryAccess::WRITE_ONLY, - accessFlag, usage}; - addAccessStatus(resourceAccessGraph, resourceGraph, node, viewStatus); - auto lastVertId = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, viewStatus); - if (lastVertId != INVALID_ID) { - tryAddEdge(lastVertId, vertID, resourceAccessGraph); - tryAddEdge(lastVertId, vertID, relationGraph); - dependent = true; - } - } - // sort for vector intersection - std::sort(node.attachmentStatus.begin(), node.attachmentStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); - - return dependent; -} - -void fillRenderPassInfo(gfx::LoadOp loadOp, gfx::StoreOp storeOp, AttachmentType attachmentType, gfx::RenderPassInfo &rpInfo, uint32_t index, const ResourceDesc &viewDesc, bool resolve) { - if (attachmentType != AttachmentType::DEPTH_STENCIL) { - auto &colorAttachment = rpInfo.colorAttachments[index]; - if (colorAttachment.format == gfx::Format::UNKNOWN) { - colorAttachment.format = viewDesc.format; - colorAttachment.loadOp = loadOp; - colorAttachment.storeOp = storeOp; - colorAttachment.sampleCount = viewDesc.sampleCount; - } else { - colorAttachment.storeOp = storeOp; - } - - } else { - auto &depthStencilAttachment = resolve ? - rpInfo.depthStencilResolveAttachment : - rpInfo.depthStencilAttachment; - if (depthStencilAttachment.format == gfx::Format::UNKNOWN) { - depthStencilAttachment.format = viewDesc.format; - depthStencilAttachment.depthLoadOp = loadOp; - depthStencilAttachment.depthStoreOp = storeOp; - depthStencilAttachment.stencilLoadOp = loadOp; - depthStencilAttachment.stencilStoreOp = storeOp; - depthStencilAttachment.sampleCount = viewDesc.sampleCount; - } else { - // TODO(Zeqiang): separate ds - depthStencilAttachment.depthStoreOp = storeOp; - depthStencilAttachment.stencilStoreOp = storeOp; - } - } -} - -void processRasterPass(const Graphs &graphs, uint32_t passID, const RasterPass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - - auto vertID = add_vertex(resourceAccessGraph, passID); - auto rlgVertID = add_vertex(relationGraph, vertID); - CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, vertID); - const auto &subpasses = pass.subpassGraph.subpasses; - bool hasSubpass = !subpasses.empty(); - auto &fgRenderpassInfo = resourceAccessGraph.rpInfos.emplace(vertID, FGRenderPassInfo{}).first->second; - auto &rpInfo = fgRenderpassInfo.rpInfo; - if (!hasSubpass) { - auto &rag = resourceAccessGraph; - auto size = std::count_if(pass.rasterViews.begin(), pass.rasterViews.end(), [](const auto &pair) { - return pair.second.attachmentType != AttachmentType::DEPTH_STENCIL; - }); - rpInfo.colorAttachments.resize(size); - fgRenderpassInfo.colorAccesses.resize(size); - PmrFlatMap> viewIndex(rag.get_allocator()); - for (const auto &[name, view] : pass.rasterViews) { - auto resIter = rag.resourceIndex.find(name); - gfx::AccessFlags prevAccess = resIter == rag.resourceIndex.end() ? gfx::AccessFlags::NONE : rag.accessRecord.at(resIter->second).currStatus.accessFlag; - viewIndex.emplace(std::piecewise_construct, std::forward_as_tuple(view.slotID), std::forward_as_tuple(name, prevAccess)); - } - - bool dependent = false; - dependent |= checkRasterViews(graphs, vertID, passID, PassType::RASTER, node, pass.rasterViews); - dependent |= checkComputeViews(graphs, vertID, passID, PassType::RASTER, node, pass.computeViews); - - if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); - } - - // initial layout(accessrecord.laststatus) and final layout(accessrecord.currstatus) can be filled here - for (const auto &[slotID, pair] : viewIndex) { - const auto &name = pair.first; - const auto resID = rag.resourceIndex.at(name); - const auto &view = pass.rasterViews.at(name); - const auto &viewDesc = get(ResourceGraph::DescTag{}, resourceGraph, resID); - auto prevAccess = pair.second; - // TD:remove find - auto nodeIter = std::find_if(node.attachmentStatus.begin(), node.attachmentStatus.end(), [resID](const AccessStatus &status) { - return status.vertID == resID; - }); - auto nextAccess = nodeIter->accessFlag; - - if (rpInfo.subpasses.empty()) { - rpInfo.subpasses.emplace_back(); - } - auto &subpassInfo = rpInfo.subpasses.front(); - if (view.attachmentType != AttachmentType::DEPTH_STENCIL) { - if (view.attachmentType == AttachmentType::SHADING_RATE) { - subpassInfo.shadingRate = slotID; - } else { - if (view.accessType != AccessType::READ) { - subpassInfo.colors.emplace_back(slotID); - } - if (view.accessType != AccessType::WRITE) { - subpassInfo.inputs.emplace_back(slotID); - } - } - fgRenderpassInfo.colorAccesses[slotID].prevAccess = prevAccess; - fgRenderpassInfo.colorAccesses[slotID].nextAccess = nextAccess; - } else { - subpassInfo.depthStencil = pass.rasterViews.size() - 1; - fgRenderpassInfo.dsAccess.prevAccess = prevAccess; - fgRenderpassInfo.dsAccess.nextAccess = nextAccess; - } - fillRenderPassInfo(view.loadOp, view.storeOp, view.attachmentType, rpInfo, slotID, viewDesc, false); - fgRenderpassInfo.orderedViews.emplace_back(name); - } - } else { - auto colorSize = pass.rasterViews.size(); - bool hasDS = std::any_of(pass.rasterViews.begin(), pass.rasterViews.end(), [](const auto &pair) { - return pair.second.attachmentType == AttachmentType::DEPTH_STENCIL; - }); - colorSize -= hasDS; - const auto &subpasses = pass.subpassGraph.subpasses; - uint32_t count = 0; - const auto &resg = resourceGraph; - auto resolveNum = std::accumulate(subpasses.begin(), subpasses.end(), 0, [&resg](uint32_t initVal, const Subpass &subpass) { - auto iter = std::find_if(subpass.resolvePairs.begin(), subpass.resolvePairs.end(), [&resg](const auto &pair) { - auto resID = vertex(pair.target, resg); - const auto& desc = get(ResourceGraph::DescTag{}, resg, resID); - return desc.format == gfx::Format::DEPTH_STENCIL || desc.format == gfx::Format::DEPTH; - }); - return initVal + subpass.resolvePairs.size() - (iter != subpass.resolvePairs.end()); - }); - colorSize += resolveNum; - rpInfo.colorAttachments.resize(colorSize); - fgRenderpassInfo.colorAccesses.resize(colorSize); - } -} - -void processComputePass(const Graphs &graphs, uint32_t passID, const ComputePass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - auto vertID = add_vertex(resourceAccessGraph, passID); - auto rlgVertID = add_vertex(relationGraph, vertID); - CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); - - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, vertID); - bool dependent = checkComputeViews(graphs, vertID, passID, PassType::COMPUTE, node, pass.computeViews); - - if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); - } -} - -uint32_t record(const ccstd::vector &indices) { - uint32_t res = 0; - for (auto attachmentIndex : indices) { - res |= 1 << attachmentIndex; - } - return res; -} - -void extract(uint32_t val, ccstd::vector &preserves) { - uint32_t index = 0; - while (val) { - if (val & 0x1) { - preserves.emplace_back(index); - } - val = val >> 1; - ++index; - } -} - -void getPreserves(gfx::RenderPassInfo &rpInfo) { - std::stack stack; - for (auto &info : rpInfo.subpasses) { - stack.push(&info); - } - - uint32_t laterRead{0}; - while (!stack.empty()) { - auto *tail = stack.top(); - stack.pop(); - - auto readRecord = record(tail->inputs); - auto writeRecord = record(tail->colors); - auto resolveRecord = record(tail->resolves); - auto shown = readRecord | writeRecord | resolveRecord; - auto needPreserve = (shown | laterRead) ^ shown; - extract(needPreserve, tail->preserves); - laterRead |= readRecord; - } -} - -void processRasterSubpass(const Graphs &graphs, uint32_t passID, const RasterSubpass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - const auto &obj = renderGraph.objects.at(passID); - const auto parentID = obj.parents.front().target; - const auto parentRagVert = resourceAccessGraph.passIndex.at(parentID); - const auto *parentPass = get_if(parentID, &renderGraph); - CC_EXPECTS(parentPass); - const auto &rag = resourceAccessGraph; - const auto &resg = resourceGraph; - const auto &uberPass = *parentPass; - - resourceAccessGraph.passIndex[passID] = parentRagVert; - - static const uint32_t ACCESS_TYPE_WEIGHT[] = {0, 1, 2}; - static const uint32_t ATTACHMENT_TYPE_WEIGHT[] = {0, 2, 1}; - - struct SubpassRasterViewSortKey { - uint32_t accessType; - uint32_t attachmentType; - std::string_view slotName; - uint32_t samplesReverseWeight; - }; - using RasterViewSortKey = std::tuple; - struct SubpassRasterViewData { - SubpassRasterViewSortKey sortKey; - std::string_view name; - gfx::AccessFlags access; - }; - - bool hasDS{false}; - ccstd::vector viewIndex; - for (const auto &[name, view] : pass.rasterViews) { - auto resIter = rag.resourceIndex.find(name); - const auto &resID = vertex(name, resourceGraph); - const auto &desc = get(ResourceGraph::DescTag{}, resg, resID); - gfx::AccessFlags prevAccess = resIter == rag.resourceIndex.end() ? gfx::AccessFlags::NONE : rag.accessRecord.at(resIter->second).currStatus.accessFlag; - viewIndex.emplace_back(SubpassRasterViewData{ - {ACCESS_TYPE_WEIGHT[static_cast(view.accessType)], ATTACHMENT_TYPE_WEIGHT[static_cast(view.attachmentType)], view.slotName, static_cast(desc.sampleCount)}, - name, - prevAccess, - }); - hasDS |= view.attachmentType == AttachmentType::DEPTH_STENCIL; - } - - for (const auto &resolve : pass.resolvePairs) { - auto resIter = rag.resourceIndex.find(resolve.target); - gfx::AccessFlags prevAccess = resIter == rag.resourceIndex.end() ? gfx::AccessFlags::NONE : rag.accessRecord.at(resIter->second).currStatus.accessFlag; - viewIndex.emplace_back(SubpassRasterViewData{ - {ACCESS_TYPE_WEIGHT[static_cast(AccessType::WRITE)], ATTACHMENT_TYPE_WEIGHT[static_cast(AttachmentType::RENDER_TARGET)], "_", 0xFFFFFFFF}, - resolve.target, - prevAccess, - }); - } - - std::sort(viewIndex.begin(), viewIndex.end(), [](const SubpassRasterViewData &lhs, const SubpassRasterViewData &rhs) { - if (lhs.sortKey.samplesReverseWeight != rhs.sortKey.samplesReverseWeight) { - return lhs.sortKey.samplesReverseWeight < rhs.sortKey.samplesReverseWeight; - } - if (lhs.sortKey.accessType != rhs.sortKey.accessType) { - return lhs.sortKey.accessType < rhs.sortKey.accessType; - } - if (lhs.sortKey.attachmentType != rhs.sortKey.attachmentType) { - return lhs.sortKey.attachmentType < rhs.sortKey.attachmentType; - } - return lhs.sortKey.slotName < rhs.sortKey.slotName; - }); - - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, parentRagVert); - auto &fgRenderpassInfo = resourceAccessGraph.rpInfos.at(parentRagVert); - auto &rpInfo = fgRenderpassInfo.rpInfo; - auto &subpassInfo = rpInfo.subpasses.emplace_back(); - auto *lastNode = &node; - uint32_t subpassIndex = 0; - while (lastNode->nextSubpass) { - lastNode = lastNode->nextSubpass; - ++subpassIndex; - } - lastNode->nextSubpass = new ResourceAccessNode; - resourceAccessGraph.subpassIndex.emplace(passID, subpassIndex); - auto *head = lastNode->nextSubpass; - bool dependent{false}; - dependent |= checkRasterViews(graphs, parentRagVert, passID, PassType::RASTER, *head, pass.rasterViews); - dependent |= checkComputeViews(graphs, parentRagVert, passID, PassType::RASTER, *head, pass.computeViews); - dependent |= checkResolveResource(graphs, parentRagVert, passID, *head, pass.resolvePairs); - - if (!dependent) { - tryAddEdge(EXPECT_START_ID, parentRagVert, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, parentRagVert, relationGraph); - } - - if (!pass.resolvePairs.empty()) { - // ds resolve stores in depthStencilResolve - subpassInfo.resolves.resize(pass.rasterViews.size() - hasDS, gfx::INVALID_BINDING); - } - - uint32_t localSlot = 0; - bool dsAppeared{false}; - for (const auto &[sortKey, name, access] : viewIndex) { - const auto *const resName = name.data(); - auto findByResID = [&](const AccessStatus &status) { - return status.vertID == rag.resourceIndex.at(resName); - }; - auto iter = std::find_if(node.attachmentStatus.begin(), node.attachmentStatus.end(), findByResID); - - // TODO(Zeqiang): remove find - const auto &targetName = name; - auto resID = rag.resourceIndex.at(resName); - const auto &viewDesc = get(ResourceGraph::DescTag{}, resg, rag.resourceIndex.at(resName)); - - AttachmentType attachmentType{AttachmentType::RENDER_TARGET}; - AccessType accessType{AccessType::WRITE}; - gfx::LoadOp loadOp{gfx::LoadOp::DISCARD}; - gfx::StoreOp storeOp{gfx::StoreOp::STORE}; - - uint32_t slot = dsAppeared ? localSlot - 1 : localSlot; - // std::distance(uberPass.rasterViews.begin(), uberPass.rasterViews.find(resName)); - // slot = dsAppeared ? slot - 1 : slot; - /*if (attachmentType != AttachmentType::DEPTH_STENCIL) { - CC_ASSERT(uberPass.attachmentIndexMap.count(resName)); - slot = uberPass.attachmentIndexMap.at(resName); - }*/ - - // TD:remove find - auto nodeIter = std::find_if(head->attachmentStatus.begin(), head->attachmentStatus.end(), [resID](const AccessStatus &status) { - return status.vertID == resID; - }); - auto nextAccess = nodeIter->accessFlag; - - auto resolveIter = std::find_if(pass.resolvePairs.begin(), pass.resolvePairs.end(), [&targetName](const ResolvePair &resolve) { - return strcmp(resolve.target.c_str(), targetName.data()) == 0; - }); - bool resolveView = resolveIter != pass.resolvePairs.end(); - if (resolveView) { - attachmentType = viewDesc.format == gfx::Format::DEPTH_STENCIL ? AttachmentType::DEPTH_STENCIL : AttachmentType::RENDER_TARGET; - if (attachmentType == AttachmentType::DEPTH_STENCIL) { - subpassInfo.depthStencilResolve = slot; - subpassInfo.depthResolveMode = gfx::ResolveMode::SAMPLE_ZERO; // resolveiter->mode; - subpassInfo.stencilResolveMode = gfx::ResolveMode::SAMPLE_ZERO; // resolveiter->mode1; - fgRenderpassInfo.dsResolveAccess.nextAccess = nextAccess; - } else { - auto indexIter = std::find(fgRenderpassInfo.orderedViews.begin(), fgRenderpassInfo.orderedViews.end(), resolveIter->source.c_str()); - auto srcIndex = indexIter == fgRenderpassInfo.orderedViews.end() ? fgRenderpassInfo.orderedViews.size() - : std::distance(fgRenderpassInfo.orderedViews.begin(), indexIter); - subpassInfo.resolves[srcIndex] = slot; - fgRenderpassInfo.colorAccesses[slot].nextAccess = nextAccess; - } - accessType = AccessType::WRITE; - } else { - const auto &view = pass.rasterViews.at(resName); - attachmentType = view.attachmentType; - accessType = view.accessType; - loadOp = view.loadOp; - storeOp = view.storeOp; - - if (attachmentType != AttachmentType::DEPTH_STENCIL) { - if (attachmentType == AttachmentType::SHADING_RATE) { - subpassInfo.shadingRate = slot; - } else { - if (accessType != AccessType::READ) { - subpassInfo.colors.emplace_back(slot); - } - if (accessType != AccessType::WRITE) { - subpassInfo.inputs.emplace_back(slot); - } - } - fgRenderpassInfo.colorAccesses[slot].nextAccess = nextAccess; - } else { - fgRenderpassInfo.dsAccess.nextAccess = nextAccess; - subpassInfo.depthStencil = rpInfo.colorAttachments.size(); - dsAppeared = true; - } - } - - if (iter == node.attachmentStatus.end()) { - auto curIter = std::find_if(head->attachmentStatus.begin(), head->attachmentStatus.end(), findByResID); - node.attachmentStatus.emplace_back(*curIter); - auto prevAccess = access; - CC_ASSERT(head->attachmentStatus.size() > localSlot); - auto nextAccess = head->attachmentStatus[localSlot].accessFlag; - - if (attachmentType == AttachmentType::DEPTH_STENCIL) { - if (resolveView) { - fgRenderpassInfo.dsResolveAccess.prevAccess = prevAccess; - } else { - fgRenderpassInfo.dsAccess.prevAccess = prevAccess; - } - } else { - fgRenderpassInfo.colorAccesses[slot].prevAccess = prevAccess; - } - fgRenderpassInfo.orderedViews.emplace_back(resName); - } - fillRenderPassInfo(loadOp, storeOp, attachmentType, rpInfo, slot, viewDesc, resolveView); - fgRenderpassInfo.needResolve |= resolveView; - ++localSlot; - } - - if (pass.subpassID == uberPass.subpassGraph.subpasses.size() - 1) { - getPreserves(rpInfo); - } -} - -void processComputeSubpass(const Graphs &graphs, uint32_t passID, const ComputeSubpass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - const auto &obj = renderGraph.objects.at(passID); - const auto parentID = obj.parents.front().target; - const auto parentRagVert = resourceAccessGraph.passIndex.at(parentID); - const auto *parentPass = get_if(parentID, &renderGraph); - CC_EXPECTS(parentPass); - const auto &rag = resourceAccessGraph; - const auto &resg = resourceGraph; - const auto &uberPass = *parentPass; - - resourceAccessGraph.passIndex[passID] = parentRagVert; - - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, parentRagVert); - - auto *lastNode = &node; - while (lastNode->nextSubpass) { - lastNode = lastNode->nextSubpass; - } - lastNode->nextSubpass = new ResourceAccessNode; - auto *head = lastNode->nextSubpass; - - bool dependent = checkComputeViews(graphs, parentRagVert, passID, PassType::COMPUTE, *head, pass.computeViews); - - if (!dependent) { - tryAddEdge(EXPECT_START_ID, parentRagVert, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, parentRagVert, relationGraph); - } -} - -void processCopyPass(const Graphs &graphs, uint32_t passID, const CopyPass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - - auto vertID = add_vertex(resourceAccessGraph, passID); - auto rlgVertID = add_vertex(relationGraph, vertID); - CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); - - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, vertID); - bool dependent = false; - for (const auto &pair : pass.copyPairs) { - auto sourceRange = Range{ - TextureRange{ - pair.sourceFirstSlice, - pair.sourcePlaneSlice, - pair.mipLevels, - pair.numSlices, - }}; - auto targetRange = Range{ - TextureRange{ - pair.targetFirstSlice, - pair.targetPlaneSlice, - pair.mipLevels, - pair.numSlices, - }}; - ResourceUsage srcUsage = gfx::TextureUsage::TRANSFER_SRC; - 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, gfx::AccessFlags::TRANSFER_WRITE, dstUsage}; - addCopyAccessStatus(resourceAccessGraph, resourceGraph, node, dstViewStatus, targetRange); - - uint32_t lastVertSrc = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, srcViewStatus); - if (lastVertSrc != INVALID_ID) { - tryAddEdge(lastVertSrc, vertID, resourceAccessGraph); - tryAddEdge(lastVertSrc, rlgVertID, relationGraph); - dependent = true; - } - uint32_t lastVertDst = dependencyCheck(resourceAccessGraph, vertID, resourceGraph, dstViewStatus); - if (lastVertDst != INVALID_ID) { - tryAddEdge(lastVertDst, vertID, resourceAccessGraph); - tryAddEdge(lastVertDst, rlgVertID, relationGraph); - dependent = true; - } - } - if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); - } - std::sort(node.attachmentStatus.begin(), node.attachmentStatus.end(), [](const AccessStatus &lhs, const AccessStatus &rhs) { return lhs.vertID < rhs.vertID; }); -} - -void processRaytracePass(const Graphs &graphs, uint32_t passID, const RaytracePass &pass) { - const auto &[renderGraph, resourceGraph, layoutGraphData, resourceAccessGraph, relationGraph] = graphs; - - auto vertID = add_vertex(resourceAccessGraph, passID); - auto rlgVertID = add_vertex(relationGraph, vertID); - CC_EXPECTS(static_cast(rlgVertID) == static_cast(vertID)); - - auto &node = get(RAG::AccessNodeTag{}, resourceAccessGraph, vertID); - bool dependent = checkComputeViews(graphs, vertID, passID, PassType::RAYTRACE, node, pass.computeViews); - - if (!dependent) { - tryAddEdge(EXPECT_START_ID, vertID, resourceAccessGraph); - tryAddEdge(EXPECT_START_ID, rlgVertID, relationGraph); - } -} - #pragma endregion assisstantFuncDefinition } // namespace render diff --git a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp index 23fdda466b..c52a13d114 100644 --- a/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeExecutor.cpp @@ -35,6 +35,7 @@ #include "RenderGraphGraphs.h" #include "RenderGraphTypes.h" #include "RenderingModule.h" +#include "NativeRenderGraphUtils.h" #include "cocos/renderer/gfx-base/GFXBarrier.h" #include "cocos/renderer/gfx-base/GFXDef-common.h" #include "cocos/renderer/gfx-base/GFXDescriptorSetLayout.h" @@ -70,7 +71,6 @@ struct RenderGraphVisitorContext { const RenderGraph& g; ResourceGraph& resourceGraph; const FrameGraphDispatcher& fgd; - const FrameGraphDispatcher::BarrierMap& barrierMap; const ccstd::pmr::vector& validPasses; gfx::Device* device = nullptr; gfx::CommandBuffer* cmdBuff = nullptr; @@ -164,145 +164,24 @@ gfx::GeneralBarrier* getGeneralBarrier(gfx::Device* device, const RasterView& vi return nullptr; } +ResourceGraph::vertex_descriptor getResourceID(const ccstd::pmr::string& name, const FrameGraphDispatcher& fgd) { + return fgd.realResourceID(name); +} + PersistentRenderPassAndFramebuffer createPersistentRenderPassAndFramebuffer( RenderGraphVisitorContext& ctx, const RasterPass& pass, - boost::container::pmr::memory_resource* scratch) { + boost::container::pmr::memory_resource* /*scratch*/) { auto& resg = ctx.resourceGraph; PersistentRenderPassAndFramebuffer data(pass.get_allocator()); - gfx::RenderPassInfo rpInfo{}; + auto [rpInfo, fbInfo, clearColors, clearDepth, clearStencil] = ctx.fgd.getRenderPassAndFrameBuffer(ctx.currentInFlightPassID, resg); - gfx::FramebufferInfo fbInfo{ - data.renderPass, - }; - fbInfo.colorTextures.reserve(pass.rasterViews.size()); - - PmrFlatSet set(scratch); - auto fillFrameBufferInfo = [&](const ccstd::vector& passViews, bool hasResolve) { - std::ignore = hasResolve; - const auto& uberPass = pass; - auto numTotalAttachments = static_cast(passViews.size()); - - // uint32_t dsvCount = 0; - uint32_t index = 0; - for (const auto& nameIn : passViews) { - const char* name = nameIn.c_str(); - bool colorLikeView{true}; - bool dsResolveAttachment{false}; - auto clearColor = gfx::Color{}; - auto iter = pass.rasterViews.find(name); - if(iter != pass.rasterViews.end()) { - const auto& view = iter->second; - colorLikeView = view.attachmentType == AttachmentType::RENDER_TARGET || view.attachmentType == AttachmentType::SHADING_RATE; - clearColor = view.clearColor; - } else { - // resolves - const auto resID = vertex(name, ctx.resourceGraph); - const auto& desc = get(ResourceGraph::DescTag{}, ctx.resourceGraph, resID); - CC_ASSERT(hasResolve && desc.sampleCount == gfx::SampleCount::X1); - colorLikeView = desc.format != gfx::Format::DEPTH_STENCIL && desc.format != gfx::Format::DEPTH; - dsResolveAttachment = !colorLikeView; - } - - if (colorLikeView) { // RenderTarget - data.clearColors.emplace_back(clearColor); - - auto resID = findVertex(name, resg); - visitObject( - resID, resg, - [&](const ManagedResource& res) { - std::ignore = res; - CC_EXPECTS(false); - }, - [&](const ManagedBuffer& res) { - std::ignore = res; - CC_EXPECTS(false); - }, - [&](const ManagedTexture& tex) { - CC_EXPECTS(tex.texture); - fbInfo.colorTextures.emplace_back(tex.texture); - }, - [&](const IntrusivePtr& res) { - std::ignore = res; - CC_EXPECTS(false); - }, - [&](const IntrusivePtr& tex) { - fbInfo.colorTextures.emplace_back(tex); - }, - [&](const IntrusivePtr& fb) { - CC_EXPECTS(fb->getColorTextures().size() == 1); - CC_EXPECTS(fb->getColorTextures().at(0)); - fbInfo.colorTextures.emplace_back(fb->getColorTextures()[index]); - // render window attaches a depthStencil by default, which may differs from renderpassInfo here. - // data.framebuffer = fb; - }, - [&](const RenderSwapchain& sc) { - fbInfo.colorTextures.emplace_back(sc.swapchain->getColorTexture()); - }, - [&](const FormatView& view) { - // TODO(zhouzhenglong): add ImageView support - std::ignore = view; - CC_EXPECTS(false); - }, - [&](const SubresourceView& view) { - // TODO(zhouzhenglong): add ImageView support - std::ignore = view; - CC_EXPECTS(false); - }); - } else { // DepthStencil - if (!dsResolveAttachment) { - data.clearDepth = clearColor.x; - data.clearStencil = static_cast(clearColor.y); - } - - auto &dsAttachment = dsResolveAttachment ? fbInfo.depthStencilResolveTexture : fbInfo.depthStencilTexture; - - auto resID = findVertex(name, resg); - visitObject( - resID, resg, - [&](const ManagedTexture& tex) { - CC_EXPECTS(tex.texture); - dsAttachment = tex.texture.get(); - }, - [&](const IntrusivePtr& tex) { - dsAttachment = tex.get(); - }, - [&](const FormatView& view) { - std::ignore = view; - CC_EXPECTS(false); - }, - [&](const SubresourceView& view) { - std::ignore = view; - CC_EXPECTS(false); - }, - [](const auto& /*unused*/) { - CC_EXPECTS(false); - }); - } - ++index; - } - }; - - const auto passID = ctx.currentInFlightPassID; - const auto ragVertID = ctx.fgd.resourceAccessGraph.passIndex.at(passID); - if (pass.subpassGraph.subpasses.empty()) { - const auto numInputs = getRasterPassInputCount(pass); - const auto numColors = getRasterPassOutputCount(pass); - - // persistent cache - data.clearColors.reserve(numColors); - const auto& fgdRpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID); - rpInfo = fgdRpInfo.rpInfo; - fillFrameBufferInfo(fgdRpInfo.orderedViews, false); - - } else { - const auto& fgdRpInfo = ctx.fgd.resourceAccessGraph.rpInfos.at(ragVertID); - rpInfo = fgdRpInfo.rpInfo; - fillFrameBufferInfo(fgdRpInfo.orderedViews, fgdRpInfo.needResolve); - } - CC_ENSURES(rpInfo.colorAttachments.size() == data.clearColors.size()); + // CC_ENSURES(rpInfo.colorAttachments.size() == data.clearColors.size()); CC_ENSURES(rpInfo.colorAttachments.size() == fbInfo.colorTextures.size()); + data.clearColors = std::move(clearColors); + data.clearDepth = clearDepth; + data.clearStencil = clearStencil; data.renderPass = ctx.device->createRenderPass(rpInfo); fbInfo.renderPass = data.renderPass; data.framebuffer = ctx.device->createFramebuffer(fbInfo); @@ -660,28 +539,23 @@ gfx::DescriptorSet* initDescriptorSet( } break; case DescriptorTypeOrder::INPUT_ATTACHMENT: { - for (auto d : block.descriptors) { - CC_EXPECTS(d.count == 1); - auto iter = resourceIndex.find(d.descriptorID); - if (iter != resourceIndex.end()) { - // render graph textures - auto* texture = resg.getTexture(iter->second); - gfx::AccessFlags access = gfx::AccessFlagBit::NONE; - if (accessNode != nullptr) { - auto accIter = std::find_if( - accessNode->attachmentStatus.begin(), accessNode->attachmentStatus.end(), - [iter](const AccessStatus& status) { - return status.vertID == iter->second; - }); - access = accIter != accessNode->attachmentStatus.end() ? accIter->accessFlag : gfx::AccessFlagBit::NONE; - } - - CC_ENSURES(texture); - newSet->bindTexture(bindID, texture, 0, access); + for (const auto& [descID, resID] : resourceIndex) { + std::ignore = descID; + // render graph textures + auto* texture = resg.getTexture(resID); + gfx::AccessFlags access = gfx::AccessFlagBit::NONE; + if (accessNode != nullptr) { + // whole access only now. + auto parentID = parent(resID, resg); + parentID = parentID == ResourceGraph::null_vertex() ? resID : parentID; + const auto& resName = get(ResourceGraph::NameTag{}, resg, parentID); + access = accessNode->resourceStatus.at(resName).accessFlag; } - bindID += d.count; - } + CC_ENSURES(texture); + newSet->bindTexture(bindID, texture, 0, access); + bindID += 1; + } }; break; default: @@ -908,26 +782,6 @@ void submitProfilerCommands( cmdBuff->draw(ia); } -PmrFlatMap -buildResourceIndex( - const ResourceGraph& resg, - const LayoutGraphData& lg, - const PmrTransparentMap>& computeViews, - boost::container::pmr::memory_resource* scratch) { - PmrFlatMap resourceIndex(scratch); - resourceIndex.reserve(computeViews.size() * 2); - for (const auto& [resName, computeViews] : computeViews) { - const auto resID = vertex(resName, resg); - for (const auto& computeView : computeViews) { - const auto& name = computeView.name; - CC_EXPECTS(!name.empty()); - const auto nameID = lg.attributeIndex.at(name); - resourceIndex.emplace(nameID, resID); - } - } - return resourceIndex; -} - const PmrTransparentMap>& getComputeViews(RenderGraph::vertex_descriptor passID, const RenderGraph& rg) { if (holds(passID, rg)) { @@ -1073,8 +927,7 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { } // build pass resources - const auto& resourceIndex = buildResourceIndex( - ctx.resourceGraph, ctx.lg, computeViews, ctx.scratch); + const auto& resourceIndex = ctx.fgd.buildDescriptorIndex(computeViews, ctx.scratch); // populate set auto& set = iter->second; @@ -1106,8 +959,7 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { } // build pass resources - const auto& resourceIndex = buildResourceIndex( - ctx.resourceGraph, ctx.lg, computeViews, ctx.scratch); + const auto& resourceIndex = ctx.fgd.buildDescriptorIndex(computeViews, ctx.scratch); // find scene resource const auto* const sceneResource = getFirstSceneResource(vertID); @@ -1148,7 +1000,6 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { const auto& subpass = get(RasterSubpassTag{}, vertID, ctx.g); // render pass const auto& layoutName = get(RenderGraph::LayoutTag{}, ctx.g, vertID); - auto parentLayoutID = ctx.currentPassLayoutID; auto layoutID = parentLayoutID; if (!layoutName.empty()) { @@ -1169,35 +1020,12 @@ struct RenderGraphUploadVisitor : boost::dfs_visitor<> { return; } - // build pass resources - /* const auto& resourceIndex = buildResourceIndex( - ctx.resourceGraph, ctx.lg, subpass.computeViews, ctx.scratch);*/ - PmrFlatMap resourceIndex(ctx.scratch); - - resourceIndex.reserve(subpass.rasterViews.size() * 2); - for (const auto& [resName, rasterView] : subpass.rasterViews) { - const auto resID = vertex(resName, ctx.resourceGraph); - auto ragId = ctx.fgd.resourceAccessGraph.passIndex.at(vertID); - const auto& attachments = ctx.fgd.resourceAccessGraph.access[ragId].attachmentStatus; - auto resIter = std::find_if(attachments.begin(), attachments.end(), [resID](const AccessStatus& status) { - return status.vertID == resID; - }); - - auto slotName = rasterView.slotName; - if (rasterView.accessType == AccessType::READ || rasterView.accessType == AccessType::READ_WRITE) { - slotName.insert(0, "__in"); - } - auto iter = ctx.lg.attributeIndex.find(slotName); - if (iter != ctx.lg.attributeIndex.end()) { - resourceIndex.emplace(iter->second, resID); - } - } - + const auto& resourceIndex = ctx.fgd.buildDescriptorIndex(subpass.computeViews, subpass.rasterViews, ctx.scratch); // populate set auto& set = iter->second; const auto& user = get(RenderGraph::DataTag{}, ctx.g, vertID); auto& node = ctx.context.layoutGraphResources.at(layoutID); - const auto& accessNode = ctx.fgd.getAttachmentStatus(vertID); + const auto& accessNode = ctx.fgd.getAccessNode(vertID); auto* perPassSet = initDescriptorSet( ctx.resourceGraph, @@ -1258,25 +1086,15 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { textureBarriers.data(), textures.data(), static_cast(textureBarriers.size())); } void frontBarriers(RenderGraph::vertex_descriptor vertID) const { - auto iter = ctx.fgd.resourceAccessGraph.passIndex.find(vertID); - if (iter == ctx.fgd.resourceAccessGraph.passIndex.end()) { - return; - } - const auto& nodeID = iter->second; - auto iter2 = ctx.barrierMap.find(nodeID); - if (iter2 != ctx.barrierMap.end()) { - submitBarriers(iter2->second.blockBarrier.frontBarriers); + const auto& barrier = ctx.fgd.getBarrier(vertID); + if (!barrier.frontBarriers.empty()) { + submitBarriers(barrier.frontBarriers); } } void rearBarriers(RenderGraph::vertex_descriptor vertID) const { - auto iter = ctx.fgd.resourceAccessGraph.passIndex.find(vertID); - if (iter == ctx.fgd.resourceAccessGraph.passIndex.end()) { - return; - } - const auto& nodeID = iter->second; - auto iter2 = ctx.barrierMap.find(nodeID); - if (iter2 != ctx.barrierMap.end()) { - submitBarriers(iter2->second.blockBarrier.rearBarriers); + const auto& barrier = ctx.fgd.getBarrier(vertID); + if (!barrier.rearBarriers.empty()) { + submitBarriers(barrier.rearBarriers); } } void tryBindPerPassDescriptorSet(RenderGraph::vertex_descriptor vertID) const { @@ -1352,6 +1170,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { if (subpass.subpassID) { ctx.cmdBuff->nextSubpass(); } + //ctx.cmdBuff->setViewport(subpass); tryBindPerPassDescriptorSet(vertID); ctx.subpassIndex = subpass.subpassID; // noop @@ -1546,32 +1365,14 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { const auto* scene = camera->getScene(); const auto& queueDesc = ctx.context.sceneCulling.sceneQueryIndex.at(sceneID); const auto& queue = ctx.context.sceneCulling.renderQueues[queueDesc.renderQueueTarget]; - bool bDraw = any(sceneData.flags & SceneFlags::DRAW_NON_INSTANCING); - bool bDrawInstancing = any(sceneData.flags & SceneFlags::DRAW_INSTANCING); - if (!bDraw && !bDrawInstancing) { - bDraw = true; - bDrawInstancing = true; - } - const bool bDrawBlend = any(sceneData.flags & SceneFlags::TRANSPARENT_OBJECT); - const bool bDrawOpaqueOrMask = any(sceneData.flags & (SceneFlags::OPAQUE_OBJECT | SceneFlags::CUTOUT_OBJECT)); - const bool bDrawShadowCaster = any(sceneData.flags & SceneFlags::SHADOW_CASTER); - - if (bDrawShadowCaster || bDrawOpaqueOrMask) { - queue.opaqueQueue.recordCommandBuffer( - ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); - if (bDrawInstancing) { - queue.opaqueInstancingQueue.recordCommandBuffer( - ctx.currentPass, ctx.cmdBuff); - } - } - if (bDrawBlend) { - queue.transparentQueue.recordCommandBuffer( - ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); - if (bDrawInstancing) { - queue.transparentInstancingQueue.recordCommandBuffer( - ctx.currentPass, ctx.cmdBuff); - } - } + queue.opaqueQueue.recordCommandBuffer( + ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); + queue.opaqueInstancingQueue.recordCommandBuffer( + ctx.currentPass, ctx.cmdBuff); + queue.transparentQueue.recordCommandBuffer( + ctx.device, camera, ctx.currentPass, ctx.cmdBuff, 0); + queue.transparentInstancingQueue.recordCommandBuffer( + ctx.currentPass, ctx.cmdBuff); if (any(sceneData.flags & SceneFlags::UI)) { submitUICommands(ctx.currentPass, ctx.currentPassLayoutID, camera, ctx.cmdBuff); @@ -1750,41 +1551,41 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { } void end(const gfx::Viewport& pass, RenderGraph::vertex_descriptor vertID) const { } + + void mountResource(const ccstd::pmr::string& name) const { // NOLINT(misc-no-recursion) + auto resIter = ctx.fgd.resourceAccessGraph.resourceIndex.find(name); + if (resIter != ctx.fgd.resourceAccessGraph.resourceIndex.end()) { + auto resID = resIter->second; + auto& resg = ctx.resourceGraph; + resg.mount(ctx.device, resID); + for (const auto& subres : makeRange(children(resID, resg))) { + const auto& subresName = get(ResourceGraph::NameTag{}, resg, subres.target); + mountResource(subresName); + } + } + } void mountResources(const Subpass& pass) const { - auto& resg = ctx.resourceGraph; // mount managed resources for (const auto& [name, view] : pass.rasterViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } for (const auto& [name, views] : pass.computeViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } for (const auto& resolve : pass.resolvePairs) { - auto resID = findVertex(resolve.target, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(resolve.target); } } void mountResources(const RasterPass& pass) const { - auto& resg = ctx.resourceGraph; // mount managed resources for (const auto& [name, view] : pass.rasterViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } for (const auto& [name, views] : pass.computeViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } - for (const auto& subpass : pass.subpassGraph.subpasses) { mountResources(subpass); } @@ -1794,9 +1595,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { auto& resg = ctx.resourceGraph; PmrFlatSet mounted(ctx.scratch); for (const auto& [name, views] : pass.computeViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } } @@ -1804,9 +1603,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { auto& resg = ctx.resourceGraph; PmrFlatSet mounted(ctx.scratch); for (const auto& [name, views] : pass.computeViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } } @@ -1814,9 +1611,7 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { auto& resg = ctx.resourceGraph; PmrFlatSet mounted(ctx.scratch); for (const auto& [name, views] : pass.computeViews) { - auto resID = findVertex(name, resg); - CC_EXPECTS(resID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, resID); + mountResource(name); } } @@ -1824,12 +1619,8 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { auto& resg = ctx.resourceGraph; PmrFlatSet mounted(ctx.scratch); for (const auto& pair : pass.resolvePairs) { - const auto& srcID = findVertex(pair.source, resg); - CC_EXPECTS(srcID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, srcID); - const auto& dstID = findVertex(pair.target, resg); - CC_EXPECTS(dstID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, dstID); + mountResource(pair.source); + mountResource(pair.target); } } @@ -1837,17 +1628,11 @@ struct RenderGraphVisitor : boost::dfs_visitor<> { auto& resg = ctx.resourceGraph; PmrFlatSet mounted(ctx.scratch); for (const auto& pair : pass.copyPairs) { - const auto& srcID = findVertex(pair.source, resg); - CC_EXPECTS(srcID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, srcID); - const auto& dstID = findVertex(pair.target, resg); - CC_EXPECTS(dstID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, dstID); + mountResource(pair.source); + mountResource(pair.target); } for (const auto& pair : pass.uploadPairs) { - const auto& dstID = findVertex(pair.target, resg); - CC_EXPECTS(dstID != ResourceGraph::null_vertex()); - resg.mount(ctx.device, dstID); + mountResource(pair.target); } } @@ -2223,7 +2008,7 @@ void NativePipeline::executeRenderGraph(const RenderGraph& rg) { RenderGraphVisitorContext ctx{ ppl.nativeContext, lg, rg, ppl.resourceGraph, - fgd, fgd.barrierMap, + fgd, validPasses, ppl.device, submit.primaryCommandBuffer, &ppl, diff --git a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp index ff89a8cd6d..f747e151f3 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp @@ -42,6 +42,50 @@ namespace cc { namespace render { +template +void addSubresourceNode(ResourceGraph::vertex_descriptor v, const ccstd::string &name, ResourceGraph &resg); + +template <> +void addSubresourceNode(ResourceGraph::vertex_descriptor v, const ccstd::string &name, ResourceGraph &resg) { + SubresourceView view{ + nullptr, + gfx::Format::DEPTH_STENCIL, + 0, 1, 0, 1, 0, 1}; + + auto desc = get(ResourceGraph::DescTag{}, resg, v); + auto traits = get(ResourceGraph::TraitsTag{}, resg, v); + auto samplerInfo = get(ResourceGraph::SamplerTag{}, resg, v); + + ccstd::string depthName{name}; + depthName += "/"; + depthName += DEPTH_PLANE_NAME; + auto depthID = addVertex( + SubresourceViewTag{}, + std::forward_as_tuple(depthName.c_str()), + std::forward_as_tuple(desc), + std::forward_as_tuple(traits.residency), + std::forward_as_tuple(), + std::forward_as_tuple(samplerInfo), + std::forward_as_tuple(view), + resg, + v); + + view.firstPlane = 1; + ccstd::string stencilName{name}; + stencilName += "/"; + stencilName += STENCIL_PLANE_NAME; + auto stencilID = addVertex( + SubresourceViewTag{}, + std::forward_as_tuple(stencilName.c_str()), + std::forward_as_tuple(desc), + std::forward_as_tuple(traits.residency), + std::forward_as_tuple(), + std::forward_as_tuple(samplerInfo), + std::forward_as_tuple(view), + resg, + v); +} + NativePipeline::NativePipeline(const allocator_type &alloc) noexcept : device(gfx::Device::getInstance()), globalDSManager(std::make_unique()), @@ -194,7 +238,8 @@ uint32_t NativePipeline::addDepthStencil(const ccstd::string &name, gfx::Format samplerInfo.magFilter = gfx::Filter::POINT; samplerInfo.minFilter = gfx::Filter::POINT; samplerInfo.mipFilter = gfx::Filter::NONE; - return addVertex( + + auto resID = addVertex( ManagedTextureTag{}, std::forward_as_tuple(name.c_str()), std::forward_as_tuple(desc), @@ -203,6 +248,9 @@ uint32_t NativePipeline::addDepthStencil(const ccstd::string &name, gfx::Format std::forward_as_tuple(samplerInfo), std::forward_as_tuple(), resourceGraph); + + addSubresourceNode(resID, name, resourceGraph); + return resID; } uint32_t NativePipeline::addResource(const ccstd::string& name, ResourceDimension dimension, diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp index 528c95d5ce..91c9dcf73b 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraph.cpp @@ -298,6 +298,21 @@ void addRasterViewImpl( auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); const auto slotID = getSlotID(pass, name, attachmentType); CC_EXPECTS(subpass.rasterViews.size() == subpassData.rasterViews.size()); + auto nameIter = subpassData.rasterViews.find(name); + + if (nameIter != subpassData.rasterViews.end()) { + auto &view = subpass.rasterViews.at(name.data()); + if (!defaultAttachment(slotName)) { + nameIter->second.slotName = slotName; + view.slotName = slotName; + } + if (!defaultAttachment(slotName1)) { + nameIter->second.slotName1 = slotName1; + view.slotName1 = slotName1; + } + return; + } + { auto res = subpassData.rasterViews.emplace( std::piecewise_construct, @@ -321,6 +336,7 @@ void addRasterViewImpl( std::forward_as_tuple(name), std::forward_as_tuple( ccstd::pmr::string(slotName, subpassData.get_allocator()), + ccstd::pmr::string(slotName1, subpassData.get_allocator()), accessType, attachmentType, loadOp, @@ -533,18 +549,18 @@ void NativeRenderSubpassBuilderImpl::setShowStatistics(bool enable) { void NativeMultisampleRenderSubpassBuilder::resolveRenderTarget( const ccstd::string &source, const ccstd::string &target) { // NOLINT(bugprone-easily-swappable-parameters) auto &subpass = get(RasterSubpassTag{}, nodeID, *renderGraph); - + auto parentID = parent(nodeID, *renderGraph); auto &pass = get(RasterPassTag{}, parentID, *renderGraph); auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); - + subpass.resolvePairs.emplace_back( ccstd::pmr::string(source.data(), renderGraph->get_allocator()), ccstd::pmr::string(target.data(), renderGraph->get_allocator()), ResolveFlags::COLOR, gfx::ResolveMode::AVERAGE, gfx::ResolveMode::NONE); - + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } @@ -559,7 +575,7 @@ void NativeMultisampleRenderSubpassBuilder::resolveDepthStencil( if (stencilMode != gfx::ResolveMode::NONE) { flags |= ResolveFlags::STENCIL; } - + auto parentID = parent(nodeID, *renderGraph); auto &pass = get(RasterPassTag{}, parentID, *renderGraph); auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); @@ -570,7 +586,7 @@ void NativeMultisampleRenderSubpassBuilder::resolveDepthStencil( flags, depthMode, stencilMode); - + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } @@ -1137,17 +1153,17 @@ void NativeMultisampleRenderPassBuilder::setShowStatistics(bool enable) { void NativeMultisampleRenderPassBuilder::resolveRenderTarget( const ccstd::string &source, const ccstd::string &target) { // NOLINT(bugprone-easily-swappable-parameters) auto &subpass = get(RasterSubpassTag{}, subpassID, *renderGraph); - + auto &pass = get(RasterPassTag{}, nodeID, *renderGraph); auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); - + subpass.resolvePairs.emplace_back( ccstd::pmr::string(source.data(), renderGraph->get_allocator()), ccstd::pmr::string(target.data(), renderGraph->get_allocator()), ResolveFlags::COLOR, gfx::ResolveMode::AVERAGE, gfx::ResolveMode::NONE); - + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } @@ -1162,7 +1178,7 @@ void NativeMultisampleRenderPassBuilder::resolveDepthStencil( if (stencilMode != gfx::ResolveMode::NONE) { flags |= ResolveFlags::STENCIL; } - + auto &pass = get(RasterPassTag{}, nodeID, *renderGraph); auto &subpassData = get(SubpassGraph::SubpassTag{}, pass.subpassGraph, subpass.subpassID); @@ -1172,7 +1188,7 @@ void NativeMultisampleRenderPassBuilder::resolveDepthStencil( flags, depthMode, stencilMode); - + subpassData.resolvePairs.emplace_back(subpass.resolvePairs.back()); } diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h index 1885886921..bf1ff54740 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h +++ b/native/cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h @@ -211,6 +211,19 @@ void addSubpassComputeViewImpl( subpassData.computeViews.find(std::string_view{name})->second.size()); } +inline bool defaultAttachment(std::string_view slotName) { + return slotName.empty() || slotName == "_"; +} + +static constexpr std::string_view DEPTH_PLANE_NAME = "depth"; +static constexpr std::string_view STENCIL_PLANE_NAME = "stencil"; +static constexpr std::string_view CUBE_TOP_NAME = "Top"; +static constexpr std::string_view CUBE_BOTTOM_NAME = "Bottom"; +static constexpr std::string_view CUBE_FRONT_NAME = "Front"; +static constexpr std::string_view CUBE_REAR_NAME = "Rear"; +static constexpr std::string_view CUBE_LEFT_NAME = "Left"; +static constexpr std::string_view CUBE_RIGHT_NAME = "Right"; + } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp index 984e215a9a..5c8ce3ee84 100644 --- a/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeResourceGraph.cpp @@ -22,10 +22,12 @@ THE SOFTWARE. ****************************************************************************/ +#include #include "NativePipelineTypes.h" #include "RenderGraphGraphs.h" #include "RenderGraphTypes.h" #include "cocos/renderer/gfx-base/GFXDevice.h" +#include "details/GraphView.h" #include "details/Range.h" #include "gfx-base/GFXDef-common.h" #include "pipeline/custom/RenderCommonFwd.h" @@ -168,6 +170,23 @@ gfx::TextureInfo getTextureInfo(const ResourceDesc& desc, bool bCube = false) { }; } +gfx::TextureViewInfo getTextureViewInfo(const SubresourceView& subresView, const ResourceDesc& desc, bool bCube = false) { + using namespace gfx; // NOLINT(google-build-using-namespace) + + const auto& textureInfo = getTextureInfo(desc, bCube); + + return { + nullptr, + textureInfo.type, + subresView.format, + subresView.indexOrFirstMipLevel, + subresView.numMipLevels, + subresView.firstArraySlice, + subresView.numArraySlices, + subresView.firstPlane, + subresView.numPlanes, + }; +} } // namespace bool ManagedTexture::checkResource(const ResourceDesc& desc) const { @@ -243,10 +262,9 @@ void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { CC_EXPECTS(parentID != resg.null_vertex()); CC_EXPECTS(resg.isTexture(parentID)); CC_ENSURES(!resg.isTextureView(parentID)); - mount(device, parentID); + mount(device, parentID); // NOLINT(misc-no-recursion) }, - [&](const SubresourceView& view) { // NOLINT(misc-no-recursion) - std::ignore = view; + [&](SubresourceView& view) { // NOLINT(misc-no-recursion) auto parentID = parent(vertID, resg); CC_EXPECTS(parentID != resg.null_vertex()); while (resg.isTextureView(parentID)) { @@ -255,7 +273,13 @@ void ResourceGraph::mount(gfx::Device* device, vertex_descriptor vertID) { CC_EXPECTS(parentID != resg.null_vertex()); CC_EXPECTS(resg.isTexture(parentID)); CC_ENSURES(!resg.isTextureView(parentID)); - mount(device, parentID); + auto* parentTexture = resg.getTexture(parentID); + const auto& desc = get(ResourceGraph::DescTag{}, resg, vertID); + if (!view.textureView) { + auto textureViewInfo = getTextureViewInfo(view, desc); + textureViewInfo.texture = parentTexture; + view.textureView = device->createTexture(textureViewInfo); + } }); } @@ -362,8 +386,7 @@ gfx::Texture* ResourceGraph::getTexture(vertex_descriptor resID) { }, [&](const SubresourceView& view) { // TODO(zhouzhenglong): add ImageView support - std::ignore = view; - CC_EXPECTS(false); + texture = view.textureView; }, [&](const auto& buffer) { std::ignore = buffer; diff --git a/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp b/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp index f2cfd0111b..0b9a286525 100644 --- a/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp @@ -104,7 +104,7 @@ void SceneCulling::collectCullingQueries( } namespace { - +const pipeline::PipelineSceneData* pSceneData = nullptr; bool isNodeVisible(const Node* node, uint32_t visibility) { return node && ((visibility & node->getLayer()) == node->getLayer()); } @@ -113,9 +113,18 @@ uint32_t isModelVisible(const scene::Model& model, uint32_t visibility) { return visibility & static_cast(model.getVisFlags()); } -bool isFrustumVisible(const scene::Model& model, const geometry::Frustum& frustum) { +bool isFrustumVisible(const scene::Model& model, const geometry::Frustum& frustum, bool castShadow) { const auto* const modelWorldBounds = model.getWorldBounds(); - return !modelWorldBounds || modelWorldBounds->aabbFrustum(frustum); + if (!modelWorldBounds) { + return true; + } + geometry::AABB transWorldBounds{}; + transWorldBounds.set(modelWorldBounds->getCenter(), modelWorldBounds->getHalfExtents()); + const scene::Shadows& shadows = *pSceneData->getShadows(); + if (shadows.getType() == scene::ShadowType::PLANAR && castShadow) { + modelWorldBounds->transform(shadows.getMatLight(), &transWorldBounds); + } + return transWorldBounds.aabbFrustum(frustum); } void octreeCulling( @@ -183,7 +192,7 @@ void bruteForceCulling( // filter model by view visibility if (isNodeVisible(model.getNode(), visibility) || isModelVisible(model, visibility)) { // frustum culling - if (!isFrustumVisible(model, cameraOrLightFrustum)) { + if (!isFrustumVisible(model, cameraOrLightFrustum, bCastShadow)) { continue; } // is skybox, skip @@ -248,14 +257,23 @@ void SceneCulling::batchCulling(const pipeline::PipelineSceneData& pplSceneData) models); break; case scene::LightType::DIRECTIONAL: { - const auto& csmLayers = *pplSceneData.getCSMLayers(); + auto& csmLayers = *pplSceneData.getCSMLayers(); const auto* mainLight = dynamic_cast(light); const auto& csmLevel = mainLight->getCSMLevel(); const geometry::Frustum* frustum = nullptr; - if (mainLight->isShadowFixedArea() || csmLevel == scene::CSMLevel::LEVEL_1) { - frustum = &csmLayers.getSpecialLayer()->getValidFrustum(); + const auto& shadows = *pplSceneData.getShadows(); + if (shadows.getType() == scene::ShadowType::PLANAR) { + frustum = &camera.getFrustum(); } else { - frustum = &csmLayers.getLayers()[level]->getValidFrustum(); + if (shadows.isEnabled() && shadows.getType() == scene::ShadowType::SHADOW_MAP && mainLight && mainLight->getNode()) { + csmLayers.update(&pplSceneData, &camera); + } + // const + if (mainLight->isShadowFixedArea() || csmLevel == scene::CSMLevel::LEVEL_1) { + frustum = &csmLayers.getSpecialLayer()->getValidFrustum(); + } else { + frustum = &csmLayers.getLayers()[level]->getValidFrustum(); + } } sceneCulling( skyboxModelToSkip, @@ -281,7 +299,6 @@ void SceneCulling::batchCulling(const pipeline::PipelineSceneData& pplSceneData) } namespace { - bool isBlend(const scene::Pass& pass) { bool bBlend = false; for (const auto& target : pass.getBlendState()->targets) { @@ -307,7 +324,6 @@ void addRenderObject( LayoutGraphData::vertex_descriptor phaseLayoutID, const bool bDrawOpaqueOrMask, const bool bDrawBlend, - const bool bDrawShadowCaster, const scene::Camera& camera, const scene::Model& model, NativeRenderQueue& queue) { @@ -328,15 +344,13 @@ void addRenderObject( // check scene flags const bool bBlend = isBlend(pass); const bool bOpaqueOrMask = !bBlend; - if (!bDrawShadowCaster) { - if (!bDrawBlend && bBlend) { - // skip transparent object - continue; - } - if (!bDrawOpaqueOrMask && bOpaqueOrMask) { - // skip opaque object - continue; - } + if (!bDrawBlend && bBlend) { + // skip transparent object + continue; + } + if (!bDrawOpaqueOrMask && bOpaqueOrMask) { + // skip opaque object + continue; } // add object to queue @@ -417,7 +431,7 @@ void SceneCulling::fillRenderQueues( // fill native queue for (const auto* const model : sourceModels) { addRenderObject( - phaseLayoutID, bDrawOpaqueOrMask, bDrawBlend, bDrawShadowCaster, + phaseLayoutID, bDrawOpaqueOrMask, bDrawBlend, *sceneData.camera, *model, nativeQueue); } @@ -429,6 +443,7 @@ void SceneCulling::fillRenderQueues( void SceneCulling::buildRenderQueues( const RenderGraph& rg, const LayoutGraphData& lg, const pipeline::PipelineSceneData& pplSceneData) { + pSceneData = &pplSceneData; collectCullingQueries(rg, lg); batchCulling(pplSceneData); fillRenderQueues(rg, pplSceneData); diff --git a/native/cocos/renderer/pipeline/custom/test/test.h b/native/cocos/renderer/pipeline/custom/test/test.h index ed8f44f5ee..f329ac731f 100644 --- a/native/cocos/renderer/pipeline/custom/test/test.h +++ b/native/cocos/renderer/pipeline/custom/test/test.h @@ -60,7 +60,6 @@ using framegraph::PassBarrierPair; using framegraph::ResourceBarrier; using RasterViews = PmrTransparentMap; using ComputeViews = PmrTransparentMap>; -using BarrierMap = FrameGraphDispatcher::BarrierMap; static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescInfo, const LayoutInfo &layoutInfo, RenderGraph &renderGraph, ResourceGraph &rescGraph, LayoutGraphData &layoutGraphData) { for (const auto &resc : rescInfo) { @@ -104,6 +103,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn auto addRasterNode = [&](const vector>> &subpasses, uint32_t count, uint32_t passID) { const ccstd::string name = "pass" + std::to_string(passID); const auto vertexID = add_vertex(renderGraph, RasterPassTag{}, name.c_str()); + renderGraph.sortedVertices.emplace_back(vertexID); auto &raster = get(RasterPassTag{}, vertexID, renderGraph); auto &subpassGraph = raster.subpassGraph; @@ -195,6 +195,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn const ccstd::string name = "pass" + std::to_string(passCount++); const auto vertexID = add_vertex(renderGraph, ComputeTag{}, name.c_str()); + renderGraph.sortedVertices.emplace_back(vertexID); assert(subpasses.back().size() == 2); // inputs and outputs auto &computePass = get(ComputeTag{}, vertexID, renderGraph); @@ -231,6 +232,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn const ccstd::string name = "pass" + std::to_string(passCount++); const auto vertexID = add_vertex(renderGraph, CopyTag{}, name.c_str()); + renderGraph.sortedVertices.emplace_back(vertexID); assert(subpasses.back().size() == 2); // inputs and outputs auto ©Pass = get(CopyTag{}, vertexID, renderGraph); const auto &inputsAndOutputs = subpasses.back(); @@ -260,302 +262,6 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn fgDispatcher.run(); */ } -static void fillBarriers(const ResourceGraph &resourceGraph, const BarrierPair &barrierInfo, framegraph::PassNodeBuilder &builder, PassBarrierPair &barriers) { - auto doFill = [&builder, &resourceGraph](const std::vector &edgeInfo, std::vector &edgeBarriers) { - for (const auto &resBarrier : edgeInfo) { - const auto &name = get(ResourceGraph::NameTag{}, resourceGraph, resBarrier.resourceID); - const auto &desc = get(ResourceGraph::DescTag{}, resourceGraph, resBarrier.resourceID); - auto type = desc.dimension == ResourceDimension::BUFFER ? cc::framegraph::ResourceType::BUFFER : cc::framegraph::ResourceType::TEXTURE; - framegraph::Range layerRange; - framegraph::Range mipRange; - if (type == framegraph::ResourceType::BUFFER) { - auto bufferRange = ccstd::get(resBarrier.beginStatus.range); - layerRange = {0, 0}; - mipRange = {bufferRange.offset, bufferRange.size}; - } else { - auto textureRange = ccstd::get(resBarrier.beginStatus.range); - layerRange = {textureRange.firstSlice, textureRange.numSlices}; - mipRange = {textureRange.mipLevel, textureRange.levelCount}; - } - - edgeBarriers.emplace_back(cc::framegraph::ResourceBarrier{ - type, - resBarrier.type, - builder.readFromBlackboard(framegraph::FrameGraph::stringToHandle(name.c_str())), - {resBarrier.beginStatus.passType, - resBarrier.beginStatus.visibility, - resBarrier.beginStatus.access}, - {resBarrier.endStatus.passType, - resBarrier.endStatus.visibility, - resBarrier.endStatus.access}, - layerRange, - mipRange, - }); - } - }; - - doFill(barrierInfo.frontBarriers, barriers.frontBarriers); - doFill(barrierInfo.rearBarriers, barriers.rearBarriers); -} - -struct TestRenderData { - ccstd::vector> outputTexes; -}; - -struct FrameGraphPassInfo { - framegraph::FrameGraph &frameGraph; - const RenderGraph &renderGraph; - const ResourceGraph &resourceGraph; - const RasterViews &rasterViews; - const ComputeViews &computeViews; - const BarrierMap &barrierMap; - uint32_t passID{0}; - bool isSubpass{false}; - bool subpassEnd{false}; -}; - -static void addPassToFrameGraph(const FrameGraphPassInfo &info) { - const auto &rasterViews = info.rasterViews; - const auto &passID = info.passID; - const auto &barrierMap = info.barrierMap; - const auto &renderGraph = info.renderGraph; - const auto &resourceGraph = info.resourceGraph; - auto &frameGraph = info.frameGraph; - bool isSupass = info.isSubpass; - bool subpassEnd = info.subpassEnd; - - auto forwardSetup = [&](framegraph::PassNodeBuilder &builder, TestRenderData &data) { - if (isSupass) { - builder.subpass(subpassEnd); - } - - auto goThroughRasterViews = [&](const RasterViews &views) { - for (const auto &view : views) { - const auto handle = framegraph::FrameGraph::stringToHandle(view.second.slotName.c_str()); - auto typedHandle = builder.readFromBlackboard(handle); - data.outputTexes.emplace_back(); - auto &lastTex = data.outputTexes.back(); - framegraph::Texture::Descriptor colorTexInfo; - colorTexInfo.format = gfx::Format::RGBA8; - - // if (rasterView.second.accessType == AccessType::READ) { - colorTexInfo.usage = gfx::TextureUsage::INPUT_ATTACHMENT | gfx::TextureUsage::COLOR_ATTACHMENT; - //} - lastTex.first = view.second.accessType; - lastTex.second = static_cast(typedHandle); - - if (framegraph::Handle::IndexType(typedHandle) == framegraph::Handle::UNINITIALIZED) { - colorTexInfo.width = 960; - colorTexInfo.height = 640; - - lastTex.second = builder.create(handle, colorTexInfo); - } - - framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - colorAttachmentInfo.usage = view.second.attachmentType == AttachmentType::RENDER_TARGET ? framegraph::RenderTargetAttachment::Usage::COLOR : framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL; - colorAttachmentInfo.clearColor = view.second.clearColor; - colorAttachmentInfo.loadOp = view.second.loadOp; - if (view.second.accessType == AccessType::WRITE) { - lastTex.second = builder.write(lastTex.second, colorAttachmentInfo); - builder.writeToBlackboard(handle, lastTex.second); - colorAttachmentInfo.beginAccesses = colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::COLOR_ATTACHMENT_WRITE; - } else { - colorAttachmentInfo.beginAccesses = colorAttachmentInfo.endAccesses = gfx::AccessFlagBit::COLOR_ATTACHMENT_READ; - auto res = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(handle))); - builder.writeToBlackboard(handle, res); - } - } - }; - - auto goThroughComputeViews = [&](const ComputeViews &views) { - for (const auto &pair : views) { - for (const auto &view : pair.second) { - const auto handle = framegraph::FrameGraph::stringToHandle(view.name.c_str()); - auto typedHandle = builder.readFromBlackboard(handle); - data.outputTexes.emplace_back(); - auto &lastTex = data.outputTexes.back(); - framegraph::Texture::Descriptor colorTexInfo; - colorTexInfo.format = gfx::Format::RGBA8; - - // if (rasterView.second.accessType == AccessType::READ) { - colorTexInfo.usage = gfx::TextureUsage::INPUT_ATTACHMENT | gfx::TextureUsage::COLOR_ATTACHMENT; - //} - lastTex.first = view.accessType; - lastTex.second = static_cast(typedHandle); - - if (framegraph::Handle::IndexType(typedHandle) == framegraph::Handle::UNINITIALIZED) { - colorTexInfo.width = 960; - colorTexInfo.height = 640; - - lastTex.second = builder.create(handle, colorTexInfo); - } - - framegraph::RenderTargetAttachment::Descriptor colorAttachmentInfo; - - if (view.accessType == AccessType::WRITE) { - lastTex.second = builder.write(lastTex.second); - builder.writeToBlackboard(handle, lastTex.second); - } else { - auto res = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(handle))); - builder.writeToBlackboard(handle, res); - } - } - } - }; - - goThroughRasterViews(info.rasterViews); - goThroughComputeViews(info.computeViews); - - builder.setViewport({0U, 640U, 0U, 960U, 0.0F, 1.0F}, {0U, 0U, 960U, 640U}); - - if (barrierMap.find(passID + 1) == barrierMap.end()) { - return; - } - const auto &barrier = barrierMap.at(passID + 1); - PassBarrierPair barrierPairs; - fillBarriers(resourceGraph, barrier.blockBarrier, builder, barrierPairs); - builder.setBarrier(barrierPairs); - }; - - auto forwardExec = [](const TestRenderData &data, - const framegraph::DevicePassResourceTable &table) { - /*for(const auto& pair: data.outputTexes) { - if(pair.first == AccessType::WRITE) { - table.getWrite(pair.second); - } - if(pair.first == AccessType::READ) { - table.getRead(pair.second); - } - if(pair.first == AccessType::READ_WRITE) { - table.getRead(pair.second); - table.getWrite(pair.second); - } - }*/ - }; - - auto passHandle = framegraph::FrameGraph::stringToHandle(get(RenderGraph::NameTag{}, renderGraph, passID).c_str()); - - string presentHandle; - - for (const auto &view : rasterViews) { - // write or read_write - if (view.second.accessType != AccessType::READ) { - presentHandle = view.first; - break; - } - } - - frameGraph.addPass(static_cast(ForwardInsertPoint::IP_FORWARD), passHandle, forwardSetup, forwardExec); -} - -static void runTestGraph(const RenderGraph &renderGraph, const ResourceGraph &resourceGraph, const LayoutGraphData &layoutGraphData, const FrameGraphDispatcher &fgDispatcher) { - const auto &barriers = fgDispatcher.getBarriers(); - - framegraph::FrameGraph framegraph; - - auto *device = gfx::Device::getInstance(); - if (!device) { - device = gfx::DeviceManager::create(); - } - - for (const auto passID : makeRange(vertices(renderGraph))) { - visitObject( - passID, renderGraph, - [&](const RasterPass &pass) { - // TestRenderData tmpData; - const auto &subpasses = get(SubpassGraph::SubpassTag{}, pass.subpassGraph); - uint32_t count = 0; - for (const auto &subpass : *subpasses.container) { - FrameGraphPassInfo info = { - framegraph, - renderGraph, - resourceGraph, - subpass.rasterViews, - subpass.computeViews, - fgDispatcher.getBarriers(), - passID, - true, - count < subpasses.container->size() - 1}; - addPassToFrameGraph(info); - ++count; - }; - if ((*subpasses.container).empty()) { - FrameGraphPassInfo info = { - framegraph, - renderGraph, - resourceGraph, - pass.rasterViews, - pass.computeViews, - fgDispatcher.getBarriers(), - passID, - false, - false}; - addPassToFrameGraph(info); - ++count; - } - }, - [&](const ComputePass &pass) { - // TestRenderData tmpData; - FrameGraphPassInfo info = { - framegraph, - renderGraph, - resourceGraph, - {}, - pass.computeViews, - fgDispatcher.getBarriers(), - passID, - false, - false}; - addPassToFrameGraph(info); - }, - [&](const CopyPass &pass) { - auto forwardSetup = [&](framegraph::PassNodeBuilder &builder, TestRenderData &data) { - for (const auto &pair : pass.copyPairs) { - for (size_t i = 0; i < 2; ++i) { - bool write = (i % 2 == 0); - const auto handle = framegraph::FrameGraph::stringToHandle(write ? pair.target.c_str() : pair.source.c_str()); - auto typedHandle = builder.readFromBlackboard(handle); - data.outputTexes.emplace_back(); - auto &lastTex = data.outputTexes.back(); - framegraph::Texture::Descriptor colorTexInfo; - colorTexInfo.format = gfx::Format::RGBA8; - colorTexInfo.usage = write ? gfx::TextureUsage::TRANSFER_DST : gfx::TextureUsage::TRANSFER_SRC; - - lastTex.second = static_cast(typedHandle); - - if (framegraph::Handle::IndexType(typedHandle) == framegraph::Handle::UNINITIALIZED) { - colorTexInfo.width = 960; - colorTexInfo.height = 640; - - lastTex.second = builder.create(handle, colorTexInfo); - } - - if (write) { - lastTex.second = builder.write(lastTex.second); - builder.writeToBlackboard(handle, lastTex.second); - } else { - auto res = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(handle))); - builder.writeToBlackboard(handle, res); - } - } - } - }; - - auto forwardExec = [](const TestRenderData &data, - const framegraph::DevicePassResourceTable &table) { - }; - - auto passHandle = framegraph::FrameGraph::stringToHandle(get(RenderGraph::NameTag{}, renderGraph, passID).c_str()); - framegraph.addPass(static_cast(ForwardInsertPoint::IP_FORWARD), passHandle, forwardSetup, forwardExec); - }, - [&](const RaytracePass &pass) {}, - [&](const auto & /*pass*/) {}); - } - framegraph.compile(); - framegraph.execute(); - framegraph.reset(); -} - #define TEST_CASE_DEFINE \ using namespace cc::render; \ using cc::gfx::AccessFlagBit; \ diff --git a/native/tests/unit-test/src/complicated_barrier_case.cpp b/native/tests/unit-test/src/complicated_barrier_case.cpp index 3fdb5ae8a4..a837a4867a 100644 --- a/native/tests/unit-test/src/complicated_barrier_case.cpp +++ b/native/tests/unit-test/src/complicated_barrier_case.cpp @@ -46,202 +46,67 @@ TEST(complicatedBarrierTest, test12) { }); }; - const auto& barrierMap = fgDispatcher.getBarriers(); + const auto& barrierMap = fgDispatcher.resourceAccessGraph.barrier; const auto& rag = fgDispatcher.resourceAccessGraph; - ExpectEq(rag._vertices.size() == 17, true); + ExpectEq(rag._vertices.size() == 23, true); // head const auto& head = barrierMap.at(0); - ExpectEq(head.blockBarrier.frontBarriers.empty(), true); - ExpectEq(head.blockBarrier.rearBarriers.empty(), true); - ExpectEq(head.subpassBarriers.empty(), true); + ExpectEq(head.frontBarriers.empty(), true); + ExpectEq(head.rearBarriers.empty(), true); // 1st node const auto& node1 = barrierMap.at(1); // block barrier: replace by rnderpass info, same below //ExpectEq(node1.blockBarrier.frontBarriers.size() == 2, true); //ExpectEq(node1.blockBarrier.rearBarriers.size() == 1, true); - ExpectEq(node1.subpassBarriers.empty(), false); - - //ExpectEq(node1.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].resourceID == 1, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].beginStatus.vertID == 1, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].endStatus.vertID == 1, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].endStatus.access == MemoryAccessBit::READ_ONLY, true); - - //subpass barrier: like normal pass - const auto& node1subpass = node1.subpassBarriers; - ExpectEq(node1subpass[0].frontBarriers.empty(), false); - ExpectEq(node1subpass[0].rearBarriers.size() == 1, true); - - // undefined external depends - const auto& node1subpassres0 = node1subpass[0].rearBarriers[0]; - ExpectEq(node1subpassres0.type == cc::gfx::BarrierType::FULL, true); - ExpectEq(node1subpassres0.resourceID == 0, true); - // vertid in subpass:subpass index, same below - ExpectEq(node1subpassres0.beginStatus.vertID == 0, true); - ExpectEq(node1subpassres0.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(node1subpassres0.beginStatus.passType == PassType::RASTER, true); - ExpectEq(node1subpassres0.endStatus.vertID == 1, true); - ; - ExpectEq(node1subpassres0.endStatus.access == MemoryAccessBit::READ_ONLY, true); - ExpectEq(node1subpassres0.endStatus.passType == PassType::RASTER, true); - - ExpectEq(node1subpass[1].frontBarriers.size() == 1, true); - const auto& node1subpassres1 = node1subpass[1].rearBarriers[0]; - ExpectEq(node1subpassres1.type == cc::gfx::BarrierType::FULL, true); - ExpectEq(node1subpassres1.resourceID == 1, true); - ExpectEq(node1subpassres1.beginStatus.vertID == 1, true); - ExpectEq(node1subpassres1.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(node1subpassres1.beginStatus.passType == PassType::RASTER, true); - ExpectEq(node1subpassres1.endStatus.vertID == 1, true); - ; - ExpectEq(node1subpassres1.endStatus.access == MemoryAccessBit::READ_ONLY, true); - ExpectEq(node1subpassres1.endStatus.passType == PassType::RASTER, true); - - //node2 - const auto& node2 = barrierMap.at(2); - //ExpectEq(node2.blockBarrier.frontBarriers.size() == 2, true); - //ExpectEq(node2.blockBarrier.rearBarriers.size() == 1, true); - ExpectEq(node2.subpassBarriers.size() == 2, true); - - //const auto& node2blockRear = node2.blockBarrier.rearBarriers; - //auto iter3in2 = findBarrierByResID(node2blockRear, 3); - //const auto& res3in2 = (*iter3in2); - //ExpectEq(res3in2.resourceID == 3, true); - //ExpectEq(res3in2.type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(res3in2.beginStatus.vertID == 2, true); - //ExpectEq(res3in2.beginStatus.passType == PassType::RASTER, true); - //ExpectEq(res3in2.endStatus.vertID == 2, true); - //ExpectEq(res3in2.endStatus.passType == PassType::RASTER, true); - - const auto& node2subpass = node2.subpassBarriers; - ExpectEq(node2subpass.empty(), false); - // subpass dependency instead of extra barrier - ExpectEq(node2subpass[0].frontBarriers.size() == 1, true); - ExpectEq(node2subpass[0].rearBarriers.empty(), false); - - const auto& node2subpassRes2 = node2subpass[0].rearBarriers[0]; - ExpectEq(node2subpassRes2.type == cc::gfx::BarrierType::FULL, true); - ExpectEq(node2subpassRes2.resourceID == 2, true); - ExpectEq(node2subpassRes2.beginStatus.vertID == 0, true); - ExpectEq(node2subpassRes2.beginStatus.passType == PassType::RASTER, true); - ExpectEq(node2subpassRes2.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(node2subpassRes2.endStatus.vertID == 1, true); - ExpectEq(node2subpassRes2.endStatus.access == MemoryAccessBit::READ_ONLY, true); //node3 // renderpass info layout instead - const auto& node3 = barrierMap.at(3); - ExpectEq(node3.blockBarrier.frontBarriers.empty(), true); - ExpectEq(node3.blockBarrier.rearBarriers.empty(), true); + const auto& node3 = barrierMap.at(7); + ExpectEq(node3.frontBarriers.empty(), true); + ExpectEq(node3.rearBarriers.empty(), true); - // subpass barrier size is the same as renderpass subpassinfo, though maybe empty. - ExpectEq(node3.subpassBarriers.size() == 1, true); - ExpectEq(node3.subpassBarriers.front().frontBarriers.empty(), true); - ExpectEq(node3.subpassBarriers.front().rearBarriers.empty(), true); + const auto& node11 = barrierMap.at(11); + ExpectEq(node11.frontBarriers.size() == 1, true); + ExpectEq(node11.rearBarriers.size() == 1, true); - //node4 - const auto& node4 = barrierMap.at(4); - //ExpectEq(node4.blockBarrier.frontBarriers.size() == 2, true); - //ExpectEq(node4.blockBarrier.rearBarriers.size() == 1, true); - ExpectEq(node4.subpassBarriers.empty(), false); + auto iter7in11 = findBarrierByResID(node11.rearBarriers, 7); + const auto& res7in11 = (*iter7in11); + ExpectEq(res7in11.type == cc::gfx::BarrierType::FULL, true); + ExpectEq(res7in11.resourceID == 7, true); + ExpectEq(res7in11.beginStatus.accessFlag == AccessFlagBit::TRANSFER_WRITE, true); + ExpectEq(res7in11.endStatus.accessFlag == AccessFlagBit::TRANSFER_READ, true); - //const auto& node4block = node4.blockBarrier; - //auto iter5in4 = findBarrierByResID(node4block.rearBarriers, 5); - //ExpectEq(iter5in4 == node4block.rearBarriers.end(), true); - - //auto iter6in4 = findBarrierByResID(node4block.rearBarriers, 6); - //ExpectEq(iter6in4 != node4block.rearBarriers.end(), true); - //ExpectEq((*iter6in4).type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq((*iter6in4).resourceID == 6, true); - //ExpectEq((*iter6in4).beginStatus.vertID == 4, true); - //ExpectEq((*iter6in4).endStatus.vertID == 14, true); - - const auto& node4subpass0 = node4.subpassBarriers[0]; - // subpass undefined external depends - ExpectEq(node4subpass0.frontBarriers.empty(), false); - ExpectEq(node4subpass0.rearBarriers.size() == 1, true); - ExpectEq(node4subpass0.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - ExpectEq(node4subpass0.rearBarriers[0].resourceID == 5, true); - ExpectEq(node4subpass0.rearBarriers[0].beginStatus.vertID == 0, true); - ExpectEq(node4subpass0.rearBarriers[0].beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(node4subpass0.rearBarriers[0].endStatus.vertID == 1, true); - ExpectEq(node4subpass0.rearBarriers[0].endStatus.access == MemoryAccessBit::READ_ONLY, true); - - const auto& node4subpass1 = node4.subpassBarriers[1]; - ExpectEq(node4subpass1.frontBarriers.empty(), false); - ExpectEq(node4subpass1.rearBarriers.size() == 1, true); - ExpectEq(node4subpass1.rearBarriers[0].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - ExpectEq(node4subpass1.rearBarriers[0].resourceID == 6, true); - // external subpass depends - ExpectEq(node4subpass1.rearBarriers[0].beginStatus.vertID == 0xFFFFFFFF, true); - ExpectEq(node4subpass1.rearBarriers[0].beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - // external subpass depends - ExpectEq(node4subpass1.rearBarriers[0].endStatus.vertID == 0xFFFFFFFF, true); - ExpectEq(node4subpass1.rearBarriers[0].endStatus.access == MemoryAccessBit::READ_ONLY, true); - - const auto& node5 = barrierMap.at(5); - ExpectEq(node5.blockBarrier.frontBarriers.size() == 1, true); - ExpectEq(node5.blockBarrier.rearBarriers.size() == 1, true); - // not raster pass - ExpectEq(node5.subpassBarriers.empty(), true); - - auto iter7in5 = findBarrierByResID(node5.blockBarrier.rearBarriers, 7); - const auto& res7in5 = (*iter7in5); - ExpectEq(res7in5.type == cc::gfx::BarrierType::FULL, true); - ExpectEq(res7in5.resourceID == 7, true); - ExpectEq(res7in5.beginStatus.vertID == 5, true); - ExpectEq(res7in5.endStatus.vertID == 5, true); - ExpectEq(res7in5.beginStatus.passType == PassType::COPY, true); - ExpectEq(res7in5.endStatus.passType == PassType::COPY, true); - ExpectEq(res7in5.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(res7in5.endStatus.access == MemoryAccessBit::READ_ONLY, true); - - const auto& node6 = barrierMap.at(6); - ExpectEq(node6.blockBarrier.frontBarriers.size() == 1, true); + const auto& node12 = barrierMap.at(12); + ExpectEq(node12.frontBarriers.size() == 1, true); // resource later used by raster pass, so that layout can be transferred automatically. - ExpectEq(node6.blockBarrier.rearBarriers.empty(), true); - // not a raster pass - ExpectEq(node6.subpassBarriers.empty(), true); + ExpectEq(node12.rearBarriers.empty(), true); // node7 - const auto& node7 = barrierMap.at(7); + const auto& node13 = barrierMap.at(13); // undefined layout already in initial layout - ExpectEq(node7.blockBarrier.frontBarriers.empty(), true); - ExpectEq(node7.blockBarrier.rearBarriers.empty(), true); - ExpectEq(node7.subpassBarriers.empty(), false); - - ExpectEq(node7.blockBarrier.rearBarriers.size(), 0); - - //node8: almost the same as node7 - //node9: almost the same as node8 - //node10: ditto - //node11: ditto - //node12: ditto + ExpectEq(node13.frontBarriers.empty(), true); + ExpectEq(node13.rearBarriers.empty(), true); //node13 - const auto& node13 = barrierMap.at(13); - ExpectEq(node13.blockBarrier.frontBarriers.size(), 0); - ExpectEq(node13.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node13.subpassBarriers.empty(), false); + const auto& node19 = barrierMap.at(19); + ExpectEq(node19.frontBarriers.size(), 0); + ExpectEq(node19.rearBarriers.size(), 0); //node14: almost the same as 13 //node15: ditto - const auto& node15 = barrierMap.at(15); - const auto& theone = node15.blockBarrier.rearBarriers.front(); + const auto& node21 = barrierMap.at(21); + const auto& theone = node21.rearBarriers.front(); ExpectEq(theone.resourceID == 22, true); ExpectEq(theone.type == cc::gfx::BarrierType::FULL, true); - ExpectEq(theone.endStatus.vertID == 0xFFFFFFFF, true); + ExpectEq(theone.endStatus.accessFlag == AccessFlagBit::PRESENT, true); //node16 const auto& node16 = barrierMap.at(16); - ExpectEq(node16.blockBarrier.frontBarriers.empty(), true); - ExpectEq(node16.blockBarrier.rearBarriers.empty(), true); - // not raster pass - ExpectEq(node16.subpassBarriers.empty(), true); + ExpectEq(node16.frontBarriers.empty(), true); + ExpectEq(node16.rearBarriers.empty(), true); //runTestGraph(renderGraph, rescGraph, layoutGraphData, fgDispatcher); } diff --git a/native/tests/unit-test/src/simple_barrier_test.cpp b/native/tests/unit-test/src/simple_barrier_test.cpp index d6c7dc7b5f..108418e7ce 100644 --- a/native/tests/unit-test/src/simple_barrier_test.cpp +++ b/native/tests/unit-test/src/simple_barrier_test.cpp @@ -40,44 +40,22 @@ TEST(barrierTest, test10) { FrameGraphDispatcher fgDispatcher(rescGraph, renderGraph, layoutGraphData, resource, resource); fgDispatcher.run(); - const auto& barrierMap = fgDispatcher.getBarriers(); + const auto& barrierMap = fgDispatcher.resourceAccessGraph.barrier; const auto& rag = fgDispatcher.resourceAccessGraph; - ExpectEq(rag._vertices.size() == 4, true); + ExpectEq(rag._vertices.size() == 6, true); // head const auto& head = barrierMap.at(0); - ExpectEq(head.blockBarrier.frontBarriers.empty(), true); - ExpectEq(head.blockBarrier.rearBarriers.empty(), true); - - // 1st node - const auto& node1 = barrierMap.at(1); - //ExpectEq(node1.blockBarrier.frontBarriers.size() == 4, true); - //ExpectEq(node1.blockBarrier.rearBarriers.size() == 1, true); - - // undefined external - ExpectEq(node1.subpassBarriers[0].frontBarriers.size() == 3, true); - ExpectEq(node1.subpassBarriers[0].rearBarriers.size() == 3, true); - - // undefined external - ExpectEq(node1.subpassBarriers[1].frontBarriers.size() == 1, true); - ExpectEq(node1.subpassBarriers[1].rearBarriers.size() == 1, true); - - //const auto& barrier = node1.blockBarrier.rearBarriers[0]; - //ExpectEq(barrier.type == BarrierType::FULL, true); - //ExpectEq(barrier.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ////resID 3 - //ExpectEq(barrier.beginStatus.visibility == std::get<2>(layoutInfo[0][3]), true); + ExpectEq(head.frontBarriers.empty(), true); + ExpectEq(head.rearBarriers.empty(), true); //// 2nd node - const auto& node2 = barrierMap.at(2); - ExpectEq(node2.blockBarrier.frontBarriers.size(), 0); - ExpectEq(node2.blockBarrier.rearBarriers.size() == 1, true); + const auto& node4 = barrierMap.at(4); + ExpectEq(node4.frontBarriers.size(), 0); + ExpectEq(node4.rearBarriers.size() == 1, true); - const auto& node2RearBarrier0 = node2.blockBarrier.rearBarriers.back(); - ExpectEq(node2RearBarrier0.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - ExpectEq(node2RearBarrier0.beginStatus.visibility == ShaderStageFlagBit::FRAGMENT, true); - ExpectEq(node2RearBarrier0.endStatus.accessFlag == AccessFlagBit::PRESENT, true); - //endstatus: whatever it was, it's COLOR_ATTACHMENT_OPTIMAL + const auto& node4RearBarrier0 = node4.rearBarriers.back(); + ExpectEq(node4RearBarrier0.endStatus.accessFlag == AccessFlagBit::PRESENT, true); //runTestGraph(renderGraph, rescGraph, layoutGraphData, fgDispatcher); } diff --git a/native/tests/unit-test/src/simple_closed_barrier_test.cpp b/native/tests/unit-test/src/simple_closed_barrier_test.cpp index 644132e90f..095cc34550 100644 --- a/native/tests/unit-test/src/simple_closed_barrier_test.cpp +++ b/native/tests/unit-test/src/simple_closed_barrier_test.cpp @@ -40,148 +40,29 @@ TEST(simpleClosedBarrierTest, test11) { FrameGraphDispatcher fgDispatcher(rescGraph, renderGraph, layoutGraphData, resource, resource); fgDispatcher.run(); - const auto& barrierMap = fgDispatcher.getBarriers(); + const auto& barrierMap = fgDispatcher.resourceAccessGraph.barrier; const auto& rag = fgDispatcher.resourceAccessGraph; ExpectEq(rag._vertices.size() == 10, true); // head const auto& head = barrierMap.at(0); - ExpectEq(head.blockBarrier.frontBarriers.empty(), true); - ExpectEq(head.blockBarrier.rearBarriers.empty(), true); - ExpectEq(head.subpassBarriers.empty(), true); + ExpectEq(head.frontBarriers.empty(), true); + ExpectEq(head.rearBarriers.empty(), true); // 1st node const auto& node1 = barrierMap.at(1); - ExpectEq(node1.blockBarrier.frontBarriers.size(), 0); - ExpectEq(node1.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node1.subpassBarriers.size() == 1, true); - ExpectEq(node1.subpassBarriers.front().frontBarriers.empty(), true); - ExpectEq(node1.subpassBarriers.front().rearBarriers.empty(), true); - - // transitioned by renderpass info - //ExpectEq(node1.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node1.blockBarrier.rearBarriers[0].endStatus.vertID == 1, true); - //ExpectEq(node1.blockBarrier.rearBarriers[1].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq(node1.blockBarrier.rearBarriers[1].endStatus.vertID == 3, true); + ExpectEq(node1.frontBarriers.size(), 0); + ExpectEq(node1.rearBarriers.size(), 0); const auto& node2 = barrierMap.at(2); - ExpectEq(node2.blockBarrier.frontBarriers.size(), 0); - ExpectEq(node2.blockBarrier.rearBarriers.size(), 0); - ExpectEq(node2.subpassBarriers.size() == 1, true); - ExpectEq(node2.subpassBarriers.front().frontBarriers.empty(), true); - ExpectEq(node2.subpassBarriers.front().rearBarriers.empty(), true); - - // ditto - //// res3 - //ExpectEq(node2.blockBarrier.rearBarriers[1].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq(node2.blockBarrier.rearBarriers[1].beginStatus.vertID == 2, true); - //ExpectEq(node2.blockBarrier.rearBarriers[1].endStatus.vertID == 5, true); - //// res2 - //ExpectEq(node2.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq(node2.blockBarrier.rearBarriers[0].beginStatus.vertID == 2, true); - //ExpectEq(node2.blockBarrier.rearBarriers[0].endStatus.vertID == 4, true); - - //const auto& node3 = barrierMap.at(3); - //ExpectEq(node3.blockBarrier.frontBarriers.size() == 3, true); - //ExpectEq(node3.blockBarrier.rearBarriers.size() == 2, true); - //ExpectEq(node3.subpassBarriers.empty(), true); - - //const auto& res1Index = std::find_if(node3.blockBarrier.frontBarriers.begin(), node3.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 1; }); - //ExpectEq(res1Index != node3.blockBarrier.frontBarriers.end(), true); - //ExpectEq(res1Index->type == cc::gfx::BarrierType::SPLIT_END, true); - //ExpectEq(res1Index->beginStatus.vertID == 1, true); - //ExpectEq(res1Index->endStatus.vertID == 3, true); - //// res 5 - //ExpectEq(node3.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node3.blockBarrier.rearBarriers[0].beginStatus.vertID == 3, true); - //ExpectEq(node3.blockBarrier.rearBarriers[0].endStatus.vertID == 3, true); - //// res 4 - //ExpectEq(node3.blockBarrier.rearBarriers[1].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq(node3.blockBarrier.rearBarriers[1].beginStatus.vertID == 3, true); - //ExpectEq(node3.blockBarrier.rearBarriers[1].endStatus.vertID == 5, true); - - //const auto& node4 = barrierMap.at(4); - //ExpectEq(node4.blockBarrier.frontBarriers.size() == 2, true); - //ExpectEq(node4.blockBarrier.rearBarriers.size() == 1, true); - //ExpectEq(node4.subpassBarriers.empty(), true); - - //const auto& res3Index = std::find_if(node4.blockBarrier.frontBarriers.begin(), node4.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 3; }); - //ExpectEq(res3Index != node4.blockBarrier.frontBarriers.end(), true); - //ExpectEq(res3Index->type == cc::gfx::BarrierType::SPLIT_END, true); - //ExpectEq(res3Index->beginStatus.vertID == 2, true); - //ExpectEq(res3Index->endStatus.vertID == 4, true); - - //ExpectEq(node4.blockBarrier.rearBarriers[0].resourceID == 6, true); - //ExpectEq(node4.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node4.blockBarrier.rearBarriers[0].beginStatus.vertID == 4, true); - //ExpectEq(node4.blockBarrier.rearBarriers[0].endStatus.vertID == 4, true); - - //const auto& node5 = barrierMap.at(5); - //ExpectEq(node5.blockBarrier.frontBarriers.size() == 3, true); - //ExpectEq(node5.blockBarrier.rearBarriers.size() == 1, true); - //ExpectEq(node5.subpassBarriers.empty(), true); - - //const auto& res2Index = std::find_if(node5.blockBarrier.frontBarriers.begin(), node5.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 2; }); - //ExpectEq(res2Index != node5.blockBarrier.frontBarriers.end(), true); - //ExpectEq(res2Index->type == cc::gfx::BarrierType::SPLIT_END, true); - //ExpectEq(res2Index->beginStatus.vertID == 2, true); - //ExpectEq(res2Index->endStatus.vertID == 5, true); - //const auto& res4Index = std::find_if(node5.blockBarrier.frontBarriers.begin(), node5.blockBarrier.frontBarriers.end(), [](const Barrier& barrier) { return barrier.resourceID == 4; }); - //ExpectEq(res4Index != node5.blockBarrier.frontBarriers.end(), true); - //ExpectEq(res4Index->type == cc::gfx::BarrierType::SPLIT_END, true); - //ExpectEq(res4Index->beginStatus.vertID == 3, true); - //ExpectEq(res4Index->endStatus.vertID == 5, true); - - //ExpectEq(node5.blockBarrier.rearBarriers[0].resourceID == 7, true); - //ExpectEq(node5.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::SPLIT_BEGIN, true); - //ExpectEq(node5.blockBarrier.rearBarriers[0].beginStatus.vertID == 5, true); - //ExpectEq(node5.blockBarrier.rearBarriers[0].endStatus.vertID == 8, true); - - //const auto& node6 = barrierMap.at(6); - //ExpectEq(node6.blockBarrier.frontBarriers.size() == 1, true); - //ExpectEq(node6.blockBarrier.rearBarriers.size() == 1, true); - //ExpectEq(node6.subpassBarriers.empty(), true); - - //ExpectEq(node6.blockBarrier.rearBarriers[0].resourceID == 8, true); - //ExpectEq(node6.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node6.blockBarrier.rearBarriers[0].beginStatus.vertID == 6, true); - //ExpectEq(node6.blockBarrier.rearBarriers[0].endStatus.vertID == 6, true); - - //const auto& node7 = barrierMap.at(7); - //ExpectEq(node7.subpassBarriers.empty(), true); - //ExpectEq(node7.blockBarrier.frontBarriers.size() == 1, true); - //ExpectEq(node7.blockBarrier.rearBarriers.size() == 1, true); - - //ExpectEq(node7.blockBarrier.rearBarriers[0].resourceID == 9, true); - //ExpectEq(node7.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node7.blockBarrier.rearBarriers[0].beginStatus.vertID == 7, true); - //ExpectEq(node7.blockBarrier.rearBarriers[0].endStatus.vertID == 7, true); - - //const auto& node8 = barrierMap.at(8); - //ExpectEq(node8.subpassBarriers.empty(), true); - //ExpectEq(node8.blockBarrier.frontBarriers.empty(), false); // size == 1 - //ExpectEq(node8.blockBarrier.rearBarriers.size() == 1, true); - - //ExpectEq(node8.blockBarrier.frontBarriers[1].resourceID == 7, true); - //ExpectEq(node8.blockBarrier.frontBarriers[1].type == cc::gfx::BarrierType::SPLIT_END, true); - //ExpectEq(node8.blockBarrier.frontBarriers[1].beginStatus.vertID == 5, true); - //ExpectEq(node8.blockBarrier.frontBarriers[1].endStatus.vertID == 8, true); - - //ExpectEq(node8.blockBarrier.rearBarriers[0].resourceID == 22, true); - //ExpectEq(node8.blockBarrier.rearBarriers[0].type == cc::gfx::BarrierType::FULL, true); - //ExpectEq(node8.blockBarrier.rearBarriers[0].beginStatus.vertID == 8, true); - //ExpectEq(node8.blockBarrier.rearBarriers[0].endStatus.vertID == 0xFFFFFFFF, true); + ExpectEq(node2.frontBarriers.size(), 0); + ExpectEq(node2.rearBarriers.size(), 0); // TODO: validate renderpassInfo instead const auto& node9 = barrierMap.at(9); - ExpectEq(node9.subpassBarriers.empty(), true); - ExpectEq(node9.blockBarrier.frontBarriers.empty(), true); - ExpectEq(node9.blockBarrier.rearBarriers.empty(), true); - // const auto& node2RearBarrier0 = node2.blockBarrier.rearBarriers.back(); - // ExpectEq(node2RearBarrier0.beginStatus.access == MemoryAccessBit::WRITE_ONLY, true); - // ExpectEq(node2RearBarrier0.beginStatus.visibility == ShaderStageFlagBit::VERTEX, true); - // ExpectEq(node2RearBarrier0.endStatus.access == MemoryAccessBit::READ_ONLY, true); + ExpectEq(node9.frontBarriers.empty(), true); + ExpectEq(node9.rearBarriers.empty(), true); //endstatus: whatever it was, it's COLOR_ATTACHMENT_OPTIMAL //runTestGraph(renderGraph, rescGraph, layoutGraphData, fgDispatcher);