From 3fab846f7b75f4211a2fa4daeb6da38cb78d66bc Mon Sep 17 00:00:00 2001 From: Zach Lee Date: Thu, 13 Apr 2023 17:41:30 +0800 Subject: [PATCH] GFX Pipeline Cache. (#14759) --- native/CMakeLists.txt | 8 + native/cocos/base/BinaryArchive.cpp | 46 +++++ native/cocos/base/BinaryArchive.h | 94 ++++++++++ native/cocos/core/assets/EffectAsset.h | 2 +- native/cocos/renderer/core/ProgramLib.cpp | 2 +- .../cocos/renderer/gfx-base/GFXDef-common.h | 4 + native/cocos/renderer/gfx-base/GFXShader.cpp | 2 +- native/cocos/renderer/gfx-base/GFXShader.h | 1 + native/cocos/renderer/gfx-base/GFXUtil.cpp | 34 ++++ native/cocos/renderer/gfx-base/GFXUtil.h | 34 ++++ .../renderer/gfx-gles3/GLES3Commands.cpp | 52 +++++- .../cocos/renderer/gfx-gles3/GLES3Commands.h | 2 +- .../gfx-gles3/GLES3DescriptorSetLayout.cpp | 10 + .../cocos/renderer/gfx-gles3/GLES3Device.cpp | 8 + native/cocos/renderer/gfx-gles3/GLES3Device.h | 3 + .../renderer/gfx-gles3/GLES3GPUObjects.h | 14 +- .../renderer/gfx-gles3/GLES3PipelineCache.cpp | 171 ++++++++++++++++++ .../renderer/gfx-gles3/GLES3PipelineCache.h | 59 ++++++ .../gfx-gles3/GLES3PipelineLayout.cpp | 3 + .../renderer/gfx-gles3/GLES3PipelineState.cpp | 22 ++- .../cocos/renderer/gfx-gles3/GLES3Shader.cpp | 20 +- .../cocos/renderer/gfx-vulkan/VKCommands.cpp | 12 +- native/cocos/renderer/gfx-vulkan/VKDevice.cpp | 10 +- native/cocos/renderer/gfx-vulkan/VKDevice.h | 3 + .../cocos/renderer/gfx-vulkan/VKGPUObjects.h | 1 - .../renderer/gfx-vulkan/VKPipelineCache.cpp | 129 +++++++++++++ .../renderer/gfx-vulkan/VKPipelineCache.h | 55 ++++++ .../pipeline/custom/NativeProgramLibrary.cpp | 9 + 28 files changed, 771 insertions(+), 39 deletions(-) create mode 100644 native/cocos/base/BinaryArchive.cpp create mode 100644 native/cocos/base/BinaryArchive.h create mode 100644 native/cocos/renderer/gfx-base/GFXUtil.cpp create mode 100644 native/cocos/renderer/gfx-base/GFXUtil.h create mode 100644 native/cocos/renderer/gfx-gles3/GLES3PipelineCache.cpp create mode 100644 native/cocos/renderer/gfx-gles3/GLES3PipelineCache.h create mode 100644 native/cocos/renderer/gfx-vulkan/VKPipelineCache.cpp create mode 100644 native/cocos/renderer/gfx-vulkan/VKPipelineCache.h diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index f03c0c1721..288b445a30 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -453,6 +453,8 @@ cocos_source_files( cocos/base/ThreadPool.cpp cocos/base/ThreadPool.h cocos/base/TypeDef.h + cocos/base/BinaryArchive.cpp + cocos/base/BinaryArchive.h cocos/base/std/any.h cocos/base/std/optional.h cocos/base/std/variant.h @@ -1144,6 +1146,8 @@ cocos_source_files( cocos/renderer/gfx-base/GFXTexture.cpp cocos/renderer/gfx-base/GFXTexture.h cocos/renderer/gfx-base/GFXDeviceObject.h + cocos/renderer/gfx-base/GFXUtil.cpp + cocos/renderer/gfx-base/GFXUtil.h cocos/renderer/gfx-base/states/GFXGeneralBarrier.cpp cocos/renderer/gfx-base/states/GFXGeneralBarrier.h cocos/renderer/gfx-base/states/GFXSampler.cpp @@ -1628,6 +1632,8 @@ if(CC_USE_GLES3) cocos/renderer/gfx-gles3/GLES3Texture.h cocos/renderer/gfx-gles3/GLES3Wrangler.cpp cocos/renderer/gfx-gles3/GLES3Wrangler.h + cocos/renderer/gfx-gles3/GLES3PipelineCache.cpp + cocos/renderer/gfx-gles3/GLES3PipelineCache.h cocos/renderer/gfx-gles3/states/GLES3GeneralBarrier.cpp cocos/renderer/gfx-gles3/states/GLES3GeneralBarrier.h cocos/renderer/gfx-gles3/states/GLES3Sampler.cpp @@ -1725,6 +1731,8 @@ if(CC_USE_VULKAN) cocos/renderer/gfx-vulkan/volk.c cocos/renderer/gfx-vulkan/volk.h cocos/renderer/gfx-vulkan/VKGPURecycleBin.cpp + cocos/renderer/gfx-vulkan/VKPipelineCache.cpp + cocos/renderer/gfx-vulkan/VKPipelineCache.h cocos/renderer/gfx-vulkan/states/VKGeneralBarrier.cpp cocos/renderer/gfx-vulkan/states/VKGeneralBarrier.h cocos/renderer/gfx-vulkan/states/VKSampler.cpp diff --git a/native/cocos/base/BinaryArchive.cpp b/native/cocos/base/BinaryArchive.cpp new file mode 100644 index 0000000000..ac47e663c5 --- /dev/null +++ b/native/cocos/base/BinaryArchive.cpp @@ -0,0 +1,46 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "BinaryArchive.h" +#include "base/Assertf.h" + +namespace cc { + +bool BinaryInputArchive::load(char *data, uint32_t size) { + CC_ASSERT(!!_stream); + return _stream.rdbuf()->sgetn(data, size) == size; +} + +void BinaryInputArchive::move(uint32_t length) { + CC_ASSERT(!!_stream); + _stream.ignore(length); +} + +void BinaryOutputArchive::save(const char *data, uint32_t size) { + CC_ASSERT(!!_stream); + auto len = _stream.rdbuf()->sputn(data, size); + CC_ASSERT(len == size); +} + +} // namespace cc diff --git a/native/cocos/base/BinaryArchive.h b/native/cocos/base/BinaryArchive.h new file mode 100644 index 0000000000..9e52f1da20 --- /dev/null +++ b/native/cocos/base/BinaryArchive.h @@ -0,0 +1,94 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + + +#pragma once + +#include + +namespace cc { + +/** + * Binary input stream archive. + */ +class BinaryInputArchive { +public: + explicit BinaryInputArchive(std::istream &stream) : _stream(stream) {} + ~BinaryInputArchive() = default; + + /** + * Read data from stream. + * @param data Pointer to data address to read. + * @param size Length of the data. + */ + bool load(char *data, uint32_t size); + + /** + * Read arithmetic data from stream. + * @param val Data to read. + */ + template >> + bool load(T &val) { + return load(reinterpret_cast(std::addressof(val)), sizeof(T)); + } + + /** + * Skip data length + * @param length Skip length + */ + void move(uint32_t length); + +private: + std::istream &_stream; +}; + +/** + * Binary output stream archive. + */ +class BinaryOutputArchive { +public: + explicit BinaryOutputArchive(std::ostream &stream) : _stream(stream) {} + ~BinaryOutputArchive() = default; + + /** + * Write data to stream. + * @param data Pointer to data address to write. + * @param size Length of the data. + */ + void save(const char* data, uint32_t size); + + /** + * Write arithmetic data to stream. + * @param val Data to write. + */ + template >> + void save(const T &v) { + save(reinterpret_cast(std::addressof(v)), sizeof(T)); + } + +private: + std::ostream &_stream; +}; + +} // namespace cc diff --git a/native/cocos/core/assets/EffectAsset.h b/native/cocos/core/assets/EffectAsset.h index 23c560867f..a942e96acd 100644 --- a/native/cocos/core/assets/EffectAsset.h +++ b/native/cocos/core/assets/EffectAsset.h @@ -523,7 +523,7 @@ struct IShaderSource { struct IShaderInfo { ccstd::string name; - ccstd::hash_t hash{0xFFFFFFFFU}; + ccstd::hash_t hash{gfx::INVALID_SHADER_HASH}; IShaderSource glsl4; IShaderSource glsl3; IShaderSource glsl1; diff --git a/native/cocos/renderer/core/ProgramLib.cpp b/native/cocos/renderer/core/ProgramLib.cpp index 36097092d4..ab2faddc85 100644 --- a/native/cocos/renderer/core/ProgramLib.cpp +++ b/native/cocos/renderer/core/ProgramLib.cpp @@ -488,7 +488,7 @@ gfx::Shader *ProgramLib::getGFXShader(gfx::Device *device, const ccstd::string & tmplInfo.shaderInfo.attributes = render::getActiveAttributes(tmpl, tmplInfo.gfxAttributes, defines); tmplInfo.shaderInfo.name = render::getShaderInstanceName(name, macroArray); - + tmplInfo.shaderInfo.hash = tmpl.hash; auto *shader = device->createShader(tmplInfo.shaderInfo); _cache[key] = shader; // CC_LOG_DEBUG("ProgramLib::_cache[%s]=%p, defines: %d", key.c_str(), shader, defines.size()); diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index b682c2506f..a5f42afa02 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -36,6 +36,8 @@ #undef Status #endif +#define CC_USE_PIPELINE_CACHE 0 + /** * Some general guide lines: * Always use explicit numeric types rather than `int`, `long`, etc. for a stable memory layout @@ -96,6 +98,7 @@ using IndexList = ccstd::vector; constexpr uint32_t MAX_ATTACHMENTS = 4U; constexpr uint32_t INVALID_BINDING = ~0U; constexpr uint32_t SUBPASS_EXTERNAL = ~0U; +constexpr ccstd::hash_t INVALID_SHADER_HASH = 0xFFFFFFFFU; // Although the standard is not limited, some devices do not support up to 65536 queries constexpr uint32_t DEFAULT_MAX_QUERY_OBJECTS = 32767; @@ -1261,6 +1264,7 @@ struct ShaderInfo { UniformTextureList textures; UniformStorageImageList images; UniformInputAttachmentList subpassInputs; + ccstd::hash_t hash = INVALID_SHADER_HASH; EXPOSE_COPY_FN(ShaderInfo) }; diff --git a/native/cocos/renderer/gfx-base/GFXShader.cpp b/native/cocos/renderer/gfx-base/GFXShader.cpp index 031d8cf5de..06e074c9ac 100644 --- a/native/cocos/renderer/gfx-base/GFXShader.cpp +++ b/native/cocos/renderer/gfx-base/GFXShader.cpp @@ -46,7 +46,7 @@ void Shader::initialize(const ShaderInfo &info) { _textures = info.textures; _images = info.images; _subpassInputs = info.subpassInputs; - + _hash = info.hash; doInit(info); } diff --git a/native/cocos/renderer/gfx-base/GFXShader.h b/native/cocos/renderer/gfx-base/GFXShader.h index af853d1c99..c66395ecb6 100644 --- a/native/cocos/renderer/gfx-base/GFXShader.h +++ b/native/cocos/renderer/gfx-base/GFXShader.h @@ -63,6 +63,7 @@ protected: UniformTextureList _textures; UniformStorageImageList _images; UniformInputAttachmentList _subpassInputs; + ccstd::hash_t _hash = 0; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXUtil.cpp b/native/cocos/renderer/gfx-base/GFXUtil.cpp new file mode 100644 index 0000000000..84bede7137 --- /dev/null +++ b/native/cocos/renderer/gfx-base/GFXUtil.cpp @@ -0,0 +1,34 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "GFXUtil.h" +#include "platform/FileUtils.h" + +namespace cc::gfx { + +ccstd::string getPipelineCacheFolder() { + return FileUtils::getInstance()->getWritablePath(); +} + +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-base/GFXUtil.h b/native/cocos/renderer/gfx-base/GFXUtil.h new file mode 100644 index 0000000000..d90703177f --- /dev/null +++ b/native/cocos/renderer/gfx-base/GFXUtil.h @@ -0,0 +1,34 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "base/std/container/string.h" + +namespace cc::gfx { + +// FileUtils `enum class Status conflicts` with `#define Status int` in Xlib.h +ccstd::string getPipelineCacheFolder(); + +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index 1424ad1507..a7c479634f 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -25,6 +25,7 @@ #include "GLES3Commands.h" #include "GLES3Device.h" #include "GLES3QueryPool.h" +#include "GLES3PipelineCache.h" #include "GLES3Std.h" #include "base/StringUtil.h" #include "gfx-base/GFXDef-common.h" @@ -1028,8 +1029,25 @@ GLuint GLES3GPUSampler::getGLSampler(uint16_t minLod, uint16_t maxLod) { return _cache[hash]; } -// NOLINTNEXTLINE(google-readability-function-size, readability-function-size) -void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { +bool cmdFuncGLES3CreateProgramByBinary(GLES3Device *device, GLES3GPUShader *gpuShader, GLES3GPUPipelineLayout *pipelineLayout) { + auto *pipelineCache = device->pipelineCache(); + if (pipelineCache == nullptr || gpuShader->hash == INVALID_SHADER_HASH) { + return false; + } + + ccstd::hash_t hash = gpuShader->hash; + ccstd::hash_combine(hash, pipelineLayout->hash); + + auto *item = pipelineCache->fetchBinary(gpuShader->name, hash); + if (item != nullptr) { + GL_CHECK(gpuShader->glProgram = glCreateProgram()); + GL_CHECK(glProgramBinary(gpuShader->glProgram, item->format, item->data.data(), item->data.size())); + return true; + } + return false; +} + +bool cmdFuncGLES3CreateProgramBySource(GLES3Device *device, GLES3GPUShader *gpuShader, GLES3GPUPipelineLayout *pipelineLayout) { GLenum glShaderStage = 0; ccstd::string shaderStageStr; GLint status; @@ -1055,7 +1073,7 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { } default: { CC_ABORT(); - return; + return false; } } GL_CHECK(gpuStage.glShader = glCreateShader(glShaderStage)); @@ -1079,7 +1097,7 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { CC_FREE(logs); GL_CHECK(glDeleteShader(gpuStage.glShader)); gpuStage.glShader = 0; - return; + return false; } } @@ -1115,10 +1133,34 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { CC_LOG_ERROR(logs); CC_FREE(logs); - return; + return false; } } + auto *cache = device->pipelineCache(); + if (cache != nullptr && gpuShader->hash != INVALID_SHADER_HASH) { + GLint binaryLength = 0; + GL_CHECK(glGetProgramiv(gpuShader->glProgram, GL_PROGRAM_BINARY_LENGTH, &binaryLength)); + GLsizei length = 0; + IntrusivePtr binary = ccnew GLES3GPUProgramBinary(); + binary->name = gpuShader->name; + binary->hash = gpuShader->hash; + ccstd::hash_combine(binary->hash, pipelineLayout->hash); + binary->data.resize(binaryLength); + GL_CHECK(glGetProgramBinary(gpuShader->glProgram, binaryLength, &length, &binary->format, binary->data.data())); + cache->addBinary(binary); + } + return true; +} + +// NOLINTNEXTLINE(google-readability-function-size, readability-function-size) +void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader, GLES3GPUPipelineLayout *pipelineLayout) { + + if (!cmdFuncGLES3CreateProgramByBinary(device, gpuShader, pipelineLayout)) { + if (!cmdFuncGLES3CreateProgramBySource(device, gpuShader, pipelineLayout)) { + return; + } + } CC_LOG_INFO("Shader '%s' compilation succeeded.", gpuShader->name.c_str()); GLint attrMaxLength = 0; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.h b/native/cocos/renderer/gfx-gles3/GLES3Commands.h index 9546b77047..38f9a19815 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.h @@ -246,7 +246,7 @@ void cmdFuncGLES3ResizeBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer); void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture); void cmdFuncGLES3DestroyTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture); void cmdFuncGLES3ResizeTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture); -void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader); +void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader, GLES3GPUPipelineLayout *pipelineLayout); void cmdFuncGLES3DestroyShader(GLES3Device *device, GLES3GPUShader *gpuShader); void cmdFuncGLES3CreateRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRenderPass); void cmdFuncGLES3DestroyRenderPass(GLES3Device *device, GLES3GPURenderPass *gpuRenderPass); diff --git a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.cpp b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.cpp index 494fdd44f2..06d1e2acd9 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3DescriptorSetLayout.cpp @@ -26,6 +26,7 @@ #include "GLES3Commands.h" #include "GLES3DescriptorSetLayout.h" +#include "states/GLES3Sampler.h" namespace cc { namespace gfx { @@ -45,12 +46,21 @@ void GLES3DescriptorSetLayout::doInit(const DescriptorSetLayoutInfo & /*info*/) _gpuDescriptorSetLayout->descriptorIndices = _descriptorIndices; _gpuDescriptorSetLayout->bindings = _bindings; + auto &hash = _gpuDescriptorSetLayout->hash; for (auto &binding : _bindings) { if (hasAnyFlags(binding.descriptorType, DESCRIPTOR_DYNAMIC_TYPE)) { for (uint32_t j = 0U; j < binding.count; j++) { _gpuDescriptorSetLayout->dynamicBindings.push_back(binding.binding); } } + + ccstd::hash_combine(hash, binding.binding); + ccstd::hash_combine(hash, binding.descriptorType); + ccstd::hash_combine(hash, binding.count); + ccstd::hash_combine(hash, binding.stageFlags); + for (auto &sampler : binding.immutableSamplers) { + ccstd::hash_combine(hash, sampler->getHash()); + } } } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index 4874be7bd1..f70fa8c2db 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -42,6 +42,7 @@ #include "GLES3Shader.h" #include "GLES3Swapchain.h" #include "GLES3Texture.h" +#include "GLES3PipelineCache.h" #include "application/ApplicationManager.h" #include "platform/java/modules/XRInterface.h" #include "profiler/Profiler.h" @@ -222,6 +223,11 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { _gpuStateCache->initialize(_caps.maxTextureUnits, _caps.maxImageUnits, _caps.maxUniformBufferBindings, _caps.maxShaderStorageBufferBindings, _caps.maxVertexAttributes); +#if CC_USE_PIPELINE_CACHE + _pipelineCache = std::make_unique(); + _pipelineCache->init(); +#endif + CC_LOG_INFO("GLES3 device initialized."); CC_LOG_INFO("RENDERER: %s", _renderer.c_str()); CC_LOG_INFO("VENDOR: %s", _vendor.c_str()); @@ -249,6 +255,8 @@ void GLES3Device::doDestroy() { CC_SAFE_DESTROY_AND_DELETE(_queryPool) CC_SAFE_DESTROY_AND_DELETE(_queue) CC_SAFE_DESTROY_AND_DELETE(_gpuContext) + + _pipelineCache.reset(); } void GLES3Device::acquire(Swapchain *const *swapchains, uint32_t count) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.h b/native/cocos/renderer/gfx-gles3/GLES3Device.h index 1e2a916f87..5eed7ca400 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.h @@ -39,6 +39,7 @@ class GLES3GPUStateCache; class GLES3GPUFramebufferHub; struct GLES3GPUConstantRegistry; class GLES3GPUFramebufferCacheMap; +class GLES3PipelineCache; class CC_GLES3_API GLES3Device final : public Device { public: @@ -76,6 +77,7 @@ public: inline GLES3GPUFramebufferHub *framebufferHub() const { return _gpuFramebufferHub; } inline GLES3GPUConstantRegistry *constantRegistry() const { return _gpuConstantRegistry; } inline GLES3GPUFramebufferCacheMap *framebufferCacheMap() const { return _gpuFramebufferCacheMap; } + inline GLES3PipelineCache *pipelineCache() const { return _pipelineCache.get(); } inline bool checkExtension(const ccstd::string &extension) const { return std::any_of(_extensions.begin(), _extensions.end(), [&extension](auto &ext) { @@ -135,6 +137,7 @@ protected: GLES3GPUFramebufferHub *_gpuFramebufferHub{nullptr}; GLES3GPUConstantRegistry *_gpuConstantRegistry{nullptr}; GLES3GPUFramebufferCacheMap *_gpuFramebufferCacheMap{nullptr}; + std::unique_ptr _pipelineCache; ccstd::vector _swapchains; diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index d5bf276fdd..75cf6509ab 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -23,11 +23,13 @@ #pragma once #include +#include #include "base/Macros.h" #include "base/std/container/unordered_map.h" #include "gfx-base/GFXDef-common.h" #include "gfx-base/GFXDef.h" +#include "gfx-base/GFXDeviceObject.h" #include "gfx-gles-common/GLESCommandPool.h" #include "GLES3Std.h" @@ -279,6 +281,7 @@ struct GLES3GPUShader { GLES3GPUShaderStageList gpuStages; GLuint glProgram = 0; + ccstd::hash_t hash = INVALID_SHADER_HASH; GLES3GPUInputList glInputs; GLES3GPUUniformBufferList glBuffers; GLES3GPUUniformSamplerTextureList glSamplerTextures; @@ -396,6 +399,7 @@ struct GLES3GPUDescriptorSetLayout { ccstd::vector bindingIndices; ccstd::vector descriptorIndices; uint32_t descriptorCount = 0U; + ccstd::hash_t hash = 0U; }; using GLES3GPUDescriptorSetLayoutList = ccstd::vector; @@ -406,7 +410,8 @@ struct GLES3GPUPipelineLayout { ccstd::vector> dynamicOffsetIndices; ccstd::vector dynamicOffsetOffsets; ccstd::vector dynamicOffsets; - uint32_t dynamicOffsetCount; + uint32_t dynamicOffsetCount = 0U; + ccstd::hash_t hash = 0U; }; struct GLES3GPUPipelineState { @@ -673,5 +678,12 @@ private: ccstd::unordered_map> _framebuffers; }; +struct GLES3GPUProgramBinary : public GFXDeviceObject { + ccstd::string name; + ccstd::hash_t hash = 0; + GLenum format; + std::vector data; +}; + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineCache.cpp b/native/cocos/renderer/gfx-gles3/GLES3PipelineCache.cpp new file mode 100644 index 0000000000..5de2c0095e --- /dev/null +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineCache.cpp @@ -0,0 +1,171 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "GLES3PipelineCache.h" + +#include + +#include "base/BinaryArchive.h" + +#include "gfx-base/GFXUtil.h" +#include "GLES3GPUObjects.h" + +namespace cc::gfx { + +namespace { +const char *fileName = "/pipeline_cache_gles3.bin"; +const uint32_t MAGIC = 0x4343474C; // "CCGL" +const uint32_t VERSION = 1; +} // namespace + +GLES3PipelineCache::GLES3PipelineCache() { + _savePath = getPipelineCacheFolder() + fileName; +} + +GLES3PipelineCache::~GLES3PipelineCache() { + saveCache(); +} + +void GLES3PipelineCache::loadCache() { + std::ifstream stream(_savePath, std::ios::binary); + if (!stream.is_open()) { + CC_LOG_INFO("Load program cache, no cached files."); + return; + } + + uint32_t magic = 0; + uint32_t version = 0; + + BinaryInputArchive archive(stream); + auto loadResult = archive.load(magic); + loadResult &= archive.load(version); + + if (magic != MAGIC || version < VERSION) { + return; + } + + uint32_t cachedItemNum = 0; + GLenum format = GL_NONE; + while (loadResult && archive.load(format)) { + ++cachedItemNum; + + // name length + uint32_t nameLength = 0; + loadResult &= archive.load(nameLength); + + // data length + uint32_t dataLength = 0; + loadResult &= archive.load(dataLength); + + // skip length if not valid. + if (!checkProgramFormat(format)) { + archive.move(dataLength + nameLength + sizeof(GLES3GPUProgramBinary::hash)); + continue; + } + + auto *binary = ccnew GLES3GPUProgramBinary(); + binary->format = format; + binary->name.resize(nameLength, 0); + binary->data.resize(dataLength, 0); + + // hash + loadResult &= archive.load(binary->hash); + + // name + loadResult &= archive.load(binary->name.data(), nameLength); + + // data + loadResult &= archive.load(binary->data.data(), dataLength); + + _programCaches.emplace(binary->name, binary); + } + + // If the number of cached items does not equal the number of loaded items, it may be necessary to update the cache. + _dirty = cachedItemNum != _programCaches.size(); + CC_LOG_INFO("Load program cache success. records %u, loaded %u", cachedItemNum, _programCaches.size()); +} + +void GLES3PipelineCache::saveCache() { + if (!_dirty) { + return; + } + std::ofstream stream(_savePath, std::ios::binary); + if (!stream.is_open()) { + CC_LOG_INFO("Save program cache failed."); + return; + } + BinaryOutputArchive archive(stream); + archive.save(MAGIC); + archive.save(VERSION); + + for (auto &pair : _programCaches) { + auto &binary = pair.second; + archive.save(binary->format); + archive.save(static_cast(binary->name.size())); + archive.save(static_cast(binary->data.size())); + archive.save(binary->hash); + archive.save(binary->name.data(), static_cast(binary->name.size())); + archive.save(binary->data.data(), static_cast(binary->data.size())); + CC_LOG_INFO("Save program cache success, name %s.", binary->name.c_str()); + } + _dirty = false; +} + +void GLES3PipelineCache::init() { + GLint shaderBinaryFormats = 0; + GL_CHECK(glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &shaderBinaryFormats)); + + _programBinaryFormats.resize(shaderBinaryFormats); + GL_CHECK(glGetIntegerv(GL_PROGRAM_BINARY_FORMATS, _programBinaryFormats.data())); + + loadCache(); +} + +void GLES3PipelineCache::addBinary(GLES3GPUProgramBinary *binary) { + _programCaches[binary->name] = binary; + _dirty = true; +} + +GLES3GPUProgramBinary *GLES3PipelineCache::fetchBinary(const ccstd::string &key, ccstd::hash_t hash) { + auto iter = _programCaches.find(key); + if (iter == _programCaches.end()) { + return nullptr; + } + + // if hash not match, re-generate program binary. + if (iter->second->hash != hash) { + _programCaches.erase(iter); + return nullptr; + } + + return iter->second; +} + +bool GLES3PipelineCache::checkProgramFormat(GLuint format) const { + return std::any_of(_programBinaryFormats.begin(), _programBinaryFormats.end(), [format](const auto &fmt) { + return format == fmt; + }); +} + +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineCache.h b/native/cocos/renderer/gfx-gles3/GLES3PipelineCache.h new file mode 100644 index 0000000000..97b84f26dd --- /dev/null +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineCache.h @@ -0,0 +1,59 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + + +#pragma once + +#include "base/std/container/vector.h" +#include "base/std/container/unordered_map.h" +#include "base/std/container/string.h" +#include "base/Ptr.h" +#include "base/RefCounted.h" +#include "GLES3GPUObjects.h" + +namespace cc::gfx { +class GLES3GPUShader; + +class GLES3PipelineCache : public RefCounted { +public: + GLES3PipelineCache(); + ~GLES3PipelineCache() override; + + void init(); + + void addBinary(GLES3GPUProgramBinary *binary); + GLES3GPUProgramBinary *fetchBinary(const ccstd::string &key, ccstd::hash_t hash); + bool checkProgramFormat(GLuint format) const; + +private: + void loadCache(); + void saveCache(); + + ccstd::vector _programBinaryFormats; + ccstd::unordered_map> _programCaches; + ccstd::string _savePath; + bool _dirty = false; +}; + +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp index 9387f08257..338beeeb33 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp @@ -44,6 +44,7 @@ void GLES3PipelineLayout::doInit(const PipelineLayoutInfo & /*info*/) { _gpuPipelineLayout = ccnew GLES3GPUPipelineLayout; uint32_t offset = 0U; + auto &hash = _gpuPipelineLayout->hash; _gpuPipelineLayout->dynamicOffsetIndices.resize(_setLayouts.size()); for (uint32_t i = 0U; i < _setLayouts.size(); i++) { DescriptorSetLayout *setLayout = _setLayouts[i]; @@ -59,6 +60,8 @@ void GLES3PipelineLayout::doInit(const PipelineLayoutInfo & /*info*/) { _gpuPipelineLayout->dynamicOffsetOffsets.push_back(static_cast(offset)); _gpuPipelineLayout->setLayouts.push_back(gpuSetLayout); offset += dynamicCount; + + ccstd::hash_combine(hash, gpuSetLayout->hash); } _gpuPipelineLayout->dynamicOffsetOffsets.push_back(static_cast(offset)); _gpuPipelineLayout->dynamicOffsetCount = static_cast(offset); diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp b/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp index 636d9b6e13..195f8dddb8 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineState.cpp @@ -29,6 +29,7 @@ #include "GLES3PipelineState.h" #include "GLES3RenderPass.h" #include "GLES3Shader.h" +#include "GLES3Device.h" namespace cc { namespace gfx { @@ -50,6 +51,21 @@ const GLenum GLE_S3_PRIMITIVES[] = { GL_NONE, }; +namespace { + +void initGpuShader(GLES3GPUShader *gpuShader, GLES3GPUPipelineLayout *gpuPipelineLayout) { + cmdFuncGLES3CreateShader(GLES3Device::getInstance(), gpuShader, gpuPipelineLayout); + CC_ASSERT(gpuShader->glProgram); + + // Clear shader source after they're uploaded to GPU + for (auto &stage : gpuShader->gpuStages) { + stage.source.clear(); + stage.source.shrink_to_fit(); + } +} + +} // namespace + GLES3PipelineState::GLES3PipelineState() { _typedID = generateObjectID(); } @@ -61,11 +77,15 @@ GLES3PipelineState::~GLES3PipelineState() { void GLES3PipelineState::doInit(const PipelineStateInfo & /*info*/) { _gpuPipelineState = ccnew GLES3GPUPipelineState; _gpuPipelineState->glPrimitive = GLE_S3_PRIMITIVES[static_cast(_primitive)]; - _gpuPipelineState->gpuShader = static_cast(_shader)->gpuShader(); _gpuPipelineState->rs = _rasterizerState; _gpuPipelineState->dss = _depthStencilState; _gpuPipelineState->bs = _blendState; _gpuPipelineState->gpuPipelineLayout = static_cast(_pipelineLayout)->gpuPipelineLayout(); + _gpuPipelineState->gpuShader = static_cast(_shader)->gpuShader(); + if (_gpuPipelineState->gpuShader->glProgram == 0) { + initGpuShader(_gpuPipelineState->gpuShader, _gpuPipelineState->gpuPipelineLayout); + } + if (_renderPass) _gpuPipelineState->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); for (uint32_t i = 0; i < 31; i++) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Shader.cpp b/native/cocos/renderer/gfx-gles3/GLES3Shader.cpp index fcb48b7c51..4d1a7a261f 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Shader.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Shader.cpp @@ -27,6 +27,7 @@ #include "GLES3Commands.h" #include "GLES3Device.h" #include "GLES3Shader.h" +#include "base/std/hash/hash_fwd.hpp" namespace cc { namespace gfx { @@ -39,25 +40,7 @@ GLES3Shader::~GLES3Shader() { destroy(); } -namespace { - -void initGpuShader(GLES3GPUShader *gpuShader) { - cmdFuncGLES3CreateShader(GLES3Device::getInstance(), gpuShader); - CC_ASSERT(gpuShader->glProgram); - - // Clear shader source after they're uploaded to GPU - for (auto &stage : gpuShader->gpuStages) { - stage.source.clear(); - stage.source.shrink_to_fit(); - } -} - -} // namespace - GLES3GPUShader *GLES3Shader::gpuShader() const { - if (!_gpuShader->glProgram) { - initGpuShader(_gpuShader); - } return _gpuShader; } @@ -72,6 +55,7 @@ void GLES3Shader::doInit(const ShaderInfo & /*info*/) { _gpuShader->textures = _textures; _gpuShader->images = _images; _gpuShader->subpassInputs = _subpassInputs; + _gpuShader->hash = _hash; for (const auto &stage : _stages) { GLES3GPUShaderStage gpuShaderStage = {stage.stage, stage.source}; _gpuShader->gpuStages.emplace_back(std::move(gpuShaderStage)); diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index 93fc40d4cb..46237843e3 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -33,6 +33,7 @@ #include "VKCommands.h" #include "VKDevice.h" #include "VKGPUObjects.h" +#include "VKPipelineCache.h" #include "gfx-base/GFXDef.h" #include "states/VKBufferBarrier.h" #include "states/VKGeneralBarrier.h" @@ -958,7 +959,10 @@ void cmdFuncCCVKCreateComputePipelineState(CCVKDevice *device, CCVKGPUPipelineSt ///////////////////// Creation ///////////////////// - VK_CHECK(vkCreateComputePipelines(device->gpuDevice()->vkDevice, device->gpuDevice()->vkPipelineCache, + auto *pipelineCache = device->pipelineCache(); + CC_ASSERT(pipelineCache != nullptr); + pipelineCache->setDirty(); + VK_CHECK(vkCreateComputePipelines(device->gpuDevice()->vkDevice, pipelineCache->getHandle(), 1, &createInfo, nullptr, &gpuPipelineState->vkPipeline)); } @@ -1173,8 +1177,10 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS createInfo.subpass = gpuPipelineState->subpass; ///////////////////// Creation ///////////////////// - - VK_CHECK(vkCreateGraphicsPipelines(device->gpuDevice()->vkDevice, device->gpuDevice()->vkPipelineCache, + auto *pipelineCache = device->pipelineCache(); + CC_ASSERT(pipelineCache != nullptr); + pipelineCache->setDirty(); + VK_CHECK(vkCreateGraphicsPipelines(device->gpuDevice()->vkDevice, pipelineCache->getHandle(), 1, &createInfo, nullptr, &gpuPipelineState->vkPipeline)); } diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index 1cfa546d1d..70247bf938 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -39,6 +39,7 @@ #include "VKShader.h" #include "VKSwapchain.h" #include "VKTexture.h" +#include "VKPipelineCache.h" #include "VKUtils.h" #include "base/Utils.h" #include "gfx-base/GFXDef-common.h" @@ -461,8 +462,8 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { getAccessTypes(AccessFlagBit::DEPTH_STENCIL_ATTACHMENT_WRITE, _gpuDevice->defaultDepthStencilBarrier.nextAccesses); cmdFuncCCVKCreateGeneralBarrier(this, &_gpuDevice->defaultDepthStencilBarrier); - VkPipelineCacheCreateInfo pipelineCacheInfo{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; - VK_CHECK(vkCreatePipelineCache(_gpuDevice->vkDevice, &pipelineCacheInfo, nullptr, &_gpuDevice->vkPipelineCache)); + _pipelineCache = std::make_unique(); + _pipelineCache->init(_gpuDevice->vkDevice); ///////////////////// Print Debug Info ///////////////////// @@ -545,10 +546,7 @@ void CCVKDevice::doDestroy() { _gpuFencePools.clear(); if (_gpuDevice) { - if (_gpuDevice->vkPipelineCache) { - vkDestroyPipelineCache(_gpuDevice->vkDevice, _gpuDevice->vkPipelineCache, nullptr); - _gpuDevice->vkPipelineCache = VK_NULL_HANDLE; - } + _pipelineCache.reset(); if (_gpuDevice->memoryAllocator != VK_NULL_HANDLE) { VmaStats stats; diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.h b/native/cocos/renderer/gfx-vulkan/VKDevice.h index feb297bf7e..4b2ba03416 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.h +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.h @@ -45,6 +45,7 @@ class CCVKGPUSemaphorePool; class CCVKGPUBarrierManager; class CCVKGPUDescriptorSetHub; class CCVKGPUInputAssemblerHub; +class CCVKPipelineCache; class CCVKGPUFencePool; class CCVKGPURecycleBin; @@ -96,6 +97,7 @@ public: inline CCVKGPUBarrierManager *gpuBarrierManager() const { return _gpuBarrierManager.get(); } inline CCVKGPUDescriptorSetHub *gpuDescriptorSetHub() const { return _gpuDescriptorSetHub.get(); } inline CCVKGPUInputAssemblerHub *gpuIAHub() const { return _gpuIAHub.get(); } + inline CCVKPipelineCache *pipelineCache() const { return _pipelineCache.get(); } CCVKGPUFencePool *gpuFencePool(); CCVKGPURecycleBin *gpuRecycleBin(); @@ -154,6 +156,7 @@ protected: std::unique_ptr _gpuBarrierManager; std::unique_ptr _gpuDescriptorSetHub; std::unique_ptr _gpuIAHub; + std::unique_ptr _pipelineCache; ccstd::vector _layers; ccstd::vector _extensions; diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index ba88422571..c677b9b015 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -428,7 +428,6 @@ public: ccstd::vector layers; ccstd::vector extensions; VmaAllocator memoryAllocator{VK_NULL_HANDLE}; - VkPipelineCache vkPipelineCache{VK_NULL_HANDLE}; uint32_t minorVersion{0U}; VkFormat depthFormat{VK_FORMAT_UNDEFINED}; diff --git a/native/cocos/renderer/gfx-vulkan/VKPipelineCache.cpp b/native/cocos/renderer/gfx-vulkan/VKPipelineCache.cpp new file mode 100644 index 0000000000..7844252917 --- /dev/null +++ b/native/cocos/renderer/gfx-vulkan/VKPipelineCache.cpp @@ -0,0 +1,129 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "VKPipelineCache.h" + +#include + +#include "base/BinaryArchive.h" + +#include "gfx-base/GFXUtil.h" + +namespace { +const char* fileName = "/pipeline_cache_vk.bin"; +const uint32_t MAGIC = 0x4343564B; // "CCVK" +const uint32_t VERSION = 1; + +void loadData(const ccstd::string &path, ccstd::vector &data) { + std::ifstream stream(path, std::ios::binary); + if (!stream.is_open()) { + CC_LOG_INFO("Load program cache, no cached files."); + return; + } + + uint32_t magic = 0; + uint32_t version = 0; + + cc::BinaryInputArchive archive(stream); + auto loadResult = archive.load(magic); + loadResult &= archive.load(version); + + uint32_t size = 0; + if (loadResult && magic == MAGIC && version >= VERSION) { + loadResult &= archive.load(size); + data.resize(size); + loadResult &= archive.load(data.data(), size); + } + if (loadResult) { + CC_LOG_INFO("Load pipeline cache success."); + } +} +} // namespace + +namespace cc::gfx { + +CCVKPipelineCache::CCVKPipelineCache() { + _savePath = getPipelineCacheFolder() + fileName; +} + +CCVKPipelineCache::~CCVKPipelineCache() { + if (_pipelineCache != VK_NULL_HANDLE) { +#if CC_USE_PIPELINE_CACHE + saveCache(); +#endif + vkDestroyPipelineCache(_device, _pipelineCache, nullptr); + } +} + +void CCVKPipelineCache::init(VkDevice dev) { + _device = dev; + loadCache(); +} + +void CCVKPipelineCache::loadCache() { + ccstd::vector data; +#if CC_USE_PIPELINE_CACHE + loadData(_savePath, data); +#endif + + VkPipelineCacheCreateInfo cacheInfo = {}; + cacheInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; + cacheInfo.pNext = nullptr; + cacheInfo.initialDataSize = static_cast(data.size()); + cacheInfo.pInitialData = data.data(); + VK_CHECK(vkCreatePipelineCache(_device, &cacheInfo, nullptr, &_pipelineCache)); +} + +void CCVKPipelineCache::saveCache() { + if (!_dirty) { + return; + } + std::ofstream stream(_savePath, std::ios::binary); + if (!stream.is_open()) { + CC_LOG_INFO("Save program cache failed."); + return; + } + BinaryOutputArchive archive(stream); + archive.save(MAGIC); + archive.save(VERSION); + + size_t size = 0; + vkGetPipelineCacheData(_device, _pipelineCache, &size, nullptr); + ccstd::vector data(size); + vkGetPipelineCacheData(_device, _pipelineCache, &size, data.data()); + + archive.save(static_cast(size)); + archive.save(data.data(), static_cast(size)); + _dirty = false; +} + +void CCVKPipelineCache::setDirty() { + _dirty = true; +} + +VkPipelineCache CCVKPipelineCache::getHandle() const { + return _pipelineCache; +} + +} // namespace cc::gfx diff --git a/native/cocos/renderer/gfx-vulkan/VKPipelineCache.h b/native/cocos/renderer/gfx-vulkan/VKPipelineCache.h new file mode 100644 index 0000000000..f3112d33a4 --- /dev/null +++ b/native/cocos/renderer/gfx-vulkan/VKPipelineCache.h @@ -0,0 +1,55 @@ +/**************************************************************************** + Copyright (c) 2023 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include "base/std/container/vector.h" +#include "base/std/container/unordered_map.h" +#include "base/std/container/string.h" +#include "base/Ptr.h" +#include "base/RefCounted.h" +#include "VKGPUObjects.h" + +namespace cc::gfx { + +class CCVKPipelineCache : public RefCounted { +public: + CCVKPipelineCache(); + ~CCVKPipelineCache() override; + + void init(VkDevice dev); + void loadCache(); + void saveCache(); + + void setDirty(); + VkPipelineCache getHandle() const; + +private: + VkDevice _device = VK_NULL_HANDLE; + VkPipelineCache _pipelineCache = VK_NULL_HANDLE; + ccstd::string _savePath; + bool _dirty = false; +}; + +} // namespace cc::gfx diff --git a/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp b/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp index 951c2f4490..b0ff3ae6ea 100644 --- a/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeProgramLibrary.cpp @@ -1122,6 +1122,14 @@ void populatePipelineLayoutInfo( } } +template +static ccstd::hash_t getShaderHash(ccstd::hash_t src, const T &val) { + if (src != gfx::INVALID_SHADER_HASH) { + ccstd::hash_combine(src, val); + } + return src; +} + } // namespace void NativeProgramLibrary::init(gfx::Device *deviceIn) { @@ -1492,6 +1500,7 @@ ProgramProxy *NativeProgramLibrary::getProgramVariant( info.shaderInfo.attributes = getActiveAttributes(programInfo, info.attributes, defines); info.shaderInfo.name = getShaderInstanceName(name, macroArray); + info.shaderInfo.hash = getShaderHash(programInfo.hash, prefix); IntrusivePtr shader = device->createShader(info.shaderInfo); auto res = phase.programProxies.emplace(