From bed27fcccfce3ea39fb7dfc0838c5182149199e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=90=89=E6=9E=97?= <798080536@qq.com> Date: Wed, 13 Oct 2021 18:21:03 +0800 Subject: [PATCH] V3.4.0 occlusion query2 (#3975) * occlusion query Co-authored-by: lijilin --- native/CMakeLists.txt | 16 + native/cocos/base/memory/MemoryHook.cpp | 4 +- .../renderer/gfx-agent/CommandBufferAgent.cpp | 44 +++ .../renderer/gfx-agent/CommandBufferAgent.h | 6 + .../cocos/renderer/gfx-agent/DeviceAgent.cpp | 33 +- native/cocos/renderer/gfx-agent/DeviceAgent.h | 3 + .../renderer/gfx-agent/QueryPoolAgent.cpp | 76 +++++ .../cocos/renderer/gfx-agent/QueryPoolAgent.h | 47 +++ .../renderer/gfx-base/GFXCommandBuffer.h | 3 + .../cocos/renderer/gfx-base/GFXDef-common.h | 19 ++ native/cocos/renderer/gfx-base/GFXDevice.h | 12 + .../cocos/renderer/gfx-base/GFXQueryPool.cpp | 52 +++ native/cocos/renderer/gfx-base/GFXQueryPool.h | 72 ++++ .../renderer/gfx-empty/EmptyCommandBuffer.cpp | 9 + .../renderer/gfx-empty/EmptyCommandBuffer.h | 3 + .../cocos/renderer/gfx-empty/EmptyDevice.cpp | 12 + native/cocos/renderer/gfx-empty/EmptyDevice.h | 3 + .../renderer/gfx-empty/EmptyQueryPool.cpp | 38 +++ .../cocos/renderer/gfx-empty/EmptyQueryPool.h | 40 +++ .../gfx-gles-common/GLESCommandPool.h | 21 +- .../renderer/gfx-gles2/GLES2CommandBuffer.h | 3 + .../cocos/renderer/gfx-gles2/GLES2Device.cpp | 27 +- native/cocos/renderer/gfx-gles2/GLES2Device.h | 3 + .../renderer/gfx-gles2/GLES2QueryPool.cpp | 51 +++ .../cocos/renderer/gfx-gles2/GLES2QueryPool.h | 47 +++ .../renderer/gfx-gles3/GLES3CommandBuffer.cpp | 45 +++ .../renderer/gfx-gles3/GLES3CommandBuffer.h | 6 + .../renderer/gfx-gles3/GLES3Commands.cpp | 78 +++++ .../cocos/renderer/gfx-gles3/GLES3Commands.h | 32 ++ .../cocos/renderer/gfx-gles3/GLES3Device.cpp | 33 +- native/cocos/renderer/gfx-gles3/GLES3Device.h | 3 + .../renderer/gfx-gles3/GLES3GPUObjects.h | 15 + .../gfx-gles3/GLES3PrimaryCommandBuffer.cpp | 25 ++ .../gfx-gles3/GLES3PrimaryCommandBuffer.h | 6 + .../renderer/gfx-gles3/GLES3QueryPool.cpp | 61 ++++ .../cocos/renderer/gfx-gles3/GLES3QueryPool.h | 61 ++++ .../renderer/gfx-metal/MTLCommandBuffer.h | 94 +++--- .../renderer/gfx-metal/MTLCommandBuffer.mm | 308 +++++++++--------- native/cocos/renderer/gfx-metal/MTLDevice.h | 104 +++--- native/cocos/renderer/gfx-metal/MTLDevice.mm | 125 +++---- .../cocos/renderer/gfx-metal/MTLQueryPool.h | 46 +++ .../cocos/renderer/gfx-metal/MTLQueryPool.mm | 53 +++ .../gfx-validator/CommandBufferValidator.cpp | 28 ++ .../gfx-validator/CommandBufferValidator.h | 4 + .../gfx-validator/DeviceValidator.cpp | 29 ++ .../renderer/gfx-validator/DeviceValidator.h | 3 + .../gfx-validator/QueryPoolValidator.cpp | 67 ++++ .../gfx-validator/QueryPoolValidator.h | 51 +++ .../renderer/gfx-vulkan/VKCommandBuffer.cpp | 30 ++ .../renderer/gfx-vulkan/VKCommandBuffer.h | 3 + .../cocos/renderer/gfx-vulkan/VKCommands.cpp | 19 ++ native/cocos/renderer/gfx-vulkan/VKCommands.h | 3 +- native/cocos/renderer/gfx-vulkan/VKDevice.cpp | 45 +++ native/cocos/renderer/gfx-vulkan/VKDevice.h | 3 + .../cocos/renderer/gfx-vulkan/VKGPUObjects.h | 76 +++-- .../cocos/renderer/gfx-vulkan/VKQueryPool.cpp | 61 ++++ .../cocos/renderer/gfx-vulkan/VKQueryPool.h | 57 ++++ native/cocos/renderer/gfx-vulkan/VKUtils.cpp | 12 + native/cocos/renderer/gfx-vulkan/VKUtils.h | 1 + native/cocos/renderer/pipeline/Define.cpp | 19 ++ native/cocos/renderer/pipeline/Define.h | 19 +- .../pipeline/GlobalDescriptorSetManager.cpp | 2 + .../pipeline/RenderAdditiveLightQueue.cpp | 42 +-- .../pipeline/RenderAdditiveLightQueue.h | 5 +- .../renderer/pipeline/RenderPipeline.cpp | 34 +- .../cocos/renderer/pipeline/RenderPipeline.h | 10 + .../cocos/renderer/pipeline/RenderQueue.cpp | 55 +++- native/cocos/renderer/pipeline/RenderQueue.h | 11 +- .../pipeline/common/PostProcessStage.cpp | 9 +- .../pipeline/deferred/DeferredPipeline.cpp | 2 + .../pipeline/deferred/GbufferStage.cpp | 10 +- .../renderer/pipeline/deferred/GbufferStage.h | 5 +- .../pipeline/deferred/LightingStage.cpp | 12 +- .../pipeline/forward/ForwardPipeline.cpp | 13 + .../pipeline/forward/ForwardStage.cpp | 21 +- native/cocos/scene/AABB.cpp | 31 +- native/cocos/scene/AABB.h | 1 + native/cocos/scene/Define.h | 36 +- native/cocos/scene/Model.cpp | 17 +- native/cocos/scene/Model.h | 4 + native/cocos/scene/SubModel.cpp | 5 + native/cocos/scene/SubModel.h | 18 +- native/tools/tojs/gfx.ini | 5 +- 83 files changed, 2142 insertions(+), 475 deletions(-) create mode 100644 native/cocos/renderer/gfx-agent/QueryPoolAgent.cpp create mode 100644 native/cocos/renderer/gfx-agent/QueryPoolAgent.h create mode 100644 native/cocos/renderer/gfx-base/GFXQueryPool.cpp create mode 100644 native/cocos/renderer/gfx-base/GFXQueryPool.h create mode 100644 native/cocos/renderer/gfx-empty/EmptyQueryPool.cpp create mode 100644 native/cocos/renderer/gfx-empty/EmptyQueryPool.h create mode 100644 native/cocos/renderer/gfx-gles2/GLES2QueryPool.cpp create mode 100644 native/cocos/renderer/gfx-gles2/GLES2QueryPool.h create mode 100644 native/cocos/renderer/gfx-gles3/GLES3QueryPool.cpp create mode 100644 native/cocos/renderer/gfx-gles3/GLES3QueryPool.h create mode 100644 native/cocos/renderer/gfx-metal/MTLQueryPool.h create mode 100644 native/cocos/renderer/gfx-metal/MTLQueryPool.mm create mode 100644 native/cocos/renderer/gfx-validator/QueryPoolValidator.cpp create mode 100644 native/cocos/renderer/gfx-validator/QueryPoolValidator.h create mode 100644 native/cocos/renderer/gfx-vulkan/VKQueryPool.cpp create mode 100644 native/cocos/renderer/gfx-vulkan/VKQueryPool.h diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 336e3924e6..8ae0f857cd 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -676,6 +676,8 @@ cocos_source_files( cocos/renderer/gfx-base/GFXPipelineState.h cocos/renderer/gfx-base/GFXQueue.cpp cocos/renderer/gfx-base/GFXQueue.h + cocos/renderer/gfx-base/GFXQueryPool.cpp + cocos/renderer/gfx-base/GFXQueryPool.h cocos/renderer/gfx-base/GFXRenderPass.cpp cocos/renderer/gfx-base/GFXRenderPass.h cocos/renderer/gfx-base/GFXShader.cpp @@ -711,6 +713,8 @@ cocos_source_files( cocos/renderer/gfx-agent/PipelineStateAgent.cpp cocos/renderer/gfx-agent/QueueAgent.h cocos/renderer/gfx-agent/QueueAgent.cpp + cocos/renderer/gfx-agent/QueryPoolAgent.h + cocos/renderer/gfx-agent/QueryPoolAgent.cpp cocos/renderer/gfx-agent/RenderPassAgent.h cocos/renderer/gfx-agent/RenderPassAgent.cpp cocos/renderer/gfx-agent/SwapchainAgent.h @@ -740,6 +744,8 @@ cocos_source_files( cocos/renderer/gfx-validator/PipelineStateValidator.cpp cocos/renderer/gfx-validator/QueueValidator.h cocos/renderer/gfx-validator/QueueValidator.cpp + cocos/renderer/gfx-validator/QueryPoolValidator.h + cocos/renderer/gfx-validator/QueryPoolValidator.cpp cocos/renderer/gfx-validator/RenderPassValidator.h cocos/renderer/gfx-validator/RenderPassValidator.cpp cocos/renderer/gfx-validator/ShaderValidator.h @@ -771,6 +777,8 @@ cocos_source_files( cocos/renderer/gfx-empty/EmptyPipelineState.cpp cocos/renderer/gfx-empty/EmptyQueue.h cocos/renderer/gfx-empty/EmptyQueue.cpp + cocos/renderer/gfx-empty/EmptyQueryPool.h + cocos/renderer/gfx-empty/EmptyQueryPool.cpp cocos/renderer/gfx-empty/EmptyRenderPass.h cocos/renderer/gfx-empty/EmptyRenderPass.cpp cocos/renderer/gfx-empty/EmptyShader.h @@ -935,6 +943,8 @@ if(CC_USE_GLES2) cocos/renderer/gfx-gles2/GLES2PrimaryCommandBuffer.h cocos/renderer/gfx-gles2/GLES2Queue.cpp cocos/renderer/gfx-gles2/GLES2Queue.h + cocos/renderer/gfx-gles2/GLES2QueryPool.cpp + cocos/renderer/gfx-gles2/GLES2QueryPool.h cocos/renderer/gfx-gles2/GLES2RenderPass.cpp cocos/renderer/gfx-gles2/GLES2RenderPass.h cocos/renderer/gfx-gles2/GLES2Shader.cpp @@ -981,6 +991,8 @@ if(CC_USE_GLES3) cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h cocos/renderer/gfx-gles3/GLES3Queue.cpp cocos/renderer/gfx-gles3/GLES3Queue.h + cocos/renderer/gfx-gles3/GLES3QueryPool.cpp + cocos/renderer/gfx-gles3/GLES3QueryPool.h cocos/renderer/gfx-gles3/GLES3RenderPass.cpp cocos/renderer/gfx-gles3/GLES3RenderPass.h cocos/renderer/gfx-gles3/GLES3Shader.cpp @@ -1024,6 +1036,8 @@ if(CC_USE_METAL) cocos/renderer/gfx-metal/MTLDescriptorSet.mm cocos/renderer/gfx-metal/MTLQueue.h cocos/renderer/gfx-metal/MTLQueue.mm + cocos/renderer/gfx-metal/MTLQueryPool.h + cocos/renderer/gfx-metal/MTLQueryPool.mm cocos/renderer/gfx-metal/MTLRenderPass.h cocos/renderer/gfx-metal/MTLRenderPass.mm cocos/renderer/gfx-metal/MTLSampler.h @@ -1075,6 +1089,8 @@ if(CC_USE_VULKAN) cocos/renderer/gfx-vulkan/VKPipelineState.h cocos/renderer/gfx-vulkan/VKQueue.cpp cocos/renderer/gfx-vulkan/VKQueue.h + cocos/renderer/gfx-vulkan/VKQueryPool.cpp + cocos/renderer/gfx-vulkan/VKQueryPool.h cocos/renderer/gfx-vulkan/VKRenderPass.cpp cocos/renderer/gfx-vulkan/VKRenderPass.h cocos/renderer/gfx-vulkan/VKShader.cpp diff --git a/native/cocos/base/memory/MemoryHook.cpp b/native/cocos/base/memory/MemoryHook.cpp index 80f882186d..d95b2b5f28 100644 --- a/native/cocos/base/memory/MemoryHook.cpp +++ b/native/cocos/base/memory/MemoryHook.cpp @@ -259,7 +259,7 @@ void MemoryHook::registerAll() { malloc_logger = cc_malloc_logger; g_new_hooker = newHook; g_delete_hooker = deleteHook; - #elif CC_PLATFORM_WINDOWS + #elif CC_PLATFORM == CC_PLATFORM_WINDOWS MallocHook_AddNewHook(&newHook); MallocHook_AddDeleteHook(&deleteHook); #endif @@ -273,7 +273,7 @@ void MemoryHook::unRegisterAll() { malloc_logger = g_system_malloc_logger; g_new_hooker = nullptr; g_delete_hooker = nullptr; - #elif CC_PLATFORM_WINDOWS + #elif CC_PLATFORM == CC_PLATFORM_WINDOWS MallocHook_RemoveNewHook(&newHook); MallocHook_RemoveDeleteHook(&deleteHook); #endif diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp index 4184c4b0d4..f9a028b840 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp @@ -30,6 +30,7 @@ #include "FramebufferAgent.h" #include "InputAssemblerAgent.h" #include "PipelineStateAgent.h" +#include "QueryPoolAgent.h" #include "QueueAgent.h" #include "RenderPassAgent.h" #include "TextureAgent.h" @@ -98,6 +99,14 @@ void CommandBufferAgent::destroyMessageQueue() { DeviceAgent::getInstance()->_cmdBuffRefs.erase(this); } +void CommandBufferAgent::initAgent() { + initMessageQueue(); +} + +void CommandBufferAgent::destroyAgent() { + destroyMessageQueue(); +} + void CommandBufferAgent::doInit(const CommandBufferInfo &info) { initMessageQueue(); @@ -479,5 +488,40 @@ void CommandBufferAgent::pipelineBarrier(const GlobalBarrier *barrier, const Tex }); } +void CommandBufferAgent::beginQuery(QueryPool *queryPool, uint32_t id) { + QueryPool *actorQueryPool = static_cast(queryPool)->getActor(); + ENQUEUE_MESSAGE_3( + _messageQueue, CommandBufferBeginQuery, + actor, getActor(), + queryPool, actorQueryPool, + id, id, + { + actor->beginQuery(queryPool, id); + }); +} + +void CommandBufferAgent::endQuery(QueryPool *queryPool, uint32_t id) { + QueryPool *actorQueryPool = static_cast(queryPool)->getActor(); + ENQUEUE_MESSAGE_3( + _messageQueue, CommandBufferEndQuery, + actor, getActor(), + queryPool, actorQueryPool, + id, id, + { + actor->endQuery(queryPool, id); + }); +} + +void CommandBufferAgent::resetQuery(QueryPool *queryPool) { + QueryPool *actorQueryPool = static_cast(queryPool)->getActor(); + ENQUEUE_MESSAGE_2( + _messageQueue, CommandBufferResetQuery, + actor, getActor(), + queryPool, actorQueryPool, + { + actor->resetQuery(queryPool); + }); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.h b/native/cocos/renderer/gfx-agent/CommandBufferAgent.h index 3d89db89c8..ec82919146 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.h +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.h @@ -64,6 +64,9 @@ public: void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; + void beginQuery(QueryPool *queryPool, uint32_t id) override; + void endQuery(QueryPool *queryPool, uint32_t id) override; + void resetQuery(QueryPool *queryPool) override; uint32_t getNumDrawCalls() const override { return _actor->getNumDrawCalls(); } uint32_t getNumInstances() const override { return _actor->getNumInstances(); } @@ -74,6 +77,9 @@ public: protected: friend class DeviceAgent; + void initAgent(); + void destroyAgent(); + void doInit(const CommandBufferInfo &info) override; void doDestroy() override; diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp index 2228105f75..b72b142872 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp @@ -36,6 +36,7 @@ #include "InputAssemblerAgent.h" #include "PipelineLayoutAgent.h" #include "PipelineStateAgent.h" +#include "QueryPoolAgent.h" #include "QueueAgent.h" #include "RenderPassAgent.h" #include "ShaderAgent.h" @@ -71,6 +72,7 @@ bool DeviceAgent::doInit(const DeviceInfo &info) { _api = _actor->getGfxAPI(); _deviceName = _actor->getDeviceName(); _queue = CC_NEW(QueueAgent(_actor->getQueue())); + _queryPool = CC_NEW(QueryPoolAgent(_actor->getQueryPool())); _cmdBuff = CC_NEW(CommandBufferAgent(_actor->getCommandBuffer())); _renderer = _actor->getRenderer(); _vendor = _actor->getVendor(); @@ -82,7 +84,7 @@ bool DeviceAgent::doInit(const DeviceInfo &info) { _mainMessageQueue = _CC_NEW_T_ALIGN(MessageQueue, alignof(MessageQueue)); //NOLINT static_cast(_cmdBuff)->_queue = _queue; - static_cast(_cmdBuff)->initMessageQueue(); + static_cast(_cmdBuff)->initAgent(); setMultithreaded(true); @@ -98,11 +100,16 @@ void DeviceAgent::doDestroy() { }); if (_cmdBuff) { - static_cast(_cmdBuff)->destroyMessageQueue(); + static_cast(_cmdBuff)->destroyAgent(); static_cast(_cmdBuff)->_actor = nullptr; CC_DELETE(_cmdBuff); _cmdBuff = nullptr; } + if (_queryPool) { + static_cast(_queryPool)->_actor = nullptr; + CC_DELETE(_queryPool); + _queryPool = nullptr; + } if (_queue) { static_cast(_queue)->_actor = nullptr; CC_DELETE(_queue); @@ -194,6 +201,11 @@ Queue *DeviceAgent::createQueue() { return CC_NEW(QueueAgent(actor)); } +QueryPool *DeviceAgent::createQueryPool() { + QueryPool *actor = _actor->createQueryPool(); + return CC_NEW(QueryPoolAgent(actor)); +} + Swapchain *DeviceAgent::createSwapchain() { Swapchain *actor = _actor->createSwapchain(); return CC_NEW(SwapchainAgent(actor)); @@ -345,5 +357,22 @@ void DeviceAgent::flushCommands(CommandBuffer *const *cmdBuffs, uint32_t count) }); } +void DeviceAgent::getQueryPoolResults(QueryPool *queryPool) { + QueryPool *actorQueryPool = static_cast(queryPool)->getActor(); + + ENQUEUE_MESSAGE_2( + _mainMessageQueue, DeviceGetQueryPoolResults, + actor, getActor(), + queryPool, actorQueryPool, + { + actor->getQueryPoolResults(queryPool); + }); + + auto * actorQueryPoolAgent = static_cast(actorQueryPool); + auto * queryPoolAgent = static_cast(queryPool); + std::lock_guard lock(actorQueryPoolAgent->_mutex); + queryPoolAgent->_results = actorQueryPoolAgent->_results; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.h b/native/cocos/renderer/gfx-agent/DeviceAgent.h index 68b82739b2..fef1e12540 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.h +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.h @@ -56,6 +56,7 @@ public: using Device::createInputAssembler; using Device::createPipelineLayout; using Device::createPipelineState; + using Device::createQueryPool; using Device::createQueue; using Device::createRenderPass; using Device::createSampler; @@ -68,6 +69,7 @@ public: CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; Queue * createQueue() override; + QueryPool * createQueryPool() override; Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; @@ -87,6 +89,7 @@ public: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; void flushCommands(CommandBuffer *const *cmdBuffs, uint32_t count) override; + void getQueryPoolResults(QueryPool *queryPool) override; MemoryStatus &getMemoryStatus() override { return _actor->getMemoryStatus(); } uint32_t getNumDrawCalls() const override { return _actor->getNumDrawCalls(); } uint32_t getNumInstances() const override { return _actor->getNumInstances(); } diff --git a/native/cocos/renderer/gfx-agent/QueryPoolAgent.cpp b/native/cocos/renderer/gfx-agent/QueryPoolAgent.cpp new file mode 100644 index 0000000000..1299c7b4ed --- /dev/null +++ b/native/cocos/renderer/gfx-agent/QueryPoolAgent.cpp @@ -0,0 +1,76 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#include "base/CoreStd.h" +#include "base/job-system/JobSystem.h" +#include "base/threading/MessageQueue.h" + +#include "CommandBufferAgent.h" +#include "DeviceAgent.h" +#include "QueryPoolAgent.h" + +namespace cc { +namespace gfx { + +QueryPoolAgent::QueryPoolAgent(QueryPool *actor) +: Agent(actor) { + _typedID = actor->getTypedID(); + _type = actor->getType(); + _maxQueryObjects = actor->getMaxQueryObjects(); +} + +QueryPoolAgent::~QueryPoolAgent() { + ENQUEUE_MESSAGE_1( + DeviceAgent::getInstance()->getMessageQueue(), + QueryDestruct, + actor, _actor, + { + CC_SAFE_DELETE(actor); + }); +} + +void QueryPoolAgent::doInit(const QueryPoolInfo &info) { + ENQUEUE_MESSAGE_2( + DeviceAgent::getInstance()->getMessageQueue(), + QueryInit, + actor, getActor(), + info, info, + { + actor->initialize(info); + }); +} + +void QueryPoolAgent::doDestroy() { + ENQUEUE_MESSAGE_1( + DeviceAgent::getInstance()->getMessageQueue(), + QueryDestroy, + actor, getActor(), + { + actor->destroy(); + }); +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-agent/QueryPoolAgent.h b/native/cocos/renderer/gfx-agent/QueryPoolAgent.h new file mode 100644 index 0000000000..7efd6b63d2 --- /dev/null +++ b/native/cocos/renderer/gfx-agent/QueryPoolAgent.h @@ -0,0 +1,47 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#pragma once + +#include "base/Agent.h" +#include "gfx-base/GFXQueryPool.h" + +namespace cc { +namespace gfx { + +class CC_DLL QueryPoolAgent final : public Agent { +public: + explicit QueryPoolAgent(QueryPool *actor); + ~QueryPoolAgent() override; + +protected: + friend class DeviceAgent; + + void doInit(const QueryPoolInfo &info) override; + void doDestroy() override; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h index 34ae4eda98..e55840a682 100644 --- a/native/cocos/renderer/gfx-base/GFXCommandBuffer.h +++ b/native/cocos/renderer/gfx-base/GFXCommandBuffer.h @@ -64,6 +64,9 @@ public: virtual void execute(CommandBuffer *const *cmdBuffs, uint32_t count) = 0; virtual void dispatch(const DispatchInfo &info) = 0; virtual void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) = 0; + virtual void beginQuery(QueryPool *queryPool, uint32_t id) = 0; + virtual void endQuery(QueryPool *queryPool, uint32_t id) = 0; + virtual void resetQuery(QueryPool *queryPool) = 0; inline void begin(); inline void begin(RenderPass *renderPass); diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 4fbba1db8c..2c540b66c8 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -68,12 +68,14 @@ class PipelineState; class DescriptorSet; class CommandBuffer; class Queue; +class QueryPool; class Window; class Context; using TextureBarrierList = vector; using BufferDataList = vector; using CommandBufferList = vector; +using QueryPoolList = vector; constexpr uint32_t MAX_ATTACHMENTS = 4U; constexpr uint32_t INVALID_BINDING = ~0U; @@ -100,6 +102,7 @@ enum class ObjectType : uint32_t { INPUT_ASSEMBLER, COMMAND_BUFFER, QUEUE, + QUERY_POOL, GLOBAL_BARRIER, TEXTURE_BARRIER, BUFFER_BARRIER, @@ -738,6 +741,13 @@ enum class QueueType : uint32_t { }; CC_ENUM_CONVERSION_OPERATOR(QueueType); +enum class QueryType : uint32_t { + OCCLUSION, + PIPELINE_STATISTICS, + TIMESTAMP, +}; +CC_ENUM_CONVERSION_OPERATOR(QueryType); + enum class CommandBufferType : uint32_t { PRIMARY, SECONDARY, @@ -782,6 +792,8 @@ struct DeviceCaps { Size maxComputeWorkGroupSize; Size maxComputeWorkGroupCount; + bool supportQuery{false}; + float clipSpaceMinZ{-1.F}; float screenSpaceSignY{1.F}; float clipSpaceSignY{1.F}; @@ -1276,6 +1288,13 @@ struct QueueInfo { QueueType type{QueueType::GRAPHICS}; }; +constexpr uint32_t DEFAULT_MAX_QUERY_OBJECTS = 65536U; + +struct QueryPoolInfo { + QueryType type{QueryType::OCCLUSION}; + uint32_t maxQueryObjects{DEFAULT_MAX_QUERY_OBJECTS}; +}; + struct FormatInfo { const String name; const uint32_t size{0U}; diff --git a/native/cocos/renderer/gfx-base/GFXDevice.h b/native/cocos/renderer/gfx-base/GFXDevice.h index 8ac91631fb..cd04580ab5 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.h +++ b/native/cocos/renderer/gfx-base/GFXDevice.h @@ -35,6 +35,7 @@ #include "GFXObject.h" #include "GFXPipelineLayout.h" #include "GFXPipelineState.h" +#include "GFXQueryPool.h" #include "GFXQueue.h" #include "GFXRenderPass.h" #include "GFXShader.h" @@ -68,6 +69,7 @@ public: inline CommandBuffer * createCommandBuffer(const CommandBufferInfo &info); inline Queue * createQueue(const QueueInfo &info); + inline QueryPool * createQueryPool(const QueryPoolInfo &info); inline Swapchain * createSwapchain(const SwapchainInfo &info); inline Buffer * createBuffer(const BufferInfo &info); inline Buffer * createBuffer(const BufferViewInfo &info); @@ -88,12 +90,14 @@ public: virtual void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) = 0; virtual void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) = 0; + virtual void getQueryPoolResults(QueryPool *queryPool) = 0; inline void copyBuffersToTexture(const BufferDataList &buffers, Texture *dst, const BufferTextureCopyList ®ions); inline void flushCommands(const vector &cmdBuffs); inline void acquire(const vector &swapchains); inline Queue * getQueue() const { return _queue; } + inline QueryPool * getQueryPool() const { return _queryPool; } inline CommandBuffer * getCommandBuffer() const { return _cmdBuff; } inline const DeviceCaps &getCapabilities() const { return _caps; } inline API getGfxAPI() const { return _api; } @@ -121,6 +125,7 @@ protected: virtual CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) = 0; virtual Queue * createQueue() = 0; + virtual QueryPool * createQueryPool() = 0; virtual Swapchain * createSwapchain() = 0; virtual Buffer * createBuffer() = 0; virtual Texture * createTexture() = 0; @@ -152,6 +157,7 @@ protected: std::array(Feature::COUNT)> _features; Queue * _queue{nullptr}; + QueryPool * _queryPool{nullptr}; CommandBuffer *_cmdBuff{nullptr}; uint32_t _numDrawCalls{0U}; @@ -181,6 +187,12 @@ Queue *Device::createQueue(const QueueInfo &info) { return res; } +QueryPool *Device::createQueryPool(const QueryPoolInfo &info) { + QueryPool *res = createQueryPool(); + res->initialize(info); + return res; +} + Swapchain *Device::createSwapchain(const SwapchainInfo &info) { Swapchain *res = createSwapchain(); res->initialize(info); diff --git a/native/cocos/renderer/gfx-base/GFXQueryPool.cpp b/native/cocos/renderer/gfx-base/GFXQueryPool.cpp new file mode 100644 index 0000000000..550945d147 --- /dev/null +++ b/native/cocos/renderer/gfx-base/GFXQueryPool.cpp @@ -0,0 +1,52 @@ +/**************************************************************************** + Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#include "GFXQueryPool.h" + +namespace cc { +namespace gfx { + +QueryPool::QueryPool() +: GFXObject(ObjectType::QUERY_POOL) { +} + +QueryPool::~QueryPool() = default; + +void QueryPool::initialize(const QueryPoolInfo& info) { + _type = info.type; + _maxQueryObjects = info.maxQueryObjects; + + doInit(info); +} + +void QueryPool::destroy() { + doDestroy(); + + _type = QueryType::OCCLUSION; + _maxQueryObjects = 0; +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-base/GFXQueryPool.h b/native/cocos/renderer/gfx-base/GFXQueryPool.h new file mode 100644 index 0000000000..c4741f0c7a --- /dev/null +++ b/native/cocos/renderer/gfx-base/GFXQueryPool.h @@ -0,0 +1,72 @@ +/**************************************************************************** + Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#pragma once + +#include +#include +#include +#include "GFXObject.h" + +namespace cc { +namespace gfx { + +/** + * QueryPool usage: + * Update + * Render + * getQueryPoolResults + * resetQuery + * for each renderObject + * beginQuery + * drawObject + * endQuery + */ + +class CC_DLL QueryPool : public GFXObject { +public: + QueryPool(); + ~QueryPool() override; + + void initialize(const QueryPoolInfo &info); + void destroy(); + + bool hasResult(uint32_t id) { return _results.count(id) != 0; } + uint64_t getResult(uint32_t id) { return _results[id]; } + inline QueryType getType() const { return _type; } + inline uint32_t getMaxQueryObjects() const { return _maxQueryObjects; } + +protected: + virtual void doInit(const QueryPoolInfo &info) = 0; + virtual void doDestroy() = 0; + + QueryType _type{QueryType::OCCLUSION}; + uint32_t _maxQueryObjects{0}; + std::mutex _mutex; + std::unordered_map _results; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp index 5658bb0819..481961d39f 100644 --- a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.cpp @@ -103,5 +103,14 @@ void EmptyCommandBuffer::dispatch(const DispatchInfo &info) { void EmptyCommandBuffer::pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) { } +void EmptyCommandBuffer::beginQuery(QueryPool *queryPool, uint32_t id) { +} + +void EmptyCommandBuffer::endQuery(QueryPool *queryPool, uint32_t id) { +} + +void EmptyCommandBuffer::resetQuery(QueryPool *queryPool) { +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h index a045386c26..30e08015c4 100644 --- a/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h +++ b/native/cocos/renderer/gfx-empty/EmptyCommandBuffer.h @@ -55,6 +55,9 @@ public: void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; + void beginQuery(QueryPool *queryPool, uint32_t id) override; + void endQuery(QueryPool *queryPool, uint32_t id) override; + void resetQuery(QueryPool *queryPool) override; protected: void doInit(const CommandBufferInfo &info) override; diff --git a/native/cocos/renderer/gfx-empty/EmptyDevice.cpp b/native/cocos/renderer/gfx-empty/EmptyDevice.cpp index 870e064b77..eabbb96594 100644 --- a/native/cocos/renderer/gfx-empty/EmptyDevice.cpp +++ b/native/cocos/renderer/gfx-empty/EmptyDevice.cpp @@ -34,6 +34,7 @@ #include "EmptyInputAssembler.h" #include "EmptyPipelineLayout.h" #include "EmptyPipelineState.h" +#include "EmptyQueryPool.h" #include "EmptyQueue.h" #include "EmptyRenderPass.h" #include "EmptyShader.h" @@ -62,6 +63,9 @@ bool EmptyDevice::doInit(const DeviceInfo & /*info*/) { queueInfo.type = QueueType::GRAPHICS; _queue = createQueue(queueInfo); + QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS}; + _queryPool = createQueryPool(queryPoolInfo); + CommandBufferInfo cmdBuffInfo; cmdBuffInfo.type = CommandBufferType::PRIMARY; cmdBuffInfo.queue = _queue; @@ -74,6 +78,7 @@ bool EmptyDevice::doInit(const DeviceInfo & /*info*/) { void EmptyDevice::doDestroy() { CC_SAFE_DESTROY(_cmdBuff); + CC_SAFE_DESTROY(_queryPool); CC_SAFE_DESTROY(_queue); } @@ -92,6 +97,10 @@ Queue *EmptyDevice::createQueue() { return CC_NEW(EmptyQueue()); } +QueryPool *EmptyDevice::createQueryPool() { + return CC_NEW(EmptyQueryPool()); +} + Swapchain *EmptyDevice::createSwapchain() { return CC_NEW(EmptySwapchain()); } @@ -154,5 +163,8 @@ void EmptyDevice::copyBuffersToTexture(const uint8_t *const *buffers, Texture *d void EmptyDevice::copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) { } +void EmptyDevice::getQueryPoolResults(QueryPool *queryPool) { +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-empty/EmptyDevice.h b/native/cocos/renderer/gfx-empty/EmptyDevice.h index cc2834aff8..d61a143286 100644 --- a/native/cocos/renderer/gfx-empty/EmptyDevice.h +++ b/native/cocos/renderer/gfx-empty/EmptyDevice.h @@ -47,6 +47,7 @@ public: using Device::createInputAssembler; using Device::createPipelineLayout; using Device::createPipelineState; + using Device::createQueryPool; using Device::createQueue; using Device::createRenderPass; using Device::createSampler; @@ -60,6 +61,7 @@ public: CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool emptyhas) override; Queue * createQueue() override; + QueryPool * createQueryPool() override; Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; @@ -78,6 +80,7 @@ public: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; + void getQueryPoolResults(QueryPool *queryPool) override; protected: static EmptyDevice *instance; diff --git a/native/cocos/renderer/gfx-empty/EmptyQueryPool.cpp b/native/cocos/renderer/gfx-empty/EmptyQueryPool.cpp new file mode 100644 index 0000000000..04f4fc5cd1 --- /dev/null +++ b/native/cocos/renderer/gfx-empty/EmptyQueryPool.cpp @@ -0,0 +1,38 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#include "EmptyQueryPool.h" + +namespace cc { +namespace gfx { + +void EmptyQueryPool::doInit(const QueryPoolInfo& info) { +} + +void EmptyQueryPool::doDestroy() { +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-empty/EmptyQueryPool.h b/native/cocos/renderer/gfx-empty/EmptyQueryPool.h new file mode 100644 index 0000000000..1167590e4b --- /dev/null +++ b/native/cocos/renderer/gfx-empty/EmptyQueryPool.h @@ -0,0 +1,40 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#pragma once + +#include "gfx-base/GFXQueryPool.h" + +namespace cc { +namespace gfx { + +class CC_DLL EmptyQueryPool final : public QueryPool { +protected: + void doInit(const QueryPoolInfo &info) override; + void doDestroy() override; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h b/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h index 435f2f88a4..d6b9f289fa 100644 --- a/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h +++ b/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h @@ -57,13 +57,14 @@ enum class GLESCmdType : uint8_t { BLIT_TEXTURE, DISPATCH, BARRIER, + QUERY, COUNT, }; class GLESCmd : public Object { public: GLESCmdType type; - uint32_t refCount = 0; + uint32_t refCount = 0; explicit GLESCmd(GLESCmdType type) : type(type) {} ~GLESCmd() override = default; @@ -77,8 +78,8 @@ template ::v class CommandPool { public: CommandPool() : _freeCmds(INITIAL_CAPACITY) { - _frees = new T *[INITIAL_CAPACITY]; - _count = INITIAL_CAPACITY; + _frees = new T *[INITIAL_CAPACITY]; + _count = INITIAL_CAPACITY; _freeIdx = INITIAL_CAPACITY - 1; for (uint32_t i = 0; i < _count; ++i) { _frees[i] = CC_NEW(T); @@ -99,9 +100,9 @@ public: T *alloc() { if (_freeIdx < 0) { - T **oldFrees = _frees; - uint32_t size = _count * 2; - _frees = new T *[size]; + T ** oldFrees = _frees; + uint32_t size = _count * 2; + _frees = new T *[size]; uint32_t increase = size - _count; for (uint32_t i = 0; i < increase; ++i) { _frees[i] = CC_NEW(T); @@ -115,7 +116,7 @@ public: _freeIdx += static_cast(increase); } - T *cmd = _frees[_freeIdx]; + T *cmd = _frees[_freeIdx]; _frees[_freeIdx--] = nullptr; ++cmd->refCount; return cmd; @@ -146,10 +147,10 @@ public: } protected: - T **_frees = nullptr; - uint32_t _count = 0; + T ** _frees = nullptr; + uint32_t _count = 0; CachedArray _freeCmds; - int _freeIdx = 0; + int _freeIdx = 0; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h index c3871b9718..fcbfbc79a3 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles2/GLES2CommandBuffer.h @@ -67,6 +67,9 @@ public: void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override {} void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override {} + void beginQuery(QueryPool *queryPool, uint32_t id) override {} + void endQuery(QueryPool *queryPool, uint32_t id) override {} + void resetQuery(QueryPool *queryPool) override {} protected: void doInit(const CommandBufferInfo &info) override; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp index c7ec4a80eb..020dcba7c4 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp @@ -37,6 +37,7 @@ #include "GLES2PipelineLayout.h" #include "GLES2PipelineState.h" #include "GLES2PrimaryCommandBuffer.h" +#include "GLES2QueryPool.h" #include "GLES2Queue.h" #include "GLES2RenderPass.h" #include "GLES2Shader.h" @@ -80,15 +81,6 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { return false; }; - QueueInfo queueInfo; - queueInfo.type = QueueType::GRAPHICS; - _queue = createQueue(queueInfo); - - CommandBufferInfo cmdBuffInfo; - cmdBuffInfo.type = CommandBufferType::PRIMARY; - cmdBuffInfo.queue = _queue; - _cmdBuff = createCommandBuffer(cmdBuffInfo); - String extStr = reinterpret_cast(glGetString(GL_EXTENSIONS)); _extensions = StringUtil::split(extStr, " "); @@ -217,6 +209,18 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) { glGetIntegerv(GL_MAX_TEXTURE_SIZE, reinterpret_cast(&_caps.maxTextureSize)); glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, reinterpret_cast(&_caps.maxCubeMapTextureSize)); + QueueInfo queueInfo; + queueInfo.type = QueueType::GRAPHICS; + _queue = createQueue(queueInfo); + + QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS}; + _queryPool = GLES2Device::getInstance()->createQueryPool(queryPoolInfo); + + CommandBufferInfo cmdBuffInfo; + cmdBuffInfo.type = CommandBufferType::PRIMARY; + cmdBuffInfo.queue = _queue; + _cmdBuff = createCommandBuffer(cmdBuffInfo); + _gpuStateCache->initialize(_caps.maxTextureUnits, _caps.maxVertexAttributes); _gpuBlitManager->initialize(); @@ -243,6 +247,7 @@ void GLES2Device::doDestroy() { CCASSERT(!_memoryStatus.textureSize, "Texture memory leaked"); CC_SAFE_DESTROY(_cmdBuff) + CC_SAFE_DESTROY(_queryPool) CC_SAFE_DESTROY(_queue) CC_SAFE_DESTROY(_gpuContext) } @@ -283,6 +288,10 @@ Queue *GLES2Device::createQueue() { return CC_NEW(GLES2Queue); } +QueryPool *GLES2Device::createQueryPool() { + return CC_NEW(GLES2QueryPool); +} + Swapchain *GLES2Device::createSwapchain() { return CC_NEW(GLES2Swapchain); } diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.h b/native/cocos/renderer/gfx-gles2/GLES2Device.h index 118d12a0dd..77844d03a7 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.h @@ -55,6 +55,7 @@ public: using Device::createInputAssembler; using Device::createPipelineLayout; using Device::createPipelineState; + using Device::createQueryPool; using Device::createQueue; using Device::createRenderPass; using Device::createSampler; @@ -88,6 +89,7 @@ protected: void doDestroy() override; CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; Queue * createQueue() override; + QueryPool * createQueryPool() override; Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; @@ -106,6 +108,7 @@ protected: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; + void getQueryPoolResults(QueryPool *queryPool) override {} void bindContext(bool bound) override; diff --git a/native/cocos/renderer/gfx-gles2/GLES2QueryPool.cpp b/native/cocos/renderer/gfx-gles2/GLES2QueryPool.cpp new file mode 100644 index 0000000000..e2016259f1 --- /dev/null +++ b/native/cocos/renderer/gfx-gles2/GLES2QueryPool.cpp @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#include "GLES2Std.h" + +#include "GLES2CommandBuffer.h" +#include "GLES2Commands.h" +#include "GLES2Device.h" +#include "GLES2QueryPool.h" + +namespace cc { +namespace gfx { + +GLES2QueryPool::GLES2QueryPool() { + _typedID = generateObjectID(); +} + +GLES2QueryPool::~GLES2QueryPool() { + destroy(); +} + +void GLES2QueryPool::doInit(const QueryPoolInfo& info) { +} + +void GLES2QueryPool::doDestroy() { +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2QueryPool.h b/native/cocos/renderer/gfx-gles2/GLES2QueryPool.h new file mode 100644 index 0000000000..1bd7fde540 --- /dev/null +++ b/native/cocos/renderer/gfx-gles2/GLES2QueryPool.h @@ -0,0 +1,47 @@ +/**************************************************************************** + Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#pragma once + +#include "GLES2Std.h" +#include "gfx-base/GFXQueryPool.h" + +namespace cc { +namespace gfx { + +class CC_GLES2_API GLES2QueryPool final : public QueryPool { +public: + GLES2QueryPool(); + ~GLES2QueryPool() override; + +protected: + friend class GLES2Device; + + void doInit(const QueryPoolInfo &info) override; + void doDestroy() override; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp index b079b93915..85db9eefaf 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.cpp @@ -33,6 +33,7 @@ #include "GLES3Framebuffer.h" #include "GLES3InputAssembler.h" #include "GLES3PipelineState.h" +#include "GLES3QueryPool.h" #include "GLES3RenderPass.h" #include "GLES3Texture.h" #include "states/GLES3GlobalBarrier.h" @@ -436,5 +437,49 @@ void GLES3CommandBuffer::pipelineBarrier(const GlobalBarrier *barrier, const Tex _curCmdPackage->cmds.push(GLESCmdType::BARRIER); } +void GLES3CommandBuffer::beginQuery(QueryPool *queryPool, uint32_t id) { + auto * gles3QueryPool = static_cast(queryPool); + GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); + cmd->queryPool = gles3QueryPool; + cmd->type = GLES3QueryType::BEGIN; + cmd->id = id; + + _curCmdPackage->queryCmds.push(cmd); + _curCmdPackage->cmds.push(GLESCmdType::QUERY); +} + +void GLES3CommandBuffer::endQuery(QueryPool *queryPool, uint32_t id) { + auto * gles3QueryPool = static_cast(queryPool); + GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); + cmd->queryPool = gles3QueryPool; + cmd->type = GLES3QueryType::END; + cmd->id = id; + + _curCmdPackage->queryCmds.push(cmd); + _curCmdPackage->cmds.push(GLESCmdType::QUERY); +} + +void GLES3CommandBuffer::resetQuery(QueryPool *queryPool) { + auto * gles3QueryPool = static_cast(queryPool); + GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); + cmd->queryPool = gles3QueryPool; + cmd->type = GLES3QueryType::RESET; + cmd->id = 0; + + _curCmdPackage->queryCmds.push(cmd); + _curCmdPackage->cmds.push(GLESCmdType::QUERY); +} + +void GLES3CommandBuffer::getQueryPoolResults(QueryPool *queryPool) { + auto * gles3QueryPool = static_cast(queryPool); + GLES3CmdQuery *cmd = _cmdAllocator->queryCmdPool.alloc(); + cmd->queryPool = gles3QueryPool; + cmd->type = GLES3QueryType::GET_RESULTS; + cmd->id = 0; + + _curCmdPackage->queryCmds.push(cmd); + _curCmdPackage->cmds.push(GLESCmdType::QUERY); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h index cefd9198db..77798ff9ea 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3CommandBuffer.h @@ -65,9 +65,15 @@ public: void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; + void beginQuery(QueryPool *queryPool, uint32_t id) override; + void endQuery(QueryPool *queryPool, uint32_t id) override; + void resetQuery(QueryPool *queryPool) override; protected: friend class GLES3Queue; + friend class GLES3Device; + + virtual void getQueryPoolResults(QueryPool *query); void doInit(const CommandBufferInfo &info) override; void doDestroy() override; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index 2a76cfaaad..e25f242690 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -27,6 +27,7 @@ #include "GLES3Commands.h" #include "GLES3Device.h" +#include "GLES3QueryPool.h" #include "gfx-base/GFXDef-common.h" #define BUFFER_OFFSET(idx) (static_cast(0) + (idx)) @@ -1765,6 +1766,78 @@ void cmdFuncGLES3CreateGlobalBarrier(const std::vector &prevAccesses } } +void cmdFuncGLES3CreateQuery(GLES3Device * /*device*/, GLES3GPUQueryPool *gpuQueryPool) { + GL_CHECK(glGenQueries(gpuQueryPool->maxQueryObjects, &gpuQueryPool->glQueryIds[0])); +} + +void cmdFuncGLES3DestroyQuery(GLES3Device * /*device*/, GLES3GPUQueryPool *gpuQueryPool) { + GL_CHECK(glDeleteQueries(gpuQueryPool->maxQueryObjects, &gpuQueryPool->glQueryIds[0])); +} + +void cmdFuncGLES3Query(GLES3Device * /*device*/, GLES3QueryPool *queryPool, GLES3QueryType type, uint32_t id) { + GLES3GPUQueryPool *gpuQueryPool = queryPool->gpuQueryPool(); + + switch (type) { + case GLES3QueryType::BEGIN: { + auto queryId = queryPool->getIdCount(); + GLuint glQueryId = gpuQueryPool->mapGLQueryId(queryId); + if (glQueryId != -1) { + GL_CHECK(glBeginQuery(GL_ANY_SAMPLES_PASSED, glQueryId)); + } + break; + } + case GLES3QueryType::END: { + auto queryId = queryPool->getIdCount(); + GLuint glQueryId = gpuQueryPool->mapGLQueryId(queryId); + if (glQueryId != -1) { + GL_CHECK(glEndQuery(GL_ANY_SAMPLES_PASSED)); + queryPool->addId(id); + } + break; + } + case GLES3QueryType::RESET: { + queryPool->clearId(); + break; + } + case GLES3QueryType::GET_RESULTS: { + auto queryCount = queryPool->getIdCount(); + std::vector results(queryCount); + + for (auto queryId = 0U; queryId < queryCount; queryId++) { + GLuint glQueryId = gpuQueryPool->mapGLQueryId(queryId); + + if (glQueryId != -1) { + GLuint result{0}; + GL_CHECK(glGetQueryObjectuiv(glQueryId, GL_QUERY_RESULT, &result)); + results[queryId] = static_cast(result); + } else { + results[queryId] = 1ULL; + } + } + + std::unordered_map mapResults; + for (auto queryId = 0U; queryId < queryCount; queryId++) { + uint32_t id = queryPool->getId(queryId); + auto iter = mapResults.find(id); + if (iter != mapResults.end()) { + iter->second += results[queryId]; + } else { + mapResults[id] = results[queryId]; + } + } + + { + std::lock_guard lock(queryPool->getMutex()); + queryPool->setResults(std::move(mapResults)); + } + break; + } + default: { + break; + } + } +} + void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint32_t subpassIdx, GLES3GPURenderPass *gpuRenderPass, GLES3GPUFramebuffer *gpuFramebuffer, const Rect *renderArea, const Color *clearColors, float clearDepth, uint32_t clearStencil) { @@ -3027,6 +3100,11 @@ void cmdFuncGLES3ExecuteCmds(GLES3Device *device, GLES3CmdPackage *cmdPackage) { cmdFuncGLES3BlitTexture(device, cmd->gpuTextureSrc, cmd->gpuTextureDst, cmd->regions, cmd->count, cmd->filter); break; } + case GLESCmdType::QUERY: { + GLES3CmdQuery *cmd = cmdPackage->queryCmds[cmdIdx]; + cmdFuncGLES3Query(device, cmd->queryPool, cmd->type, cmd->id); + break; + } default: break; } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.h b/native/cocos/renderer/gfx-gles3/GLES3Commands.h index 7aa01eea19..b18744d44c 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.h @@ -31,6 +31,7 @@ namespace cc { namespace gfx { class GLES3Device; +class GLES3QueryPool; class GLES3CmdBeginRenderPass final : public GLESCmd { public: @@ -149,6 +150,28 @@ public: } }; +enum class GLES3QueryType : uint8_t { + BEGIN, + END, + RESET, + GET_RESULTS, +}; + +class GLES3CmdQuery final : public GLESCmd { +public: + GLES3QueryPool *queryPool = nullptr; + GLES3QueryType type = GLES3QueryType::BEGIN; + uint32_t id = 0U; + + GLES3CmdQuery() : GLESCmd(GLESCmdType::QUERY) {} + + void clear() override { + queryPool = nullptr; + type = GLES3QueryType::BEGIN; + id = 0U; + } +}; + class GLES3CmdPackage final : public Object { public: CachedArray cmds; @@ -160,6 +183,7 @@ public: CachedArray updateBufferCmds; CachedArray copyBufferToTextureCmds; CachedArray blitTextureCmds; + CachedArray queryCmds; }; class GLES3GPUCommandAllocator final : public Object { @@ -172,6 +196,7 @@ public: CommandPool updateBufferCmdPool; CommandPool copyBufferToTextureCmdPool; CommandPool blitTextureCmdPool; + CommandPool queryCmdPool; void clearCmds(GLES3CmdPackage *cmdPackage) { if (cmdPackage->beginRenderPassCmds.size()) { @@ -198,6 +223,9 @@ public: if (cmdPackage->blitTextureCmds.size()) { blitTextureCmdPool.freeCmds(cmdPackage->blitTextureCmds); } + if (cmdPackage->queryCmds.size()) { + queryCmdPool.freeCmds(cmdPackage->queryCmds); + } cmdPackage->cmds.clear(); } @@ -231,6 +259,10 @@ CC_GLES3_API void cmdFuncGLES3DestroyInputAssembler(GLES3Device *device, GLES3GP CC_GLES3_API void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO); CC_GLES3_API void cmdFuncGLES3DestroyFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO); CC_GLES3_API void cmdFuncGLES3CreateGlobalBarrier(const std::vector &prevAccesses, const std::vector &nextAccesses, GLES3GPUGlobalBarrier *barrier); +CC_GLES3_API void cmdFuncGLES3CreateQuery(GLES3Device *device, GLES3GPUQueryPool *gpuQueryPool); +CC_GLES3_API void cmdFuncGLES3DestroyQuery(GLES3Device *device, GLES3GPUQueryPool *gpuQueryPool); + +CC_GLES3_API void cmdFuncGLES3Query(GLES3Device *device, GLES3QueryPool *query, GLES3QueryType type, uint32_t id); CC_GLES3_API void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint32_t subpassIdx, GLES3GPURenderPass * gpuRenderPass = nullptr, diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index e10c53b2bc..d998321447 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -37,6 +37,7 @@ #include "GLES3PipelineLayout.h" #include "GLES3PipelineState.h" #include "GLES3PrimaryCommandBuffer.h" +#include "GLES3QueryPool.h" #include "GLES3Queue.h" #include "GLES3RenderPass.h" #include "GLES3Shader.h" @@ -80,15 +81,6 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { return false; }; - QueueInfo queueInfo; - queueInfo.type = QueueType::GRAPHICS; - _queue = createQueue(queueInfo); - - CommandBufferInfo cmdBuffInfo; - cmdBuffInfo.type = CommandBufferType::PRIMARY; - cmdBuffInfo.queue = _queue; - _cmdBuff = createCommandBuffer(cmdBuffInfo); - String extStr = reinterpret_cast(glGetString(GL_EXTENSIONS)); _extensions = StringUtil::split(extStr, " "); @@ -214,6 +206,19 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 1, reinterpret_cast(&_caps.maxComputeWorkGroupCount.y)); glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 2, reinterpret_cast(&_caps.maxComputeWorkGroupCount.z)); } + _caps.supportQuery = true; + + QueueInfo queueInfo; + queueInfo.type = QueueType::GRAPHICS; + _queue = createQueue(queueInfo); + + QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS}; + _queryPool = GLES3Device::getInstance()->createQueryPool(queryPoolInfo); + + CommandBufferInfo cmdBuffInfo; + cmdBuffInfo.type = CommandBufferType::PRIMARY; + cmdBuffInfo.queue = _queue; + _cmdBuff = createCommandBuffer(cmdBuffInfo); _gpuStateCache->initialize(_caps.maxTextureUnits, _caps.maxImageUnits, _caps.maxUniformBufferBindings, _caps.maxShaderStorageBufferBindings, _caps.maxVertexAttributes); @@ -236,6 +241,7 @@ void GLES3Device::doDestroy() { CCASSERT(!_memoryStatus.textureSize, "Texture memory leaked"); CC_SAFE_DESTROY(_cmdBuff) + CC_SAFE_DESTROY(_queryPool) CC_SAFE_DESTROY(_queue) CC_SAFE_DESTROY(_gpuContext) } @@ -276,6 +282,10 @@ Queue *GLES3Device::createQueue() { return CC_NEW(GLES3Queue); } +QueryPool *GLES3Device::createQueryPool() { + return CC_NEW(GLES3QueryPool); +} + Swapchain *GLES3Device::createSwapchain() { return CC_NEW(GLES3Swapchain); } @@ -340,5 +350,10 @@ void GLES3Device::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buff cmdFuncGLES3CopyTextureToBuffers(this, static_cast(srcTexture)->gpuTexture(), buffers, regions, count); } +void GLES3Device::getQueryPoolResults(QueryPool *queryPool) { + auto *cmdBuff = static_cast(getCommandBuffer()); + cmdBuff->getQueryPoolResults(queryPool); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.h b/native/cocos/renderer/gfx-gles3/GLES3Device.h index 94c204dd5f..ac0337114c 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.h @@ -53,6 +53,7 @@ public: using Device::createInputAssembler; using Device::createPipelineLayout; using Device::createPipelineState; + using Device::createQueryPool; using Device::createQueue; using Device::createRenderPass; using Device::createSampler; @@ -86,6 +87,7 @@ protected: void doDestroy() override; CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; Queue * createQueue() override; + QueryPool * createQueryPool() override; Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; @@ -104,6 +106,7 @@ protected: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; + void getQueryPoolResults(QueryPool *queryPool) override; void bindContext(bool bound) override; diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 49c8ee15b1..6330f0160d 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -97,6 +97,21 @@ public: GLuint glFramebuffer{0}; }; +class GLES3GPUQueryPool final : public Object { +public: + QueryType type{QueryType::OCCLUSION}; + uint32_t maxQueryObjects{0}; + std::vector glQueryIds; + + inline GLuint mapGLQueryId(uint32_t queryId) { + if (queryId < maxQueryObjects) { + return glQueryIds[queryId]; + } + + return -1; + } +}; + class GLES3GPUBuffer final : public Object { public: BufferUsage usage = BufferUsage::NONE; diff --git a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp index 088fda79d4..9e679f0fc2 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.cpp @@ -33,6 +33,7 @@ #include "GLES3InputAssembler.h" #include "GLES3PipelineState.h" #include "GLES3PrimaryCommandBuffer.h" +#include "GLES3QueryPool.h" #include "GLES3RenderPass.h" #include "GLES3Texture.h" #include "states/GLES3GlobalBarrier.h" @@ -148,6 +149,30 @@ void GLES3PrimaryCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTex cmdFuncGLES3BlitTexture(GLES3Device::getInstance(), gpuTextureSrc, gpuTextureDst, regions, count, filter); } +void GLES3PrimaryCommandBuffer::beginQuery(QueryPool *queryPool, uint32_t id) { + auto *gles3QueryPool = static_cast(queryPool); + + cmdFuncGLES3Query(GLES3Device::getInstance(), gles3QueryPool, GLES3QueryType::BEGIN, id); +} + +void GLES3PrimaryCommandBuffer::endQuery(QueryPool *queryPool, uint32_t id) { + auto *gles3QueryPool = static_cast(queryPool); + + cmdFuncGLES3Query(GLES3Device::getInstance(), gles3QueryPool, GLES3QueryType::END, id); +} + +void GLES3PrimaryCommandBuffer::resetQuery(QueryPool *queryPool) { + auto *gles3QueryPool = static_cast(queryPool); + + cmdFuncGLES3Query(GLES3Device::getInstance(), gles3QueryPool, GLES3QueryType::RESET, 0); +} + +void GLES3PrimaryCommandBuffer::getQueryPoolResults(QueryPool *queryPool) { + auto *gles3QueryPool = static_cast(queryPool); + + cmdFuncGLES3Query(GLES3Device::getInstance(), gles3QueryPool, GLES3QueryType::GET_RESULTS, 0); +} + void GLES3PrimaryCommandBuffer::execute(CommandBuffer *const *cmdBuffs, uint32_t count) { for (uint32_t i = 0; i < count; ++i) { auto *cmdBuff = static_cast(cmdBuffs[i]); diff --git a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h index 85400d4703..49f3152d2c 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h +++ b/native/cocos/renderer/gfx-gles3/GLES3PrimaryCommandBuffer.h @@ -49,9 +49,15 @@ public: void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) override; + void beginQuery(QueryPool *queryPool, uint32_t id) override; + void endQuery(QueryPool *queryPool, uint32_t id) override; + void resetQuery(QueryPool *queryPool) override; protected: friend class GLES3Queue; + friend class GLES3QueryPool; + + void getQueryPoolResults(QueryPool *query) override; void bindStates() override; }; diff --git a/native/cocos/renderer/gfx-gles3/GLES3QueryPool.cpp b/native/cocos/renderer/gfx-gles3/GLES3QueryPool.cpp new file mode 100644 index 0000000000..3612bfb300 --- /dev/null +++ b/native/cocos/renderer/gfx-gles3/GLES3QueryPool.cpp @@ -0,0 +1,61 @@ +/**************************************************************************** + Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#include "GLES3QueryPool.h" +#include "GLES3CommandBuffer.h" +#include "GLES3Commands.h" +#include "GLES3Device.h" + +namespace cc { +namespace gfx { + +GLES3QueryPool::GLES3QueryPool() { + _typedID = generateObjectID(); +} + +GLES3QueryPool::~GLES3QueryPool() { + destroy(); +} + +void GLES3QueryPool::doInit(const QueryPoolInfo& /*info*/) { + GLES3Device* device = GLES3Device::getInstance(); + _gpuQueryPool = CC_NEW(GLES3GPUQueryPool); + _gpuQueryPool->type = _type; + _gpuQueryPool->maxQueryObjects = _maxQueryObjects; + _gpuQueryPool->glQueryIds.resize(_maxQueryObjects, 0U); + + cmdFuncGLES3CreateQuery(device, _gpuQueryPool); +} + +void GLES3QueryPool::doDestroy() { + if (_gpuQueryPool) { + cmdFuncGLES3DestroyQuery(GLES3Device::getInstance(), _gpuQueryPool); + CC_DELETE(_gpuQueryPool); + _gpuQueryPool = nullptr; + } +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3QueryPool.h b/native/cocos/renderer/gfx-gles3/GLES3QueryPool.h new file mode 100644 index 0000000000..8e176d2bd7 --- /dev/null +++ b/native/cocos/renderer/gfx-gles3/GLES3QueryPool.h @@ -0,0 +1,61 @@ +/**************************************************************************** + Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#pragma once + +#include +#include "GLES3Std.h" +#include "gfx-base/GFXQueryPool.h" + +namespace cc { +namespace gfx { + +class GLES3GPUQueryPool; + +class CC_GLES3_API GLES3QueryPool final : public QueryPool { +public: + GLES3QueryPool(); + ~GLES3QueryPool() override; + + inline GLES3GPUQueryPool *gpuQueryPool() const { return _gpuQueryPool; } + inline uint32_t getIdCount() const { return static_cast(_ids.size()); } + inline void clearId() { _ids.clear(); } + inline void addId(uint32_t id) { _ids.push_back(id); } + inline uint32_t getId(uint32_t index) const { return _ids[index]; } + inline std::mutex & getMutex() { return _mutex; } + inline void setResults(std::unordered_map &&results) { _results = results; } + +protected: + friend class GLES3CommandBuffer; + + void doInit(const QueryPoolInfo &info) override; + void doDestroy() override; + + GLES3GPUQueryPool * _gpuQueryPool = nullptr; + std::vector _ids; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h index 44f1f9265e..8eb3bdbaa9 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.h @@ -27,11 +27,12 @@ #include "gfx-base/GFXCommandBuffer.h" -#include "MTLGPUObjects.h" -#include "MTLRenderCommandEncoder.h" -#include "MTLComputeCommandEncoder.h" #import #import +#include "MTLComputeCommandEncoder.h" +#include "MTLGPUObjects.h" +#include "MTLRenderCommandEncoder.h" + namespace cc { namespace gfx { @@ -48,63 +49,66 @@ public: explicit CCMTLCommandBuffer(); ~CCMTLCommandBuffer(); CCMTLCommandBuffer(const CCMTLCommandBuffer &) = delete; - CCMTLCommandBuffer(CCMTLCommandBuffer &&) = delete; + CCMTLCommandBuffer(CCMTLCommandBuffer &&) = delete; CCMTLCommandBuffer &operator=(const CCMTLCommandBuffer &) = delete; CCMTLCommandBuffer &operator=(CCMTLCommandBuffer &&) = delete; - void begin(RenderPass *renderPass, uint subpass, Framebuffer *frameBuffer) override; - void end() override; - void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint stencil, CommandBuffer *const *secondaryCBs, uint secondaryCBCount) override; - void endRenderPass() override; - void bindPipelineState(PipelineState *pso) override; - void bindDescriptorSet(uint set, DescriptorSet *descriptorSet, uint dynamicOffsetCount, const uint *dynamicOffsets) override; - void bindInputAssembler(InputAssembler *ia) override; - void setViewport(const Viewport &vp) override; - void setScissor(const Rect &rect) override; - void setLineWidth(float width) override; - void setDepthBias(float constant, float clamp, float slope) override; - void setBlendConstants(const Color &constants) override; - void setDepthBound(float minBounds, float maxBounds) override; - void setStencilWriteMask(StencilFace face, uint mask) override; - void setStencilCompareMask(StencilFace face, uint ref, uint mask) override; - void nextSubpass() override; - void draw(const DrawInfo &info) override; - void updateBuffer(Buffer *buff, const void *data, uint size) override; - void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint count) override; - void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint count, Filter filter) override; - void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; - void dispatch(const DispatchInfo &info) override; - void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint textureBarrierCount) override; - void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *regions, uint count); - inline bool isCommandBufferBegan() const { return _commandBufferBegan; } - inline CCMTLGPUCommandBufferObject* gpuCommandBufferObj() const { return _gpuCommandBufferObj; } - + void begin(RenderPass *renderPass, uint subpass, Framebuffer *frameBuffer) override; + void end() override; + void beginRenderPass(RenderPass *renderPass, Framebuffer *fbo, const Rect &renderArea, const Color *colors, float depth, uint stencil, CommandBuffer *const *secondaryCBs, uint secondaryCBCount) override; + void endRenderPass() override; + void bindPipelineState(PipelineState *pso) override; + void bindDescriptorSet(uint set, DescriptorSet *descriptorSet, uint dynamicOffsetCount, const uint *dynamicOffsets) override; + void bindInputAssembler(InputAssembler *ia) override; + void setViewport(const Viewport &vp) override; + void setScissor(const Rect &rect) override; + void setLineWidth(float width) override; + void setDepthBias(float constant, float clamp, float slope) override; + void setBlendConstants(const Color &constants) override; + void setDepthBound(float minBounds, float maxBounds) override; + void setStencilWriteMask(StencilFace face, uint mask) override; + void setStencilCompareMask(StencilFace face, uint ref, uint mask) override; + void nextSubpass() override; + void draw(const DrawInfo &info) override; + void updateBuffer(Buffer *buff, const void *data, uint size) override; + void copyBuffersToTexture(const uint8_t *const *buffers, Texture *texture, const BufferTextureCopy *regions, uint count) override; + void blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint count, Filter filter) override; + void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; + void dispatch(const DispatchInfo &info) override; + void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint textureBarrierCount) override; + void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *regions, uint count); + void beginQuery(QueryPool *queryPool, uint32_t id) override {} + void endQuery(QueryPool *queryPool, uint32_t id) override {} + void resetQuery(QueryPool *queryPool) override {} + inline bool isCommandBufferBegan() const { return _commandBufferBegan; } + inline CCMTLGPUCommandBufferObject *gpuCommandBufferObj() const { return _gpuCommandBufferObj; } + void reset(); - + protected: friend class CCMTLQueue; void doInit(const CommandBufferInfo &info) override; void doDestroy() override; - void bindDescriptorSets(); - void updateDepthStencilState(uint32_t subPassIndex, MTLRenderPassDescriptor* descriptor); + void bindDescriptorSets(); + void updateDepthStencilState(uint32_t subPassIndex, MTLRenderPassDescriptor *descriptor); static bool isRenderingEntireDrawable(const Rect &rect, const CCMTLRenderPass *renderPass); vector _GPUDescriptorSets; // NOLINT(bugprone-reserved-identifier) - vector> _dynamicOffsets; - uint _firstDirtyDescriptorSet = UINT_MAX; + vector> _dynamicOffsets; + uint _firstDirtyDescriptorSet = UINT_MAX; - bool _indirectDrawSuppotred = false; - bool _commandBufferBegan = false; - CCMTLDevice *_mtlDevice = nullptr; - id _mtlCommandQueue = nil; - CCMTLRenderCommandEncoder _renderEncoder; - CCMTLComputeCommandEncoder _computeEncoder; - id _parallelEncoder = nil; - MTLPrimitiveType _mtlPrimitiveType = MTLPrimitiveType::MTLPrimitiveTypeTriangle; + bool _indirectDrawSuppotred = false; + bool _commandBufferBegan = false; + CCMTLDevice * _mtlDevice = nullptr; + id _mtlCommandQueue = nil; + CCMTLRenderCommandEncoder _renderEncoder; + CCMTLComputeCommandEncoder _computeEncoder; + id _parallelEncoder = nil; + MTLPrimitiveType _mtlPrimitiveType = MTLPrimitiveType::MTLPrimitiveTypeTriangle; - CCMTLGPUCommandBufferObject* _gpuCommandBufferObj = nullptr; + CCMTLGPUCommandBufferObject *_gpuCommandBufferObj = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm index 4667af9fc7..54110abb08 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm @@ -25,6 +25,7 @@ #import "MTLStd.h" +#import #import #import "MTLBuffer.h" #import "MTLCommandBuffer.h" @@ -33,13 +34,13 @@ #import "MTLFramebuffer.h" #import "MTLInputAssembler.h" #import "MTLPipelineState.h" +#import "MTLQueue.h" #import "MTLRenderPass.h" #import "MTLSampler.h" #import "MTLSwapchain.h" #import "MTLTexture.h" #import "TargetConditionals.h" -#import -#import "MTLQueue.h" + namespace cc { namespace gfx { @@ -68,11 +69,11 @@ void CCMTLCommandBuffer::doDestroy() { _GPUDescriptorSets.clear(); _dynamicOffsets.clear(); _firstDirtyDescriptorSet = UINT_MAX; - _indirectDrawSuppotred = false; - _commandBufferBegan = false; - _mtlDevice = nullptr; - _mtlCommandQueue = nil; - _parallelEncoder = nil; + _indirectDrawSuppotred = false; + _commandBufferBegan = false; + _mtlDevice = nullptr; + _mtlCommandQueue = nil; + _parallelEncoder = nil; // mtlCommandbuffer released in present.completeHandler CC_SAFE_DELETE(_gpuCommandBufferObj); @@ -93,7 +94,7 @@ void CCMTLCommandBuffer::begin(RenderPass *renderPass, uint subpass, Framebuffer } if (!_gpuCommandBufferObj->isSecondary) { - auto* mtlQueue = static_cast(_queue)->gpuQueueObj()->mtlCommandQueue; + auto *mtlQueue = static_cast(_queue)->gpuQueueObj()->mtlCommandQueue; // Only primary command buffer should request command buffer explicitly _gpuCommandBufferObj->mtlCommandBuffer = [mtlQueue commandBuffer]; [_gpuCommandBufferObj->mtlCommandBuffer enqueue]; @@ -129,40 +130,39 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb if (_gpuCommandBufferObj->isSecondary) { return; } - _gpuCommandBufferObj->renderPass = static_cast(renderPass); - _gpuCommandBufferObj->fbo = static_cast(fbo); + _gpuCommandBufferObj->renderPass = static_cast(renderPass); + _gpuCommandBufferObj->fbo = static_cast(fbo); - auto *ccMtlRenderPass = static_cast(renderPass); - auto isOffscreen = _gpuCommandBufferObj->fbo->isOffscreen(); - const SubpassInfoList& subpasses = renderPass->getSubpasses(); - const ColorAttachmentList& colorAttachments = renderPass->getColorAttachments(); + auto * ccMtlRenderPass = static_cast(renderPass); + auto isOffscreen = _gpuCommandBufferObj->fbo->isOffscreen(); + const SubpassInfoList & subpasses = renderPass->getSubpasses(); + const ColorAttachmentList &colorAttachments = renderPass->getColorAttachments(); MTLRenderPassDescriptor *mtlRenderPassDescriptor = static_cast(renderPass)->getMTLRenderPassDescriptor(); - const TextureList &colorTextures = fbo->getColorTextures(); - Texture *dsTexture = fbo->getDepthStencilTexture(); - auto* swapchain = static_cast(_gpuCommandBufferObj->fbo->swapChain()); + const TextureList & colorTextures = fbo->getColorTextures(); + Texture * dsTexture = fbo->getDepthStencilTexture(); + auto * swapchain = static_cast(_gpuCommandBufferObj->fbo->swapChain()); - if(subpasses.empty()) { + if (subpasses.empty()) { if (dsTexture) { auto *ccMtlTexture = static_cast(dsTexture); ccMtlRenderPass->setDepthStencilAttachment(ccMtlTexture, 0); } else { - const DepthStencilAttachment& dsa = renderPass->getDepthStencilAttachment(); - if(dsa.format != Format::UNKNOWN) { + const DepthStencilAttachment &dsa = renderPass->getDepthStencilAttachment(); + if (dsa.format != Format::UNKNOWN) { ccMtlRenderPass->setDepthStencilAttachment(swapchain->depthStencilTexture(), 0); } } - if(colorAttachments.empty()) { + if (colorAttachments.empty()) { ccMtlRenderPass->setColorAttachment(0, swapchain->colorTexture(), 0); - }else { + } else { for (size_t i = 0; i < colorAttachments.size(); ++i) { auto *ccMtlTexture = static_cast(colorTextures[i]); ccMtlRenderPass->setColorAttachment(i, ccMtlTexture, 0); - mtlRenderPassDescriptor.colorAttachments[i].clearColor = mu::toMTLClearColor(colors[i]); - mtlRenderPassDescriptor.colorAttachments[i].loadAction = mu::toMTLLoadAction(colorAttachments[i].loadOp); - mtlRenderPassDescriptor.colorAttachments[i].storeAction = mu::isFramebufferFetchSupported() ? - mu::toMTLStoreAction(colorAttachments[i].storeOp) : MTLStoreActionStore; + mtlRenderPassDescriptor.colorAttachments[i].clearColor = mu::toMTLClearColor(colors[i]); + mtlRenderPassDescriptor.colorAttachments[i].loadAction = mu::toMTLLoadAction(colorAttachments[i].loadOp); + mtlRenderPassDescriptor.colorAttachments[i].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[i].storeOp) : MTLStoreActionStore; } } } else { @@ -171,41 +171,39 @@ 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(visited[input]) + if (visited[input]) continue; auto *ccMtlTexture = static_cast(colorTextures[input]); ccMtlRenderPass->setColorAttachment(input, ccMtlTexture, 0); - mtlRenderPassDescriptor.colorAttachments[input].clearColor = mu::toMTLClearColor(colors[input]); - mtlRenderPassDescriptor.colorAttachments[input].loadAction = mu::toMTLLoadAction(colorAttachments[input].loadOp); - mtlRenderPassDescriptor.colorAttachments[input].storeAction = mu::isFramebufferFetchSupported() ? - mu::toMTLStoreAction(colorAttachments[input].storeOp) : MTLStoreActionStore; - visited[input] = true; + mtlRenderPassDescriptor.colorAttachments[input].clearColor = mu::toMTLClearColor(colors[input]); + mtlRenderPassDescriptor.colorAttachments[input].loadAction = mu::toMTLLoadAction(colorAttachments[input].loadOp); + mtlRenderPassDescriptor.colorAttachments[input].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[input].storeOp) : MTLStoreActionStore; + visited[input] = true; } for (size_t j = 0; j < subpasses[i].colors.size(); ++j) { uint32_t color = subpasses[i].colors[j]; - if(visited[color]) + if (visited[color]) continue; auto *ccMtlTexture = static_cast(colorTextures[color]); ccMtlRenderPass->setColorAttachment(color, ccMtlTexture, 0); - mtlRenderPassDescriptor.colorAttachments[color].clearColor = mu::toMTLClearColor(colors[color]); - mtlRenderPassDescriptor.colorAttachments[color].loadAction = mu::toMTLLoadAction(colorAttachments[color].loadOp); - mtlRenderPassDescriptor.colorAttachments[color].storeAction = mu::isFramebufferFetchSupported() ? - mu::toMTLStoreAction(colorAttachments[color].storeOp) : MTLStoreActionStore; - visited[color] = true; - if(subpasses[i].resolves.size() > j) { - uint32_t resolve = subpasses[i].resolves[j]; - auto *resolveTex = static_cast(colorTextures[resolve]); - if(resolveTex->textureInfo().samples == SampleCount::ONE) + mtlRenderPassDescriptor.colorAttachments[color].clearColor = mu::toMTLClearColor(colors[color]); + mtlRenderPassDescriptor.colorAttachments[color].loadAction = mu::toMTLLoadAction(colorAttachments[color].loadOp); + mtlRenderPassDescriptor.colorAttachments[color].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[color].storeOp) : MTLStoreActionStore; + visited[color] = true; + if (subpasses[i].resolves.size() > j) { + uint32_t resolve = subpasses[i].resolves[j]; + auto * resolveTex = static_cast(colorTextures[resolve]); + if (resolveTex->textureInfo().samples == SampleCount::ONE) continue; - mtlRenderPassDescriptor.colorAttachments[color].resolveTexture = resolveTex->getMTLTexture(); - mtlRenderPassDescriptor.colorAttachments[color].resolveLevel = 0; - mtlRenderPassDescriptor.colorAttachments[color].resolveSlice = 0; + mtlRenderPassDescriptor.colorAttachments[color].resolveTexture = resolveTex->getMTLTexture(); + mtlRenderPassDescriptor.colorAttachments[color].resolveLevel = 0; + mtlRenderPassDescriptor.colorAttachments[color].resolveSlice = 0; mtlRenderPassDescriptor.colorAttachments[color].resolveDepthPlane = 0; - mtlRenderPassDescriptor.colorAttachments[color].storeAction = MTLStoreActionMultisampleResolve; + mtlRenderPassDescriptor.colorAttachments[color].storeAction = MTLStoreActionMultisampleResolve; } } for (size_t j = 0; j < subpasses[i].preserves.size(); ++j) { - uint32_t preserves = subpasses[i].preserves[j]; + uint32_t preserves = subpasses[i].preserves[j]; mtlRenderPassDescriptor.colorAttachments[preserves].storeAction = MTLStoreActionStoreAndMultisampleResolve; } } @@ -228,7 +226,7 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb CCMTLCommandBuffer *cmdBuff = (CCMTLCommandBuffer *)secondaryCBs[i]; cmdBuff->_renderEncoder.initialize(_parallelEncoder); cmdBuff->_gpuCommandBufferObj->mtlCommandBuffer = mtlCommandBuffer; - cmdBuff->_gpuCommandBufferObj->isSecondary = true; + cmdBuff->_gpuCommandBufferObj->isSecondary = true; } } else { _renderEncoder.initialize(mtlCommandBuffer, mtlRenderPassDescriptor); @@ -257,49 +255,49 @@ void CCMTLCommandBuffer::endRenderPass() { } void CCMTLCommandBuffer::reset() { - _gpuCommandBufferObj->renderPass = nullptr; - _gpuCommandBufferObj->fbo = nullptr; - _gpuCommandBufferObj->inputAssembler = nullptr; - _gpuCommandBufferObj->pipelineState = nullptr; + _gpuCommandBufferObj->renderPass = nullptr; + _gpuCommandBufferObj->fbo = nullptr; + _gpuCommandBufferObj->inputAssembler = nullptr; + _gpuCommandBufferObj->pipelineState = nullptr; _gpuCommandBufferObj->mtlCommandBuffer = nil; } void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDescriptor *descriptor) { - CCMTLRenderPass* curRenderPass = _gpuCommandBufferObj->renderPass; - CCMTLFramebuffer* curFBO = _gpuCommandBufferObj->fbo; - const SubpassInfoList& subpasses = curRenderPass->getSubpasses(); - const SubpassInfo subpass = subpasses[index]; - if(subpass.depthStencil != INVALID_BINDING) { - const TextureList& colorTextures = curFBO->getColorTextures(); - if(subpass.depthStencil >= colorTextures.size() ) { - auto* ccMTLTexture = static_cast(curFBO->getDepthStencilTexture()); + CCMTLRenderPass * curRenderPass = _gpuCommandBufferObj->renderPass; + CCMTLFramebuffer * curFBO = _gpuCommandBufferObj->fbo; + const SubpassInfoList &subpasses = curRenderPass->getSubpasses(); + const SubpassInfo subpass = subpasses[index]; + if (subpass.depthStencil != INVALID_BINDING) { + const TextureList &colorTextures = curFBO->getColorTextures(); + if (subpass.depthStencil >= colorTextures.size()) { + auto *ccMTLTexture = static_cast(curFBO->getDepthStencilTexture()); descriptor.depthAttachment.texture = ccMTLTexture->getMTLTexture(); - if(ccMTLTexture->getFormat() == Format::DEPTH_STENCIL) + if (ccMTLTexture->getFormat() == Format::DEPTH_STENCIL) descriptor.stencilAttachment.texture = ccMTLTexture->getMTLTexture(); } else { - auto* ccMTLTexture = static_cast(colorTextures[subpass.depthStencil]); + auto *ccMTLTexture = static_cast(colorTextures[subpass.depthStencil]); descriptor.depthAttachment.texture = ccMTLTexture->getMTLTexture(); - if(ccMTLTexture->getFormat() == Format::DEPTH_STENCIL) + if (ccMTLTexture->getFormat() == Format::DEPTH_STENCIL) descriptor.stencilAttachment.texture = ccMTLTexture->getMTLTexture(); } - if(subpass.depthStencilResolve != INVALID_BINDING) { - const CCMTLTexture* dsResolveTex = nullptr; - if(subpass.depthStencilResolve >= colorTextures.size()) { + if (subpass.depthStencilResolve != INVALID_BINDING) { + const CCMTLTexture *dsResolveTex = nullptr; + if (subpass.depthStencilResolve >= colorTextures.size()) { dsResolveTex = static_cast(curFBO->getDepthStencilTexture()); } else { dsResolveTex = static_cast(colorTextures[subpass.depthStencilResolve]); } - descriptor.depthAttachment.resolveTexture = dsResolveTex->getMTLTexture(); - descriptor.depthAttachment.resolveLevel = 0; - descriptor.depthAttachment.resolveSlice = 0; + descriptor.depthAttachment.resolveTexture = dsResolveTex->getMTLTexture(); + descriptor.depthAttachment.resolveLevel = 0; + descriptor.depthAttachment.resolveSlice = 0; descriptor.depthAttachment.resolveDepthPlane = 0; - descriptor.depthAttachment.storeAction = subpass.depthResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; + descriptor.depthAttachment.storeAction = subpass.depthResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; - descriptor.stencilAttachment.resolveTexture = dsResolveTex->getMTLTexture(); - descriptor.stencilAttachment.resolveLevel = 0; - descriptor.stencilAttachment.resolveSlice = 0; + descriptor.stencilAttachment.resolveTexture = dsResolveTex->getMTLTexture(); + descriptor.stencilAttachment.resolveLevel = 0; + descriptor.stencilAttachment.resolveSlice = 0; descriptor.stencilAttachment.resolveDepthPlane = 0; - descriptor.stencilAttachment.storeAction = subpass.stencilResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; + descriptor.stencilAttachment.storeAction = subpass.stencilResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; descriptor.depthAttachment.depthResolveFilter = mu::toMTLDepthResolveMode(subpass.depthResolveMode); if (@available(iOS 12.0, *)) { @@ -310,13 +308,12 @@ void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDe } void CCMTLCommandBuffer::bindPipelineState(PipelineState *pso) { - PipelineBindPoint bindPoint = pso->getBindPoint(); - CCMTLGPUPipelineState* pplState = nullptr; - auto* ccPipeline = static_cast(pso); + PipelineBindPoint bindPoint = pso->getBindPoint(); + CCMTLGPUPipelineState *pplState = nullptr; + auto * ccPipeline = static_cast(pso); if (bindPoint == PipelineBindPoint::GRAPHICS) { - ccPipeline->check(_gpuCommandBufferObj->renderPass); - pplState = ccPipeline->getGPUPipelineState(); + pplState = ccPipeline->getGPUPipelineState(); _mtlPrimitiveType = pplState->primitiveType; _renderEncoder.setCullMode(pplState->cullMode); @@ -397,33 +394,33 @@ void CCMTLCommandBuffer::setStencilCompareMask(StencilFace /*face*/, uint /*ref* } void CCMTLCommandBuffer::nextSubpass() { - CCMTLRenderPass* curRenderPass = _gpuCommandBufferObj->renderPass; - if(curRenderPass) { - auto *ccRenderpass = static_cast(curRenderPass); + CCMTLRenderPass *curRenderPass = _gpuCommandBufferObj->renderPass; + if (curRenderPass) { + auto *ccRenderpass = static_cast(curRenderPass); ccRenderpass->nextSubpass(); // with framebuffer fetch enabled we can get texture as attachments by color[n] (except mac before m1), // otherwise setFragmentTexture manually. bool setTexNeeded = !mu::isFramebufferFetchSupported(); - if(setTexNeeded) { + if (setTexNeeded) { _renderEncoder.endEncoding(); - uint curSubpassIndex = ccRenderpass->getCurrentSubpassIndex(); - auto *mtlRenderPassDescriptor = ccRenderpass->getMTLRenderPassDescriptor(); - const auto &colorAttachments = curRenderPass->getColorAttachments(); - const auto colorAttachmentCount = colorAttachments.size(); + uint curSubpassIndex = ccRenderpass->getCurrentSubpassIndex(); + auto * mtlRenderPassDescriptor = ccRenderpass->getMTLRenderPassDescriptor(); + const auto &colorAttachments = curRenderPass->getColorAttachments(); + const auto colorAttachmentCount = colorAttachments.size(); for (size_t slot = 0U; slot < colorAttachmentCount; slot++) { - mtlRenderPassDescriptor.colorAttachments[slot].loadAction = MTLLoadActionLoad;// mu::toMTLLoadAction(colorAttachments[slot].loadOp); + mtlRenderPassDescriptor.colorAttachments[slot].loadAction = MTLLoadActionLoad; // mu::toMTLLoadAction(colorAttachments[slot].loadOp); mtlRenderPassDescriptor.colorAttachments[slot].storeAction = mu::toMTLStoreAction(colorAttachments[slot].storeOp); } updateDepthStencilState(curSubpassIndex, mtlRenderPassDescriptor); _renderEncoder.initialize(_gpuCommandBufferObj->mtlCommandBuffer, ccRenderpass->getMTLRenderPassDescriptor()); - const TextureList &colorTextures = _gpuCommandBufferObj->fbo->getColorTextures(); - const SubpassInfoList& subpasses = curRenderPass->getSubpasses(); - if(!subpasses.empty()) { - const auto& inputs = subpasses[curSubpassIndex].inputs; + const TextureList & colorTextures = _gpuCommandBufferObj->fbo->getColorTextures(); + const SubpassInfoList &subpasses = curRenderPass->getSubpasses(); + if (!subpasses.empty()) { + const auto &inputs = subpasses[curSubpassIndex].inputs; for (size_t i = 0; i < inputs.size(); i++) { - const uint input = inputs[i]; - auto *ccMtlTexture = static_cast(colorTextures[input]); + const uint input = inputs[i]; + auto * ccMtlTexture = static_cast(colorTextures[input]); _renderEncoder.setFragmentTexture(ccMtlTexture->getMTLTexture(), input); } } @@ -435,10 +432,10 @@ void CCMTLCommandBuffer::draw(const DrawInfo &info) { if (_firstDirtyDescriptorSet < _GPUDescriptorSets.size()) { bindDescriptorSets(); } - CCMTLInputAssembler* inputAssembler = _gpuCommandBufferObj->inputAssembler; - const auto *indirectBuffer = static_cast(inputAssembler->getIndirectBuffer()); - const auto *indexBuffer = static_cast(inputAssembler->getIndexBuffer()); - auto mtlEncoder = _renderEncoder.getMTLEncoder(); + CCMTLInputAssembler *inputAssembler = _gpuCommandBufferObj->inputAssembler; + const auto * indirectBuffer = static_cast(inputAssembler->getIndirectBuffer()); + const auto * indexBuffer = static_cast(inputAssembler->getIndexBuffer()); + auto mtlEncoder = _renderEncoder.getMTLEncoder(); if (indirectBuffer) { const auto indirectMTLBuffer = indirectBuffer->getMTLBuffer(); @@ -616,7 +613,7 @@ void CCMTLCommandBuffer::copyBuffersToTexture(const uint8_t *const *buffers, Tex CC_FREE(convertedData); } } - if (hasFlag(static_cast(texture)->textureInfo().flags, TextureFlags::GEN_MIPMAP) && mu::pixelFormatIsColorRenderable(convertedFormat)) { + if (hasFlag(static_cast(texture)->textureInfo().flags, TextureFlags::GEN_MIPMAP) && mu::pixelFormatIsColorRenderable(convertedFormat)) { [encoder generateMipmapsForTexture:dstTexture]; } [encoder endEncoding]; @@ -632,9 +629,9 @@ void CCMTLCommandBuffer::execute(CommandBuffer *const *commandBuffs, uint32_t co } void CCMTLCommandBuffer::bindDescriptorSets() { - CCMTLInputAssembler* inputAssembler = _gpuCommandBufferObj->inputAssembler; - CCMTLGPUPipelineState* pipelineStateObj = _gpuCommandBufferObj->pipelineState->getGPUPipelineState(); - const auto &vertexBuffers = inputAssembler->getVertexBuffers(); + CCMTLInputAssembler * inputAssembler = _gpuCommandBufferObj->inputAssembler; + CCMTLGPUPipelineState *pipelineStateObj = _gpuCommandBufferObj->pipelineState->getGPUPipelineState(); + const auto & vertexBuffers = inputAssembler->getVertexBuffers(); for (const auto &bindingInfo : pipelineStateObj->vertexBufferBindingInfo) { auto index = std::get<0>(bindingInfo); auto stream = std::get<1>(bindingInfo); @@ -704,88 +701,86 @@ void CCMTLCommandBuffer::bindDescriptorSets() { void CCMTLCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint count, Filter filter) { if (srcTexture && dstTexture && regions) { - - bool cmdActivated = _gpuCommandBufferObj->mtlCommandBuffer; + bool cmdActivated = _gpuCommandBufferObj->mtlCommandBuffer; id mtlCmdBuffer = nil; - if(cmdActivated) { + if (cmdActivated) { mtlCmdBuffer = _gpuCommandBufferObj->mtlCommandBuffer; } else { - mtlCmdBuffer = [static_cast(_queue)->gpuQueueObj()->mtlCommandQueue commandBufferWithUnretainedReferences]; + mtlCmdBuffer = [static_cast(_queue)->gpuQueueObj()->mtlCommandQueue commandBufferWithUnretainedReferences]; [mtlCmdBuffer enqueue]; } - auto* ccSrcTex = static_cast(srcTexture); - auto* ccDstTex = static_cast(dstTexture); + auto *ccSrcTex = static_cast(srcTexture); + auto *ccDstTex = static_cast(dstTexture); - id src = nil; - if(ccSrcTex->swapChain()) { + id src = nil; + if (ccSrcTex->swapChain()) { src = ccSrcTex->swapChain()->currentDrawable().texture; } else { src = ccSrcTex->getMTLTexture(); } - id dst = nil; - if(ccDstTex->swapChain()) { + id dst = nil; + if (ccDstTex->swapChain()) { dst = ccDstTex->swapChain()->currentDrawable().texture; } else { dst = ccDstTex->getMTLTexture(); } - + id mtlDevice = static_cast>(_mtlDevice->getMTLDevice()); - + //format conversion MTLTextureDescriptor *descriptor = [[MTLTextureDescriptor alloc] init]; - descriptor.width = src.width; - descriptor.height = src.height; - descriptor.depth = src.depth; - descriptor.pixelFormat = dst.pixelFormat; - descriptor.textureType = src.textureType; - descriptor.usage = MTLTextureUsageShaderWrite | MTLTextureUsageShaderRead; - descriptor.storageMode = MTLStorageModePrivate; - + descriptor.width = src.width; + descriptor.height = src.height; + descriptor.depth = src.depth; + descriptor.pixelFormat = dst.pixelFormat; + descriptor.textureType = src.textureType; + descriptor.usage = MTLTextureUsageShaderWrite | MTLTextureUsageShaderRead; + descriptor.storageMode = MTLStorageModePrivate; + // 1. format conversion - id formatTex = [mtlDevice newTextureWithDescriptor:descriptor]; - MPSImageConversion *conversion = [[MPSImageConversion alloc] initWithDevice: mtlDevice srcAlpha:MPSAlphaTypeNonPremultiplied destAlpha:MPSAlphaTypeNonPremultiplied backgroundColor:nil conversionInfo:nil]; + id formatTex = [mtlDevice newTextureWithDescriptor:descriptor]; + MPSImageConversion *conversion = [[MPSImageConversion alloc] initWithDevice:mtlDevice srcAlpha:MPSAlphaTypeNonPremultiplied destAlpha:MPSAlphaTypeNonPremultiplied backgroundColor:nil conversionInfo:nil]; [conversion encodeToCommandBuffer:mtlCmdBuffer sourceTexture:src destinationTexture:formatTex]; [conversion release]; - + double scaleFactorW = [dst width] / (double)[src width]; double scaleFactorH = [dst height] / (double)[src height]; double scaleFactorD = [dst depth] / (double)[src depth]; - + double uniformScale = scaleFactorW > scaleFactorH ? scaleFactorW : scaleFactorH; - + id sizeTex = formatTex; - if([dst width] > [src width] || [dst height] > [src height]) { + if ([dst width] > [src width] || [dst height] > [src height]) { // 2. size conversion - descriptor.width = dst.width; - descriptor.height = dst.height; - descriptor.depth = dst.depth; + descriptor.width = dst.width; + descriptor.height = dst.height; + descriptor.depth = dst.depth; descriptor.pixelFormat = dst.pixelFormat; descriptor.textureType = dst.textureType; - descriptor.usage = MTLTextureUsageShaderWrite; - + descriptor.usage = MTLTextureUsageShaderWrite; + sizeTex = [mtlDevice newTextureWithDescriptor:descriptor]; - + MPSImageLanczosScale *imgScale = [[MPSImageLanczosScale alloc] initWithDevice:mtlDevice]; - - MPSScaleTransform scale {uniformScale, uniformScale, 0, 0}; + + MPSScaleTransform scale{uniformScale, uniformScale, 0, 0}; [imgScale setScaleTransform:&scale]; [imgScale encodeToCommandBuffer:mtlCmdBuffer sourceTexture:formatTex destinationTexture:sizeTex]; [imgScale release]; [formatTex release]; - } - + //blit id encoder = [mtlCmdBuffer blitCommandEncoder]; for (uint i = 0; i < count; ++i) { // source region scale - uint32_t width = (uint32_t)(regions[i].srcExtent.width * scaleFactorW); + uint32_t width = (uint32_t)(regions[i].srcExtent.width * scaleFactorW); uint32_t height = (uint32_t)(regions[i].srcExtent.height * scaleFactorH); - uint32_t depth = (uint32_t)(regions[i].srcExtent.depth * scaleFactorD); - uint32_t x = (uint32_t)(regions[i].srcOffset.x * scaleFactorW); - uint32_t y = (uint32_t)(regions[i].srcOffset.y * scaleFactorH); - uint32_t z = (uint32_t)(regions[i].srcOffset.z * scaleFactorD); + uint32_t depth = (uint32_t)(regions[i].srcExtent.depth * scaleFactorD); + uint32_t x = (uint32_t)(regions[i].srcOffset.x * scaleFactorW); + uint32_t y = (uint32_t)(regions[i].srcOffset.y * scaleFactorH); + uint32_t z = (uint32_t)(regions[i].srcOffset.z * scaleFactorD); [encoder copyFromTexture:sizeTex sourceSlice:regions[i].srcSubres.baseArrayLayer sourceLevel:regions[i].srcSubres.mipLevel @@ -797,12 +792,12 @@ void CCMTLCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, c destinationOrigin:MTLOriginMake(regions[i].dstOffset.x, regions[i].dstOffset.y, regions[i].dstOffset.z)]; } [encoder endEncoding]; - + [sizeTex release]; - + [descriptor release]; - if(!cmdActivated) { + if (!cmdActivated) { [mtlCmdBuffer commit]; } } @@ -826,18 +821,18 @@ void CCMTLCommandBuffer::pipelineBarrier(const GlobalBarrier *barrier, const Tex } void CCMTLCommandBuffer::copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *regions, uint count) { - auto *ccMTLTexture = static_cast(src); - Format convertedFormat = ccMTLTexture->getConvertedFormat(); - id mtlTexture = ccMTLTexture->getMTLTexture(); + auto * ccMTLTexture = static_cast(src); + Format convertedFormat = ccMTLTexture->getConvertedFormat(); + id mtlTexture = ccMTLTexture->getMTLTexture(); for (size_t i = 0; i < count; ++i) { - uint32_t width = regions[i].texExtent.width; - uint32_t height = regions[i].texExtent.height; - uint32_t depth = regions[i].texExtent.depth; - uint32_t bytesPerRow = mu::getBytesPerRow(convertedFormat, width); - uint32_t bytesPerImage = formatSize(convertedFormat, width, height, depth); - const Offset& origin = regions[i].texOffset; - const Extent& extent = regions[i].texExtent; + uint32_t width = regions[i].texExtent.width; + uint32_t height = regions[i].texExtent.height; + uint32_t depth = regions[i].texExtent.depth; + uint32_t bytesPerRow = mu::getBytesPerRow(convertedFormat, width); + uint32_t bytesPerImage = formatSize(convertedFormat, width, height, depth); + const Offset &origin = regions[i].texOffset; + const Extent &extent = regions[i].texExtent; [mtlTexture getBytes:buffers[i] bytesPerRow:bytesPerRow @@ -845,7 +840,6 @@ void CCMTLCommandBuffer::copyTextureToBuffers(Texture *src, uint8_t *const *buff fromRegion:{MTLOriginMake(origin.x, origin.y, origin.z), MTLSizeMake(extent.width, extent.height, extent.depth)} mipmapLevel:regions[i].texSubres.mipLevel slice:regions[i].texSubres.baseArrayLayer]; - } } diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.h b/native/cocos/renderer/gfx-metal/MTLDevice.h index ea54d669f4..1f3b59bf0e 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.h +++ b/native/cocos/renderer/gfx-metal/MTLDevice.h @@ -25,8 +25,9 @@ #pragma once -#import "gfx-base/GFXDevice.h" #import "MTLConfig.h" +#import "gfx-base/GFXDevice.h" + namespace cc { namespace gfx { @@ -45,7 +46,7 @@ public: ~CCMTLDevice(); CCMTLDevice(const CCMTLDevice &) = delete; - CCMTLDevice(CCMTLDevice &&) = delete; + CCMTLDevice(CCMTLDevice &&) = delete; CCMTLDevice &operator=(const CCMTLDevice &) = delete; CCMTLDevice &operator=(CCMTLDevice &&) = delete; @@ -58,6 +59,7 @@ public: using Device::createInputAssembler; using Device::createPipelineLayout; using Device::createPipelineState; + using Device::createQueryPool; using Device::createQueue; using Device::createRenderPass; using Device::createShader; @@ -68,72 +70,74 @@ public: void onPresentCompleted(); - inline void *getMTLCommandQueue() const { return _mtlCommandQueue; } - inline void *getMTLDevice() const { return _mtlDevice; } - inline uint getMaximumSamplerUnits() const { return _maxSamplerUnits; } - inline uint getMaximumColorRenderTargets() const { return _caps.maxColorRenderTargets; } - inline uint getMaximumBufferBindingIndex() const { return _maxBufferBindingIndex; } - inline bool isIndirectCommandBufferSupported() const { return _icbSuppored; } - inline bool isIndirectDrawSupported() const { return _indirectDrawSupported; } + inline void * getMTLCommandQueue() const { return _mtlCommandQueue; } + inline void * getMTLDevice() const { return _mtlDevice; } + inline uint getMaximumSamplerUnits() const { return _maxSamplerUnits; } + inline uint getMaximumColorRenderTargets() const { return _caps.maxColorRenderTargets; } + inline uint getMaximumBufferBindingIndex() const { return _maxBufferBindingIndex; } + inline bool isIndirectCommandBufferSupported() const { return _icbSuppored; } + inline bool isIndirectDrawSupported() const { return _indirectDrawSupported; } inline CCMTLGPUStagingBufferPool *gpuStagingBufferPool() const { return _gpuStagingBufferPools[_currentFrameIndex]; } - inline bool isSamplerDescriptorCompareFunctionSupported() const { return _isSamplerDescriptorCompareFunctionSupported; } - inline uint currentFrameIndex() const { return _currentFrameIndex; } + inline bool isSamplerDescriptorCompareFunctionSupported() const { return _isSamplerDescriptorCompareFunctionSupported; } + inline uint currentFrameIndex() const { return _currentFrameIndex; } - inline void registerSwapchain(CCMTLSwapchain* swapchain) { _swapchains.push_back(swapchain); } - inline void unRegisterSwapchain(CCMTLSwapchain* swapchain) { + inline void registerSwapchain(CCMTLSwapchain *swapchain) { _swapchains.push_back(swapchain); } + inline void unRegisterSwapchain(CCMTLSwapchain *swapchain) { auto iter = std::find(_swapchains.begin(), _swapchains.end(), swapchain); - if(iter != _swapchains.end()) { + if (iter != _swapchains.end()) { _swapchains.erase(iter); } } protected: - static CCMTLDevice * _instance; + static CCMTLDevice *_instance; friend class DeviceManager; - bool doInit(const DeviceInfo &info) override; - void doDestroy() override; - CommandBuffer *createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; - Queue *createQueue() override; - Buffer *createBuffer() override; - Texture *createTexture() override; - Shader *createShader() override; - InputAssembler *createInputAssembler() override; - RenderPass *createRenderPass() override; - Framebuffer *createFramebuffer() override; - DescriptorSet *createDescriptorSet() override; + bool doInit(const DeviceInfo &info) override; + void doDestroy() override; + CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; + Queue * createQueue() override; + QueryPool * createQueryPool() override; + Buffer * createBuffer() override; + Texture * createTexture() override; + Shader * createShader() override; + InputAssembler * createInputAssembler() override; + RenderPass * createRenderPass() override; + Framebuffer * createFramebuffer() override; + DescriptorSet * createDescriptorSet() override; DescriptorSetLayout *createDescriptorSetLayout() override; - PipelineLayout *createPipelineLayout() override; - PipelineState *createPipelineState() override; - GlobalBarrier *createGlobalBarrier(const GlobalBarrierInfo &info, size_t hash) override; - TextureBarrier *createTextureBarrier(const TextureBarrierInfo& info, size_t hash) override; - Sampler *createSampler(const SamplerInfo& info, size_t hash) override; - Swapchain *createSwapchain() override; - void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; - void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; + PipelineLayout *createPipelineLayout() override; + PipelineState *createPipelineState() override; + GlobalBarrier *createGlobalBarrier(const GlobalBarrierInfo &info, size_t hash) override; + TextureBarrier *createTextureBarrier(const TextureBarrierInfo& info, size_t hash) override; + Sampler *createSampler(const SamplerInfo& info, size_t hash) override; + Swapchain *createSwapchain() override; + void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) override; + void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint count) override; + void getQueryPoolResults(QueryPool *queryPool) override {} void onMemoryWarning(); - void *_autoreleasePool = nullptr; - void *_mtlCommandQueue = nullptr; - void *_mtlDevice = nullptr; - void *_activeDrawable = nullptr; - unsigned long _mtlFeatureSet = 0; - uint _maxSamplerUnits = 0; - uint _maxBufferBindingIndex = 0; - bool _icbSuppored = false; - bool _indirectDrawSupported = false; - bool _isSamplerDescriptorCompareFunctionSupported = false; + void * _autoreleasePool = nullptr; + void * _mtlCommandQueue = nullptr; + void * _mtlDevice = nullptr; + void * _activeDrawable = nullptr; + unsigned long _mtlFeatureSet = 0; + uint _maxSamplerUnits = 0; + uint _maxBufferBindingIndex = 0; + bool _icbSuppored = false; + bool _indirectDrawSupported = false; + bool _isSamplerDescriptorCompareFunctionSupported = false; CCMTLGPUStagingBufferPool *_gpuStagingBufferPools[MAX_FRAMES_IN_FLIGHT] = {nullptr}; - uint _currentBufferPoolId = 0; - uint _currentFrameIndex = 0; - CCMTLSemaphore *_inFlightSemaphore = nullptr; - CC_UNUSED uint32_t _memoryAlarmListenerId = 0; + uint _currentBufferPoolId = 0; + uint _currentFrameIndex = 0; + CCMTLSemaphore * _inFlightSemaphore = nullptr; + CC_UNUSED uint32_t _memoryAlarmListenerId = 0; - std::vector _swapchains; + std::vector _swapchains; - CCMTLGPUDeviceObject* _gpuDeviceObj = nullptr; + CCMTLGPUDeviceObject *_gpuDeviceObj = nullptr; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index 9031fbd54b..0ac250d119 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -32,9 +32,11 @@ #import "MTLDescriptorSetLayout.h" #import "MTLDevice.h" #import "MTLFramebuffer.h" +#import "MTLGPUObjects.h" #import "MTLInputAssembler.h" #import "MTLPipelineLayout.h" #import "MTLPipelineState.h" +#import "MTLQueryPool.h" #import "MTLQueue.h" #import "MTLRenderPass.h" #import "MTLSampler.h" @@ -44,7 +46,7 @@ #import "MTLTexture.h" #import "cocos/bindings/event/CustomEventTypes.h" #import "cocos/bindings/event/EventDispatcher.h" -#import "MTLGPUObjects.h" + namespace cc { namespace gfx { @@ -56,12 +58,13 @@ CCMTLDevice *CCMTLDevice::getInstance() { } CCMTLDevice::CCMTLDevice() { - _api = API::METAL; + _api = API::METAL; _deviceName = "Metal"; - _caps.clipSpaceMinZ = 0.0f; + _caps.supportQuery = false; + _caps.clipSpaceMinZ = 0.0f; _caps.screenSpaceSignY = -1.0f; - _caps.clipSpaceSignY = 1.0f; + _caps.clipSpaceSignY = 1.0f; CCMTLDevice::_instance = this; } @@ -71,45 +74,36 @@ CCMTLDevice::~CCMTLDevice() { } bool CCMTLDevice::doInit(const DeviceInfo &info) { - _gpuDeviceObj = CC_NEW(CCMTLGPUDeviceObject); + _gpuDeviceObj = CC_NEW(CCMTLGPUDeviceObject); _inFlightSemaphore = CC_NEW(CCMTLSemaphore(MAX_FRAMES_IN_FLIGHT)); _currentFrameIndex = 0; id mtlDevice = MTLCreateSystemDefaultDevice(); - _mtlDevice = mtlDevice; + _mtlDevice = mtlDevice; - _mtlFeatureSet = mu::highestSupportedFeatureSet(mtlDevice); - const auto gpuFamily = mu::getGPUFamily(MTLFeatureSet(_mtlFeatureSet)); - _indirectDrawSupported = mu::isIndirectDrawSupported(gpuFamily); + _mtlFeatureSet = mu::highestSupportedFeatureSet(mtlDevice); + const auto gpuFamily = mu::getGPUFamily(MTLFeatureSet(_mtlFeatureSet)); + _indirectDrawSupported = mu::isIndirectDrawSupported(gpuFamily); _caps.maxVertexAttributes = mu::getMaxVertexAttributes(gpuFamily); _caps.maxTextureUnits = _caps.maxVertexTextureUnits = mu::getMaxEntriesInTextureArgumentTable(gpuFamily); - _maxSamplerUnits = mu::getMaxEntriesInSamplerStateArgumentTable(gpuFamily); - _caps.maxTextureSize = mu::getMaxTexture2DWidthHeight(gpuFamily); - _caps.maxCubeMapTextureSize = mu::getMaxCubeMapTextureWidthHeight(gpuFamily); - _caps.maxColorRenderTargets = mu::getMaxColorRenderTarget(gpuFamily); - _caps.uboOffsetAlignment = mu::getMinBufferOffsetAlignment(gpuFamily); - _caps.maxComputeWorkGroupInvocations = mu::getMaxThreadsPerGroup(gpuFamily); - _caps.maxVertexUniformVectors = 255;//no explicit limit on vertex stage. - _maxBufferBindingIndex = mu::getMaxEntriesInBufferArgumentTable(gpuFamily); - _icbSuppored = mu::isIndirectCommandBufferSupported(MTLFeatureSet(_mtlFeatureSet)); - _isSamplerDescriptorCompareFunctionSupported = mu::isSamplerDescriptorCompareFunctionSupported(gpuFamily); - - QueueInfo queueInfo; - queueInfo.type = QueueType::GRAPHICS; - _queue = createQueue(queueInfo); - - CommandBufferInfo cmdBuffInfo; - cmdBuffInfo.type = CommandBufferType::PRIMARY; - cmdBuffInfo.queue = _queue; - _cmdBuff = createCommandBuffer(cmdBuffInfo); + _maxSamplerUnits = mu::getMaxEntriesInSamplerStateArgumentTable(gpuFamily); + _caps.maxTextureSize = mu::getMaxTexture2DWidthHeight(gpuFamily); + _caps.maxCubeMapTextureSize = mu::getMaxCubeMapTextureWidthHeight(gpuFamily); + _caps.maxColorRenderTargets = mu::getMaxColorRenderTarget(gpuFamily); + _caps.uboOffsetAlignment = mu::getMinBufferOffsetAlignment(gpuFamily); + _caps.maxComputeWorkGroupInvocations = mu::getMaxThreadsPerGroup(gpuFamily); + _caps.maxVertexUniformVectors = 255; //no explicit limit on vertex stage. + _maxBufferBindingIndex = mu::getMaxEntriesInBufferArgumentTable(gpuFamily); + _icbSuppored = mu::isIndirectCommandBufferSupported(MTLFeatureSet(_mtlFeatureSet)); + _isSamplerDescriptorCompareFunctionSupported = mu::isSamplerDescriptorCompareFunctionSupported(gpuFamily); for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) { _gpuStagingBufferPools[i] = CC_NEW(CCMTLGPUStagingBufferPool(mtlDevice)); } - _features[toNumber(Feature::COLOR_FLOAT)] = mu::isColorBufferFloatSupported(gpuFamily); - _features[toNumber(Feature::COLOR_HALF_FLOAT)] = mu::isColorBufferHalfFloatSupported(gpuFamily); - _features[toNumber(Feature::TEXTURE_FLOAT_LINEAR)] = mu::isLinearTextureSupported(gpuFamily); + _features[toNumber(Feature::COLOR_FLOAT)] = mu::isColorBufferFloatSupported(gpuFamily); + _features[toNumber(Feature::COLOR_HALF_FLOAT)] = mu::isColorBufferHalfFloatSupported(gpuFamily); + _features[toNumber(Feature::TEXTURE_FLOAT_LINEAR)] = mu::isLinearTextureSupported(gpuFamily); _features[toNumber(Feature::TEXTURE_HALF_FLOAT_LINEAR)] = mu::isLinearTextureSupported(gpuFamily); String compressedFormats; @@ -130,20 +124,32 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { compressedFormats += "dxt "; } - _features[toNumber(Feature::TEXTURE_FLOAT)] = true; - _features[toNumber(Feature::TEXTURE_HALF_FLOAT)] = true; - _features[toNumber(Feature::FORMAT_R11G11B10F)] = true; - _features[toNumber(Feature::FORMAT_SRGB)] = true; - _features[toNumber(Feature::INSTANCED_ARRAYS)] = true; - _features[toNumber(Feature::MULTIPLE_RENDER_TARGETS)] = true; - _features[toNumber(Feature::BLEND_MINMAX)] = true; - _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; - _features[toNumber(Feature::COMPUTE_SHADER)] = true; + _features[toNumber(Feature::TEXTURE_FLOAT)] = true; + _features[toNumber(Feature::TEXTURE_HALF_FLOAT)] = true; + _features[toNumber(Feature::FORMAT_R11G11B10F)] = true; + _features[toNumber(Feature::FORMAT_SRGB)] = true; + _features[toNumber(Feature::INSTANCED_ARRAYS)] = true; + _features[toNumber(Feature::MULTIPLE_RENDER_TARGETS)] = true; + _features[toNumber(Feature::BLEND_MINMAX)] = true; + _features[toNumber(Feature::ELEMENT_INDEX_UINT)] = true; + _features[toNumber(Feature::COMPUTE_SHADER)] = true; _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = true; _features[toNumber(Feature::FORMAT_RGB8)] = false; -// _memoryAlarmListenerId = EventDispatcher::addCustomEventListener(EVENT_MEMORY_WARNING, std::bind(&CCMTLDevice::onMemoryWarning, this)); + QueueInfo queueInfo; + queueInfo.type = QueueType::GRAPHICS; + _queue = createQueue(queueInfo); + + QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS}; + _queryPool = createQueryPool(queryPoolInfo); + + CommandBufferInfo cmdBuffInfo; + cmdBuffInfo.type = CommandBufferType::PRIMARY; + cmdBuffInfo.queue = _queue; + _cmdBuff = createCommandBuffer(cmdBuffInfo); + + // _memoryAlarmListenerId = EventDispatcher::addCustomEventListener(EVENT_MEMORY_WARNING, std::bind(&CCMTLDevice::onMemoryWarning, this)); CCMTLGPUGarbageCollectionPool::getInstance()->initialize(std::bind(&CCMTLDevice::currentFrameIndex, this)); @@ -153,15 +159,15 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { } void CCMTLDevice::doDestroy() { -// if (_memoryAlarmListenerId != 0) { -// EventDispatcher::removeCustomEventListener(EVENT_MEMORY_WARNING, _memoryAlarmListenerId); -// _memoryAlarmListenerId = 0; -// } + // if (_memoryAlarmListenerId != 0) { + // EventDispatcher::removeCustomEventListener(EVENT_MEMORY_WARNING, _memoryAlarmListenerId); + // _memoryAlarmListenerId = 0; + // } CC_DELETE(_gpuDeviceObj); if (_autoreleasePool) { - [(NSAutoreleasePool*)_autoreleasePool drain]; + [(NSAutoreleasePool *)_autoreleasePool drain]; _autoreleasePool = nullptr; } @@ -171,6 +177,7 @@ void CCMTLDevice::doDestroy() { _inFlightSemaphore->syncAll(); } + CC_SAFE_DESTROY(_queryPool) CC_SAFE_DESTROY(_queue); CC_SAFE_DESTROY(_cmdBuff); CC_SAFE_DELETE(_inFlightSemaphore); @@ -189,16 +196,16 @@ void CCMTLDevice::doDestroy() { void CCMTLDevice::acquire(Swapchain *const *swapchains, uint32_t count) { _inFlightSemaphore->wait(); - for (CCMTLSwapchain* swapchain : _swapchains) { + for (CCMTLSwapchain *swapchain : _swapchains) { swapchain->acquire(); } if (!_autoreleasePool) { _autoreleasePool = [[NSAutoreleasePool alloc] init]; -// CC_LOG_INFO("POOL: %p ALLOCED", _autoreleasePool); + // CC_LOG_INFO("POOL: %p ALLOCED", _autoreleasePool); } // Clear queue stats - CCMTLQueue *queue = static_cast(_queue); + CCMTLQueue *queue = static_cast(_queue); queue->gpuQueueObj()->numDrawCalls = 0; queue->gpuQueueObj()->numInstances = 0; queue->gpuQueueObj()->numTriangles = 0; @@ -206,18 +213,18 @@ void CCMTLDevice::acquire(Swapchain *const *swapchains, uint32_t count) { void CCMTLDevice::present() { CCMTLQueue *queue = (CCMTLQueue *)_queue; - _numDrawCalls = queue->gpuQueueObj()->numDrawCalls; - _numInstances = queue->gpuQueueObj()->numInstances; - _numTriangles = queue->gpuQueueObj()->numTriangles; + _numDrawCalls = queue->gpuQueueObj()->numDrawCalls; + _numInstances = queue->gpuQueueObj()->numInstances; + _numTriangles = queue->gpuQueueObj()->numTriangles; //hold this pointer before update _currentFrameIndex _currentBufferPoolId = _currentFrameIndex; _currentFrameIndex = (_currentFrameIndex + 1) % MAX_FRAMES_IN_FLIGHT; std::vector> releaseQ; - for (auto* swapchain: _swapchains) { + for (auto *swapchain : _swapchains) { auto drawable = swapchain->currentDrawable(); - if(drawable) { + if (drawable) { releaseQ.push_back([drawable retain]); } swapchain->release(); @@ -229,7 +236,7 @@ void CCMTLDevice::present() { [cmdBuffer enqueue]; - for (auto drawable: releaseQ) { + for (auto drawable : releaseQ) { [cmdBuffer presentDrawable:drawable]; [drawable release]; } @@ -242,8 +249,8 @@ void CCMTLDevice::present() { }); if (_autoreleasePool) { -// CC_LOG_INFO("POOL: %p RELEASED", _autoreleasePool); - [(NSAutoreleasePool*)_autoreleasePool drain]; + // CC_LOG_INFO("POOL: %p RELEASED", _autoreleasePool); + [(NSAutoreleasePool *)_autoreleasePool drain]; _autoreleasePool = nullptr; } } @@ -263,6 +270,10 @@ Queue *CCMTLDevice::createQueue() { return CC_NEW(CCMTLQueue); } +QueryPool *CCMTLDevice::createQueryPool() { + return CC_NEW(CCMTLQueryPool); +} + CommandBuffer *CCMTLDevice::createCommandBuffer(const CommandBufferInfo &info, bool /*hasAgent*/) { return CC_NEW(CCMTLCommandBuffer); } diff --git a/native/cocos/renderer/gfx-metal/MTLQueryPool.h b/native/cocos/renderer/gfx-metal/MTLQueryPool.h new file mode 100644 index 0000000000..5475e94b85 --- /dev/null +++ b/native/cocos/renderer/gfx-metal/MTLQueryPool.h @@ -0,0 +1,46 @@ +/**************************************************************************** + Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#pragma once + +#import "gfx-base/GFXQueryPool.h" + +namespace cc { +namespace gfx { + +class CCMTLQueryPool final : public QueryPool { +public: + CCMTLQueryPool(); + ~CCMTLQueryPool() override; + +protected: + friend class CCMTLDevice; + + void doInit(const QueryPoolInfo &info) override; + void doDestroy() override; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-metal/MTLQueryPool.mm b/native/cocos/renderer/gfx-metal/MTLQueryPool.mm new file mode 100644 index 0000000000..2123a71b81 --- /dev/null +++ b/native/cocos/renderer/gfx-metal/MTLQueryPool.mm @@ -0,0 +1,53 @@ +/**************************************************************************** + Copyright (c) 2019-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#import "MTLStd.h" + +#import "MTLCommandBuffer.h" +#import "MTLDevice.h" +#import "MTLFramebuffer.h" +#import "MTLGPUObjects.h" +#import "MTLQueryPool.h" +#import "MTLSwapchain.h" + +namespace cc { +namespace gfx { + +CCMTLQueryPool::CCMTLQueryPool() { + _typedID = generateObjectID(); +} + +CCMTLQueryPool::~CCMTLQueryPool() { + destroy(); +} + +void CCMTLQueryPool::doInit(const QueryPoolInfo& info) { +} + +void CCMTLQueryPool::doDestroy() { +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp index ae5df1cda9..40768fd8b5 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.cpp @@ -33,6 +33,7 @@ #include "FramebufferValidator.h" #include "InputAssemblerValidator.h" #include "PipelineStateValidator.h" +#include "QueryPoolValidator.h" #include "QueueValidator.h" #include "RenderPassValidator.h" #include "TextureValidator.h" @@ -61,6 +62,9 @@ void CommandBufferValidator::initValidator() { _curStates.dynamicOffsets.resize(descriptorSetCount); } +void CommandBufferValidator::destroyValidator() { +} + void CommandBufferValidator::doInit(const CommandBufferInfo &info) { initValidator(); @@ -456,5 +460,29 @@ void CommandBufferValidator::pipelineBarrier(const GlobalBarrier *barrier, const _actor->pipelineBarrier(barrier, textureBarriers, actorTextures, textureBarrierCount); } +void CommandBufferValidator::beginQuery(QueryPool *queryPool, uint32_t id) { + CCASSERT(isInited(), "already destroyed?"); + CCASSERT(static_cast(queryPool)->isInited(), "already destroyed?"); + + QueryPool *actorQueryPool = static_cast(queryPool)->getActor(); + _actor->beginQuery(actorQueryPool, id); +} + +void CommandBufferValidator::endQuery(QueryPool *queryPool, uint32_t id) { + CCASSERT(isInited(), "already destroyed?"); + CCASSERT(static_cast(queryPool)->isInited(), "already destroyed?"); + + QueryPool *actorQueryPool = static_cast(queryPool)->getActor(); + _actor->endQuery(actorQueryPool, id); +} + +void CommandBufferValidator::resetQuery(QueryPool *queryPool) { + CCASSERT(isInited(), "already destroyed?"); + CCASSERT(static_cast(queryPool)->isInited(), "already destroyed?"); + + QueryPool *actorQueryPool = static_cast(queryPool)->getActor(); + _actor->resetQuery(actorQueryPool); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h index 81c6f78888..6e6ababe30 100644 --- a/native/cocos/renderer/gfx-validator/CommandBufferValidator.h +++ b/native/cocos/renderer/gfx-validator/CommandBufferValidator.h @@ -61,6 +61,9 @@ public: void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; + void beginQuery(QueryPool *queryPool, uint32_t id) override; + void endQuery(QueryPool *queryPool, uint32_t id) override; + void resetQuery(QueryPool *queryPool) override; uint32_t getNumDrawCalls() const override { return _actor->getNumDrawCalls(); } uint32_t getNumInstances() const override { return _actor->getNumInstances(); } @@ -73,6 +76,7 @@ protected: friend class DeviceValidator; void initValidator(); + void destroyValidator(); void doInit(const CommandBufferInfo &info) override; void doDestroy() override; diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp index 4cbf8e84a7..dbfc4c027c 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.cpp +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.cpp @@ -34,6 +34,7 @@ #include "InputAssemblerValidator.h" #include "PipelineLayoutValidator.h" #include "PipelineStateValidator.h" +#include "QueryPoolValidator.h" #include "QueueValidator.h" #include "RenderPassValidator.h" #include "ShaderValidator.h" @@ -68,6 +69,7 @@ bool DeviceValidator::doInit(const DeviceInfo &info) { _api = _actor->getGfxAPI(); _deviceName = _actor->getDeviceName(); _queue = CC_NEW(QueueValidator(_actor->getQueue())); + _queryPool = CC_NEW(QueryPoolValidator(_actor->getQueryPool())); _cmdBuff = CC_NEW(CommandBufferValidator(_actor->getCommandBuffer())); _renderer = _actor->getRenderer(); _vendor = _actor->getVendor(); @@ -75,10 +77,12 @@ bool DeviceValidator::doInit(const DeviceInfo &info) { memcpy(_features.data(), _actor->_features.data(), static_cast(Feature::COUNT) * sizeof(bool)); static_cast(_queue)->_inited = true; + static_cast(_queryPool)->_inited = true; static_cast(_cmdBuff)->_queue = _queue; static_cast(_cmdBuff)->initValidator(); DeviceResourceTracker::push(_cmdBuff); + DeviceResourceTracker::push(_queryPool); DeviceResourceTracker::push(_queue); CC_LOG_INFO("Device validator enabled."); @@ -88,10 +92,16 @@ bool DeviceValidator::doInit(const DeviceInfo &info) { void DeviceValidator::doDestroy() { if (_cmdBuff) { + static_cast(_cmdBuff)->destroyValidator(); static_cast(_cmdBuff)->_actor = nullptr; CC_DELETE(_cmdBuff); _cmdBuff = nullptr; } + if (_queryPool) { + static_cast(_queryPool)->_actor = nullptr; + CC_DELETE(_queryPool); + _queryPool = nullptr; + } if (_queue) { static_cast(_queue)->_actor = nullptr; CC_DELETE(_queue); @@ -99,6 +109,7 @@ void DeviceValidator::doDestroy() { } DeviceResourceTracker::checkEmpty(); + DeviceResourceTracker::checkEmpty(); DeviceResourceTracker::checkEmpty(); DeviceResourceTracker::checkEmpty(); DeviceResourceTracker::checkEmpty(); @@ -148,6 +159,13 @@ Queue *DeviceValidator::createQueue() { return result; } +QueryPool *DeviceValidator::createQueryPool() { + QueryPool *actor = _actor->createQueryPool(); + QueryPool *result = CC_NEW(QueryPoolValidator(actor)); + DeviceResourceTracker::push(result); + return result; +} + Swapchain *DeviceValidator::createSwapchain() { Swapchain *actor = _actor->createSwapchain(); Swapchain *result = CC_NEW(SwapchainValidator(actor)); @@ -271,5 +289,16 @@ void DeviceValidator::flushCommands(CommandBuffer *const *cmdBuffs, uint32_t cou _actor->flushCommands(cmdBuffActors.data(), count); } +void DeviceValidator::getQueryPoolResults(QueryPool *queryPool) { + auto *actorQueryPool = static_cast(queryPool)->getActor(); + + _actor->getQueryPoolResults(actorQueryPool); + + auto * actorQueryPoolValidator = static_cast(actorQueryPool); + auto * queryPoolValidator = static_cast(queryPool); + std::lock_guard lock(actorQueryPoolValidator->_mutex); + queryPoolValidator->_results = actorQueryPoolValidator->_results; +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.h b/native/cocos/renderer/gfx-validator/DeviceValidator.h index 3e72eb9e2a..87e84dc46b 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.h +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.h @@ -47,6 +47,7 @@ public: using Device::createInputAssembler; using Device::createPipelineLayout; using Device::createPipelineState; + using Device::createQueryPool; using Device::createQueue; using Device::createRenderPass; using Device::createSampler; @@ -59,6 +60,7 @@ public: CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; Queue * createQueue() override; + QueryPool * createQueryPool() override; Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; @@ -77,6 +79,7 @@ public: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; + void getQueryPoolResults(QueryPool *queryPool) override; void flushCommands(CommandBuffer *const *cmdBuffs, uint32_t count) override; MemoryStatus &getMemoryStatus() override { return _actor->getMemoryStatus(); } diff --git a/native/cocos/renderer/gfx-validator/QueryPoolValidator.cpp b/native/cocos/renderer/gfx-validator/QueryPoolValidator.cpp new file mode 100644 index 0000000000..0db46e0259 --- /dev/null +++ b/native/cocos/renderer/gfx-validator/QueryPoolValidator.cpp @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#include "base/CoreStd.h" + +#include "CommandBufferValidator.h" +#include "DeviceValidator.h" +#include "QueryPoolValidator.h" +#include "ValidationUtils.h" + +namespace cc { +namespace gfx { + +QueryPoolValidator::QueryPoolValidator(QueryPool *actor) +: Agent(actor) { + _typedID = actor->getTypedID(); + _type = actor->getType(); + _maxQueryObjects = actor->getMaxQueryObjects(); +} + +QueryPoolValidator::~QueryPoolValidator() { + DeviceResourceTracker::erase(this); + CC_SAFE_DELETE(_actor); +} + +void QueryPoolValidator::doInit(const QueryPoolInfo &info) { + CCASSERT(!isInited(), "initializing twice?"); + _inited = true; + + /////////// execute /////////// + + _actor->initialize(info); +} + +void QueryPoolValidator::doDestroy() { + CCASSERT(isInited(), "destroying twice?"); + _inited = false; + + /////////// execute /////////// + + _actor->destroy(); +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-validator/QueryPoolValidator.h b/native/cocos/renderer/gfx-validator/QueryPoolValidator.h new file mode 100644 index 0000000000..3165673f1f --- /dev/null +++ b/native/cocos/renderer/gfx-validator/QueryPoolValidator.h @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#pragma once + +#include "base/Agent.h" +#include "gfx-base/GFXQueryPool.h" + +namespace cc { +namespace gfx { + +class CC_DLL QueryPoolValidator final : public Agent { +public: + explicit QueryPoolValidator(QueryPool *actor); + ~QueryPoolValidator() override; + + inline bool isInited() const { return _inited; } + +protected: + friend class DeviceValidator; + + void doInit(const QueryPoolInfo &info) override; + void doDestroy() override; + + bool _inited{false}; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp index 6ad304fba9..30510d8c0f 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp @@ -33,6 +33,7 @@ #include "VKFramebuffer.h" #include "VKInputAssembler.h" #include "VKPipelineState.h" +#include "VKQueryPool.h" #include "VKQueue.h" #include "VKRenderPass.h" #include "VKTexture.h" @@ -638,5 +639,34 @@ void CCVKCommandBuffer::pipelineBarrier(const GlobalBarrier *barrier, const Text 0, nullptr, textureBarrierCount, pImageMemoryBarriers); } +void CCVKCommandBuffer::beginQuery(QueryPool *queryPool, uint32_t /*id*/) { + auto * vkQueryPool = static_cast(queryPool); + CCVKGPUQueryPool *gpuQueryPool = vkQueryPool->gpuQueryPool(); + auto queryId = static_cast(vkQueryPool->_ids.size()); + + if (queryId < queryPool->getMaxQueryObjects()) { + vkCmdBeginQuery(_gpuCommandBuffer->vkCommandBuffer, gpuQueryPool->pool, queryId, 0); + } +} + +void CCVKCommandBuffer::endQuery(QueryPool *queryPool, uint32_t id) { + auto * vkQueryPool = static_cast(queryPool); + CCVKGPUQueryPool *gpuQueryPool = vkQueryPool->gpuQueryPool(); + auto queryId = static_cast(vkQueryPool->_ids.size()); + + if (queryId < queryPool->getMaxQueryObjects()) { + vkCmdEndQuery(_gpuCommandBuffer->vkCommandBuffer, gpuQueryPool->pool, queryId); + vkQueryPool->_ids.push_back(id); + } +} + +void CCVKCommandBuffer::resetQuery(QueryPool *queryPool) { + auto * vkQueryPool = static_cast(queryPool); + CCVKGPUQueryPool *gpuQueryPool = vkQueryPool->gpuQueryPool(); + + vkCmdResetQueryPool(_gpuCommandBuffer->vkCommandBuffer, gpuQueryPool->pool, 0, queryPool->getMaxQueryObjects()); + vkQueryPool->_ids.clear(); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h index 3997a238fd..310b139e43 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.h @@ -60,6 +60,9 @@ public: void execute(CommandBuffer *const *cmdBuffs, uint32_t count) override; void dispatch(const DispatchInfo &info) override; void pipelineBarrier(const GlobalBarrier *barrier, const TextureBarrier *const *textureBarriers, const Texture *const *textures, uint32_t textureBarrierCount) override; + void beginQuery(QueryPool *queryPool, uint32_t id) override; + void endQuery(QueryPool *queryPool, uint32_t id) override; + void resetQuery(QueryPool *queryPool) override; CCVKGPUCommandBuffer *gpuCommandBuffer() const { return _gpuCommandBuffer; } diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index 8170e1fef4..9f7de9d4f2 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -95,6 +95,14 @@ void cmdFuncCCVKGetDeviceQueue(CCVKDevice *device, CCVKGPUQueue *gpuQueue) { gpuQueue->queueFamilyIndex = gpuQueue->possibleQueueFamilyIndices[0]; } +void cmdFuncCCVKCreateQuery(CCVKDevice *device, CCVKGPUQueryPool *gpuQueryPool) { + VkQueryPoolCreateInfo queryPoolInfo = {}; + queryPoolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; + queryPoolInfo.queryType = mapVkQueryType(gpuQueryPool->type); + queryPoolInfo.queryCount = gpuQueryPool->maxQueryObjects; + VK_CHECK(vkCreateQueryPool(device->gpuDevice()->vkDevice, &queryPoolInfo, nullptr, &gpuQueryPool->pool)); +} + void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { if (!gpuTexture->size) return; @@ -1372,6 +1380,10 @@ CC_VULKAN_API void cmdFuncCCVKCopyTextureToBuffers(CCVKDevice *device, CCVKGPUTe device->gpuBarrierManager()->checkIn(srcTexture); } +void cmdFuncCCVKDestroyQuery(CCVKGPUDevice *gpuDevice, CCVKGPUQueryPool *gpuQueryPool) { + vkDestroyQueryPool(gpuDevice->vkDevice, gpuQueryPool->pool, nullptr); +} + void cmdFuncCCVKDestroyRenderPass(CCVKGPUDevice *gpuDevice, CCVKGPURenderPass *gpuRenderPass) { gpuRenderPass->beginAccesses.clear(); gpuRenderPass->endAccesses.clear(); @@ -1486,6 +1498,13 @@ void CCVKGPURecycleBin::clear() { res.vkImageView = VK_NULL_HANDLE; } break; + case RecycledType::QUERY: + if (res.gpuQueryPool) { + cmdFuncCCVKDestroyQuery(_device, res.gpuQueryPool); + CC_DELETE(res.gpuQueryPool); + res.gpuQueryPool = nullptr; + } + break; case RecycledType::RENDER_PASS: if (res.gpuRenderPass) { cmdFuncCCVKDestroyRenderPass(_device, res.gpuRenderPass); diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.h b/native/cocos/renderer/gfx-vulkan/VKCommands.h index 11e236006f..4de2869a2c 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.h +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.h @@ -33,7 +33,7 @@ namespace gfx { class CCVKDevice; CC_VULKAN_API void cmdFuncCCVKGetDeviceQueue(CCVKDevice *device, CCVKGPUQueue *gpuQueue); - +CC_VULKAN_API void cmdFuncCCVKCreateQuery(CCVKDevice *device, CCVKGPUQueryPool *gpuQueryPool); CC_VULKAN_API void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture); CC_VULKAN_API void cmdFuncCCVKCreateTextureView(CCVKDevice *device, CCVKGPUTextureView *gpuTextureView); CC_VULKAN_API void cmdFuncCCVKCreateSampler(CCVKDevice *device, CCVKGPUSampler *gpuSampler); @@ -50,6 +50,7 @@ CC_VULKAN_API void cmdFuncCCVKUpdateBuffer(CCVKDevice *device, CCVKGPUBuffer *gp CC_VULKAN_API void cmdFuncCCVKCopyBuffersToTexture(CCVKDevice *device, const uint8_t *const *buffers, CCVKGPUTexture *gpuTexture, const BufferTextureCopy *regions, uint32_t count, const CCVKGPUCommandBuffer *gpuCommandBuffer); CC_VULKAN_API void cmdFuncCCVKCopyTextureToBuffers(CCVKDevice *device, CCVKGPUTexture *srcTexture, CCVKGPUBuffer *destBuffer, const BufferTextureCopy *regions, uint32_t count, const CCVKGPUCommandBuffer *gpuCommandBuffer); +CC_VULKAN_API void cmdFuncCCVKDestroyQuery(CCVKGPUDevice *device, CCVKGPUQueryPool *gpuQueryPool); CC_VULKAN_API void cmdFuncCCVKDestroyRenderPass(CCVKGPUDevice *device, CCVKGPURenderPass *gpuRenderPass); CC_VULKAN_API void cmdFuncCCVKDestroySampler(CCVKGPUDevice *device, CCVKGPUSampler *gpuSampler); CC_VULKAN_API void cmdFuncCCVKDestroyShader(CCVKGPUDevice *device, CCVKGPUShader *gpuShader); diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index 7b313f2e73..c558249857 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -34,6 +34,7 @@ #include "VKInputAssembler.h" #include "VKPipelineLayout.h" #include "VKPipelineState.h" +#include "VKQueryPool.h" #include "VKQueue.h" #include "VKRenderPass.h" #include "VKShader.h" @@ -74,6 +75,7 @@ CCVKDevice::CCVKDevice() { _api = API::VULKAN; _deviceName = "Vulkan"; + _caps.supportQuery = true; _caps.clipSpaceMinZ = 0.0F; _caps.screenSpaceSignY = -1.0F; _caps.clipSpaceSignY = -1.0F; @@ -297,6 +299,9 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { queueInfo.type = QueueType::GRAPHICS; _queue = createQueue(queueInfo); + QueryPoolInfo queryPoolInfo{QueryType::OCCLUSION, DEFAULT_MAX_QUERY_OBJECTS}; + _queryPool = CCVKDevice::getInstance()->createQueryPool(queryPoolInfo); + CommandBufferInfo cmdBuffInfo; cmdBuffInfo.type = CommandBufferType::PRIMARY; cmdBuffInfo.queue = _queue; @@ -456,6 +461,7 @@ void CCVKDevice::doDestroy() { } _depthStencilTextures.clear(); + CC_SAFE_DESTROY(_queryPool) CC_SAFE_DESTROY(_queue) CC_SAFE_DESTROY(_cmdBuff) @@ -682,6 +688,10 @@ Queue *CCVKDevice::createQueue() { return CC_NEW(CCVKQueue); } +QueryPool *CCVKDevice::createQueryPool() { + return CC_NEW(CCVKQueryPool); +} + Swapchain *CCVKDevice::createSwapchain() { return CC_NEW(CCVKSwapchain); } @@ -779,6 +789,41 @@ void CCVKDevice::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buffe } } +void CCVKDevice::getQueryPoolResults(QueryPool *queryPool) { + auto *vkQueryPool = static_cast(queryPool); + auto queryCount = static_cast(vkQueryPool->_ids.size()); + CCASSERT(queryCount <= vkQueryPool->getMaxQueryObjects(), "Too many query commands."); + std::vector results(queryCount, 0ULL); + + if (queryCount > 0U) { + VK_CHECK(vkGetQueryPoolResults( + gpuDevice()->vkDevice, + vkQueryPool->_gpuQueryPool->pool, + 0, + queryCount, + queryCount * sizeof(uint64_t), + results.data(), + sizeof(uint64_t), + VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT)); + } + + std::unordered_map mapResults; + for (auto queryId = 0U; queryId < queryCount; queryId++) { + uint32_t id = vkQueryPool->_ids[queryId]; + auto iter = mapResults.find(id); + if (iter != mapResults.end()) { + iter->second += results[queryId]; + } else { + mapResults[id] = results[queryId]; + } + } + + { + std::lock_guard lock(vkQueryPool->_mutex); + vkQueryPool->_results = std::move(mapResults); + } +} + //////////////////////////// Function Fallbacks ///////////////////////////////////////// static VkResult VKAPI_PTR vkCreateRenderPass2KHRFallback( diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.h b/native/cocos/renderer/gfx-vulkan/VKDevice.h index 8a59fbb569..99279781a0 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.h +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.h @@ -64,6 +64,7 @@ public: using Device::createInputAssembler; using Device::createPipelineLayout; using Device::createPipelineState; + using Device::createQueryPool; using Device::createQueue; using Device::createRenderPass; using Device::createSampler; @@ -106,6 +107,7 @@ protected: void doDestroy() override; CommandBuffer * createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) override; Queue * createQueue() override; + QueryPool * createQueryPool() override; Swapchain * createSwapchain() override; Buffer * createBuffer() override; Texture * createTexture() override; @@ -124,6 +126,7 @@ protected: void copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint32_t count) override; void copyTextureToBuffers(Texture *src, uint8_t *const *buffers, const BufferTextureCopy *region, uint32_t count) override; + void getQueryPoolResults(QueryPool *queryPool) override; void destroySwapchain(); bool checkSwapchainStatus(); diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index 0cd4c74a56..f779078ffa 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -104,12 +104,12 @@ public: TextureType type = TextureType::TEX2D; Format format = Format::UNKNOWN; TextureUsage usage = TextureUsageBit::NONE; - uint32_t width = 0U; - uint32_t height = 0U; - uint32_t depth = 1U; - uint32_t size = 0U; - uint32_t arrayLayers = 1U; - uint32_t mipLevels = 1U; + uint32_t width = 0U; + uint32_t height = 0U; + uint32_t depth = 1U; + uint32_t size = 0U; + uint32_t arrayLayers = 1U; + uint32_t mipLevels = 1U; SampleCount samples = SampleCount::ONE; TextureFlags flags = TextureFlagBit::NONE; VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; @@ -134,10 +134,10 @@ public: CCVKGPUTexture *gpuTexture = nullptr; TextureType type = TextureType::TEX2D; Format format = Format::UNKNOWN; - uint32_t baseLevel = 0U; - uint32_t levelCount = 1U; - uint32_t baseLayer = 0U; - uint32_t layerCount = 1U; + uint32_t baseLevel = 0U; + uint32_t levelCount = 1U; + uint32_t baseLayer = 0U; + uint32_t layerCount = 1U; vector swapchainVkImageViews; @@ -153,7 +153,7 @@ public: Address addressU = Address::WRAP; Address addressV = Address::WRAP; Address addressW = Address::WRAP; - uint32_t maxAnisotropy = 0U; + uint32_t maxAnisotropy = 0U; ComparisonFunc cmpFunc = ComparisonFunc::NEVER; // descriptor infos @@ -164,8 +164,8 @@ class CCVKGPUBuffer final : public Object { public: BufferUsage usage = BufferUsage::NONE; MemoryUsage memUsage = MemoryUsage::NONE; - uint32_t stride = 0U; - uint32_t count = 0U; + uint32_t stride = 0U; + uint32_t count = 0U; void * buffer = nullptr; bool isDrawIndirectByIndex = false; @@ -194,8 +194,8 @@ public: class CCVKGPUBufferView final : public Object { public: CCVKGPUBuffer *gpuBuffer = nullptr; - uint32_t offset = 0U; - uint32_t range = 0U; + uint32_t offset = 0U; + uint32_t range = 0U; VkDeviceSize getStartOffset(uint32_t curBackBufferIndex) const { return gpuBuffer->getStartOffset(curBackBufferIndex) + offset; @@ -221,7 +221,7 @@ public: VkSurfaceKHR vkSurface = VK_NULL_HANDLE; VkSwapchainCreateInfoKHR createInfo{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; - uint32_t curImageIndex = 0U; + uint32_t curImageIndex = 0U; VkSwapchainKHR vkSwapchain = VK_NULL_HANDLE; FramebufferListMap vkSwapchainFramebufferListMap; vector queueFamilyPresentables; @@ -235,7 +235,7 @@ class CCVKGPUCommandBuffer final : public Object { public: VkCommandBuffer vkCommandBuffer = VK_NULL_HANDLE; VkCommandBufferLevel level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - uint32_t queueFamilyIndex = 0U; + uint32_t queueFamilyIndex = 0U; bool began = false; mutable unordered_set recordedBuffers; }; @@ -244,13 +244,20 @@ class CCVKGPUQueue final : public Object { public: QueueType type = QueueType::GRAPHICS; VkQueue vkQueue = VK_NULL_HANDLE; - uint32_t queueFamilyIndex = 0U; - vector possibleQueueFamilyIndices; + uint32_t queueFamilyIndex = 0U; + vector possibleQueueFamilyIndices; vector lastSignaledSemaphores; vector submitStageMasks; vector commandBuffers; }; +class CCVKGPUQueryPool final : public Object { +public: + QueryType type{QueryType::OCCLUSION}; + uint32_t maxQueryObjects{0}; + VkQueryPool pool; +}; + struct CCVKGPUShaderStage { CCVKGPUShaderStage(ShaderStageFlagBit t, String s) : type(t), @@ -334,7 +341,7 @@ public: BlendState bs; DynamicStateList dynamicStates; CCVKGPURenderPass * gpuRenderPass = nullptr; - uint32_t subpass = 0U; + uint32_t subpass = 0U; VkPipeline vkPipeline = VK_NULL_HANDLE; }; @@ -367,7 +374,7 @@ public: vector extensions; VmaAllocator memoryAllocator{VK_NULL_HANDLE}; VkPipelineCache vkPipelineCache{VK_NULL_HANDLE}; - uint32_t minorVersion{0U}; + uint32_t minorVersion{0U}; VkFormat depthFormat{VK_FORMAT_UNDEFINED}; VkFormat depthStencilFormat{VK_FORMAT_UNDEFINED}; @@ -449,7 +456,7 @@ public: private: CCVKGPUDevice * _device = nullptr; - uint32_t _count = 0U; + uint32_t _count = 0U; vector _fences; }; @@ -494,7 +501,7 @@ public: private: CCVKGPUDevice * _device; - uint32_t _count = 0U; + uint32_t _count = 0U; vector _semaphores; }; @@ -556,8 +563,8 @@ public: return output; } - size_t size = _pools.size(); - uint32_t idx = 0U; + size_t size = _pools.size(); + uint32_t idx = 0U; for (; idx < size; idx++) { if (!_pools[idx].freeSets.empty()) { output = _pools[idx].freeSets.back(); @@ -617,13 +624,13 @@ private: vector _poolSizes; vector _setLayouts; - uint32_t _maxSetsPerPool = 0U; + uint32_t _maxSetsPerPool = 0U; }; class CCVKGPUDescriptorSetLayout final : public Object { public: DescriptorSetLayoutBindingList bindings; - vector dynamicBindings; + vector dynamicBindings; vector vkBindings; VkDescriptorSetLayout vkDescriptorSetLayout = VK_NULL_HANDLE; @@ -736,7 +743,7 @@ private: }; CCVKGPUDevice *_device = nullptr; - uint32_t _lastBackBufferIndex = 0U; + uint32_t _lastBackBufferIndex = 0U; unordered_map _pools; }; @@ -1034,7 +1041,7 @@ private: CachedArray descriptors; }; - unordered_map _bufferInstanceIndices; + unordered_map _bufferInstanceIndices; unordered_map> _buffers; unordered_map> _textures; unordered_map> _samplers; @@ -1103,6 +1110,7 @@ public: DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUFramebuffer, RecycledType::FRAMEBUFFER, res.gpuFramebuffer = gpuRes) DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUSampler, RecycledType::SAMPLER, res.gpuSampler = gpuRes) DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUShader, RecycledType::SHADER, res.gpuShader = gpuRes) + DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUQueryPool, RecycledType::QUERY, res.gpuQueryPool = gpuRes) DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUDescriptorSetLayout, RecycledType::DESCRIPTOR_SET_LAYOUT, res.gpuDescriptorSetLayout = gpuRes) DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUPipelineLayout, RecycledType::PIPELINE_LAYOUT, res.gpuPipelineLayout = gpuRes) DEFINE_RECYCLE_BIN_COLLECT_FN(CCVKGPUPipelineState, RecycledType::PIPELINE_STATE, res.gpuPipelineState = gpuRes) @@ -1119,6 +1127,7 @@ private: FRAMEBUFFER, SAMPLER, SHADER, + QUERY, DESCRIPTOR_SET_LAYOUT, PIPELINE_LAYOUT, PIPELINE_STATE, @@ -1144,6 +1153,7 @@ private: CCVKGPUFramebuffer * gpuFramebuffer; CCVKGPUSampler * gpuSampler; CCVKGPUShader * gpuShader; + CCVKGPUQueryPool * gpuQueryPool; CCVKGPUDescriptorSetLayout *gpuDescriptorSetLayout; CCVKGPUPipelineLayout * gpuPipelineLayout; CCVKGPUPipelineState * gpuPipelineState; @@ -1151,7 +1161,7 @@ private: }; CCVKGPUDevice * _device = nullptr; vector _resources; - uint32_t _count = 0U; + uint32_t _count = 0U; }; /** @@ -1296,9 +1306,9 @@ public: private: struct BufferUpdate { - uint32_t srcIndex = 0U; - size_t size = 0U; - bool canMemcpy = false; + uint32_t srcIndex = 0U; + size_t size = 0U; + bool canMemcpy = false; }; vector> _buffersToBeUpdated; diff --git a/native/cocos/renderer/gfx-vulkan/VKQueryPool.cpp b/native/cocos/renderer/gfx-vulkan/VKQueryPool.cpp new file mode 100644 index 0000000000..5dd99836c6 --- /dev/null +++ b/native/cocos/renderer/gfx-vulkan/VKQueryPool.cpp @@ -0,0 +1,61 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#include "VKStd.h" + +#include "VKCommandBuffer.h" +#include "VKCommands.h" +#include "VKDevice.h" +#include "VKQueryPool.h" +#include "vulkan/vulkan_core.h" + +namespace cc { +namespace gfx { + +CCVKQueryPool::CCVKQueryPool() { + _typedID = generateObjectID(); +} + +CCVKQueryPool::~CCVKQueryPool() { + destroy(); +} + +void CCVKQueryPool::doInit(const QueryPoolInfo& /*info*/) { + CCVKDevice* device = CCVKDevice::getInstance(); + _gpuQueryPool = CC_NEW(CCVKGPUQueryPool); + _gpuQueryPool->type = _type; + _gpuQueryPool->maxQueryObjects = _maxQueryObjects; + cmdFuncCCVKCreateQuery(device, _gpuQueryPool); +} + +void CCVKQueryPool::doDestroy() { + if (_gpuQueryPool) { + CCVKDevice::getInstance()->gpuRecycleBin()->collect(_gpuQueryPool); + _gpuQueryPool = nullptr; + } +} + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKQueryPool.h b/native/cocos/renderer/gfx-vulkan/VKQueryPool.h new file mode 100644 index 0000000000..559c35313c --- /dev/null +++ b/native/cocos/renderer/gfx-vulkan/VKQueryPool.h @@ -0,0 +1,57 @@ +/**************************************************************************** + Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + 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. +****************************************************************************/ + +#pragma once + +#include +#include +#include "VKStd.h" +#include "gfx-base/GFXQueryPool.h" + +namespace cc { +namespace gfx { + +class CCVKGPUQueryPool; + +class CC_VULKAN_API CCVKQueryPool final : public QueryPool { +public: + CCVKQueryPool(); + ~CCVKQueryPool() override; + + inline CCVKGPUQueryPool *gpuQueryPool() const { return _gpuQueryPool; } + +protected: + friend class CCVKCommandBuffer; + friend class CCVKDevice; + + void doInit(const QueryPoolInfo &info) override; + void doDestroy() override; + + CCVKGPUQueryPool * _gpuQueryPool{nullptr}; + std::vector _ids; +}; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp index 31c8675529..4459a978a1 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp @@ -29,6 +29,18 @@ namespace cc { namespace gfx { +VkQueryType mapVkQueryType(QueryType type) { + switch (type) { + case QueryType::OCCLUSION: return VK_QUERY_TYPE_OCCLUSION; + case QueryType::PIPELINE_STATISTICS: return VK_QUERY_TYPE_PIPELINE_STATISTICS; + case QueryType::TIMESTAMP: return VK_QUERY_TYPE_TIMESTAMP; + default: { + CCASSERT(false, "Unsupported query type, convert to VkQueryType failed."); + return VK_QUERY_TYPE_OCCLUSION; + } + } +} + VkFormat mapVkFormat(Format format, const CCVKGPUDevice *gpuDevice) { switch (format) { case Format::R8: return VK_FORMAT_R8_UNORM; diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.h b/native/cocos/renderer/gfx-vulkan/VKUtils.h index 79f6b6387d..fa8537e984 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.h +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.h @@ -52,6 +52,7 @@ namespace gfx { class CCVKGPUDevice; +extern VkQueryType mapVkQueryType(QueryType type); extern VkFormat mapVkFormat(Format format, const CCVKGPUDevice *gpuDevice); extern VkAttachmentLoadOp mapVkLoadOp(LoadOp loadOp); extern VkAttachmentStoreOp mapVkStoreOp(StoreOp storeOp); diff --git a/native/cocos/renderer/pipeline/Define.cpp b/native/cocos/renderer/pipeline/Define.cpp index ae802aa931..f7a128ba17 100644 --- a/native/cocos/renderer/pipeline/Define.cpp +++ b/native/cocos/renderer/pipeline/Define.cpp @@ -168,6 +168,25 @@ const gfx::UniformBlock UBOLocal::LAYOUT = { 1, }; +const String UBOWorldBound::NAME = "CCWorldBound"; +const gfx::DescriptorSetLayoutBinding UBOWorldBound::DESCRIPTOR = { + UBOWorldBound::BINDING, + gfx::DescriptorType::UNIFORM_BUFFER, + 1, + gfx::ShaderStageFlagBit::VERTEX | gfx::ShaderStageFlagBit::COMPUTE, + {}, +}; +const gfx::UniformBlock UBOWorldBound::LAYOUT = { + localSet, + UBOWorldBound::BINDING, + UBOWorldBound::NAME, + { + {"cc_worldBoundCenter", gfx::Type::FLOAT4, 1}, + {"cc_worldBoundHalfExtents", gfx::Type::FLOAT4, 1}, + }, + 1, +}; + const String UBOForwardLight::NAME = "CCForwardLight"; const gfx::DescriptorSetLayoutBinding UBOForwardLight::DESCRIPTOR = { UBOForwardLight::BINDING, diff --git a/native/cocos/renderer/pipeline/Define.h b/native/cocos/renderer/pipeline/Define.h index bbc00bbea3..b746619be4 100644 --- a/native/cocos/renderer/pipeline/Define.h +++ b/native/cocos/renderer/pipeline/Define.h @@ -132,8 +132,8 @@ struct CC_DLL InternalBindingInst : public InternalBindingDesc { }; struct CC_DLL RenderQueueCreateInfo { - bool isTransparent = false; - uint phases = 0; + bool isTransparent = false; + uint phases = 0; std::function sortFunc; }; @@ -151,8 +151,8 @@ enum class CC_DLL RenderQueueSortMode { CC_ENUM_CONVERSION_OPERATOR(RenderQueueSortMode) struct CC_DLL RenderQueueDesc { - bool isTransparent = false; - RenderQueueSortMode sortMode = RenderQueueSortMode::FRONT_TO_BACK; + bool isTransparent = false; + RenderQueueSortMode sortMode = RenderQueueSortMode::FRONT_TO_BACK; StringArray stages; }; using RenderQueueDescList = std::vector; @@ -285,6 +285,17 @@ struct CC_DLL UBOLocal { static const String NAME; }; +struct CC_DLL UBOWorldBound { + static constexpr uint WORLD_BOUND_CENTER = 0; + static constexpr uint WORLD_BOUND_HALF_EXTENTS = UBOWorldBound::WORLD_BOUND_CENTER + 4; + static constexpr uint COUNT = UBOWorldBound::WORLD_BOUND_HALF_EXTENTS + 4; + static constexpr uint SIZE = UBOWorldBound::COUNT * 4; + static constexpr uint BINDING = static_cast(ModelLocalBindings::UBO_LOCAL); + static const gfx::DescriptorSetLayoutBinding DESCRIPTOR; + static const gfx::UniformBlock LAYOUT; + static const String NAME; +}; + struct CC_DLL UBOForwardLight { static constexpr uint LIGHTS_PER_PASS = 1; static constexpr uint LIGHT_POS_OFFSET = 0; diff --git a/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp b/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp index a9a4cdaa96..c27d39401b 100644 --- a/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp +++ b/native/cocos/renderer/pipeline/GlobalDescriptorSetManager.cpp @@ -175,6 +175,8 @@ void GlobalDSManager::setDescriptorSetLayout() { localDescriptorSetLayout.bindings[UBOLocalBatched::BINDING] = UBOLocalBatched::DESCRIPTOR; localDescriptorSetLayout.blocks[UBOLocal::NAME] = UBOLocal::LAYOUT; localDescriptorSetLayout.bindings[UBOLocal::BINDING] = UBOLocal::DESCRIPTOR; + localDescriptorSetLayout.blocks[UBOWorldBound::NAME] = UBOWorldBound::LAYOUT; + localDescriptorSetLayout.bindings[UBOWorldBound::BINDING] = UBOWorldBound::DESCRIPTOR; localDescriptorSetLayout.blocks[UBOForwardLight::NAME] = UBOForwardLight::LAYOUT; localDescriptorSetLayout.bindings[UBOForwardLight::BINDING] = UBOForwardLight::DESCRIPTOR; localDescriptorSetLayout.blocks[UBOSkinningTexture::NAME] = UBOSkinningTexture::LAYOUT; diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp index 3cd416b431..044f3df0b0 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp @@ -72,31 +72,35 @@ RenderAdditiveLightQueue ::~RenderAdditiveLightQueue() { destroy(); } -void RenderAdditiveLightQueue::recordCommandBuffer(gfx::Device *device, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer) { +void RenderAdditiveLightQueue::recordCommandBuffer(gfx::Device *device, scene::Camera *camera, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer) { _instancedQueue->recordCommandBuffer(device, renderPass, cmdBuffer); _batchedQueue->recordCommandBuffer(device, renderPass, cmdBuffer); + bool enableOcclusionQuery = _pipeline->getOcclusionQueryEnabled(); for (const auto &lightPass : _lightPasses) { - const auto *const subModel = lightPass.subModel; - const auto * pass = lightPass.pass; - const auto & dynamicOffsets = lightPass.dynamicOffsets; - auto * shader = lightPass.shader; - const auto lights = lightPass.lights; - auto * ia = subModel->getInputAssembler(); - auto * pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, ia, renderPass); - auto * descriptorSet = subModel->getDescriptorSet(); + const auto *const subModel = lightPass.subModel; - cmdBuffer->bindPipelineState(pso); - cmdBuffer->bindDescriptorSet(materialSet, pass->getDescriptorSet()); - cmdBuffer->bindInputAssembler(ia); + if (!enableOcclusionQuery || !_pipeline->isOccluded(camera, subModel)) { + const auto *pass = lightPass.pass; + const auto &dynamicOffsets = lightPass.dynamicOffsets; + auto * shader = lightPass.shader; + const auto lights = lightPass.lights; + auto * ia = subModel->getInputAssembler(); + auto * pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, ia, renderPass); + auto * descriptorSet = subModel->getDescriptorSet(); - for (size_t i = 0; i < dynamicOffsets.size(); ++i) { - const auto light = lights[i]; - auto * globalDescriptorSet = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(light); - _dynamicOffsets[0] = dynamicOffsets[i]; - cmdBuffer->bindDescriptorSet(globalSet, globalDescriptorSet); - cmdBuffer->bindDescriptorSet(localSet, descriptorSet, _dynamicOffsets); - cmdBuffer->draw(ia); + cmdBuffer->bindPipelineState(pso); + cmdBuffer->bindDescriptorSet(materialSet, pass->getDescriptorSet()); + cmdBuffer->bindInputAssembler(ia); + + for (size_t i = 0; i < dynamicOffsets.size(); ++i) { + const auto light = lights[i]; + auto * globalDescriptorSet = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(light); + _dynamicOffsets[0] = dynamicOffsets[i]; + cmdBuffer->bindDescriptorSet(globalSet, globalDescriptorSet); + cmdBuffer->bindDescriptorSet(localSet, descriptorSet, _dynamicOffsets); + cmdBuffer->draw(ia); + } } } } diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h index 831128402f..83e88913ad 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.h @@ -34,6 +34,9 @@ #include "scene/SpotLight.h" namespace cc { +namespace scene { +struct Camera; +} namespace pipeline { struct RenderObject; class RenderPipeline; @@ -55,7 +58,7 @@ public: explicit RenderAdditiveLightQueue(RenderPipeline *pipeline); ~RenderAdditiveLightQueue() override; - void recordCommandBuffer(gfx::Device *device, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer); + void recordCommandBuffer(gfx::Device *device, scene::Camera *camera, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer); void gatherLightPasses(const scene::Camera *camera, gfx::CommandBuffer *cmdBuffer); void destroy() const; diff --git a/native/cocos/renderer/pipeline/RenderPipeline.cpp b/native/cocos/renderer/pipeline/RenderPipeline.cpp index fcff89820f..c6927053f3 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.cpp +++ b/native/cocos/renderer/pipeline/RenderPipeline.cpp @@ -133,6 +133,11 @@ void RenderPipeline::destroy() { CC_SAFE_DESTROY(_pipelineUBO); CC_SAFE_DESTROY(_pipelineSceneData); + for (auto *const queryPool : _queryPools) { + queryPool->destroy(); + } + _queryPools.clear(); + for (auto *const cmdBuffer : _commandBuffers) { cmdBuffer->destroy(); } @@ -225,14 +230,13 @@ void RenderPipeline::ensureEnoughSize(const vector &cameras) { } gfx::Viewport RenderPipeline::getViewport(scene::Camera *camera) { - auto scale{_pipelineSceneData->getSharedData()->shadingScale}; + auto scale{_pipelineSceneData->getSharedData()->shadingScale}; const gfx::Rect &rect = getRenderArea(camera); return { static_cast(rect.x * scale), static_cast(rect.y * scale), static_cast(rect.width * scale), - static_cast(rect.height * scale) - }; + static_cast(rect.height * scale)}; } gfx::Rect RenderPipeline::getRenderArea(scene::Camera *camera) { @@ -305,5 +309,29 @@ RenderStage *RenderPipeline::getRenderstageByName(const String &name) const { return nullptr; } +bool RenderPipeline::isOccluded(const scene::Camera *camera, const scene::SubModel *subModel) { + auto *model = subModel->getOwner(); + auto *worldBound = model->getWorldBounds(); + + // assume visible if there is no worldBound. + if (!worldBound) { + return false; + } + + // assume visible if camera is inside of worldBound. + if (worldBound->contain(camera->position)) { + return false; + } + + // assume visible if no query in the last frame. + uint32_t id = subModel->getId(); + if (!_queryPools[0]->hasResult(id)) { + return false; + } + + // check query results. + return _queryPools[0]->getResult(id) == 0; +} + } // namespace pipeline } // namespace cc diff --git a/native/cocos/renderer/pipeline/RenderPipeline.h b/native/cocos/renderer/pipeline/RenderPipeline.h index 25aa644217..d653e25bc8 100644 --- a/native/cocos/renderer/pipeline/RenderPipeline.h +++ b/native/cocos/renderer/pipeline/RenderPipeline.h @@ -25,6 +25,7 @@ #pragma once +#include #include "Define.h" #include "GlobalDescriptorSetManager.h" #include "PipelineSceneData.h" @@ -42,6 +43,9 @@ class CommandBuffer; class DescriptorSet; class DescriptorSetLayout; } // namespace gfx +namespace scene { +class SubModel; +} // namespace scene namespace pipeline { class DefineMap; class GlobalDSManager; @@ -81,10 +85,14 @@ public: inline gfx::Texture * getDefaultTexture() const { return _defaultTexture; } inline PipelineSceneData * getPipelineSceneData() const { return _pipelineSceneData; } inline const gfx::CommandBufferList & getCommandBuffers() const { return _commandBuffers; } + inline const gfx::QueryPoolList & getQueryPools() const { return _queryPools; } inline PipelineUBO * getPipelineUBO() const { return _pipelineUBO; } inline const String & getConstantMacros() const { return _constantMacros; } inline gfx::Device * getDevice() const { return _device; } RenderStage * getRenderstageByName(const String &name) const; + bool isOccluded(const scene::Camera *camera, const scene::SubModel *subModel); + bool getOcclusionQueryEnabled() const { return _occlusionQueryEnabled && _device->getCapabilities().supportQuery; } + void setOcclusionQueryEnabled(bool enable) { _occlusionQueryEnabled = enable; } gfx::Rect getRenderArea(scene::Camera *camera); gfx::Viewport getViewport(scene::Camera *camera); @@ -114,6 +122,7 @@ protected: void destroyQuadInputAssembler(); gfx::CommandBufferList _commandBuffers; + gfx::QueryPoolList _queryPools; RenderFlowList _flows; map _globalBindings; DefineMap _macros; @@ -141,6 +150,7 @@ protected: // use cluster culling or not bool _clusterEnabled{false}; bool _bloomEnabled{false}; + bool _occlusionQueryEnabled{true}; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/RenderQueue.cpp b/native/cocos/renderer/pipeline/RenderQueue.cpp index 2ee66d4582..530ba6e316 100644 --- a/native/cocos/renderer/pipeline/RenderQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderQueue.cpp @@ -27,15 +27,17 @@ #include #include "PipelineStateManager.h" +#include "RenderPipeline.h" #include "gfx-base/GFXCommandBuffer.h" +#include "gfx-base/GFXDevice.h" #include "gfx-base/GFXShader.h" #include "scene/SubModel.h" namespace cc { namespace pipeline { -RenderQueue::RenderQueue(RenderQueueCreateInfo desc) -: _passDesc(std::move(desc)) { +RenderQueue::RenderQueue(RenderPipeline *pipeline, RenderQueueCreateInfo desc, bool useOcclusionQuery) +: _pipeline(pipeline), _passDesc(std::move(desc)), _useOcclusionQuery(useOcclusionQuery) { } void RenderQueue::clear() { @@ -57,6 +59,7 @@ bool RenderQueue::insertRenderPass(const RenderObject &renderObj, uint subModelI const auto hash = (0 << 30) | (passPriority << 16) | (modelPriority << 8) | passIdx; RenderPass renderPass = {hash, renderObj.depth, shaderId, passIdx, subModel}; _queue.emplace_back(renderPass); + return true; } @@ -64,21 +67,45 @@ void RenderQueue::sort() { std::sort(_queue.begin(), _queue.end(), _passDesc.sortFunc); } -void RenderQueue::recordCommandBuffer(gfx::Device * /*device*/, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, uint32_t subpassIndex) { +void RenderQueue::recordCommandBuffer(gfx::Device * /*device*/, scene::Camera *camera, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, uint32_t subpassIndex) { + PipelineSceneData *const sceneData = _pipeline->getPipelineSceneData(); + const scene::PipelineSharedSceneData *sharedData = sceneData->getSharedData(); + bool enableOcclusionQuery = _pipeline->getOcclusionQueryEnabled() && _useOcclusionQuery; + auto * queryPool = _pipeline->getQueryPools()[0]; for (auto &i : _queue) { - const auto *const subModel = i.subModel; - const auto passIdx = i.passIndex; - auto * inputAssembler = subModel->getInputAssembler(); + const auto *subModel = i.subModel; + if (enableOcclusionQuery) { + cmdBuff->beginQuery(queryPool, subModel->getId()); + } - const auto *pass = subModel->getPass(passIdx); - auto * shader = subModel->getShader(passIdx); + if (enableOcclusionQuery && _pipeline->isOccluded(camera, subModel)) { + auto * inputAssembler = sharedData->occlusionQueryInputAssembler; + const auto *pass = sharedData->occlusionQueryPass; + auto * shader = sharedData->occlusionQueryShader; + auto * pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass, subpassIndex); - auto *pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass, subpassIndex); - cmdBuff->bindPipelineState(pso); - cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); - cmdBuff->bindDescriptorSet(localSet, subModel->getDescriptorSet()); - cmdBuff->bindInputAssembler(inputAssembler); - cmdBuff->draw(inputAssembler); + cmdBuff->bindPipelineState(pso); + cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); + cmdBuff->bindDescriptorSet(localSet, subModel->getWorldBoundDescriptorSet()); + cmdBuff->bindInputAssembler(inputAssembler); + cmdBuff->draw(inputAssembler); + } else { + const auto passIdx = i.passIndex; + auto * inputAssembler = subModel->getInputAssembler(); + const auto *pass = subModel->getPass(passIdx); + auto * shader = subModel->getShader(passIdx); + auto * pso = PipelineStateManager::getOrCreatePipelineState(pass, shader, inputAssembler, renderPass, subpassIndex); + + cmdBuff->bindPipelineState(pso); + cmdBuff->bindDescriptorSet(materialSet, pass->getDescriptorSet()); + cmdBuff->bindDescriptorSet(localSet, subModel->getDescriptorSet()); + cmdBuff->bindInputAssembler(inputAssembler); + cmdBuff->draw(inputAssembler); + } + + if (enableOcclusionQuery) { + cmdBuff->endQuery(queryPool, subModel->getId()); + } } } diff --git a/native/cocos/renderer/pipeline/RenderQueue.h b/native/cocos/renderer/pipeline/RenderQueue.h index 5aebde3a9e..676ba7548a 100644 --- a/native/cocos/renderer/pipeline/RenderQueue.h +++ b/native/cocos/renderer/pipeline/RenderQueue.h @@ -28,21 +28,28 @@ #include "Define.h" namespace cc { +namespace scene { +struct Camera; +} namespace pipeline { +class RenderPipeline; + class CC_DLL RenderQueue : public Object { public: - explicit RenderQueue(RenderQueueCreateInfo desc); + explicit RenderQueue(RenderPipeline *pipeline, RenderQueueCreateInfo desc, bool useOcclusionQuery = false); void clear(); bool insertRenderPass(const RenderObject &renderObj, uint subModelIdx, uint passIdx); - void recordCommandBuffer(gfx::Device *device, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, uint32_t subpassIndex = 0); + void recordCommandBuffer(gfx::Device *device, scene::Camera *camera, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuff, uint32_t subpassIndex = 0); void sort(); bool empty() { return _queue.empty(); } private: + RenderPipeline * _pipeline = nullptr; RenderPassList _queue; RenderQueueCreateInfo _passDesc; + bool _useOcclusionQuery{false}; }; } // namespace pipeline diff --git a/native/cocos/renderer/pipeline/common/PostProcessStage.cpp b/native/cocos/renderer/pipeline/common/PostProcessStage.cpp index 11ab450600..5f9df6371f 100644 --- a/native/cocos/renderer/pipeline/common/PostProcessStage.cpp +++ b/native/cocos/renderer/pipeline/common/PostProcessStage.cpp @@ -26,9 +26,9 @@ #include "PostProcessStage.h" #include "../PipelineStateManager.h" +#include "../RenderPipeline.h" #include "../RenderQueue.h" #include "UIPhase.h" -#include "../RenderPipeline.h" #include "frame-graph/DevicePass.h" #include "frame-graph/PassNodeBuilder.h" #include "frame-graph/Resource.h" @@ -39,6 +39,7 @@ #include "pipeline/helper/Utils.h" #include "scene/SubModel.h" + namespace cc { namespace pipeline { namespace { @@ -87,7 +88,7 @@ void PostProcessStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { } RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; - _renderQueues.emplace_back(CC_NEW(RenderQueue(std::move(info)))); + _renderQueues.emplace_back(CC_NEW(RenderQueue(_pipeline, std::move(info)))); } } @@ -191,8 +192,8 @@ void PostProcessStage::render(scene::Camera *camera) { gfx::Shader *sd = sceneData->getSharedData()->pipelinePostPassShader; // get pso and draw quad - gfx::InputAssembler *ia = pipeline->getIAByRenderArea(pipeline->getRenderArea(camera)); - gfx::PipelineState * pso = PipelineStateManager::getOrCreatePipelineState(pv, sd, ia, renderPass); + gfx::InputAssembler *ia = pipeline->getIAByRenderArea(pipeline->getRenderArea(camera)); + gfx::PipelineState * pso = PipelineStateManager::getOrCreatePipelineState(pv, sd, ia, renderPass); pv->getDescriptorSet()->bindTexture(0, table.getRead(data.outColorTex)); pv->getDescriptorSet()->bindSampler(0, pipeline->getDevice()->getSampler({ diff --git a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp index cf88d16adb..4583bdc19d 100644 --- a/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp +++ b/native/cocos/renderer/pipeline/deferred/DeferredPipeline.cpp @@ -122,6 +122,7 @@ void DeferredPipeline::render(const vector &cameras) { bool DeferredPipeline::activeRenderer(gfx::Swapchain *swapchain) { _commandBuffers.push_back(_device->getCommandBuffer()); + _queryPools.push_back(_device->getQueryPool()); auto *const sharedData = _pipelineSceneData->getSharedData(); gfx::Sampler *const sampler = _device->getSampler({ @@ -182,6 +183,7 @@ void DeferredPipeline::destroy() { } _renderPasses.clear(); + _queryPools.clear(); _commandBuffers.clear(); CC_SAFE_DELETE(_clusterComp); diff --git a/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp b/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp index 247f7805df..c30c9371fe 100644 --- a/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp @@ -71,7 +71,7 @@ void GbufferStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { uint phase = convertPhase(descriptor.stages); RenderQueueSortFunc sortFunc = convertQueueSortFunc(descriptor.sortMode); RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; - _renderQueues.emplace_back(CC_NEW(RenderQueue(std::move(info)))); + _renderQueues.emplace_back(CC_NEW(RenderQueue(_pipeline, std::move(info)))); } _planarShadowQueue = CC_NEW(PlanarShadowQueue(_pipeline)); } @@ -127,7 +127,7 @@ void GbufferStage::dispenseRenderObject2Queues() { queue->sort(); } } -void GbufferStage::recordCommands(DeferredPipeline *pipeline, gfx::RenderPass *renderPass) { +void GbufferStage::recordCommands(DeferredPipeline *pipeline, scene::Camera *camera, gfx::RenderPass *renderPass) { auto *cmdBuff = pipeline->getCommandBuffers()[0]; // DescriptorSet bindings @@ -135,7 +135,7 @@ void GbufferStage::recordCommands(DeferredPipeline *pipeline, gfx::RenderPass *r cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), utils::toUint(globalOffsets.size()), globalOffsets.data()); // record commands - _renderQueues[0]->recordCommandBuffer(_device, renderPass, cmdBuff); + _renderQueues[0]->recordCommandBuffer(_device, camera, renderPass, cmdBuff); _instancedQueue->recordCommandBuffer(_device, renderPass, cmdBuff); _batchedQueue->recordCommandBuffer(_device, renderPass, cmdBuff); } @@ -224,8 +224,8 @@ void GbufferStage::render(scene::Camera *camera) { builder.setViewport(pipeline->getViewport(camera), _renderArea); }; - auto gbufferExec = [this](const RenderData & /*data*/, const framegraph::DevicePassResourceTable &table) { - recordCommands(static_cast(_pipeline), table.getRenderPass()); + auto gbufferExec = [this, camera](const RenderData & /*data*/, const framegraph::DevicePassResourceTable &table) { + recordCommands(static_cast(_pipeline), camera, table.getRenderPass()); }; // Command 'updateBuffer' must be recorded outside render passes, cannot put them in execute lambda diff --git a/native/cocos/renderer/pipeline/deferred/GbufferStage.h b/native/cocos/renderer/pipeline/deferred/GbufferStage.h index 4446fdede8..759f95defc 100644 --- a/native/cocos/renderer/pipeline/deferred/GbufferStage.h +++ b/native/cocos/renderer/pipeline/deferred/GbufferStage.h @@ -29,6 +29,9 @@ #include "pipeline/RenderStage.h" namespace cc { +namespace scene { +struct Camera; +} namespace pipeline { class RenderFlow; @@ -54,7 +57,7 @@ public: private: void dispenseRenderObject2Queues(); - void recordCommands(DeferredPipeline *pipeline, gfx::RenderPass *renderPass); + void recordCommands(DeferredPipeline *pipeline, scene::Camera *camera, gfx::RenderPass *renderPass); static RenderStageInfo initInfo; PlanarShadowQueue * _planarShadowQueue = nullptr; diff --git a/native/cocos/renderer/pipeline/deferred/LightingStage.cpp b/native/cocos/renderer/pipeline/deferred/LightingStage.cpp index ad57ed5da0..bd764e8d2e 100644 --- a/native/cocos/renderer/pipeline/deferred/LightingStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/LightingStage.cpp @@ -275,7 +275,7 @@ void LightingStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { uint phase = convertPhase(descriptor.stages); RenderQueueSortFunc sortFunc = convertQueueSortFunc(descriptor.sortMode); RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; - _renderQueues.emplace_back(CC_NEW(RenderQueue(std::move(info)))); + _renderQueues.emplace_back(CC_NEW(RenderQueue(_pipeline, std::move(info)))); } // not use cluster shading, go normal deferred render path @@ -298,7 +298,7 @@ void LightingStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { _reflectionComp = new ReflectionComp(); _reflectionComp->init(_device, 8, 8); - _reflectionRenderQueue = CC_NEW(RenderQueue(std::move(info))); + _reflectionRenderQueue = CC_NEW(RenderQueue(_pipeline, std::move(info))); gfx::SamplerInfo samplerInfo; samplerInfo.minFilter = gfx::Filter::POINT; @@ -495,7 +495,7 @@ void LightingStage::fgTransparent(scene::Camera *camera) { builder.setViewport(pipeline->getViewport(camera), pipeline->getRenderArea(camera)); }; - auto transparentExec = [this](RenderData const & /*data*/, const framegraph::DevicePassResourceTable &table) { + auto transparentExec = [this, camera](RenderData const & /*data*/, const framegraph::DevicePassResourceTable &table) { auto *pipeline = static_cast(_pipeline); auto *cmdBuff = pipeline->getCommandBuffers()[0]; @@ -508,7 +508,7 @@ void LightingStage::fgTransparent(scene::Camera *camera) { // transparent for (auto *queue : _renderQueues) { queue->sort(); - queue->recordCommandBuffer(pipeline->getDevice(), table.getRenderPass(), cmdBuff, table.getSubpassIndex()); + queue->recordCommandBuffer(pipeline->getDevice(), camera, table.getRenderPass(), cmdBuff, table.getSubpassIndex()); } //_planarShadowQueue->recordCommandBuffer(_device, renderPass, cmdBuff); @@ -778,7 +778,7 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { builder.setViewport(pipeline->getViewport(camera), pipeline->getRenderArea(camera)); }; - auto renderExec = [this](DataRender const &data, const framegraph::DevicePassResourceTable &table) { + auto renderExec = [this, camera](DataRender const &data, const framegraph::DevicePassResourceTable &table) { auto *pipeline = static_cast(_pipeline); auto *cmdBuff = pipeline->getCommandBuffers()[0]; auto &elem = _reflectionElems[_denoiseIndex]; @@ -799,7 +799,7 @@ void LightingStage::fgSsprPass(scene::Camera *camera) { gfx::RenderPass *renderPass = table.getRenderPass(); _reflectionRenderQueue->sort(); - _reflectionRenderQueue->recordCommandBuffer(pipeline->getDevice(), renderPass, cmdBuff); + _reflectionRenderQueue->recordCommandBuffer(pipeline->getDevice(), camera, renderPass, cmdBuff); }; // step 5 add framegraph passes diff --git a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp index 2c83e3ab27..ede3f9b9b7 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardPipeline.cpp @@ -82,7 +82,18 @@ bool ForwardPipeline::activate(gfx::Swapchain *swapchain) { } void ForwardPipeline::render(const vector &cameras) { + auto *device = gfx::Device::getInstance(); + bool enableOcclusionQuery = getOcclusionQueryEnabled(); + if (enableOcclusionQuery) { + device->getQueryPoolResults(_queryPools[0]); + } + _commandBuffers[0]->begin(); + + if (enableOcclusionQuery) { + _commandBuffers[0]->resetQuery(_queryPools[0]); + } + _pipelineUBO->updateGlobalUBO(cameras[0]); _pipelineUBO->updateMultiCameraUBO(cameras); ensureEnoughSize(cameras); @@ -105,6 +116,7 @@ void ForwardPipeline::render(const vector &cameras) { bool ForwardPipeline::activeRenderer(gfx::Swapchain *swapchain) { _commandBuffers.push_back(_device->getCommandBuffer()); + _queryPools.push_back(_device->getQueryPool()); auto *const sharedData = _pipelineSceneData->getSharedData(); gfx::Sampler *const shadowMapSampler = _device->getSampler({ @@ -156,6 +168,7 @@ void ForwardPipeline::destroy() { } _renderPasses.clear(); + _queryPools.clear(); _commandBuffers.clear(); RenderPipeline::destroy(); diff --git a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp index 577e0db15f..21b1e44f84 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp @@ -33,9 +33,10 @@ #include "../RenderQueue.h" #include "../helper/Utils.h" #include "ForwardPipeline.h" -#include "pipeline/common/UIPhase.h" #include "gfx-base/GFXCommandBuffer.h" #include "gfx-base/GFXFramebuffer.h" +#include "pipeline/common/UIPhase.h" + namespace cc { namespace pipeline { @@ -67,10 +68,10 @@ void ForwardStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { RenderStage::activate(pipeline, flow); for (const auto &descriptor : _renderQueueDescriptors) { - const uint phase = convertPhase(descriptor.stages); - const RenderQueueSortFunc sortFunc = convertQueueSortFunc(descriptor.sortMode); - RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; - _renderQueues.emplace_back(CC_NEW(RenderQueue(std::move(info)))); + uint phase = convertPhase(descriptor.stages); + RenderQueueSortFunc sortFunc = convertQueueSortFunc(descriptor.sortMode); + RenderQueueCreateInfo info = {descriptor.isTransparent, phase, sortFunc}; + _renderQueues.emplace_back(CC_NEW(RenderQueue(_pipeline, std::move(info), true))); } _additiveLightQueue = CC_NEW(RenderAdditiveLightQueue(_pipeline)); @@ -206,19 +207,19 @@ void ForwardStage::render(scene::Camera *camera) { auto offset = _pipeline->getPipelineUBO()->getCurrentCameraUBOOffset(); auto forwardExec = [this, camera, offset](const RenderData & /*data*/, const framegraph::DevicePassResourceTable &table) { - auto * renderPass = table.getRenderPass(); - auto * cmdBuff = _pipeline->getCommandBuffers()[0]; + auto *renderPass = table.getRenderPass(); + auto *cmdBuff = _pipeline->getCommandBuffers()[0]; cmdBuff->bindDescriptorSet(globalSet, _pipeline->getDescriptorSet(), 1, &offset); if (!_pipeline->getPipelineSceneData()->getRenderObjects().empty()) { - _renderQueues[0]->recordCommandBuffer(_device, renderPass, cmdBuff); + _renderQueues[0]->recordCommandBuffer(_device, camera, renderPass, cmdBuff); _instancedQueue->recordCommandBuffer(_device, renderPass, cmdBuff); _batchedQueue->recordCommandBuffer(_device, renderPass, cmdBuff); - _additiveLightQueue->recordCommandBuffer(_device, renderPass, cmdBuff); + _additiveLightQueue->recordCommandBuffer(_device, camera, renderPass, cmdBuff); cmdBuff->bindDescriptorSet(globalSet, _pipeline->getDescriptorSet(), 1, &offset); _planarShadowQueue->recordCommandBuffer(_device, renderPass, cmdBuff); - _renderQueues[1]->recordCommandBuffer(_device, renderPass, cmdBuff); + _renderQueues[1]->recordCommandBuffer(_device, camera, renderPass, cmdBuff); } }; diff --git a/native/cocos/scene/AABB.cpp b/native/cocos/scene/AABB.cpp index 595a5e95fd..cbdbe7af66 100644 --- a/native/cocos/scene/AABB.cpp +++ b/native/cocos/scene/AABB.cpp @@ -77,35 +77,35 @@ void AABB::getBoundary(cc::Vec3 *minPos, cc::Vec3 *maxPos) const { void AABB::merge(const AABB &aabb) { const cc::Vec3 minA = getCenter() - getHalfExtents(); - const cc::Vec3 minB = aabb.getCenter() - aabb.getHalfExtents(); - const cc::Vec3 maxA = getCenter() + getHalfExtents(); - const cc::Vec3 maxB = aabb.getCenter() + aabb.getHalfExtents(); - cc::Vec3 maxP; - cc::Vec3 minP; + const cc::Vec3 minB = aabb.getCenter() - aabb.getHalfExtents(); + const cc::Vec3 maxA = getCenter() + getHalfExtents(); + const cc::Vec3 maxB = aabb.getCenter() + aabb.getHalfExtents(); + cc::Vec3 maxP; + cc::Vec3 minP; cc::Vec3::max(maxA, maxB, &maxP); cc::Vec3::min(minA, minB, &minP); const cc::Vec3 addP = maxP + minP; - const cc::Vec3 subP = maxP - minP; + const cc::Vec3 subP = maxP - minP; setCenter(addP * 0.5F); setHalfExtents(subP * 0.5F); } -void AABB::merge(const cc::Vec3& point) { +void AABB::merge(const cc::Vec3 &point) { cc::Vec3 minPos = getCenter() - getHalfExtents(); cc::Vec3 maxPos = getCenter() + getHalfExtents(); if (point.x < minPos.x) { minPos.x = point.x; - } + } if (point.y < minPos.y) { minPos.y = point.y; } if (point.z < minPos.z) { minPos.z = point.z; - } + } if (point.x > maxPos.x) { maxPos.x = point.x; - } + } if (point.y > maxPos.y) { maxPos.y = point.y; } @@ -118,7 +118,7 @@ void AABB::merge(const cc::Vec3& point) { setHalfExtents(maxPos.x - center.x, maxPos.y - center.y, maxPos.z - center.z); } -void AABB::merge(const Frustum& frustum) { +void AABB::merge(const Frustum &frustum) { const std::array &vertices = frustum.vertices; for (uint i = 0; i < vertices.max_size(); ++i) { merge(vertices[i]); @@ -136,6 +136,15 @@ void AABB::transform(const Mat4 &m, AABB *out) const { transformExtentM4(&layout->halfExtents, getHalfExtents(), m); } +bool AABB::contain(const cc::Vec3 &point) const { + cc::Vec3 minPos = getCenter() - getHalfExtents(); + cc::Vec3 maxPos = getCenter() + getHalfExtents(); + + return !(point.x > maxPos.x || point.x < minPos.x || + point.y > maxPos.y || point.y < minPos.y || + point.z > maxPos.z || point.z < minPos.z); +} + void AABB::transformExtentM4(Vec3 *out, const Vec3 &extent, const Mat4 &m4) { Mat3 m3Tmp; m3Tmp.m[0] = abs(m4.m[0]); diff --git a/native/cocos/scene/AABB.h b/native/cocos/scene/AABB.h index 12f1d0a4df..8f2be0b001 100644 --- a/native/cocos/scene/AABB.h +++ b/native/cocos/scene/AABB.h @@ -65,6 +65,7 @@ public: void merge(const Frustum &frustum); void set(const cc::Vec3 ¢erVal, const cc::Vec3 &halfExtentVal); void transform(const Mat4 &m, AABB *out) const; + bool contain(const cc::Vec3 &point) const; inline void setCenter(float x, float y, float z) { _aabbLayout->center.set(x, y, z); } inline void setCenter(const Vec3 ¢er) { _aabbLayout->center.set(center); } inline void setValid(bool isValid) { _isValid = isValid; } diff --git a/native/cocos/scene/Define.h b/native/cocos/scene/Define.h index 42bfb8abc8..fc12ea0270 100644 --- a/native/cocos/scene/Define.h +++ b/native/cocos/scene/Define.h @@ -30,6 +30,7 @@ #include "math/Vec2.h" #include "math/Vec3.h" #include "math/Vec4.h" +#include "renderer/gfx-base/GFXInputAssembler.h" #include "renderer/gfx-base/GFXShader.h" #include "scene/Model.h" @@ -108,24 +109,27 @@ struct Ambient { }; struct PipelineSharedSceneData { - bool isHDR{true}; - float shadingScale{0.0F}; - Ambient * ambient{nullptr}; - Shadow * shadow{nullptr}; - Skybox * skybox{nullptr}; - Fog * fog{nullptr}; - Pass * deferredLightPass{nullptr}; - gfx::Shader * deferredLightPassShader{nullptr}; - Pass * bloomPrefilterPass{nullptr}; - gfx::Shader * bloomPrefilterPassShader{nullptr}; + bool isHDR{true}; + float shadingScale{0.0F}; + Ambient * ambient{nullptr}; + Shadow * shadow{nullptr}; + Skybox * skybox{nullptr}; + Fog * fog{nullptr}; + gfx::InputAssembler *occlusionQueryInputAssembler{nullptr}; + Pass * occlusionQueryPass{nullptr}; + gfx::Shader * occlusionQueryShader{nullptr}; + Pass * deferredLightPass{nullptr}; + gfx::Shader * deferredLightPassShader{nullptr}; + Pass * bloomPrefilterPass{nullptr}; + gfx::Shader * bloomPrefilterPassShader{nullptr}; std::vector bloomDownsamplePass; - gfx::Shader * bloomDownsamplePassShader{nullptr}; + gfx::Shader * bloomDownsamplePassShader{nullptr}; std::vector bloomUpsamplePass; - gfx::Shader * bloomUpsamplePassShader{nullptr}; - Pass * bloomCombinePass{nullptr}; - gfx::Shader * bloomCombinePassShader{nullptr}; - Pass * pipelinePostPass{nullptr}; - gfx::Shader * pipelinePostPassShader{nullptr}; + gfx::Shader * bloomUpsamplePassShader{nullptr}; + Pass * bloomCombinePass{nullptr}; + gfx::Shader * bloomCombinePassShader{nullptr}; + Pass * pipelinePostPass{nullptr}; + gfx::Shader * pipelinePostPassShader{nullptr}; }; struct FlatBuffer { diff --git a/native/cocos/scene/Model.cpp b/native/cocos/scene/Model.cpp index 29c0d41b01..1a97b29f3d 100644 --- a/native/cocos/scene/Model.cpp +++ b/native/cocos/scene/Model.cpp @@ -27,7 +27,6 @@ #include "scene/RenderScene.h" #include "scene/SubModel.h" - namespace cc { namespace scene { void Model::uploadMat4AsVec4x3(const Mat4 &mat, float *v1, float *v2, float *v3) { @@ -80,10 +79,26 @@ void Model::updateUBOs(uint32_t stamp) { Mat4::inverseTranspose(worldMatrix, &mat4); memcpy(bufferView.data() + pipeline::UBOLocal::MAT_WORLD_IT_OFFSET, mat4.m, sizeof(Mat4)); _localBuffer->update(bufferView.data(), pipeline::UBOLocal::SIZE); + + updateWorldBoundUBOs(); + } +} + +void Model::updateWorldBoundUBOs() { + if (_worldBoundBuffer) { + std::array worldBoundBufferView; + const Vec3 & center = _worldBounds ? _worldBounds->getCenter() : Vec3{0.0F, 0.0F, 0.0F}; + const Vec3 & halfExtents = _worldBounds ? _worldBounds->getHalfExtents() : Vec3{1.0F, 1.0F, 1.0F}; + const Vec4 worldBoundCenter{center.x, center.y, center.z, 0.0F}; + const Vec4 worldBoundHalfExtents{halfExtents.x, halfExtents.y, halfExtents.z, 1.0F}; + memcpy(worldBoundBufferView.data() + pipeline::UBOWorldBound::WORLD_BOUND_CENTER, &worldBoundCenter.x, sizeof(Vec4)); + memcpy(worldBoundBufferView.data() + pipeline::UBOWorldBound::WORLD_BOUND_HALF_EXTENTS, &worldBoundHalfExtents.x, sizeof(Vec4)); + _worldBoundBuffer->update(worldBoundBufferView.data(), pipeline::UBOWorldBound::SIZE); } } void Model::setSubModel(uint32_t idx, SubModel *subModel) { + subModel->setOwner(this); if (idx >= static_cast(_subModels.size())) { _subModels.emplace_back(subModel); return; diff --git a/native/cocos/scene/Model.h b/native/cocos/scene/Model.h index 6b5260cff9..b2d8b67c43 100644 --- a/native/cocos/scene/Model.h +++ b/native/cocos/scene/Model.h @@ -65,6 +65,7 @@ public: virtual void updateTransform(uint32_t stamp); virtual void updateUBOs(uint32_t stamp); + void updateWorldBoundUBOs(); void setSubModel(uint32_t idx, SubModel *subModel); @@ -72,6 +73,7 @@ public: inline void setEnabled(bool value) { _enabled = value; } inline void setInstMatWorldIdx(int32_t idx) { _instMatWorldIdx = idx; } inline void setLocalBuffer(gfx::Buffer *buffer) { _localBuffer = buffer; } + inline void setWorldBoundBuffer(gfx::Buffer *buffer) { _worldBoundBuffer = buffer; } inline void setNode(Node *node) { _node = node; } inline void setReceiveShadow(bool value) { _receiveShadow = value; } inline void setTransform(Node *node) { _transform = node; } @@ -97,6 +99,7 @@ public: inline uint8_t * getInstancedBuffer() const { return std::get<0>(_instancedBuffer); } inline uint32_t getInstancedBufferSize() const { return std::get<1>(_instancedBuffer); } inline gfx::Buffer * getLocalBuffer() const { return _localBuffer; } + inline gfx::Buffer * getWorldBoundBuffer() const { return _worldBoundBuffer; } inline float * getLocalData() const { return _localData; } inline const AABB & getModelBounds() const { return _modelBounds; } inline Node * getNode() const { return _node; } @@ -132,6 +135,7 @@ private: float * _localData{nullptr}; std::tuple _instancedBuffer{nullptr, 0}; gfx::Buffer * _localBuffer{nullptr}; + gfx::Buffer * _worldBoundBuffer{nullptr}; InstancedAttributeBlock _instanceAttributeBlock{}; std::vector _subModels; std::vector _instanceAttributes; diff --git a/native/cocos/scene/SubModel.cpp b/native/cocos/scene/SubModel.cpp index 19ecddad28..d7838d1c83 100644 --- a/native/cocos/scene/SubModel.cpp +++ b/native/cocos/scene/SubModel.cpp @@ -28,11 +28,16 @@ namespace cc { namespace scene { +SubModel::SubModel() { + _id = generateId(); +} + void SubModel::update() { for (Pass *pass : _passes) { pass->update(); } _descriptSet->update(); + _worldBoundDescriptorSet->update(); } SubModel::~SubModel() { diff --git a/native/cocos/scene/SubModel.h b/native/cocos/scene/SubModel.h index 7c1fdc9254..788133263f 100644 --- a/native/cocos/scene/SubModel.h +++ b/native/cocos/scene/SubModel.h @@ -25,20 +25,23 @@ #pragma once +#include #include #include "renderer/gfx-base/GFXDescriptorSet.h" #include "renderer/gfx-base/GFXInputAssembler.h" #include "renderer/gfx-base/GFXShader.h" #include "scene/Define.h" + namespace cc { namespace scene { class Pass; +class Model; class SubModel final { public: - SubModel() = default; + SubModel(); SubModel(const SubModel &) = delete; SubModel(SubModel &&) = delete; ~SubModel(); @@ -53,10 +56,12 @@ public: inline void setShaders(const std::vector &shaders) { _shaders = shaders; } inline void setPasses(const std::vector &passes) { _passes = passes; } inline void setDescriptorSet(gfx::DescriptorSet *descriptorSet) { _descriptSet = descriptorSet; } + inline void setWorldBoundDescriptorSet(gfx::DescriptorSet *descriptorSet) { _worldBoundDescriptorSet = descriptorSet; } inline void setInputAssembler(gfx::InputAssembler *ia) { _ia = ia; } inline void setPlanarInstanceShader(gfx::Shader *shader) { _planarInstanceShader = shader; } inline void setPlanarShader(gfx::Shader *shader) { _planarShader = shader; } inline void setPriority(RenderPriority priority) { _priority = priority; } + inline void setOwner(Model *model) { _owner = model; } inline void setSubMeshBuffers(const std::vector &flatBuffers) { if (!_subMesh) { _subMesh = new RenderingSubMesh(); @@ -65,6 +70,7 @@ public: } inline gfx::DescriptorSet * getDescriptorSet() const { return _descriptSet; } + inline gfx::DescriptorSet * getWorldBoundDescriptorSet() const { return _worldBoundDescriptorSet; } inline gfx::InputAssembler * getInputAssembler() const { return _ia; } inline std::vector &getShaders() { return _shaders; } inline const std::vector & getPasses() const { return _passes; } @@ -72,16 +78,26 @@ public: inline gfx::Shader * getPlanarShader() const { return _planarShader; } inline RenderPriority getPriority() const { return _priority; } inline RenderingSubMesh * getSubMesh() const { return _subMesh; } + inline Model * getOwner() const { return _owner; } + inline uint32_t getId() const { return _id; } private: + static inline uint32_t generateId() { + static uint32_t generator = 0; + return generator++; + } + RenderPriority _priority{RenderPriority::DEFAULT}; gfx::Shader * _planarShader{nullptr}; gfx::Shader * _planarInstanceShader{nullptr}; gfx::DescriptorSet * _descriptSet{nullptr}; + gfx::DescriptorSet * _worldBoundDescriptorSet{nullptr}; gfx::InputAssembler * _ia{nullptr}; RenderingSubMesh * _subMesh{nullptr}; std::vector _passes; std::vector _shaders; + Model * _owner{nullptr}; + uint32_t _id = -1; }; } // namespace scene diff --git a/native/tools/tojs/gfx.ini b/native/tools/tojs/gfx.ini index 190fbe026c..c6b66ab5f8 100644 --- a/native/tools/tojs/gfx.ini +++ b/native/tools/tojs/gfx.ini @@ -37,12 +37,12 @@ classes = DeviceManager, # classes GFXObject DescriptorSet DescriptorSetLayout Device Buffer CommandBuffer Framebuffer GlobalBarrier InputAssembler, - PipelineLayout PipelineState Queue RenderPass Sampler Shader Swapchain Texture TextureBarrier, + PipelineLayout PipelineState Queue QueryPool RenderPass Sampler Shader Swapchain Texture TextureBarrier, # structs Attribute BindingMappingInfo BlendState BlendTarget BufferInfo BufferTextureCopy BufferViewInfo Color ColorAttachment CommandBufferInfo, DepthStencilAttachment DepthStencilState DescriptorSetInfo DescriptorSetLayoutBinding DescriptorSetLayoutInfo DeviceCaps DeviceInfo, DispatchInfo DrawInfo Extent FramebufferInfo GlobalBarrierInfo IndirectBuffer InputAssemblerInfo InputState, - MemoryStatus Offset PipelineLayoutInfo PipelineStateInfo QueueInfo RasterizerState Rect RenderPassInfo SamplerInfo ShaderInfo ShaderStage Size SubpassInfo SubpassDependency, + MemoryStatus Offset PipelineLayoutInfo PipelineStateInfo QueueInfo QueryPoolInfo RasterizerState Rect RenderPassInfo SamplerInfo ShaderInfo ShaderStage Size SubpassInfo SubpassDependency, SwapchainInfo TextureBarrierInfo TextureBlit TextureCopy TextureInfo TextureSubresLayers TextureSubresRange TextureViewInfo Uniform, UniformBlock UniformInputAttachment UniformSampler UniformSamplerTexture UniformStorageBuffer UniformStorageImage UniformTexture Viewport ; FormatInfo @@ -65,6 +65,7 @@ skip = Buffer::[Buffer initialize update], PipelineLayout::[PipelineLayout], PipelineState::[PipelineState], Queue::[Queue], + QueryPool::[QueryPool], RenderPass::[RenderPass getColorAttachments getBindings getBindingIndices], Shader::[Shader], Swapchain::[Swapchain],