V3.4.0 occlusion query2 (#3975)

* occlusion query
Co-authored-by: lijilin <jilin.li@cocos.com>
This commit is contained in:
李吉林
2021-10-13 18:21:03 +08:00
committed by GitHub
parent 528b9b0b99
commit bed27fcccf
83 changed files with 2142 additions and 475 deletions
+16
View File
@@ -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
+2 -2
View File
@@ -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
@@ -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<QueryPoolAgent *>(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<QueryPoolAgent *>(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<QueryPoolAgent *>(queryPool)->getActor();
ENQUEUE_MESSAGE_2(
_messageQueue, CommandBufferResetQuery,
actor, getActor(),
queryPool, actorQueryPool,
{
actor->resetQuery(queryPool);
});
}
} // namespace gfx
} // namespace cc
@@ -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;
@@ -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<CommandBufferAgent *>(_cmdBuff)->_queue = _queue;
static_cast<CommandBufferAgent *>(_cmdBuff)->initMessageQueue();
static_cast<CommandBufferAgent *>(_cmdBuff)->initAgent();
setMultithreaded(true);
@@ -98,11 +100,16 @@ void DeviceAgent::doDestroy() {
});
if (_cmdBuff) {
static_cast<CommandBufferAgent *>(_cmdBuff)->destroyMessageQueue();
static_cast<CommandBufferAgent *>(_cmdBuff)->destroyAgent();
static_cast<CommandBufferAgent *>(_cmdBuff)->_actor = nullptr;
CC_DELETE(_cmdBuff);
_cmdBuff = nullptr;
}
if (_queryPool) {
static_cast<QueryPoolAgent *>(_queryPool)->_actor = nullptr;
CC_DELETE(_queryPool);
_queryPool = nullptr;
}
if (_queue) {
static_cast<QueueAgent *>(_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<QueryPoolAgent *>(queryPool)->getActor();
ENQUEUE_MESSAGE_2(
_mainMessageQueue, DeviceGetQueryPoolResults,
actor, getActor(),
queryPool, actorQueryPool,
{
actor->getQueryPoolResults(queryPool);
});
auto * actorQueryPoolAgent = static_cast<QueryPoolAgent *>(actorQueryPool);
auto * queryPoolAgent = static_cast<QueryPoolAgent *>(queryPool);
std::lock_guard<std::mutex> lock(actorQueryPoolAgent->_mutex);
queryPoolAgent->_results = actorQueryPoolAgent->_results;
}
} // namespace gfx
} // namespace cc
@@ -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(); }
@@ -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<QueryPool>(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
@@ -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<QueryPool> {
public:
explicit QueryPoolAgent(QueryPool *actor);
~QueryPoolAgent() override;
protected:
friend class DeviceAgent;
void doInit(const QueryPoolInfo &info) override;
void doDestroy() override;
};
} // namespace gfx
} // namespace cc
@@ -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);
@@ -68,12 +68,14 @@ class PipelineState;
class DescriptorSet;
class CommandBuffer;
class Queue;
class QueryPool;
class Window;
class Context;
using TextureBarrierList = vector<TextureBarrier *>;
using BufferDataList = vector<const uint8_t *>;
using CommandBufferList = vector<CommandBuffer *>;
using QueryPoolList = vector<QueryPool *>;
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};
@@ -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 &regions);
inline void flushCommands(const vector<CommandBuffer *> &cmdBuffs);
inline void acquire(const vector<Swapchain *> &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<bool, static_cast<size_t>(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);
@@ -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
@@ -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 <cstdint>
#include <mutex>
#include <unordered_map>
#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<uint32_t, uint64_t> _results;
};
} // namespace gfx
} // namespace cc
@@ -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
@@ -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;
@@ -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
@@ -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;
@@ -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
@@ -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
@@ -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 <typename T, typename = std::enable_if_t<std::is_base_of<GLESCmd, T>::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<int>(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<T *> _freeCmds;
int _freeIdx = 0;
int _freeIdx = 0;
};
} // namespace gfx
@@ -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;
@@ -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<const char *>(glGetString(GL_EXTENSIONS));
_extensions = StringUtil::split(extStr, " ");
@@ -217,6 +209,18 @@ bool GLES2Device::doInit(const DeviceInfo & /*info*/) {
glGetIntegerv(GL_MAX_TEXTURE_SIZE, reinterpret_cast<GLint *>(&_caps.maxTextureSize));
glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, reinterpret_cast<GLint *>(&_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);
}
@@ -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;
@@ -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<decltype(this)>();
}
GLES2QueryPool::~GLES2QueryPool() {
destroy();
}
void GLES2QueryPool::doInit(const QueryPoolInfo& info) {
}
void GLES2QueryPool::doDestroy() {
}
} // namespace gfx
} // namespace cc
@@ -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
@@ -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<GLES3QueryPool *>(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<GLES3QueryPool *>(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<GLES3QueryPool *>(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<GLES3QueryPool *>(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
@@ -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;
@@ -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<char *>(0) + (idx))
@@ -1765,6 +1766,78 @@ void cmdFuncGLES3CreateGlobalBarrier(const std::vector<AccessType> &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<uint64_t> 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<uint64_t>(result);
} else {
results[queryId] = 1ULL;
}
}
std::unordered_map<uint32_t, uint64_t> 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<std::mutex> 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;
}
@@ -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<GLESCmdType> cmds;
@@ -160,6 +183,7 @@ public:
CachedArray<GLES3CmdUpdateBuffer *> updateBufferCmds;
CachedArray<GLES3CmdCopyBufferToTexture *> copyBufferToTextureCmds;
CachedArray<GLES3CmdBlitTexture *> blitTextureCmds;
CachedArray<GLES3CmdQuery *> queryCmds;
};
class GLES3GPUCommandAllocator final : public Object {
@@ -172,6 +196,7 @@ public:
CommandPool<GLES3CmdUpdateBuffer> updateBufferCmdPool;
CommandPool<GLES3CmdCopyBufferToTexture> copyBufferToTextureCmdPool;
CommandPool<GLES3CmdBlitTexture> blitTextureCmdPool;
CommandPool<GLES3CmdQuery> 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<AccessType> &prevAccesses, const std::vector<AccessType> &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,
@@ -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<const char *>(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<GLint *>(&_caps.maxComputeWorkGroupCount.y));
glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_COUNT, 2, reinterpret_cast<GLint *>(&_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<GLES3Texture *>(srcTexture)->gpuTexture(), buffers, regions, count);
}
void GLES3Device::getQueryPoolResults(QueryPool *queryPool) {
auto *cmdBuff = static_cast<GLES3CommandBuffer *>(getCommandBuffer());
cmdBuff->getQueryPoolResults(queryPool);
}
} // namespace gfx
} // namespace cc
@@ -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;
@@ -97,6 +97,21 @@ public:
GLuint glFramebuffer{0};
};
class GLES3GPUQueryPool final : public Object {
public:
QueryType type{QueryType::OCCLUSION};
uint32_t maxQueryObjects{0};
std::vector<GLuint> 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;
@@ -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<GLES3QueryPool *>(queryPool);
cmdFuncGLES3Query(GLES3Device::getInstance(), gles3QueryPool, GLES3QueryType::BEGIN, id);
}
void GLES3PrimaryCommandBuffer::endQuery(QueryPool *queryPool, uint32_t id) {
auto *gles3QueryPool = static_cast<GLES3QueryPool *>(queryPool);
cmdFuncGLES3Query(GLES3Device::getInstance(), gles3QueryPool, GLES3QueryType::END, id);
}
void GLES3PrimaryCommandBuffer::resetQuery(QueryPool *queryPool) {
auto *gles3QueryPool = static_cast<GLES3QueryPool *>(queryPool);
cmdFuncGLES3Query(GLES3Device::getInstance(), gles3QueryPool, GLES3QueryType::RESET, 0);
}
void GLES3PrimaryCommandBuffer::getQueryPoolResults(QueryPool *queryPool) {
auto *gles3QueryPool = static_cast<GLES3QueryPool *>(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<GLES3PrimaryCommandBuffer *>(cmdBuffs[i]);
@@ -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;
};
@@ -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<decltype(this)>();
}
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
@@ -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 <vector>
#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<uint32_t>(_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<uint32_t, uint64_t> &&results) { _results = results; }
protected:
friend class GLES3CommandBuffer;
void doInit(const QueryPoolInfo &info) override;
void doDestroy() override;
GLES3GPUQueryPool * _gpuQueryPool = nullptr;
std::vector<uint32_t> _ids;
};
} // namespace gfx
} // namespace cc
@@ -27,11 +27,12 @@
#include "gfx-base/GFXCommandBuffer.h"
#include "MTLGPUObjects.h"
#include "MTLRenderCommandEncoder.h"
#include "MTLComputeCommandEncoder.h"
#import <Metal/MTLCommandQueue.h>
#import <MetalKit/MTKView.h>
#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<CCMTLGPUDescriptorSet *> _GPUDescriptorSets; // NOLINT(bugprone-reserved-identifier)
vector<vector<uint>> _dynamicOffsets;
uint _firstDirtyDescriptorSet = UINT_MAX;
vector<vector<uint>> _dynamicOffsets;
uint _firstDirtyDescriptorSet = UINT_MAX;
bool _indirectDrawSuppotred = false;
bool _commandBufferBegan = false;
CCMTLDevice *_mtlDevice = nullptr;
id<MTLCommandQueue> _mtlCommandQueue = nil;
CCMTLRenderCommandEncoder _renderEncoder;
CCMTLComputeCommandEncoder _computeEncoder;
id<MTLParallelRenderCommandEncoder> _parallelEncoder = nil;
MTLPrimitiveType _mtlPrimitiveType = MTLPrimitiveType::MTLPrimitiveTypeTriangle;
bool _indirectDrawSuppotred = false;
bool _commandBufferBegan = false;
CCMTLDevice * _mtlDevice = nullptr;
id<MTLCommandQueue> _mtlCommandQueue = nil;
CCMTLRenderCommandEncoder _renderEncoder;
CCMTLComputeCommandEncoder _computeEncoder;
id<MTLParallelRenderCommandEncoder> _parallelEncoder = nil;
MTLPrimitiveType _mtlPrimitiveType = MTLPrimitiveType::MTLPrimitiveTypeTriangle;
CCMTLGPUCommandBufferObject* _gpuCommandBufferObj = nullptr;
CCMTLGPUCommandBufferObject *_gpuCommandBufferObj = nullptr;
};
} // namespace gfx
@@ -25,6 +25,7 @@
#import "MTLStd.h"
#import <MetalPerformanceShaders/MetalPerformanceShaders.h>
#import <QuartzCore/CAMetalLayer.h>
#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 <MetalPerformanceShaders/MetalPerformanceShaders.h>
#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<CCMTLQueue*>(_queue)->gpuQueueObj()->mtlCommandQueue;
auto *mtlQueue = static_cast<CCMTLQueue *>(_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<CCMTLRenderPass*>(renderPass);
_gpuCommandBufferObj->fbo = static_cast<CCMTLFramebuffer*>(fbo);
_gpuCommandBufferObj->renderPass = static_cast<CCMTLRenderPass *>(renderPass);
_gpuCommandBufferObj->fbo = static_cast<CCMTLFramebuffer *>(fbo);
auto *ccMtlRenderPass = static_cast<CCMTLRenderPass *>(renderPass);
auto isOffscreen = _gpuCommandBufferObj->fbo->isOffscreen();
const SubpassInfoList& subpasses = renderPass->getSubpasses();
const ColorAttachmentList& colorAttachments = renderPass->getColorAttachments();
auto * ccMtlRenderPass = static_cast<CCMTLRenderPass *>(renderPass);
auto isOffscreen = _gpuCommandBufferObj->fbo->isOffscreen();
const SubpassInfoList & subpasses = renderPass->getSubpasses();
const ColorAttachmentList &colorAttachments = renderPass->getColorAttachments();
MTLRenderPassDescriptor *mtlRenderPassDescriptor = static_cast<CCMTLRenderPass *>(renderPass)->getMTLRenderPassDescriptor();
const TextureList &colorTextures = fbo->getColorTextures();
Texture *dsTexture = fbo->getDepthStencilTexture();
auto* swapchain = static_cast<CCMTLSwapchain*>(_gpuCommandBufferObj->fbo->swapChain());
const TextureList & colorTextures = fbo->getColorTextures();
Texture * dsTexture = fbo->getDepthStencilTexture();
auto * swapchain = static_cast<CCMTLSwapchain *>(_gpuCommandBufferObj->fbo->swapChain());
if(subpasses.empty()) {
if (subpasses.empty()) {
if (dsTexture) {
auto *ccMtlTexture = static_cast<CCMTLTexture *>(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<CCMTLTexture *>(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<CCMTLTexture *>(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<CCMTLTexture *>(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<CCMTLTexture *>(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<CCMTLTexture *>(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<CCMTLTexture *>(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<CCMTLTexture *>(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<CCMTLTexture *>(colorTextures[subpass.depthStencil]);
auto *ccMTLTexture = static_cast<CCMTLTexture *>(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<CCMTLTexture *>(curFBO->getDepthStencilTexture());
} else {
dsResolveTex = static_cast<CCMTLTexture *>(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<CCMTLPipelineState *>(pso);
PipelineBindPoint bindPoint = pso->getBindPoint();
CCMTLGPUPipelineState *pplState = nullptr;
auto * ccPipeline = static_cast<CCMTLPipelineState *>(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<CCMTLRenderPass*>(curRenderPass);
CCMTLRenderPass *curRenderPass = _gpuCommandBufferObj->renderPass;
if (curRenderPass) {
auto *ccRenderpass = static_cast<CCMTLRenderPass *>(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<CCMTLTexture *>(colorTextures[input]);
const uint input = inputs[i];
auto * ccMtlTexture = static_cast<CCMTLTexture *>(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<CCMTLBuffer *>(inputAssembler->getIndirectBuffer());
const auto *indexBuffer = static_cast<CCMTLBuffer *>(inputAssembler->getIndexBuffer());
auto mtlEncoder = _renderEncoder.getMTLEncoder();
CCMTLInputAssembler *inputAssembler = _gpuCommandBufferObj->inputAssembler;
const auto * indirectBuffer = static_cast<CCMTLBuffer *>(inputAssembler->getIndirectBuffer());
const auto * indexBuffer = static_cast<CCMTLBuffer *>(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<CCMTLTexture*>(texture)->textureInfo().flags, TextureFlags::GEN_MIPMAP) && mu::pixelFormatIsColorRenderable(convertedFormat)) {
if (hasFlag(static_cast<CCMTLTexture *>(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<MTLCommandBuffer> mtlCmdBuffer = nil;
if(cmdActivated) {
if (cmdActivated) {
mtlCmdBuffer = _gpuCommandBufferObj->mtlCommandBuffer;
} else {
mtlCmdBuffer = [static_cast<CCMTLQueue*>(_queue)->gpuQueueObj()->mtlCommandQueue commandBufferWithUnretainedReferences];
mtlCmdBuffer = [static_cast<CCMTLQueue *>(_queue)->gpuQueueObj()->mtlCommandQueue commandBufferWithUnretainedReferences];
[mtlCmdBuffer enqueue];
}
auto* ccSrcTex = static_cast<CCMTLTexture*>(srcTexture);
auto* ccDstTex = static_cast<CCMTLTexture*>(dstTexture);
auto *ccSrcTex = static_cast<CCMTLTexture *>(srcTexture);
auto *ccDstTex = static_cast<CCMTLTexture *>(dstTexture);
id<MTLTexture> src = nil;
if(ccSrcTex->swapChain()) {
id<MTLTexture> src = nil;
if (ccSrcTex->swapChain()) {
src = ccSrcTex->swapChain()->currentDrawable().texture;
} else {
src = ccSrcTex->getMTLTexture();
}
id<MTLTexture> dst = nil;
if(ccDstTex->swapChain()) {
id<MTLTexture> dst = nil;
if (ccDstTex->swapChain()) {
dst = ccDstTex->swapChain()->currentDrawable().texture;
} else {
dst = ccDstTex->getMTLTexture();
}
id<MTLDevice> mtlDevice = static_cast<id<MTLDevice>>(_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<MTLTexture> formatTex = [mtlDevice newTextureWithDescriptor:descriptor];
MPSImageConversion *conversion = [[MPSImageConversion alloc] initWithDevice: mtlDevice srcAlpha:MPSAlphaTypeNonPremultiplied destAlpha:MPSAlphaTypeNonPremultiplied backgroundColor:nil conversionInfo:nil];
id<MTLTexture> 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<MTLTexture> 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<MTLBlitCommandEncoder> 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<CCMTLTexture*>(src);
Format convertedFormat = ccMTLTexture->getConvertedFormat();
id<MTLTexture> mtlTexture = ccMTLTexture->getMTLTexture();
auto * ccMTLTexture = static_cast<CCMTLTexture *>(src);
Format convertedFormat = ccMTLTexture->getConvertedFormat();
id<MTLTexture> 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];
}
}
+54 -50
View File
@@ -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<CCMTLSwapchain*> _swapchains;
std::vector<CCMTLSwapchain *> _swapchains;
CCMTLGPUDeviceObject* _gpuDeviceObj = nullptr;
CCMTLGPUDeviceObject *_gpuDeviceObj = nullptr;
};
} // namespace gfx
+68 -57
View File
@@ -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> 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<CCMTLQueue *>(_queue);
CCMTLQueue *queue = static_cast<CCMTLQueue *>(_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<id<CAMetalDrawable>> 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);
}
@@ -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
@@ -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<decltype(this)>();
}
CCMTLQueryPool::~CCMTLQueryPool() {
destroy();
}
void CCMTLQueryPool::doInit(const QueryPoolInfo& info) {
}
void CCMTLQueryPool::doDestroy() {
}
} // namespace gfx
} // namespace cc
@@ -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<QueryPoolValidator *>(queryPool)->isInited(), "already destroyed?");
QueryPool *actorQueryPool = static_cast<QueryPoolValidator *>(queryPool)->getActor();
_actor->beginQuery(actorQueryPool, id);
}
void CommandBufferValidator::endQuery(QueryPool *queryPool, uint32_t id) {
CCASSERT(isInited(), "already destroyed?");
CCASSERT(static_cast<QueryPoolValidator *>(queryPool)->isInited(), "already destroyed?");
QueryPool *actorQueryPool = static_cast<QueryPoolValidator *>(queryPool)->getActor();
_actor->endQuery(actorQueryPool, id);
}
void CommandBufferValidator::resetQuery(QueryPool *queryPool) {
CCASSERT(isInited(), "already destroyed?");
CCASSERT(static_cast<QueryPoolValidator *>(queryPool)->isInited(), "already destroyed?");
QueryPool *actorQueryPool = static_cast<QueryPoolValidator *>(queryPool)->getActor();
_actor->resetQuery(actorQueryPool);
}
} // namespace gfx
} // namespace cc
@@ -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;
@@ -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<uint32_t>(Feature::COUNT) * sizeof(bool));
static_cast<QueueValidator *>(_queue)->_inited = true;
static_cast<QueryPoolValidator *>(_queryPool)->_inited = true;
static_cast<CommandBufferValidator *>(_cmdBuff)->_queue = _queue;
static_cast<CommandBufferValidator *>(_cmdBuff)->initValidator();
DeviceResourceTracker<CommandBuffer>::push(_cmdBuff);
DeviceResourceTracker<QueryPool>::push(_queryPool);
DeviceResourceTracker<Queue>::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<CommandBufferValidator *>(_cmdBuff)->destroyValidator();
static_cast<CommandBufferValidator *>(_cmdBuff)->_actor = nullptr;
CC_DELETE(_cmdBuff);
_cmdBuff = nullptr;
}
if (_queryPool) {
static_cast<QueryPoolValidator *>(_queryPool)->_actor = nullptr;
CC_DELETE(_queryPool);
_queryPool = nullptr;
}
if (_queue) {
static_cast<QueueValidator *>(_queue)->_actor = nullptr;
CC_DELETE(_queue);
@@ -99,6 +109,7 @@ void DeviceValidator::doDestroy() {
}
DeviceResourceTracker<CommandBuffer>::checkEmpty();
DeviceResourceTracker<QueryPool>::checkEmpty();
DeviceResourceTracker<Queue>::checkEmpty();
DeviceResourceTracker<Swapchain>::checkEmpty();
DeviceResourceTracker<Buffer>::checkEmpty();
@@ -148,6 +159,13 @@ Queue *DeviceValidator::createQueue() {
return result;
}
QueryPool *DeviceValidator::createQueryPool() {
QueryPool *actor = _actor->createQueryPool();
QueryPool *result = CC_NEW(QueryPoolValidator(actor));
DeviceResourceTracker<QueryPool>::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<QueryPoolValidator *>(queryPool)->getActor();
_actor->getQueryPoolResults(actorQueryPool);
auto * actorQueryPoolValidator = static_cast<QueryPoolValidator *>(actorQueryPool);
auto * queryPoolValidator = static_cast<QueryPoolValidator *>(queryPool);
std::lock_guard<std::mutex> lock(actorQueryPoolValidator->_mutex);
queryPoolValidator->_results = actorQueryPoolValidator->_results;
}
} // namespace gfx
} // namespace cc
@@ -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(); }
@@ -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<QueryPool>(actor) {
_typedID = actor->getTypedID();
_type = actor->getType();
_maxQueryObjects = actor->getMaxQueryObjects();
}
QueryPoolValidator::~QueryPoolValidator() {
DeviceResourceTracker<QueryPool>::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
@@ -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<QueryPool> {
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
@@ -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<CCVKQueryPool *>(queryPool);
CCVKGPUQueryPool *gpuQueryPool = vkQueryPool->gpuQueryPool();
auto queryId = static_cast<uint32_t>(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<CCVKQueryPool *>(queryPool);
CCVKGPUQueryPool *gpuQueryPool = vkQueryPool->gpuQueryPool();
auto queryId = static_cast<uint32_t>(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<CCVKQueryPool *>(queryPool);
CCVKGPUQueryPool *gpuQueryPool = vkQueryPool->gpuQueryPool();
vkCmdResetQueryPool(_gpuCommandBuffer->vkCommandBuffer, gpuQueryPool->pool, 0, queryPool->getMaxQueryObjects());
vkQueryPool->_ids.clear();
}
} // namespace gfx
} // namespace cc
@@ -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; }
@@ -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);
@@ -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);
@@ -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<CCVKQueryPool *>(queryPool);
auto queryCount = static_cast<uint32_t>(vkQueryPool->_ids.size());
CCASSERT(queryCount <= vkQueryPool->getMaxQueryObjects(), "Too many query commands.");
std::vector<uint64_t> 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<uint32_t, uint64_t> 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<std::mutex> lock(vkQueryPool->_mutex);
vkQueryPool->_results = std::move(mapResults);
}
}
//////////////////////////// Function Fallbacks /////////////////////////////////////////
static VkResult VKAPI_PTR vkCreateRenderPass2KHRFallback(
@@ -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();
+43 -33
View File
@@ -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<VkImageView> 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<VkBool32> 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<VkBuffer> 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<uint32_t> possibleQueueFamilyIndices;
uint32_t queueFamilyIndex = 0U;
vector<uint32_t> possibleQueueFamilyIndices;
vector<VkSemaphore> lastSignaledSemaphores;
vector<VkPipelineStageFlags> submitStageMasks;
vector<VkCommandBuffer> 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<VkExtensionProperties> 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<VkFence> _fences;
};
@@ -494,7 +501,7 @@ public:
private:
CCVKGPUDevice * _device;
uint32_t _count = 0U;
uint32_t _count = 0U;
vector<VkSemaphore> _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<VkDescriptorPoolSize> _poolSizes;
vector<VkDescriptorSetLayout> _setLayouts;
uint32_t _maxSetsPerPool = 0U;
uint32_t _maxSetsPerPool = 0U;
};
class CCVKGPUDescriptorSetLayout final : public Object {
public:
DescriptorSetLayoutBindingList bindings;
vector<uint32_t> dynamicBindings;
vector<uint32_t> dynamicBindings;
vector<VkDescriptorSetLayoutBinding> vkBindings;
VkDescriptorSetLayout vkDescriptorSetLayout = VK_NULL_HANDLE;
@@ -736,7 +743,7 @@ private:
};
CCVKGPUDevice *_device = nullptr;
uint32_t _lastBackBufferIndex = 0U;
uint32_t _lastBackBufferIndex = 0U;
unordered_map<uint32_t, CommandBufferPool> _pools;
};
@@ -1034,7 +1041,7 @@ private:
CachedArray<T *> descriptors;
};
unordered_map<const VkDescriptorBufferInfo *, uint32_t> _bufferInstanceIndices;
unordered_map<const VkDescriptorBufferInfo *, uint32_t> _bufferInstanceIndices;
unordered_map<const CCVKGPUBufferView *, DescriptorInfo<VkDescriptorBufferInfo>> _buffers;
unordered_map<const CCVKGPUTextureView *, DescriptorInfo<VkDescriptorImageInfo>> _textures;
unordered_map<const CCVKGPUSampler *, CachedArray<VkDescriptorImageInfo *>> _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<Resource> _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<unordered_map<CCVKGPUBuffer *, BufferUpdate>> _buffersToBeUpdated;
@@ -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<decltype(this)>();
}
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
@@ -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 <mutex>
#include <vector>
#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<uint32_t> _ids;
};
} // namespace gfx
} // namespace cc
@@ -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;
@@ -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);
+19
View File
@@ -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,
+15 -4
View File
@@ -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<bool(const RenderPass &a, const RenderPass &b)> 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<RenderQueueDesc>;
@@ -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<uint>(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;
@@ -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;
@@ -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);
}
}
}
}
@@ -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;
@@ -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<scene::Camera *> &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<int>(rect.x * scale),
static_cast<int>(rect.y * scale),
static_cast<uint>(rect.width * scale),
static_cast<uint>(rect.height * scale)
};
static_cast<uint>(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
@@ -25,6 +25,7 @@
#pragma once
#include <unordered_map>
#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<String, InternalBindingInst> _globalBindings;
DefineMap _macros;
@@ -141,6 +150,7 @@ protected:
// use cluster culling or not
bool _clusterEnabled{false};
bool _bloomEnabled{false};
bool _occlusionQueryEnabled{true};
};
} // namespace pipeline
+41 -14
View File
@@ -27,15 +27,17 @@
#include <utility>
#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());
}
}
}
+9 -2
View File
@@ -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
@@ -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({
@@ -122,6 +122,7 @@ void DeferredPipeline::render(const vector<scene::Camera *> &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);
@@ -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<DeferredPipeline *>(_pipeline), table.getRenderPass());
auto gbufferExec = [this, camera](const RenderData & /*data*/, const framegraph::DevicePassResourceTable &table) {
recordCommands(static_cast<DeferredPipeline *>(_pipeline), camera, table.getRenderPass());
};
// Command 'updateBuffer' must be recorded outside render passes, cannot put them in execute lambda
@@ -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;
@@ -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<DeferredPipeline *>(_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<DeferredPipeline *>(_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
@@ -82,7 +82,18 @@ bool ForwardPipeline::activate(gfx::Swapchain *swapchain) {
}
void ForwardPipeline::render(const vector<scene::Camera *> &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<scene::Camera *> &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();
@@ -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);
}
};
+20 -11
View File
@@ -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<Vec3, 8> &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]);
+1
View File
@@ -65,6 +65,7 @@ public:
void merge(const Frustum &frustum);
void set(const cc::Vec3 &centerVal, 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 &center) { _aabbLayout->center.set(center); }
inline void setValid(bool isValid) { _isValid = isValid; }
+20 -16
View File
@@ -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<Pass *> bloomDownsamplePass;
gfx::Shader * bloomDownsamplePassShader{nullptr};
gfx::Shader * bloomDownsamplePassShader{nullptr};
std::vector<Pass *> 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 {
+16 -1
View File
@@ -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<float, pipeline::UBOWorldBound::COUNT> 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<uint32_t>(_subModels.size())) {
_subModels.emplace_back(subModel);
return;
+4
View File
@@ -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<uint8_t *, uint32_t> _instancedBuffer{nullptr, 0};
gfx::Buffer * _localBuffer{nullptr};
gfx::Buffer * _worldBoundBuffer{nullptr};
InstancedAttributeBlock _instanceAttributeBlock{};
std::vector<SubModel *> _subModels;
std::vector<gfx::Attribute> _instanceAttributes;
+5
View File
@@ -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() {
+17 -1
View File
@@ -25,20 +25,23 @@
#pragma once
#include <cstdint>
#include <vector>
#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<gfx::Shader *> &shaders) { _shaders = shaders; }
inline void setPasses(const std::vector<Pass *> &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<cc::scene::FlatBuffer> &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<gfx::Shader *> &getShaders() { return _shaders; }
inline const std::vector<Pass *> & 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<Pass *> _passes;
std::vector<gfx::Shader *> _shaders;
Model * _owner{nullptr};
uint32_t _id = -1;
};
} // namespace scene
+3 -2
View File
@@ -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],