diff --git a/native/cocos/base/LinearAllocatorPool.h b/native/cocos/base/LinearAllocatorPool.h index 815bafce61..d64b95ff5f 100644 --- a/native/cocos/base/LinearAllocatorPool.h +++ b/native/cocos/base/LinearAllocatorPool.h @@ -53,15 +53,14 @@ public: T *allocate(const uint count, uint alignment = 64U) noexcept { if (!count) return nullptr; - T * res = nullptr; - size_t size = count * sizeof(T); + T *res = nullptr; for (ThreadSafeLinearAllocator *allocator : _allocators) { - res = reinterpret_cast(allocator->allocate(size, alignment)); + res = allocator->allocate(count, alignment); if (res) return res; } - uint capacity = utils::nextPOT(static_cast(std::max(DEFAULT_BLOCK_SIZE, size + static_cast(alignment)))); // reserve enough padding space for alignment + uint capacity = utils::nextPOT(static_cast(std::max(DEFAULT_BLOCK_SIZE, count * sizeof(T) + static_cast(alignment)))); // reserve enough padding space for alignment _allocators.emplace_back(CC_NEW(ThreadSafeLinearAllocator(static_cast(capacity)))); - return reinterpret_cast(_allocators.back()->allocate(size, alignment)); + return _allocators.back()->allocate(count, alignment); } inline void reset() { diff --git a/native/cocos/base/Macros.h b/native/cocos/base/Macros.h index 4f14c43f58..f33f8f3622 100644 --- a/native/cocos/base/Macros.h +++ b/native/cocos/base/Macros.h @@ -414,6 +414,22 @@ It should work same as apples CFSwapInt32LittleToHost(..) _Pragma("clang diagnostic pop") #endif +#define ENABLE_COPY_SEMANTICS(cls) \ + cls(const cls &) = default; \ + cls &operator=(const cls &) = default; + +#define DISABLE_COPY_SEMANTICS(cls) \ + cls(const cls &) = delete; \ + cls &operator=(const cls &) = delete; + +#define ENABLE_MOVE_SEMANTICS(cls) \ + cls(cls &&) = default; \ + cls &operator=(cls &&) = default; + +#define DISABLE_MOVE_SEMANTICS(cls) \ + cls(cls &&) = delete; \ + cls &operator=(cls &&) = delete; + #if (CC_COMPILER == CC_COMPILER_MSVC) #define CC_ALIGN(N) __declspec(align(N)) #define CC_CACHE_ALIGN __declspec(align(CC_CACHELINE_SIZE)) @@ -521,7 +537,7 @@ It should work same as apples CFSwapInt32LittleToHost(..) /* Stack-alignment If macro __CC_SIMD_ALIGN_STACK defined, means there requests special code to ensure stack align to a 16-bytes boundary. - + Note: This macro can only guarantee callee stack pointer (esp) align to a 16-bytes boundary, but not that for frame pointer (ebp). diff --git a/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp b/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp index a367d771b9..631650e9dc 100644 --- a/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp +++ b/native/cocos/base/threading/ThreadSafeLinearAllocator.cpp @@ -37,7 +37,7 @@ ThreadSafeLinearAllocator::~ThreadSafeLinearAllocator() { free(_buffer); } -void *ThreadSafeLinearAllocator::allocate(size_t size, size_t alignment) noexcept { +void *ThreadSafeLinearAllocator::doAllocate(size_t size, size_t alignment) noexcept { if (size == 0) { return nullptr; } diff --git a/native/cocos/base/threading/ThreadSafeLinearAllocator.h b/native/cocos/base/threading/ThreadSafeLinearAllocator.h index ac89bbfb7f..c9ab659933 100644 --- a/native/cocos/base/threading/ThreadSafeLinearAllocator.h +++ b/native/cocos/base/threading/ThreadSafeLinearAllocator.h @@ -40,7 +40,10 @@ public: ThreadSafeLinearAllocator &operator=(ThreadSafeLinearAllocator const &) = delete; ThreadSafeLinearAllocator &operator=(ThreadSafeLinearAllocator &&) = delete; - void *allocate(size_t size, size_t alignment) noexcept; + template + inline T *allocate(size_t count, size_t alignment = 1) noexcept { + return reinterpret_cast(doAllocate(count * sizeof(T), alignment)); + } inline void * getBuffer() const noexcept { return _buffer; } inline uint32_t getCapacity() const noexcept { return _capacity; } @@ -50,6 +53,8 @@ public: inline void recycle() noexcept { _usedSize.store(0, std::memory_order_relaxed); } private: + void *doAllocate(size_t size, size_t alignment) noexcept; + void * _buffer{nullptr}; uint32_t _capacity{0}; std::atomic _usedSize{0}; diff --git a/native/cocos/bindings/auto/jsb_gfx_auto.cpp b/native/cocos/bindings/auto/jsb_gfx_auto.cpp index 7bdf596932..e43e3e7424 100644 --- a/native/cocos/bindings/auto/jsb_gfx_auto.cpp +++ b/native/cocos/bindings/auto/jsb_gfx_auto.cpp @@ -10316,6 +10316,87 @@ static bool js_gfx_SubpassInfo_set_depthStencil(se::State& s) // NOLINT(readabil } SE_BIND_PROP_SET(js_gfx_SubpassInfo_set_depthStencil) +static bool js_gfx_SubpassInfo_get_depthStencilResolve(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SubpassInfo_get_depthStencilResolve : Invalid Native Object"); + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->depthStencilResolve, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->depthStencilResolve, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_gfx_SubpassInfo_get_depthStencilResolve) + +static bool js_gfx_SubpassInfo_set_depthStencilResolve(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SubpassInfo_set_depthStencilResolve : Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->depthStencilResolve, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_SubpassInfo_set_depthStencilResolve : Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_gfx_SubpassInfo_set_depthStencilResolve) + +static bool js_gfx_SubpassInfo_get_depthResolveMode(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SubpassInfo_get_depthResolveMode : Invalid Native Object"); + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->depthResolveMode, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->depthResolveMode, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_gfx_SubpassInfo_get_depthResolveMode) + +static bool js_gfx_SubpassInfo_set_depthResolveMode(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SubpassInfo_set_depthResolveMode : Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->depthResolveMode, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_SubpassInfo_set_depthResolveMode : Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_gfx_SubpassInfo_set_depthResolveMode) + +static bool js_gfx_SubpassInfo_get_stencilResolveMode(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) +{ + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SubpassInfo_get_stencilResolveMode : Invalid Native Object"); + + CC_UNUSED bool ok = true; + se::Value jsret; + ok &= nativevalue_to_se(cobj->stencilResolveMode, jsret, s.thisObject() /*ctx*/); + s.rval() = jsret; + SE_HOLD_RETURN_VALUE(cobj->stencilResolveMode, s.thisObject(), s.rval()); + return true; +} +SE_BIND_PROP_GET(js_gfx_SubpassInfo_get_stencilResolveMode) + +static bool js_gfx_SubpassInfo_set_stencilResolveMode(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) +{ + const auto& args = s.args(); + auto* cobj = SE_THIS_OBJECT(s); + SE_PRECONDITION2(cobj, false, "js_gfx_SubpassInfo_set_stencilResolveMode : Invalid Native Object"); + + CC_UNUSED bool ok = true; + ok &= sevalue_to_native(args[0], &cobj->stencilResolveMode, s.thisObject()); + SE_PRECONDITION2(ok, false, "js_gfx_SubpassInfo_set_stencilResolveMode : Error processing new value"); + return true; +} +SE_BIND_PROP_SET(js_gfx_SubpassInfo_set_stencilResolveMode) + template<> bool sevalue_to_native(const se::Value &from, cc::gfx::SubpassInfo * to, se::Object *ctx) @@ -10349,6 +10430,18 @@ bool sevalue_to_native(const se::Value &from, cc::gfx::SubpassInfo * to, se::Obj if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->depthStencil), ctx); } + json->getProperty("depthStencilResolve", &field); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->depthStencilResolve), ctx); + } + json->getProperty("depthResolveMode", &field); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->depthResolveMode), ctx); + } + json->getProperty("stencilResolveMode", &field); + if(!field.isNullOrUndefined()) { + ok &= sevalue_to_native(field, &(to->stencilResolveMode), ctx); + } return ok; } @@ -10402,6 +10495,15 @@ static bool js_gfx_SubpassInfo_constructor(se::State& s) // NOLINT(readability-i if (argc > 4 && !args[4].isUndefined()) { ok &= sevalue_to_native(args[4], &(cobj->depthStencil), nullptr); } + if (argc > 5 && !args[5].isUndefined()) { + ok &= sevalue_to_native(args[5], &(cobj->depthStencilResolve), nullptr); + } + if (argc > 6 && !args[6].isUndefined()) { + ok &= sevalue_to_native(args[6], &(cobj->depthResolveMode), nullptr); + } + if (argc > 7 && !args[7].isUndefined()) { + ok &= sevalue_to_native(args[7], &(cobj->stencilResolveMode), nullptr); + } if(!ok) { JSB_FREE(cobj); @@ -10439,6 +10541,9 @@ bool js_register_gfx_SubpassInfo(se::Object* obj) // NOLINT(readability-identifi cls->defineProperty("resolves", _SE(js_gfx_SubpassInfo_get_resolves), _SE(js_gfx_SubpassInfo_set_resolves)); cls->defineProperty("preserves", _SE(js_gfx_SubpassInfo_get_preserves), _SE(js_gfx_SubpassInfo_set_preserves)); cls->defineProperty("depthStencil", _SE(js_gfx_SubpassInfo_get_depthStencil), _SE(js_gfx_SubpassInfo_set_depthStencil)); + cls->defineProperty("depthStencilResolve", _SE(js_gfx_SubpassInfo_get_depthStencilResolve), _SE(js_gfx_SubpassInfo_set_depthStencilResolve)); + cls->defineProperty("depthResolveMode", _SE(js_gfx_SubpassInfo_get_depthResolveMode), _SE(js_gfx_SubpassInfo_set_depthResolveMode)); + cls->defineProperty("stencilResolveMode", _SE(js_gfx_SubpassInfo_get_stencilResolveMode), _SE(js_gfx_SubpassInfo_set_stencilResolveMode)); cls->defineFinalizeFunction(_SE(js_cc_gfx_SubpassInfo_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -11442,60 +11547,6 @@ static bool js_gfx_FramebufferInfo_set_depthStencilTexture(se::State& s) // NOLI } SE_BIND_PROP_SET(js_gfx_FramebufferInfo_set_depthStencilTexture) -static bool js_gfx_FramebufferInfo_get_colorMipmapLevels(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_FramebufferInfo_get_colorMipmapLevels : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->colorMipmapLevels, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->colorMipmapLevels, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_FramebufferInfo_get_colorMipmapLevels) - -static bool js_gfx_FramebufferInfo_set_colorMipmapLevels(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_FramebufferInfo_set_colorMipmapLevels : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->colorMipmapLevels, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_FramebufferInfo_set_colorMipmapLevels : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_FramebufferInfo_set_colorMipmapLevels) - -static bool js_gfx_FramebufferInfo_get_depthStencilMipmapLevel(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) -{ - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_FramebufferInfo_get_depthStencilMipmapLevel : Invalid Native Object"); - - CC_UNUSED bool ok = true; - se::Value jsret; - ok &= nativevalue_to_se(cobj->depthStencilMipmapLevel, jsret, s.thisObject() /*ctx*/); - s.rval() = jsret; - SE_HOLD_RETURN_VALUE(cobj->depthStencilMipmapLevel, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_gfx_FramebufferInfo_get_depthStencilMipmapLevel) - -static bool js_gfx_FramebufferInfo_set_depthStencilMipmapLevel(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) -{ - const auto& args = s.args(); - auto* cobj = SE_THIS_OBJECT(s); - SE_PRECONDITION2(cobj, false, "js_gfx_FramebufferInfo_set_depthStencilMipmapLevel : Invalid Native Object"); - - CC_UNUSED bool ok = true; - ok &= sevalue_to_native(args[0], &cobj->depthStencilMipmapLevel, s.thisObject()); - SE_PRECONDITION2(ok, false, "js_gfx_FramebufferInfo_set_depthStencilMipmapLevel : Error processing new value"); - return true; -} -SE_BIND_PROP_SET(js_gfx_FramebufferInfo_set_depthStencilMipmapLevel) - template<> bool sevalue_to_native(const se::Value &from, cc::gfx::FramebufferInfo * to, se::Object *ctx) @@ -11521,14 +11572,6 @@ bool sevalue_to_native(const se::Value &from, cc::gfx::FramebufferInfo * to, se: if(!field.isNullOrUndefined()) { ok &= sevalue_to_native(field, &(to->depthStencilTexture), ctx); } - json->getProperty("colorMipmapLevels", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->colorMipmapLevels), ctx); - } - json->getProperty("depthStencilMipmapLevel", &field); - if(!field.isNullOrUndefined()) { - ok &= sevalue_to_native(field, &(to->depthStencilMipmapLevel), ctx); - } return ok; } @@ -11576,12 +11619,6 @@ static bool js_gfx_FramebufferInfo_constructor(se::State& s) // NOLINT(readabili if (argc > 2 && !args[2].isUndefined()) { ok &= sevalue_to_native(args[2], &(cobj->depthStencilTexture), nullptr); } - if (argc > 3 && !args[3].isUndefined()) { - ok &= sevalue_to_native(args[3], &(cobj->colorMipmapLevels), nullptr); - } - if (argc > 4 && !args[4].isUndefined()) { - ok &= sevalue_to_native(args[4], &(cobj->depthStencilMipmapLevel), nullptr); - } if(!ok) { JSB_FREE(cobj); @@ -11617,8 +11654,6 @@ bool js_register_gfx_FramebufferInfo(se::Object* obj) // NOLINT(readability-iden cls->defineProperty("renderPass", _SE(js_gfx_FramebufferInfo_get_renderPass), _SE(js_gfx_FramebufferInfo_set_renderPass)); cls->defineProperty("colorTextures", _SE(js_gfx_FramebufferInfo_get_colorTextures), _SE(js_gfx_FramebufferInfo_set_colorTextures)); cls->defineProperty("depthStencilTexture", _SE(js_gfx_FramebufferInfo_get_depthStencilTexture), _SE(js_gfx_FramebufferInfo_set_depthStencilTexture)); - cls->defineProperty("colorMipmapLevels", _SE(js_gfx_FramebufferInfo_get_colorMipmapLevels), _SE(js_gfx_FramebufferInfo_set_colorMipmapLevels)); - cls->defineProperty("depthStencilMipmapLevel", _SE(js_gfx_FramebufferInfo_get_depthStencilMipmapLevel), _SE(js_gfx_FramebufferInfo_set_depthStencilMipmapLevel)); cls->defineFinalizeFunction(_SE(js_cc_gfx_FramebufferInfo_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -15839,9 +15874,9 @@ bool js_register_gfx_GFXObject(se::Object* obj) // NOLINT(readability-identifier { auto* cls = se::Class::create("GFXObject", obj, nullptr, _SE(js_gfx_GFXObject_constructor)); - cls->defineProperty("typedID", _SE(js_gfx_GFXObject_getTypedID), nullptr); - cls->defineProperty("objectID", _SE(js_gfx_GFXObject_getObjectID), nullptr); cls->defineProperty("objectType", _SE(js_gfx_GFXObject_getObjectType), nullptr); + cls->defineProperty("objectID", _SE(js_gfx_GFXObject_getObjectID), nullptr); + cls->defineProperty("typedID", _SE(js_gfx_GFXObject_getTypedID), nullptr); cls->defineFinalizeFunction(_SE(js_cc_gfx_GFXObject_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -16052,12 +16087,12 @@ bool js_register_gfx_Buffer(se::Object* obj) // NOLINT(readability-identifier-na { auto* cls = se::Class::create("Buffer", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_Buffer_constructor)); - cls->defineProperty("count", _SE(js_gfx_Buffer_getCount), nullptr); + cls->defineProperty("usage", _SE(js_gfx_Buffer_getUsage), nullptr); cls->defineProperty("memUsage", _SE(js_gfx_Buffer_getMemUsage), nullptr); cls->defineProperty("stride", _SE(js_gfx_Buffer_getStride), nullptr); - cls->defineProperty("flags", _SE(js_gfx_Buffer_getFlags), nullptr); - cls->defineProperty("usage", _SE(js_gfx_Buffer_getUsage), nullptr); + cls->defineProperty("count", _SE(js_gfx_Buffer_getCount), nullptr); cls->defineProperty("size", _SE(js_gfx_Buffer_getSize), nullptr); + cls->defineProperty("flags", _SE(js_gfx_Buffer_getFlags), nullptr); cls->defineFunction("destroy", _SE(js_gfx_Buffer_destroy)); cls->defineFunction("resize", _SE(js_gfx_Buffer_resize)); cls->defineStaticFunction("computeHash", _SE(js_gfx_Buffer_computeHash)); @@ -16498,18 +16533,18 @@ bool js_register_gfx_InputAssembler(se::Object* obj) // NOLINT(readability-ident { auto* cls = se::Class::create("InputAssembler", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_InputAssembler_constructor)); - cls->defineProperty("instanceCount", _SE(js_gfx_InputAssembler_getInstanceCount), _SE(js_gfx_InputAssembler_setInstanceCount)); cls->defineProperty("vertexBuffers", _SE(js_gfx_InputAssembler_getVertexBuffers), nullptr); - cls->defineProperty("attributesHash", _SE(js_gfx_InputAssembler_getAttributesHash), nullptr); - cls->defineProperty("firstInstance", _SE(js_gfx_InputAssembler_getFirstInstance), _SE(js_gfx_InputAssembler_setFirstInstance)); - cls->defineProperty("vertexCount", _SE(js_gfx_InputAssembler_getVertexCount), _SE(js_gfx_InputAssembler_setVertexCount)); - cls->defineProperty("indexBuffer", _SE(js_gfx_InputAssembler_getIndexBuffer), nullptr); - cls->defineProperty("vertexOffset", _SE(js_gfx_InputAssembler_getVertexOffset), _SE(js_gfx_InputAssembler_setVertexOffset)); cls->defineProperty("attributes", _SE(js_gfx_InputAssembler_getAttributes), nullptr); + cls->defineProperty("indexBuffer", _SE(js_gfx_InputAssembler_getIndexBuffer), nullptr); + cls->defineProperty("indirectBuffer", _SE(js_gfx_InputAssembler_getIndirectBuffer), nullptr); + cls->defineProperty("vertexCount", _SE(js_gfx_InputAssembler_getVertexCount), _SE(js_gfx_InputAssembler_setVertexCount)); + cls->defineProperty("firstVertex", _SE(js_gfx_InputAssembler_getFirstVertex), _SE(js_gfx_InputAssembler_setFirstVertex)); cls->defineProperty("indexCount", _SE(js_gfx_InputAssembler_getIndexCount), _SE(js_gfx_InputAssembler_setIndexCount)); cls->defineProperty("firstIndex", _SE(js_gfx_InputAssembler_getFirstIndex), _SE(js_gfx_InputAssembler_setFirstIndex)); - cls->defineProperty("indirectBuffer", _SE(js_gfx_InputAssembler_getIndirectBuffer), nullptr); - cls->defineProperty("firstVertex", _SE(js_gfx_InputAssembler_getFirstVertex), _SE(js_gfx_InputAssembler_setFirstVertex)); + cls->defineProperty("vertexOffset", _SE(js_gfx_InputAssembler_getVertexOffset), _SE(js_gfx_InputAssembler_setVertexOffset)); + cls->defineProperty("instanceCount", _SE(js_gfx_InputAssembler_getInstanceCount), _SE(js_gfx_InputAssembler_setInstanceCount)); + cls->defineProperty("firstInstance", _SE(js_gfx_InputAssembler_getFirstInstance), _SE(js_gfx_InputAssembler_setFirstInstance)); + cls->defineProperty("attributesHash", _SE(js_gfx_InputAssembler_getAttributesHash), nullptr); cls->defineFunction("destroy", _SE(js_gfx_InputAssembler_destroy)); cls->defineFunction("initialize", _SE(js_gfx_InputAssembler_initialize)); cls->defineFinalizeFunction(_SE(js_cc_gfx_InputAssembler_finalize)); @@ -18224,8 +18259,8 @@ bool js_register_gfx_Framebuffer(se::Object* obj) // NOLINT(readability-identifi { auto* cls = se::Class::create("Framebuffer", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_Framebuffer_constructor)); - cls->defineProperty("colorTextures", _SE(js_gfx_Framebuffer_getColorTextures), nullptr); cls->defineProperty("renderPass", _SE(js_gfx_Framebuffer_getRenderPass), nullptr); + cls->defineProperty("colorTextures", _SE(js_gfx_Framebuffer_getColorTextures), nullptr); cls->defineProperty("depthStencilTexture", _SE(js_gfx_Framebuffer_getDepthStencilTexture), nullptr); cls->defineFunction("destroy", _SE(js_gfx_Framebuffer_destroy)); cls->defineFunction("initialize", _SE(js_gfx_Framebuffer_initialize)); @@ -18678,14 +18713,14 @@ bool js_register_gfx_PipelineState(se::Object* obj) // NOLINT(readability-identi { auto* cls = se::Class::create("PipelineState", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_PipelineState_constructor)); - cls->defineProperty("primitive", _SE(js_gfx_PipelineState_getPrimitive), nullptr); - cls->defineProperty("rasterizerState", _SE(js_gfx_PipelineState_getRasterizerState), nullptr); cls->defineProperty("shader", _SE(js_gfx_PipelineState_getShader), nullptr); + cls->defineProperty("primitive", _SE(js_gfx_PipelineState_getPrimitive), nullptr); + cls->defineProperty("bindPoint", _SE(js_gfx_PipelineState_getBindPoint), nullptr); + cls->defineProperty("inputState", _SE(js_gfx_PipelineState_getInputState), nullptr); + cls->defineProperty("rasterizerState", _SE(js_gfx_PipelineState_getRasterizerState), nullptr); + cls->defineProperty("depthStencilState", _SE(js_gfx_PipelineState_getDepthStencilState), nullptr); cls->defineProperty("blendState", _SE(js_gfx_PipelineState_getBlendState), nullptr); cls->defineProperty("renderPass", _SE(js_gfx_PipelineState_getRenderPass), nullptr); - cls->defineProperty("inputState", _SE(js_gfx_PipelineState_getInputState), nullptr); - cls->defineProperty("bindPoint", _SE(js_gfx_PipelineState_getBindPoint), nullptr); - cls->defineProperty("depthStencilState", _SE(js_gfx_PipelineState_getDepthStencilState), nullptr); cls->defineFunction("destroy", _SE(js_gfx_PipelineState_destroy)); cls->defineFunction("getDynamicStates", _SE(js_gfx_PipelineState_getDynamicStates)); cls->defineFunction("getPipelineLayout", _SE(js_gfx_PipelineState_getPipelineLayout)); @@ -19253,15 +19288,15 @@ bool js_register_gfx_Sampler(se::Object* obj) // NOLINT(readability-identifier-n { auto* cls = se::Class::create("Sampler", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_Sampler_constructor)); - cls->defineProperty("borderColor", _SE(js_gfx_Sampler_getBorderColor), nullptr); - cls->defineProperty("mipFilter", _SE(js_gfx_Sampler_getMipFilter), nullptr); cls->defineProperty("minFilter", _SE(js_gfx_Sampler_getMinFilter), nullptr); cls->defineProperty("magFilter", _SE(js_gfx_Sampler_getMagFilter), nullptr); + cls->defineProperty("mipFilter", _SE(js_gfx_Sampler_getMipFilter), nullptr); cls->defineProperty("addressU", _SE(js_gfx_Sampler_getAddressU), nullptr); cls->defineProperty("addressV", _SE(js_gfx_Sampler_getAddressV), nullptr); cls->defineProperty("addressW", _SE(js_gfx_Sampler_getAddressW), nullptr); - cls->defineProperty("cmpFunc", _SE(js_gfx_Sampler_getCmpFunc), nullptr); cls->defineProperty("maxAnisotropy", _SE(js_gfx_Sampler_getMaxAnisotropy), nullptr); + cls->defineProperty("cmpFunc", _SE(js_gfx_Sampler_getCmpFunc), nullptr); + cls->defineProperty("borderColor", _SE(js_gfx_Sampler_getBorderColor), nullptr); cls->defineProperty("mipLODBias", _SE(js_gfx_Sampler_getMipLODBias), nullptr); cls->defineFunction("destroy", _SE(js_gfx_Sampler_destroy)); cls->defineFunction("initialize", _SE(js_gfx_Sampler_initialize)); @@ -19531,10 +19566,10 @@ bool js_register_gfx_Shader(se::Object* obj) // NOLINT(readability-identifier-na { auto* cls = se::Class::create("Shader", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_Shader_constructor)); - cls->defineProperty("attributes", _SE(js_gfx_Shader_getAttributes), nullptr); - cls->defineProperty("stages", _SE(js_gfx_Shader_getStages), nullptr); - cls->defineProperty("blocks", _SE(js_gfx_Shader_getBlocks), nullptr); cls->defineProperty("name", _SE(js_gfx_Shader_getName), nullptr); + cls->defineProperty("stages", _SE(js_gfx_Shader_getStages), nullptr); + cls->defineProperty("attributes", _SE(js_gfx_Shader_getAttributes), nullptr); + cls->defineProperty("blocks", _SE(js_gfx_Shader_getBlocks), nullptr); cls->defineProperty("samplers", _SE(js_gfx_Shader_getSamplers), nullptr); cls->defineFunction("destroy", _SE(js_gfx_Shader_destroy)); cls->defineFunction("getBuffers", _SE(js_gfx_Shader_getBuffers)); @@ -19869,17 +19904,17 @@ bool js_register_gfx_Texture(se::Object* obj) // NOLINT(readability-identifier-n { auto* cls = se::Class::create("Texture", obj, __jsb_cc_gfx_GFXObject_proto, _SE(js_gfx_Texture_constructor)); - cls->defineProperty("samples", _SE(js_gfx_Texture_getSamples), nullptr); - cls->defineProperty("format", _SE(js_gfx_Texture_getFormat), nullptr); - cls->defineProperty("levelCount", _SE(js_gfx_Texture_getLevelCount), nullptr); - cls->defineProperty("height", _SE(js_gfx_Texture_getHeight), nullptr); - cls->defineProperty("width", _SE(js_gfx_Texture_getWidth), nullptr); - cls->defineProperty("depth", _SE(js_gfx_Texture_getDepth), nullptr); - cls->defineProperty("flags", _SE(js_gfx_Texture_getFlags), nullptr); - cls->defineProperty("layerCount", _SE(js_gfx_Texture_getLayerCount), nullptr); - cls->defineProperty("usage", _SE(js_gfx_Texture_getUsage), nullptr); cls->defineProperty("type", _SE(js_gfx_Texture_getType), nullptr); + cls->defineProperty("usage", _SE(js_gfx_Texture_getUsage), nullptr); + cls->defineProperty("format", _SE(js_gfx_Texture_getFormat), nullptr); + cls->defineProperty("width", _SE(js_gfx_Texture_getWidth), nullptr); + cls->defineProperty("height", _SE(js_gfx_Texture_getHeight), nullptr); + cls->defineProperty("depth", _SE(js_gfx_Texture_getDepth), nullptr); + cls->defineProperty("layerCount", _SE(js_gfx_Texture_getLayerCount), nullptr); + cls->defineProperty("levelCount", _SE(js_gfx_Texture_getLevelCount), nullptr); cls->defineProperty("size", _SE(js_gfx_Texture_getSize), nullptr); + cls->defineProperty("samples", _SE(js_gfx_Texture_getSamples), nullptr); + cls->defineProperty("flags", _SE(js_gfx_Texture_getFlags), nullptr); cls->defineFunction("destroy", _SE(js_gfx_Texture_destroy)); cls->defineFunction("isTextureView", _SE(js_gfx_Texture_isTextureView)); cls->defineFunction("resize", _SE(js_gfx_Texture_resize)); @@ -20734,22 +20769,22 @@ bool js_register_gfx_Device(se::Object* obj) // NOLINT(readability-identifier-na { auto* cls = se::Class::create("Device", obj, nullptr, nullptr); - cls->defineProperty("deviceName", _SE(js_gfx_Device_getDeviceName), nullptr); - cls->defineProperty("colorFormat", _SE(js_gfx_Device_getColorFormat), nullptr); - cls->defineProperty("vendor", _SE(js_gfx_Device_getVendor), nullptr); - cls->defineProperty("depthStencilFormat", _SE(js_gfx_Device_getDepthStencilFormat), nullptr); - cls->defineProperty("numTris", _SE(js_gfx_Device_getNumTris), nullptr); - cls->defineProperty("numDrawCalls", _SE(js_gfx_Device_getNumDrawCalls), nullptr); - cls->defineProperty("memoryStatus", _SE(js_gfx_Device_getMemoryStatus), nullptr); cls->defineProperty("gfxAPI", _SE(js_gfx_Device_getGfxAPI), nullptr); - cls->defineProperty("capabilities", _SE(js_gfx_Device_getCapabilities), nullptr); - cls->defineProperty("height", _SE(js_gfx_Device_getHeight), nullptr); - cls->defineProperty("queue", _SE(js_gfx_Device_getQueue), nullptr); - cls->defineProperty("width", _SE(js_gfx_Device_getWidth), nullptr); - cls->defineProperty("renderer", _SE(js_gfx_Device_getRenderer), nullptr); - cls->defineProperty("commandBuffer", _SE(js_gfx_Device_getCommandBuffer), nullptr); - cls->defineProperty("numInstances", _SE(js_gfx_Device_getNumInstances), nullptr); cls->defineProperty("surfaceTransform", _SE(js_gfx_Device_getSurfaceTransform), nullptr); + cls->defineProperty("deviceName", _SE(js_gfx_Device_getDeviceName), nullptr); + cls->defineProperty("width", _SE(js_gfx_Device_getWidth), nullptr); + cls->defineProperty("height", _SE(js_gfx_Device_getHeight), nullptr); + cls->defineProperty("memoryStatus", _SE(js_gfx_Device_getMemoryStatus), nullptr); + cls->defineProperty("queue", _SE(js_gfx_Device_getQueue), nullptr); + cls->defineProperty("commandBuffer", _SE(js_gfx_Device_getCommandBuffer), nullptr); + cls->defineProperty("renderer", _SE(js_gfx_Device_getRenderer), nullptr); + cls->defineProperty("vendor", _SE(js_gfx_Device_getVendor), nullptr); + cls->defineProperty("numDrawCalls", _SE(js_gfx_Device_getNumDrawCalls), nullptr); + cls->defineProperty("numInstances", _SE(js_gfx_Device_getNumInstances), nullptr); + cls->defineProperty("numTris", _SE(js_gfx_Device_getNumTris), nullptr); + cls->defineProperty("colorFormat", _SE(js_gfx_Device_getColorFormat), nullptr); + cls->defineProperty("depthStencilFormat", _SE(js_gfx_Device_getDepthStencilFormat), nullptr); + cls->defineProperty("capabilities", _SE(js_gfx_Device_getCapabilities), nullptr); cls->defineFunction("acquire", _SE(js_gfx_Device_acquire)); cls->defineFunction("bindingMappingInfo", _SE(js_gfx_Device_bindingMappingInfo)); cls->defineFunction("createCommandBuffer", _SE(js_gfx_Device_createCommandBuffer)); @@ -20783,19 +20818,6 @@ bool js_register_gfx_Device(se::Object* obj) // NOLINT(readability-identifier-na se::Object* __jsb_cc_gfx_DeviceManager_proto = nullptr; se::Class* __jsb_cc_gfx_DeviceManager_class = nullptr; -static bool js_gfx_DeviceManager_destroy(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) -{ - const auto& args = s.args(); - size_t argc = args.size(); - if (argc == 0) { - cc::gfx::DeviceManager::destroy(); - return true; - } - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; -} -SE_BIND_FUNC(js_gfx_DeviceManager_destroy) - static bool js_gfx_DeviceManager_create(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) { const auto& args = s.args(); @@ -20816,6 +20838,19 @@ static bool js_gfx_DeviceManager_create(se::State& s) // NOLINT(readability-iden } SE_BIND_FUNC(js_gfx_DeviceManager_create) +static bool js_gfx_DeviceManager_destroy(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) +{ + const auto& args = s.args(); + size_t argc = args.size(); + if (argc == 0) { + cc::gfx::DeviceManager::destroy(); + return true; + } + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); + return false; +} +SE_BIND_FUNC(js_gfx_DeviceManager_destroy) + static bool js_cc_gfx_DeviceManager_finalize(se::State& s) // NOLINT(readability-identifier-naming, google-runtime-references) { @@ -20834,8 +20869,8 @@ bool js_register_gfx_DeviceManager(se::Object* obj) // NOLINT(readability-identi { auto* cls = se::Class::create("DeviceManager", obj, nullptr, nullptr); - cls->defineStaticFunction("destroy", _SE(js_gfx_DeviceManager_destroy)); cls->defineStaticFunction("create", _SE(js_gfx_DeviceManager_create)); + cls->defineStaticFunction("destroy", _SE(js_gfx_DeviceManager_destroy)); cls->defineFinalizeFunction(_SE(js_cc_gfx_DeviceManager_finalize)); cls->install(); JSBClassType::registerClass(cls); @@ -20858,81 +20893,81 @@ bool register_all_gfx(se::Object* obj) } se::Object* ns = nsVal.toObject(); - js_register_gfx_ContextInfo(ns); - js_register_gfx_SubpassInfo(ns); - js_register_gfx_GFXObject(ns); - js_register_gfx_Buffer(ns); - js_register_gfx_TextureBarrier(ns); - js_register_gfx_Device(ns); - js_register_gfx_Texture(ns); - js_register_gfx_Uniform(ns); - js_register_gfx_DescriptorSet(ns); - js_register_gfx_BlendTarget(ns); - js_register_gfx_DispatchInfo(ns); - js_register_gfx_PipelineState(ns); - js_register_gfx_TextureBarrierInfo(ns); - js_register_gfx_PipelineLayout(ns); - js_register_gfx_Sampler(ns); - js_register_gfx_InputAssembler(ns); - js_register_gfx_RenderPass(ns); - js_register_gfx_BufferInfo(ns); - js_register_gfx_SamplerInfo(ns); - js_register_gfx_QueueInfo(ns); - js_register_gfx_UniformStorageBuffer(ns); - js_register_gfx_SubpassDependency(ns); - js_register_gfx_UniformSamplerTexture(ns); - js_register_gfx_BufferTextureCopy(ns); - js_register_gfx_PipelineLayoutInfo(ns); - js_register_gfx_InputAssemblerInfo(ns); - js_register_gfx_TextureBlit(ns); - js_register_gfx_TextureInfo(ns); - js_register_gfx_GlobalBarrierInfo(ns); - js_register_gfx_RenderPassInfo(ns); - js_register_gfx_Extent(ns); + js_register_gfx_Size(ns); + js_register_gfx_DeviceCaps(ns); js_register_gfx_Offset(ns); - js_register_gfx_CommandBuffer(ns); - js_register_gfx_Framebuffer(ns); - js_register_gfx_Viewport(ns); + js_register_gfx_Rect(ns); + js_register_gfx_Extent(ns); js_register_gfx_TextureSubresLayers(ns); - js_register_gfx_BufferViewInfo(ns); - js_register_gfx_UniformInputAttachment(ns); - js_register_gfx_UniformSampler(ns); - js_register_gfx_ShaderInfo(ns); - js_register_gfx_PipelineStateInfo(ns); - js_register_gfx_Shader(ns); - js_register_gfx_BlendState(ns); - js_register_gfx_GlobalBarrier(ns); - js_register_gfx_DescriptorSetInfo(ns); - js_register_gfx_DescriptorSetLayoutInfo(ns); - js_register_gfx_DrawInfo(ns); - js_register_gfx_InputState(ns); - js_register_gfx_CommandBufferInfo(ns); - js_register_gfx_UniformStorageImage(ns); - js_register_gfx_UniformBlock(ns); - js_register_gfx_DepthStencilAttachment(ns); js_register_gfx_TextureSubresRange(ns); - js_register_gfx_TextureViewInfo(ns); - js_register_gfx_Context(ns); - js_register_gfx_Queue(ns); - js_register_gfx_ColorAttachment(ns); - js_register_gfx_RasterizerState(ns); - js_register_gfx_DeviceManager(ns); + js_register_gfx_TextureCopy(ns); + js_register_gfx_TextureBlit(ns); + js_register_gfx_BufferTextureCopy(ns); + js_register_gfx_Viewport(ns); js_register_gfx_Color(ns); + js_register_gfx_BindingMappingInfo(ns); + js_register_gfx_BufferInfo(ns); + js_register_gfx_BufferViewInfo(ns); + js_register_gfx_DrawInfo(ns); + js_register_gfx_DispatchInfo(ns); + js_register_gfx_IndirectBuffer(ns); + js_register_gfx_TextureInfo(ns); + js_register_gfx_TextureViewInfo(ns); + js_register_gfx_SamplerInfo(ns); + js_register_gfx_Uniform(ns); + js_register_gfx_UniformBlock(ns); + js_register_gfx_UniformSamplerTexture(ns); + js_register_gfx_UniformSampler(ns); + js_register_gfx_UniformTexture(ns); + js_register_gfx_UniformStorageImage(ns); + js_register_gfx_UniformStorageBuffer(ns); + js_register_gfx_UniformInputAttachment(ns); + js_register_gfx_ShaderStage(ns); js_register_gfx_Attribute(ns); + js_register_gfx_ShaderInfo(ns); + js_register_gfx_InputAssemblerInfo(ns); + js_register_gfx_ColorAttachment(ns); + js_register_gfx_DepthStencilAttachment(ns); + js_register_gfx_SubpassInfo(ns); + js_register_gfx_SubpassDependency(ns); + js_register_gfx_RenderPassInfo(ns); + js_register_gfx_GlobalBarrierInfo(ns); + js_register_gfx_TextureBarrierInfo(ns); + js_register_gfx_FramebufferInfo(ns); + js_register_gfx_DescriptorSetLayoutBinding(ns); + js_register_gfx_DescriptorSetLayoutInfo(ns); + js_register_gfx_DescriptorSetInfo(ns); + js_register_gfx_PipelineLayoutInfo(ns); + js_register_gfx_InputState(ns); + js_register_gfx_RasterizerState(ns); + js_register_gfx_DepthStencilState(ns); + js_register_gfx_BlendTarget(ns); + js_register_gfx_BlendState(ns); + js_register_gfx_PipelineStateInfo(ns); + js_register_gfx_CommandBufferInfo(ns); + js_register_gfx_QueueInfo(ns); js_register_gfx_MemoryStatus(ns); js_register_gfx_DeviceInfo(ns); - js_register_gfx_DepthStencilState(ns); - js_register_gfx_BindingMappingInfo(ns); - js_register_gfx_FramebufferInfo(ns); - js_register_gfx_DeviceCaps(ns); - js_register_gfx_Rect(ns); - js_register_gfx_ShaderStage(ns); - js_register_gfx_DescriptorSetLayoutBinding(ns); - js_register_gfx_UniformTexture(ns); + js_register_gfx_ContextInfo(ns); + js_register_gfx_GFXObject(ns); + js_register_gfx_Buffer(ns); + js_register_gfx_InputAssembler(ns); + js_register_gfx_CommandBuffer(ns); + js_register_gfx_Context(ns); + js_register_gfx_DescriptorSet(ns); js_register_gfx_DescriptorSetLayout(ns); - js_register_gfx_TextureCopy(ns); - js_register_gfx_IndirectBuffer(ns); - js_register_gfx_Size(ns); + js_register_gfx_Framebuffer(ns); + js_register_gfx_GlobalBarrier(ns); + js_register_gfx_PipelineLayout(ns); + js_register_gfx_PipelineState(ns); + js_register_gfx_Queue(ns); + js_register_gfx_RenderPass(ns); + js_register_gfx_Sampler(ns); + js_register_gfx_Shader(ns); + js_register_gfx_Texture(ns); + js_register_gfx_TextureBarrier(ns); + js_register_gfx_Device(ns); + js_register_gfx_DeviceManager(ns); return true; } diff --git a/native/cocos/bindings/auto/jsb_gfx_auto.h b/native/cocos/bindings/auto/jsb_gfx_auto.h index 4c9f882541..31460fee3e 100644 --- a/native/cocos/bindings/auto/jsb_gfx_auto.h +++ b/native/cocos/bindings/auto/jsb_gfx_auto.h @@ -844,6 +844,6 @@ bool js_register_cc_gfx_DeviceManager(se::Object* obj); bool register_all_gfx(se::Object* obj); JSB_REGISTER_OBJECT_TYPE(cc::gfx::DeviceManager); -SE_DECLARE_FUNC(js_gfx_DeviceManager_destroy); SE_DECLARE_FUNC(js_gfx_DeviceManager_create); +SE_DECLARE_FUNC(js_gfx_DeviceManager_destroy); diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp index 004ff2c471..2245b27493 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp @@ -288,19 +288,28 @@ TextureBarrier *DeviceAgent::createTextureBarrier() { } void DeviceAgent::copyBuffersToTexture(const uint8_t *const *buffers, Texture *dst, const BufferTextureCopy *regions, uint count) { - LinearAllocatorPool *allocator = getMainAllocator(); - - auto *actorRegions = allocator->allocate(count); - memcpy(actorRegions, regions, count * sizeof(BufferTextureCopy)); - uint bufferCount = 0U; for (uint i = 0U; i < count; i++) { bufferCount += regions[i].texSubres.layerCount; } + uint totalSize = sizeof(BufferTextureCopy) * count + sizeof(uint8_t *) * bufferCount; + for (uint i = 0U, n = 0U; i < count; i++) { + const BufferTextureCopy ®ion = regions[i]; + + uint size = formatSize(dst->getFormat(), region.texExtent.width, region.texExtent.height, 1); + totalSize += size * region.texSubres.layerCount; + } + + auto *allocator = CC_NEW(ThreadSafeLinearAllocator(totalSize)); + + auto *actorRegions = allocator->allocate(count); + memcpy(actorRegions, regions, count * sizeof(BufferTextureCopy)); + const auto **actorBuffers = allocator->allocate(bufferCount); for (uint i = 0U, n = 0U; i < count; i++) { const BufferTextureCopy ®ion = regions[i]; - uint size = formatSize(dst->getFormat(), region.texExtent.width, region.texExtent.height, 1); + + uint size = formatSize(dst->getFormat(), region.texExtent.width, region.texExtent.height, 1); for (uint l = 0; l < region.texSubres.layerCount; l++) { auto *buffer = allocator->allocate(size); memcpy(buffer, buffers[n], size); @@ -308,23 +317,23 @@ void DeviceAgent::copyBuffersToTexture(const uint8_t *const *buffers, Texture *d } } - ENQUEUE_MESSAGE_5( + ENQUEUE_MESSAGE_6( _mainMessageQueue, DeviceCopyBuffersToTexture, actor, getActor(), buffers, actorBuffers, dst, static_cast(dst)->getActor(), regions, actorRegions, count, count, + allocator, allocator, { actor->copyBuffersToTexture(buffers, dst, regions, count); + CC_DELETE(allocator); }); } void DeviceAgent::flushCommands(CommandBuffer *const *cmdBuffs, uint count) { if (!_multithreaded) return; // all command buffers are immediately executed - bool multiThreaded = hasFeature(Feature::MULTITHREADED_SUBMISSION); - auto **agentCmdBuffs = getMainAllocator()->allocate(count); for (uint i = 0; i < count; ++i) { agentCmdBuffs[i] = static_cast(cmdBuffs[i]); @@ -336,7 +345,7 @@ void DeviceAgent::flushCommands(CommandBuffer *const *cmdBuffs, uint count) { _mainMessageQueue, DeviceFlushCommands, count, count, cmdBuffs, agentCmdBuffs, - multiThreaded, multiThreaded, + multiThreaded, getActor()->_multithreadedSubmission, { CommandBufferAgent::flushCommands(count, cmdBuffs, multiThreaded); }); diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 26433f6dc8..e2f93ccc18 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -142,16 +142,10 @@ enum class Feature { FORMAT_PVRTC, FORMAT_ASTC, FORMAT_RGB8, - MSAA, ELEMENT_INDEX_UINT, INSTANCED_ARRAYS, MULTIPLE_RENDER_TARGETS, BLEND_MINMAX, - DEPTH_BOUNDS, - LINE_WIDTH, - STENCIL_WRITE_MASK, - STENCIL_COMPARE_MASK, - MULTITHREADED_SUBMISSION, COMPUTE_SHADER, COUNT, }; @@ -449,13 +443,13 @@ using TextureFlags = TextureFlagBit; CC_ENUM_OPERATORS(TextureFlagBit); enum class SampleCount { - X1, - X2, - X4, - X8, - X16, - X32, - X64, + X1 = 0x1, + X2 = 0x2, + X4 = 0x4, + X8 = 0x8, + X16 = 0x10, + X32 = 0x20, + X64 = 0x40, }; enum class Filter { @@ -591,6 +585,14 @@ enum class AccessType { using AccessTypeList = std::vector; +enum class ResolveMode { + NONE, + SAMPLE_ZERO, + AVERAGE, + MIN, + MAX, +}; + enum class PipelineBindPoint { GRAPHICS, COMPUTE, @@ -1070,7 +1072,11 @@ struct SubpassInfo { std::vector colors; std::vector resolves; std::vector preserves; - uint depthStencil = INVALID_BINDING; + + uint depthStencil = INVALID_BINDING; + uint depthStencilResolve = INVALID_BINDING; + ResolveMode depthResolveMode = ResolveMode::NONE; + ResolveMode stencilResolveMode = ResolveMode::NONE; }; using SubpassInfoList = vector; @@ -1112,8 +1118,6 @@ struct FramebufferInfo { RenderPass * renderPass = nullptr; TextureList colorTextures; // @ts-overrides { type: '(Texture | null)[]' } Texture * depthStencilTexture = nullptr; // @ts-nullable - std::vector colorMipmapLevels; - uint depthStencilMipmapLevel = 0; }; struct DescriptorSetLayoutBinding { diff --git a/native/cocos/renderer/gfx-base/GFXDevice.h b/native/cocos/renderer/gfx-base/GFXDevice.h index 1879d61ff1..13612389eb 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.h +++ b/native/cocos/renderer/gfx-base/GFXDevice.h @@ -152,17 +152,18 @@ protected: String _renderer; String _vendor; String _version; - uint _width = 0; - uint _height = 0; - float _pixelRatio = 1.0F; + bool _multithreadedSubmission{true}; + uint _width{0}; + uint _height{0}; + float _pixelRatio{1.0F}; MemoryStatus _memoryStatus; - uintptr_t _windowHandle = 0; - Context * _context = nullptr; - Queue * _queue = nullptr; - CommandBuffer * _cmdBuff = nullptr; - uint _numDrawCalls = 0U; - uint _numInstances = 0U; - uint _numTriangles = 0U; + uintptr_t _windowHandle{0}; + Context * _context{nullptr}; + Queue * _queue{nullptr}; + CommandBuffer * _cmdBuff{nullptr}; + uint _numDrawCalls{0U}; + uint _numInstances{0U}; + uint _numTriangles{0U}; BindingMappingInfo _bindingMappingInfo; DeviceCaps _caps; diff --git a/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp b/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp index ee12723232..f2f13ef0df 100644 --- a/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp +++ b/native/cocos/renderer/gfx-base/GFXFramebuffer.cpp @@ -38,15 +38,13 @@ Framebuffer::Framebuffer() Framebuffer::~Framebuffer() = default; uint Framebuffer::computeHash(const FramebufferInfo &info) { - uint seed = static_cast(info.colorTextures.size() + info.colorMipmapLevels.size() + 2); + uint seed = static_cast(info.colorTextures.size() + 2); for (const Texture *attachment : info.colorTextures) { - seed ^= attachment->getObjectID() + 0x9e3779b9 + (seed << 6) + (seed >> 2); + uint id = attachment ? attachment->getObjectID() : 0; + seed ^= id + 0x9e3779b9 + (seed << 6) + (seed >> 2); } - for (uint level : info.colorMipmapLevels) { - seed ^= level + 0x9e3779b9 + (seed << 6) + (seed >> 2); - } - seed ^= info.depthStencilTexture->getObjectID() + 0x9e3779b9 + (seed << 6) + (seed >> 2); - seed ^= static_cast(info.depthStencilMipmapLevel) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + uint depthID = info.depthStencilTexture ? info.depthStencilTexture->getObjectID() : 0; + seed ^= depthID + 0x9e3779b9 + (seed << 6) + (seed >> 2); return seed; } diff --git a/native/cocos/renderer/gfx-empty/EmptyDevice.cpp b/native/cocos/renderer/gfx-empty/EmptyDevice.cpp index 9b796c5e34..d3f12a1393 100644 --- a/native/cocos/renderer/gfx-empty/EmptyDevice.cpp +++ b/native/cocos/renderer/gfx-empty/EmptyDevice.cpp @@ -101,7 +101,7 @@ void EmptyDevice::present() { std::this_thread::sleep_for(std::chrono::milliseconds(16)); } -CommandBuffer *EmptyDevice::createCommandBuffer(const CommandBufferInfo & /*info*/, bool /*Emptyhas*/) { +CommandBuffer *EmptyDevice::createCommandBuffer(const CommandBufferInfo & /*info*/, bool /*hasAgent*/) { return CC_NEW(EmptyCommandBuffer()); } diff --git a/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h b/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h index 628e0f91e2..5effabf533 100644 --- a/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h +++ b/native/cocos/renderer/gfx-gles-common/GLESCommandPool.h @@ -32,6 +32,14 @@ namespace cc { namespace gfx { +// Multisampled Render to Texture +enum class MSRTSupportLevel { + NONE, + LEVEL1, + LEVEL2, +}; + +// Framebuffer Fetch enum class FBFSupportLevel { NONE, COHERENT, @@ -39,6 +47,13 @@ enum class FBFSupportLevel { NON_COHERENT_QCOM, }; +// Pixel Local Storage +enum class PLSSupportLevel { + NONE, + LEVEL1, + LEVEL2, +}; + enum class GLESCmdType : uint8_t { BEGIN_RENDER_PASS, END_RENDER_PASS, @@ -91,7 +106,7 @@ public: T *alloc() { if (_freeIdx < 0) { - T **old_frees = _frees; + T **oldFrees = _frees; uint size = _count * 2; _frees = new T *[size]; uint increase = size - _count; @@ -99,12 +114,12 @@ public: _frees[i] = CC_NEW(T); } for (uint i = increase, j = 0; i < size; ++i, ++j) { - _frees[i] = old_frees[j]; + _frees[i] = oldFrees[j]; } - delete[](old_frees); + delete[](oldFrees); _count = size; - _freeIdx += (int)increase; + _freeIdx += static_cast(increase); } T *cmd = _frees[_freeIdx]; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp index 067a6d0e91..671efc454c 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp @@ -26,8 +26,8 @@ #include "GLES2Std.h" #include "GLES2Commands.h" -#include "GLES2Context.h" #include "GLES2Device.h" +#include "gfx-gles-common/GLESCommandPool.h" #define BUFFER_OFFSET(idx) (static_cast(0) + (idx)) @@ -35,124 +35,6 @@ namespace cc { namespace gfx { namespace { -GLenum mapGLInternalFormat(Format format) { - switch (format) { - case Format::A8: return GL_ALPHA; - case Format::L8: return GL_LUMINANCE; - case Format::LA8: return GL_LUMINANCE_ALPHA; - case Format::R8: - case Format::R8SN: - case Format::R8UI: - case Format::R8I: return GL_LUMINANCE; - case Format::RG8: - case Format::RG8SN: - case Format::RG8UI: - case Format::RG8I: return GL_LUMINANCE_ALPHA; - case Format::RGB8: - case Format::RGB8SN: - case Format::RGB8UI: - case Format::RGB8I: return GL_RGB; - case Format::RGBA8: - case Format::RGBA8SN: - case Format::RGBA8UI: - case Format::RGBA8I: return GL_RGBA; - case Format::R16I: - case Format::R16UI: - case Format::R16F: return GL_LUMINANCE; - case Format::RG16I: - case Format::RG16UI: - case Format::RG16F: return GL_LUMINANCE_ALPHA; - case Format::RGB16I: - case Format::RGB16UI: - case Format::RGB16F: return GL_RGB; - case Format::RGBA16I: - case Format::RGBA16UI: - case Format::RGBA16F: return GL_RGBA; - case Format::R32I: - case Format::R32UI: - case Format::R32F: return GL_LUMINANCE; - case Format::RG32I: - case Format::RG32UI: - case Format::RG32F: return GL_LUMINANCE_ALPHA; - case Format::RGB32I: - case Format::RGB32UI: - case Format::RGB32F: return GL_RGB; -#if CC_PLATFORM == CC_PLATFORM_WINDOWS - case Format::RGBA32F: return GL_RGBA32F_EXT; // PVRVFrame issue -#else - case Format::RGBA32F: -#endif - case Format::RGBA32I: - case Format::RGBA32UI: return GL_RGBA; - case Format::R5G6B5: return GL_RGB565; - case Format::RGB5A1: return GL_RGB5_A1; - case Format::RGBA4: return GL_RGBA4; - case Format::SRGB8: return GL_SRGB_EXT; - case Format::SRGB8_A8: return GL_SRGB_ALPHA_EXT; - case Format::RGB10A2: - case Format::RGB10A2UI: - case Format::R11G11B10F: return GL_RGB; - case Format::D16: return GL_DEPTH_COMPONENT; - case Format::D16S8: return GL_DEPTH_STENCIL_OES; - case Format::D24: return GL_DEPTH_COMPONENT; - case Format::D24S8: return GL_DEPTH_STENCIL_OES; - case Format::D32F: return GL_DEPTH_COMPONENT; - case Format::D32F_S8: return GL_DEPTH_STENCIL_OES; - - case Format::BC1: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; - case Format::BC1_ALPHA: return GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; - case Format::BC1_SRGB: return GL_COMPRESSED_SRGB_S3TC_DXT1_EXT; - case Format::BC1_SRGB_ALPHA: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; - case Format::BC2: return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; - case Format::BC2_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; - case Format::BC3: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; - case Format::BC3_SRGB: return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - - case Format::ETC_RGB8: return GL_ETC1_RGB8_OES; - case Format::ETC2_RGB8: return GL_COMPRESSED_RGB8_ETC2; - case Format::ETC2_RGBA8: return GL_COMPRESSED_RGBA8_ETC2_EAC; - - case Format::PVRTC_RGB2: return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG; - case Format::PVRTC_RGBA2: return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; - case Format::PVRTC_RGB4: return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; - case Format::PVRTC_RGBA4: return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; - - case Format::ASTC_RGBA_4X4: return GL_COMPRESSED_RGBA_ASTC_4x4_KHR; - case Format::ASTC_RGBA_5X4: return GL_COMPRESSED_RGBA_ASTC_5x4_KHR; - case Format::ASTC_RGBA_5X5: return GL_COMPRESSED_RGBA_ASTC_5x5_KHR; - case Format::ASTC_RGBA_6X5: return GL_COMPRESSED_RGBA_ASTC_6x5_KHR; - case Format::ASTC_RGBA_6X6: return GL_COMPRESSED_RGBA_ASTC_6x6_KHR; - case Format::ASTC_RGBA_8X5: return GL_COMPRESSED_RGBA_ASTC_8x5_KHR; - case Format::ASTC_RGBA_8X6: return GL_COMPRESSED_RGBA_ASTC_8x6_KHR; - case Format::ASTC_RGBA_8X8: return GL_COMPRESSED_RGBA_ASTC_8x8_KHR; - case Format::ASTC_RGBA_10X5: return GL_COMPRESSED_RGBA_ASTC_10x5_KHR; - case Format::ASTC_RGBA_10X6: return GL_COMPRESSED_RGBA_ASTC_10x6_KHR; - case Format::ASTC_RGBA_10X8: return GL_COMPRESSED_RGBA_ASTC_10x8_KHR; - case Format::ASTC_RGBA_10X10: return GL_COMPRESSED_RGBA_ASTC_10x10_KHR; - case Format::ASTC_RGBA_12X10: return GL_COMPRESSED_RGBA_ASTC_12x10_KHR; - case Format::ASTC_RGBA_12X12: return GL_COMPRESSED_RGBA_ASTC_12x12_KHR; - - case Format::ASTC_SRGBA_4X4: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; - case Format::ASTC_SRGBA_5X4: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR; - case Format::ASTC_SRGBA_5X5: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR; - case Format::ASTC_SRGBA_6X5: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR; - case Format::ASTC_SRGBA_6X6: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR; - case Format::ASTC_SRGBA_8X5: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR; - case Format::ASTC_SRGBA_8X6: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR; - case Format::ASTC_SRGBA_8X8: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR; - case Format::ASTC_SRGBA_10X5: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR; - case Format::ASTC_SRGBA_10X6: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR; - case Format::ASTC_SRGBA_10X8: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR; - case Format::ASTC_SRGBA_10X10: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR; - case Format::ASTC_SRGBA_12X10: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR; - case Format::ASTC_SRGBA_12X12: return GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR; - - default: { - CCASSERT(false, "Unsupported Format, convert to GL internal format failed."); - return GL_RGBA; - } - } -} GLenum mapGLFormat(Format format) { switch (format) { @@ -268,6 +150,30 @@ GLenum mapGLFormat(Format format) { } } +GLenum mapGLInternalFormat(Format format) { + switch (format) { + case Format::R8: return GL_R8_EXT; + case Format::R8SN: return GL_R8_SNORM; + case Format::RG8SN: return GL_RG8_SNORM; + case Format::SRGB8: return GL_SRGB_EXT; + case Format::RGBA8SN: return GL_RGBA8_SNORM; + case Format::SRGB8_A8: return GL_SRGB_ALPHA_EXT; + case Format::R32F: return GL_R32F_EXT; + case Format::RG32F: return GL_RG32F_EXT; + case Format::RGB32F: return GL_RGB32F_EXT; + case Format::RGBA32F: return GL_RGBA32F_EXT; + case Format::R5G6B5: return GL_RGB565; + case Format::RGB5A1: return GL_RGB5_A1; + case Format::RGBA4: return GL_RGBA4; + case Format::D16: return GL_DEPTH_COMPONENT16; + case Format::D16S8: return GL_DEPTH24_STENCIL8_OES; + case Format::D24S8: return GL_DEPTH24_STENCIL8_OES; + case Format::D32F: return GL_DEPTH_COMPONENT32_OES; + + default: return mapGLFormat(format); + } +} + GLenum mapGLType(Type type) { switch (type) { case Type::BOOL: return GL_BOOL; @@ -560,7 +466,7 @@ void cmdFuncGLES2CreateBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { gpuBuffer->glTarget = GL_ARRAY_BUFFER; GL_CHECK(glGenBuffers(1, &gpuBuffer->glBuffer)); if (gpuBuffer->size) { - if (device->extensionRegistry()->useVAO) { + if (device->constantRegistry()->useVAO) { if (device->stateCache()->glVAO) { GL_CHECK(glBindVertexArrayOES(0)); device->stateCache()->glVAO = 0; @@ -580,7 +486,7 @@ void cmdFuncGLES2CreateBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { gpuBuffer->glTarget = GL_ELEMENT_ARRAY_BUFFER; GL_CHECK(glGenBuffers(1, &gpuBuffer->glBuffer)); if (gpuBuffer->size) { - if (device->extensionRegistry()->useVAO) { + if (device->constantRegistry()->useVAO) { if (device->stateCache()->glVAO) { GL_CHECK(glBindVertexArrayOES(0)); device->stateCache()->glVAO = 0; @@ -613,7 +519,7 @@ void cmdFuncGLES2DestroyBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { GLES2ObjectCache &gfxStateCache = device->stateCache()->gfxStateCache; if (gpuBuffer->glBuffer) { if (hasFlag(gpuBuffer->usage, BufferUsageBit::VERTEX)) { - if (device->extensionRegistry()->useVAO) { + if (device->constantRegistry()->useVAO) { if (device->stateCache()->glVAO) { GL_CHECK(glBindVertexArrayOES(0)); device->stateCache()->glVAO = 0; @@ -625,7 +531,7 @@ void cmdFuncGLES2DestroyBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { device->stateCache()->glArrayBuffer = 0; } } else if (hasFlag(gpuBuffer->usage, BufferUsageBit::INDEX)) { - if (device->extensionRegistry()->useVAO) { + if (device->constantRegistry()->useVAO) { if (device->stateCache()->glVAO) { GL_CHECK(glBindVertexArrayOES(0)); device->stateCache()->glVAO = 0; @@ -650,7 +556,7 @@ void cmdFuncGLES2ResizeBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { if (hasFlag(gpuBuffer->usage, BufferUsageBit::VERTEX)) { gpuBuffer->glTarget = GL_ARRAY_BUFFER; if (gpuBuffer->size) { - if (device->extensionRegistry()->useVAO) { + if (device->constantRegistry()->useVAO) { if (device->stateCache()->glVAO) { GL_CHECK(glBindVertexArrayOES(0)); device->stateCache()->glVAO = 0; @@ -669,7 +575,7 @@ void cmdFuncGLES2ResizeBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { } else if (hasFlag(gpuBuffer->usage, BufferUsageBit::INDEX)) { gpuBuffer->glTarget = GL_ELEMENT_ARRAY_BUFFER; if (gpuBuffer->size) { - if (device->extensionRegistry()->useVAO) { + if (device->constantRegistry()->useVAO) { if (device->stateCache()->glVAO) { GL_CHECK(glBindVertexArrayOES(0)); device->stateCache()->glVAO = 0; @@ -703,162 +609,231 @@ void cmdFuncGLES2ResizeBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer) { } void cmdFuncGLES2CreateTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) { - gpuTexture->glInternelFmt = mapGLInternalFormat(gpuTexture->format); gpuTexture->glFormat = mapGLFormat(gpuTexture->format); gpuTexture->glType = formatToGLType(gpuTexture->format); + gpuTexture->glInternalFmt = gpuTexture->glFormat; - switch (gpuTexture->type) { - case TextureType::TEX2D: { - gpuTexture->glTarget = GL_TEXTURE_2D; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_2D, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint w = gpuTexture->width; - uint h = gpuTexture->height; - if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { - for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - GL_CHECK(glTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternelFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); - w = std::max(1U, w >> 1); - h = std::max(1U, h >> 1); - } - } else { - for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - uint imgSize = formatSize(gpuTexture->format, w, h, 1); - GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternelFmt, w, h, 0, imgSize, nullptr)); - w = std::max(1U, w >> 1); - h = std::max(1U, h >> 1); - } - } + if (gpuTexture->samples > SampleCount::X1) { + if (device->constantRegistry()->mMSRT != MSRTSupportLevel::NONE) { + GLint maxSamples; + glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples); + + auto requestedSampleCount = static_cast(gpuTexture->samples); + gpuTexture->glSamples = std::min(maxSamples, requestedSampleCount); + + // skip multi-sampled attachment resources if we can use auto resolve + if (gpuTexture->usage == TextureUsageBit::COLOR_ATTACHMENT) { + gpuTexture->memoryless = true; + return; } - break; + } else { + gpuTexture->glSamples = 1; // fallback to single sample if the extensions is not available } - case TextureType::CUBE: { - gpuTexture->glTarget = GL_TEXTURE_CUBE_MAP; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { - for (uint f = 0; f < 6; ++f) { - uint w = gpuTexture->width; - uint h = gpuTexture->height; + } + + if (gpuTexture->glSamples <= 1) { +#if CC_PLATFORM == CC_PLATFORM_WINDOWS // PVRVFrame issue + gpuTexture->glInternalFmt = mapGLInternalFormat(gpuTexture->format); +#endif + switch (gpuTexture->type) { + case TextureType::TEX2D: { + gpuTexture->glTarget = GL_TEXTURE_2D; + GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); + if (gpuTexture->size > 0) { + GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; + if (gpuTexture->glTexture != glTexture) { + GL_CHECK(glBindTexture(GL_TEXTURE_2D, gpuTexture->glTexture)); + glTexture = gpuTexture->glTexture; + } + uint w = gpuTexture->width; + uint h = gpuTexture->height; + if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - GL_CHECK(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternelFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); + GL_CHECK(glTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternalFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); w = std::max(1U, w >> 1); h = std::max(1U, h >> 1); } - } - } else { - for (uint f = 0; f < 6; ++f) { - uint w = gpuTexture->width; - uint h = gpuTexture->height; + } else { for (uint i = 0; i < gpuTexture->mipLevel; ++i) { uint imgSize = formatSize(gpuTexture->format, w, h, 1); - GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternelFmt, w, h, 0, imgSize, nullptr)); + GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternalFmt, w, h, 0, imgSize, nullptr)); w = std::max(1U, w >> 1); h = std::max(1U, h >> 1); } } } + break; } - break; + case TextureType::CUBE: { + gpuTexture->glTarget = GL_TEXTURE_CUBE_MAP; + GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); + if (gpuTexture->size > 0) { + GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; + if (gpuTexture->glTexture != glTexture) { + GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); + glTexture = gpuTexture->glTexture; + } + if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { + for (uint f = 0; f < 6; ++f) { + uint w = gpuTexture->width; + uint h = gpuTexture->height; + for (uint i = 0; i < gpuTexture->mipLevel; ++i) { + GL_CHECK(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternalFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); + w = std::max(1U, w >> 1); + h = std::max(1U, h >> 1); + } + } + } else { + for (uint f = 0; f < 6; ++f) { + uint w = gpuTexture->width; + uint h = gpuTexture->height; + for (uint i = 0; i < gpuTexture->mipLevel; ++i) { + uint imgSize = formatSize(gpuTexture->format, w, h, 1); + GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternalFmt, w, h, 0, imgSize, nullptr)); + w = std::max(1U, w >> 1); + h = std::max(1U, h >> 1); + } + } + } + } + break; + } + default: + CCASSERT(false, "Unsupported TextureType, create texture failed."); + break; + } + } else { + gpuTexture->glInternalFmt = mapGLInternalFormat(gpuTexture->format); + switch (gpuTexture->type) { + case TextureType::TEX2D: { + gpuTexture->glTarget = GL_RENDERBUFFER; + GL_CHECK(glGenRenderbuffers(1, &gpuTexture->glRenderbuffer)); + if (gpuTexture->size > 0) { + GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; + if (gpuTexture->glRenderbuffer != glRenderbuffer) { + GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, gpuTexture->glRenderbuffer)); + glRenderbuffer = gpuTexture->glRenderbuffer; + } + GL_CHECK(glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, gpuTexture->glSamples, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); + } + break; + } + default: + CCASSERT(false, "Unsupported TextureType, create texture failed."); + break; } - default: - CCASSERT(false, "Unsupported TextureType, create texture failed."); - break; } } void cmdFuncGLES2DestroyTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) { + device->framebufferCacheMap()->onTextureDestroy(gpuTexture); + if (gpuTexture->glTexture) { for (GLuint &glTexture : device->stateCache()->glTextures) { if (glTexture == gpuTexture->glTexture) { glTexture = 0; } } - device->framebufferCacheMap()->onTextureDestroy(gpuTexture); - GL_CHECK(glDeleteTextures(1, &gpuTexture->glTexture)); gpuTexture->glTexture = 0; + + } else if (gpuTexture->glRenderbuffer) { + GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; + if (gpuTexture->glRenderbuffer == glRenderbuffer) { + GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0)); + glRenderbuffer = 0; + } + GL_CHECK(glDeleteRenderbuffers(1, &gpuTexture->glRenderbuffer)); + gpuTexture->glRenderbuffer = 0; } } void cmdFuncGLES2ResizeTexture(GLES2Device *device, GLES2GPUTexture *gpuTexture) { - gpuTexture->glInternelFmt = mapGLInternalFormat(gpuTexture->format); - gpuTexture->glFormat = mapGLFormat(gpuTexture->format); - gpuTexture->glType = formatToGLType(gpuTexture->format); + if (gpuTexture->memoryless) return; - switch (gpuTexture->type) { - case TextureType::TEX2D: { - gpuTexture->glTarget = GL_TEXTURE_2D; - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_2D, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint w = gpuTexture->width; - uint h = gpuTexture->height; - if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { - for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - GL_CHECK(glTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternelFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); - w = std::max(1U, w >> 1); - h = std::max(1U, h >> 1); + if (gpuTexture->glSamples <= 1) { + switch (gpuTexture->type) { + case TextureType::TEX2D: { + gpuTexture->glTarget = GL_TEXTURE_2D; + if (gpuTexture->size > 0) { + GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; + if (gpuTexture->glTexture != glTexture) { + GL_CHECK(glBindTexture(GL_TEXTURE_2D, gpuTexture->glTexture)); + glTexture = gpuTexture->glTexture; } - } else { - for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - uint imgSize = formatSize(gpuTexture->format, w, h, 1); - GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternelFmt, w, h, 0, imgSize, nullptr)); - w = std::max(1U, w >> 1); - h = std::max(1U, h >> 1); - } - } - } - break; - } - case TextureType::CUBE: { - gpuTexture->glTarget = GL_TEXTURE_CUBE_MAP; - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { - for (uint f = 0; f < 6; ++f) { - uint w = gpuTexture->width; - uint h = gpuTexture->height; + uint w = gpuTexture->width; + uint h = gpuTexture->height; + if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - GL_CHECK(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternelFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); + GL_CHECK(glTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternalFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); w = std::max(1U, w >> 1); h = std::max(1U, h >> 1); } - } - } else { - for (uint f = 0; f < 6; ++f) { - uint w = gpuTexture->width; - uint h = gpuTexture->height; + } else { for (uint i = 0; i < gpuTexture->mipLevel; ++i) { uint imgSize = formatSize(gpuTexture->format, w, h, 1); - GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternelFmt, w, h, 0, imgSize, nullptr)); + GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternalFmt, w, h, 0, imgSize, nullptr)); w = std::max(1U, w >> 1); h = std::max(1U, h >> 1); } } } + break; } - break; + case TextureType::CUBE: { + gpuTexture->glTarget = GL_TEXTURE_CUBE_MAP; + if (gpuTexture->size > 0) { + GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; + if (gpuTexture->glTexture != glTexture) { + GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); + glTexture = gpuTexture->glTexture; + } + if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { + for (uint f = 0; f < 6; ++f) { + uint w = gpuTexture->width; + uint h = gpuTexture->height; + for (uint i = 0; i < gpuTexture->mipLevel; ++i) { + GL_CHECK(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternalFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); + w = std::max(1U, w >> 1); + h = std::max(1U, h >> 1); + } + } + } else { + for (uint f = 0; f < 6; ++f) { + uint w = gpuTexture->width; + uint h = gpuTexture->height; + for (uint i = 0; i < gpuTexture->mipLevel; ++i) { + uint imgSize = formatSize(gpuTexture->format, w, h, 1); + GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternalFmt, w, h, 0, imgSize, nullptr)); + w = std::max(1U, w >> 1); + h = std::max(1U, h >> 1); + } + } + } + } + break; + } + default: + CCASSERT(false, "Unsupported TextureType, resize texture failed."); + break; + } + } else { + switch (gpuTexture->type) { + case TextureType::TEX2D: { + if (gpuTexture->size > 0) { + GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; + if (gpuTexture->glRenderbuffer != glRenderbuffer) { + GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, gpuTexture->glRenderbuffer)); + glRenderbuffer = gpuTexture->glRenderbuffer; + } + GL_CHECK(glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER, gpuTexture->glSamples, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); + } + break; + } + default: + CCASSERT(false, "Unsupported TextureType, resize texture failed."); + break; } - default: - CCASSERT(false, "Unsupported TextureType, resize texture failed."); - break; } } @@ -1046,7 +1021,7 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { } // if // fallback subpassInputs into samplerTextures if not using FBF or PLS - if (device->extensionRegistry()->mFBF == FBFSupportLevel::NONE) { + if (device->constantRegistry()->mFBF == FBFSupportLevel::NONE) { for (const auto &subpassInput : gpuShader->subpassInputs) { auto &samplerTexture = gpuShader->samplerTextures.emplace_back(); samplerTexture.name = subpassInput.name; @@ -1269,125 +1244,184 @@ void cmdFuncGLES2DestroyInputAssembler(GLES2Device *device, GLES2GPUInputAssembl gpuInputAssembler->glVAOs.clear(); } -void cmdFuncGLES2CreateFramebuffer(GLES2Device *device, GLES2GPUFramebuffer *gpuFBO) { - uint colorAttachmentCount = gpuFBO->gpuColorTextures.size(); - static vector attachments; +static GLuint doCreateFramebuffer(GLES2Device * device, + const vector &attachments, const uint *colors, uint colorCount, + const GLES2GPUTexture *depthStencil, + const uint * resolves = nullptr, + const GLES2GPUTexture *depthStencilResolve = nullptr, + GLbitfield * resolveMask = nullptr) { + static vector drawBuffers; + GLuint glFramebuffer{0U}; + GLES2GPUStateCache * cache = device->stateCache(); - auto createFBO = [&](const vector &colorIndices, uint depthStencilIndex, GLES2GPUFramebuffer::GLFramebuffer *outFBO) { - uint offscreenCount{0U}; - for (uint idx : colorIndices) { - const auto *colorTex = gpuFBO->gpuColorTextures[idx]; - if (colorTex) ++offscreenCount; + GL_CHECK(glGenFramebuffers(1, &glFramebuffer)); + if (cache->glFramebuffer != glFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, glFramebuffer)); + cache->glFramebuffer = glFramebuffer; + } + + drawBuffers.clear(); + + auto supportLevel = device->constantRegistry()->mMSRT; + bool autoResolve = supportLevel > MSRTSupportLevel::LEVEL1 || (supportLevel != MSRTSupportLevel::NONE && colorCount <= 1); + + for (size_t j = 0; j < colorCount; ++j) { + GLES2GPUTexture *gpuColorTexture = attachments[colors[j]]; + GLES2GPUTexture *gpuResolveTexture = resolves ? attachments[resolves[j]] : nullptr; + drawBuffers.push_back(static_cast(GL_COLOR_ATTACHMENT0 + j)); + + if (gpuResolveTexture) { + if (autoResolve) { + GL_CHECK(glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), + gpuResolveTexture->glTarget, gpuResolveTexture->glTexture, 0, + gpuColorTexture->glSamples)); + continue; + } + *resolveMask |= GL_COLOR_BUFFER_BIT; // fallback to blit-based manual resolve } - CCASSERT(!offscreenCount || offscreenCount == colorIndices.size(), - "Partially offscreen FBO is not supported"); - - outFBO->isOffscreen = offscreenCount; - - if (outFBO->isOffscreen) { - GL_CHECK(glGenFramebuffers(1, &outFBO->glFramebuffer)); - if (device->stateCache()->glFramebuffer != outFBO->glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, outFBO->glFramebuffer)); - device->stateCache()->glFramebuffer = outFBO->glFramebuffer; - } - - attachments.clear(); - - for (size_t j = 0; j < colorIndices.size(); ++j) { - GLES2GPUTexture *gpuColorTexture = gpuFBO->gpuColorTextures[colorIndices[j]]; - if (gpuColorTexture) { - GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), gpuColorTexture->glTarget, gpuColorTexture->glTexture, 0)); - - attachments.push_back(static_cast(GL_COLOR_ATTACHMENT0 + j)); - } - } - - const auto *depthStencilTexture = depthStencilIndex < colorAttachmentCount - ? gpuFBO->gpuColorTextures[depthStencilIndex] - : gpuFBO->gpuDepthStencilTexture; - if (depthStencilTexture) { - GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthStencilTexture->glTarget, depthStencilTexture->glTexture, 0)); - - if (GFX_FORMAT_INFOS[static_cast(depthStencilTexture->format)].hasStencil) { - GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, depthStencilTexture->glTarget, depthStencilTexture->glTexture, 0)); - } - } - - if (device->hasFeature(Feature::MULTIPLE_RENDER_TARGETS)) { - GL_CHECK(glDrawBuffersEXT(attachments.size(), attachments.data())); - } - - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - if (status != GL_FRAMEBUFFER_COMPLETE) { - switch (status) { - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - CC_LOG_ERROR("glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - CC_LOG_ERROR("glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - CC_LOG_ERROR("glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); - break; - case GL_FRAMEBUFFER_UNSUPPORTED: - CC_LOG_ERROR("glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED"); - break; - } - } + if (gpuColorTexture->glTexture) { + GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), + gpuColorTexture->glTarget, gpuColorTexture->glTexture, 0)); } else { -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - outFBO->glFramebuffer = device->getDefaultFramebuffer(); -#endif + GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), + gpuColorTexture->glTarget, gpuColorTexture->glRenderbuffer)); + } + } + if (depthStencil) { + bool hasStencil = GFX_FORMAT_INFOS[static_cast(depthStencil->format)].hasStencil; + if (depthStencil->glTexture) { + GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthStencil->glTarget, depthStencil->glTexture, 0)); + if (hasStencil) GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, depthStencil->glTarget, depthStencil->glTexture, 0)); + } else { + GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthStencil->glTarget, depthStencil->glTexture)); + if (hasStencil) GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, depthStencil->glTarget, depthStencil->glTexture)); } - }; - if (gpuFBO->gpuRenderPass->subpasses.size() > 1) { - gpuFBO->usesFBF = device->extensionRegistry()->mFBF != FBFSupportLevel::NONE; + // fallback to blit-based manual resolve + if (depthStencilResolve) *resolveMask |= hasStencil ? GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT : GL_DEPTH_BUFFER_BIT; + } - if (gpuFBO->usesFBF) { - gpuFBO->uberColorAttachmentIndices.clear(); - for (uint i = 0U; i < gpuFBO->gpuColorTextures.size(); ++i) { - const auto *gpuTexture = gpuFBO->gpuColorTextures[i]; - if (!gpuTexture) continue; - if (GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].hasDepth) continue; - gpuFBO->uberColorAttachmentIndices.push_back(i); - } - createFBO(gpuFBO->uberColorAttachmentIndices, gpuFBO->gpuColorTextures.size(), &gpuFBO->uberInstance); - return; + if (device->hasFeature(Feature::MULTIPLE_RENDER_TARGETS)) { + GL_CHECK(glDrawBuffersEXT(drawBuffers.size(), drawBuffers.data())); + } + + GLenum status; + GL_CHECK(status = glCheckFramebufferStatus(GL_FRAMEBUFFER)); + if (status != GL_FRAMEBUFFER_COMPLETE) { + switch (status) { + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); + break; + case GL_FRAMEBUFFER_UNSUPPORTED: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED"); + break; + default: + CC_LOG_ERROR("checkFramebufferStatus() - %x", status); + break; } } - for (const auto &subpass : gpuFBO->gpuRenderPass->subpasses) { - createFBO(subpass.colors, subpass.depthStencil, &gpuFBO->instances.emplace_back()); + return glFramebuffer; +} + +static void doCreateFramebufferInstance(GLES2Device *device, GLES2GPUFramebuffer *gpuFBO, const vector &colors, + uint depthStencil, GLES2GPUFramebuffer::GLFramebuffer *outFBO, + const uint *resolves = nullptr, uint depthStencilResolve = INVALID_BINDING) { + uint offscreenCount{0U}; + for (uint idx : colors) { + const auto *colorTex = gpuFBO->gpuColorTextures[idx]; + if (colorTex) ++offscreenCount; + } + CCASSERT(!offscreenCount || offscreenCount == colors.size(), "Partially offscreen FBO is not supported"); + + const GLES2GPUTexture *depthStencilTexture = nullptr; + if (depthStencil != INVALID_BINDING) { + depthStencilTexture = depthStencil < gpuFBO->gpuColorTextures.size() + ? gpuFBO->gpuColorTextures[depthStencil] + : gpuFBO->gpuDepthStencilTexture; + } + const GLES2GPUTexture *depthStencilResolveTexture = nullptr; + if (depthStencilResolve != INVALID_BINDING) { + depthStencilResolveTexture = depthStencilResolve < gpuFBO->gpuColorTextures.size() + ? gpuFBO->gpuColorTextures[depthStencilResolve] + : gpuFBO->gpuDepthStencilTexture; + } + + if (offscreenCount || depthStencilTexture) { + outFBO->glFramebuffer = doCreateFramebuffer(device, gpuFBO->gpuColorTextures, colors.data(), colors.size(), + depthStencilTexture, resolves, depthStencilResolveTexture, &outFBO->resolveMask); + if (outFBO->resolveMask) { + uint resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? colors.size() : 0U; + outFBO->glResolveFramebuffer = doCreateFramebuffer(device, gpuFBO->gpuColorTextures, resolves, resolveCount, depthStencilResolveTexture); + } + } else { + outFBO->glFramebuffer = device->constantRegistry()->defaultFramebuffer; } } +void cmdFuncGLES2CreateFramebuffer(GLES2Device *device, GLES2GPUFramebuffer *gpuFBO) { + if (gpuFBO->gpuRenderPass->subpasses.size() > 1) { + gpuFBO->usesFBF = device->constantRegistry()->mFBF != FBFSupportLevel::NONE; + } + + if (gpuFBO->usesFBF) { + gpuFBO->uberColorAttachmentIndices.clear(); + for (uint i = 0U; i < gpuFBO->gpuColorTextures.size(); ++i) { + const auto *gpuTexture = gpuFBO->gpuColorTextures[i]; + if (!gpuTexture || gpuTexture->memoryless) continue; + if (GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].hasDepth) continue; + gpuFBO->uberColorAttachmentIndices.push_back(i); + } + doCreateFramebufferInstance(device, gpuFBO, gpuFBO->uberColorAttachmentIndices, gpuFBO->gpuColorTextures.size(), &gpuFBO->uberInstance); + } else { + for (const auto &subpass : gpuFBO->gpuRenderPass->subpasses) { + doCreateFramebufferInstance(device, gpuFBO, subpass.colors, subpass.depthStencil, &gpuFBO->instances.emplace_back(), + subpass.resolves.empty() ? nullptr : subpass.resolves.data(), subpass.depthStencilResolve); + } + } +} + +static void doDestroyFramebuffer(GLES2GPUStateCache *cache, GLuint *pFBO) { + if (cache->glFramebuffer == *pFBO) { + GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); + cache->glFramebuffer = 0; + } + GL_CHECK(glDeleteFramebuffers(1, pFBO)); + *pFBO = 0U; +} + void cmdFuncGLES2DestroyFramebuffer(GLES2Device *device, GLES2GPUFramebuffer *gpuFBO) { + auto *cache = device->stateCache(); + uint defaultFBO = device->constantRegistry()->defaultFramebuffer; + for (auto &instance : gpuFBO->instances) { - if (instance.isOffscreen && instance.glFramebuffer) { - if (device->stateCache()->glFramebuffer == instance.glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); - device->stateCache()->glFramebuffer = 0; - } - GL_CHECK(glDeleteFramebuffers(1, &instance.glFramebuffer)); - instance.glFramebuffer = 0U; + if (instance.glFramebuffer != defaultFBO) { + doDestroyFramebuffer(cache, &instance.glFramebuffer); + } + if (instance.glResolveFramebuffer != defaultFBO) { + doDestroyFramebuffer(cache, &instance.glResolveFramebuffer); } } gpuFBO->instances.clear(); - if (gpuFBO->uberInstance.isOffscreen && gpuFBO->uberInstance.glFramebuffer) { - if (device->stateCache()->glFramebuffer == gpuFBO->uberInstance.glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); - device->stateCache()->glFramebuffer = 0; - } - GL_CHECK(glDeleteFramebuffers(1, &gpuFBO->uberInstance.glFramebuffer)); - gpuFBO->uberInstance.glFramebuffer = 0U; + if (gpuFBO->uberInstance.glFramebuffer != defaultFBO) { + doDestroyFramebuffer(cache, &gpuFBO->uberInstance.glFramebuffer); + } + if (gpuFBO->uberInstance.glResolveFramebuffer != defaultFBO) { + doDestroyFramebuffer(cache, &gpuFBO->uberInstance.glResolveFramebuffer); } } void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPURenderPass *gpuRenderPass, GLES2GPUFramebuffer *gpuFramebuffer, const Rect *renderArea, const Color *clearColors, float clearDepth, uint clearStencil) { - static uint attachmentLoadOpRecord = 0U; + static uint attachmentLoadOpRecord = 0U; + static vector invalidAttachments; GLES2GPUStateCache *cache = device->stateCache(); GLES2ObjectCache & gfxStateCache = cache->gfxStateCache; @@ -1409,8 +1443,6 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR attachmentLoadOpRecord = 0U; } - GLenum *invalidAttachments = gfxStateCache.invalidAttachments; - if (gpuFramebuffer && gpuRenderPass) { const auto &instance = gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[subpassIdx]; if (cache->glFramebuffer != instance.glFramebuffer) { @@ -1440,14 +1472,10 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR cache->scissor.height = renderArea->height; } - GLbitfield glClears = 0; - uint numAttachments = 0; - bool hasBoundFBO = instance.isOffscreen; -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - hasBoundFBO = true; -#endif - - bool maskSet = false; + GLbitfield glClears = 0; + bool hasBoundFBO = instance.glFramebuffer; + bool maskSet = false; + invalidAttachments.clear(); auto performLoadOp = [&](uint attachmentIndex, uint glAttachmentIndex) { const ColorAttachment &colorAttachment = gpuRenderPass->colorAttachments[attachmentIndex]; @@ -1472,7 +1500,7 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR } case LoadOp::DISCARD: // invalidate fbo - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR_EXT); + invalidAttachments.push_back(hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR_EXT); break; } } @@ -1494,7 +1522,7 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR } break; case LoadOp::DISCARD: // invalidate fbo - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH_EXT); + invalidAttachments.push_back(hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH_EXT); break; } } // if (hasDepth) @@ -1514,13 +1542,13 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR } break; case LoadOp::DISCARD: // invalidate fbo - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL_EXT); + invalidAttachments.push_back(hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL_EXT); break; } } - if (numAttachments && device->extensionRegistry()->useDiscardFramebuffer) { - GL_CHECK(glDiscardFramebufferEXT(GL_FRAMEBUFFER, numAttachments, invalidAttachments)); + if (!invalidAttachments.empty() && device->constantRegistry()->useDiscardFramebuffer) { + GL_CHECK(glDiscardFramebufferEXT(GL_FRAMEBUFFER, invalidAttachments.size(), invalidAttachments.data())); } if (glClears) { @@ -1572,20 +1600,19 @@ void cmdFuncGLES2BeginRenderPass(GLES2Device *device, uint subpassIdx, GLES2GPUR } void cmdFuncGLES2EndRenderPass(GLES2Device *device) { - GLES2GPUStateCache * cache = device->stateCache(); - GLES2ObjectCache & gfxStateCache = cache->gfxStateCache; - GLES2GPURenderPass * gpuRenderPass = gfxStateCache.gpuRenderPass; - GLES2GPUFramebuffer *gpuFramebuffer = gfxStateCache.gpuFramebuffer; - GLenum * invalidAttachments = gfxStateCache.invalidAttachments; - const auto & instance = gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[gfxStateCache.subpassIdx]; - const SubpassInfo & subpass = gpuRenderPass->subpasses[gfxStateCache.subpassIdx]; - bool isTheLastSubpass = gfxStateCache.subpassIdx == gpuRenderPass->subpasses.size() - 1; - bool hasBoundFBO = instance.isOffscreen; -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - hasBoundFBO = true; -#endif + static vector invalidAttachments; - uint numAttachments = 0; + GLES2GPUStateCache * cache = device->stateCache(); + GLES2ObjectCache & gfxStateCache = cache->gfxStateCache; + GLES2GPURenderPass * gpuRenderPass = gfxStateCache.gpuRenderPass; + GLES2GPUFramebuffer *gpuFramebuffer = gfxStateCache.gpuFramebuffer; + const auto & instance = gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[gfxStateCache.subpassIdx]; + const SubpassInfo & subpass = gpuRenderPass->subpasses[gfxStateCache.subpassIdx]; + bool isTheLastSubpass = gfxStateCache.subpassIdx == gpuRenderPass->subpasses.size() - 1; + bool hasBoundFBO = instance.glFramebuffer; + bool skipDiscard = false; + + invalidAttachments.clear(); auto performStoreOp = [&](uint attachmentIndex, uint glAttachmentIndex) { const ColorAttachment &colorAttachment = gpuRenderPass->colorAttachments[attachmentIndex]; if (colorAttachment.format != Format::UNKNOWN) { @@ -1593,7 +1620,7 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { case StoreOp::STORE: break; case StoreOp::DISCARD: // invalidate fbo - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR_EXT); + invalidAttachments.push_back(hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR_EXT); break; } } @@ -1608,7 +1635,7 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { case StoreOp::STORE: break; case StoreOp::DISCARD: // invalidate fbo - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH_EXT); + invalidAttachments.push_back(hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH_EXT); break; } } // if (hasDepth) @@ -1618,16 +1645,55 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { case StoreOp::STORE: break; case StoreOp::DISCARD: // invalidate fbo - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL_EXT); + invalidAttachments.push_back(hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL_EXT); break; } } - if (numAttachments && device->extensionRegistry()->useDiscardFramebuffer) { - GL_CHECK(glDiscardFramebufferEXT(GL_FRAMEBUFFER, numAttachments, invalidAttachments)); + if (!skipDiscard && !invalidAttachments.empty() && device->constantRegistry()->useDiscardFramebuffer) { + GL_CHECK(glDiscardFramebufferEXT(GL_FRAMEBUFFER, invalidAttachments.size(), invalidAttachments.data())); } }; + if (instance.resolveMask) { + if (cache->glFramebuffer != instance.glResolveFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, instance.glResolveFramebuffer)); + cache->glFramebuffer = instance.glResolveFramebuffer; + } + + TextureBlit region; + + if (instance.resolveMask & GL_COLOR_BUFFER_BIT) { + for (uint i = 0; i < subpass.colors.size(); ++i) { + GLES2GPUTexture *srcTexture = gpuFramebuffer->gpuColorTextures[subpass.colors[i]]; + GLES2GPUTexture *dstTexture = gpuFramebuffer->gpuColorTextures[subpass.resolves[i]]; + + region.srcExtent.width = srcTexture->width; + region.srcExtent.height = srcTexture->height; + region.dstExtent.width = dstTexture->width; + region.dstExtent.height = dstTexture->height; + device->blitManager()->draw(srcTexture, dstTexture, ®ion, 1, Filter::POINT); + } + } + + if (instance.resolveMask & GL_DEPTH_BUFFER_BIT) { + GLES2GPUTexture *srcTexture = subpass.depthStencil < gpuFramebuffer->gpuColorTextures.size() + ? gpuFramebuffer->gpuColorTextures[subpass.depthStencil] + : gpuFramebuffer->gpuDepthStencilTexture; + GLES2GPUTexture *dstTexture = subpass.depthStencilResolve < gpuFramebuffer->gpuColorTextures.size() + ? gpuFramebuffer->gpuColorTextures[subpass.depthStencilResolve] + : gpuFramebuffer->gpuDepthStencilTexture; + + region.srcExtent.width = srcTexture->width; + region.srcExtent.height = srcTexture->height; + region.dstExtent.width = dstTexture->width; + region.dstExtent.height = dstTexture->height; + device->blitManager()->draw(srcTexture, dstTexture, ®ion, 1, Filter::POINT); + } + + skipDiscard = true; // framebuffer was already stored + } + uint glAttachmentIndex = 0U; if (gpuFramebuffer->usesFBF) { if (isTheLastSubpass) { @@ -1636,15 +1702,16 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { } performDepthStencilStoreOp(); } else if (gpuFramebuffer->usesFBF) { - if (device->extensionRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_EXT) { + if (device->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_EXT) { glFramebufferFetchBarrierEXT(); - } else if (device->extensionRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { + } else if (device->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { glFramebufferFetchBarrierQCOM(); } } } else { if (isTheLastSubpass) { - for (const auto attachmentIndex : subpass.colors) { + const auto &indices = subpass.resolves.empty() ? subpass.colors : subpass.resolves; + for (const auto attachmentIndex : indices) { performStoreOp(attachmentIndex, glAttachmentIndex++); } performDepthStencilStoreOp(); @@ -1822,42 +1889,44 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli cache->bs.blendColor = gpuPipelineState->bs.blendColor; } - BlendTarget & cacheTarget = cache->bs.targets[0]; - const BlendTarget &target = gpuPipelineState->bs.targets[0]; - if (cacheTarget.blend != target.blend) { - if (!cacheTarget.blend) { - GL_CHECK(glEnable(GL_BLEND)); - } else { - GL_CHECK(glDisable(GL_BLEND)); + if (!gpuPipelineState->bs.targets.empty()) { + BlendTarget & cacheTarget = cache->bs.targets[0]; + const BlendTarget &target = gpuPipelineState->bs.targets[0]; + if (cacheTarget.blend != target.blend) { + if (!cacheTarget.blend) { + GL_CHECK(glEnable(GL_BLEND)); + } else { + GL_CHECK(glDisable(GL_BLEND)); + } + cacheTarget.blend = target.blend; + } + if (cacheTarget.blendEq != target.blendEq || + cacheTarget.blendAlphaEq != target.blendAlphaEq) { + GL_CHECK(glBlendEquationSeparate(GLES2_BLEND_OPS[(int)target.blendEq], + GLES2_BLEND_OPS[(int)target.blendAlphaEq])); + cacheTarget.blendEq = target.blendEq; + cacheTarget.blendAlphaEq = target.blendAlphaEq; + } + if (cacheTarget.blendSrc != target.blendSrc || + cacheTarget.blendDst != target.blendDst || + cacheTarget.blendSrcAlpha != target.blendSrcAlpha || + cacheTarget.blendDstAlpha != target.blendDstAlpha) { + GL_CHECK(glBlendFuncSeparate(GLES2_BLEND_FACTORS[(int)target.blendSrc], + GLES2_BLEND_FACTORS[(int)target.blendDst], + GLES2_BLEND_FACTORS[(int)target.blendSrcAlpha], + GLES2_BLEND_FACTORS[(int)target.blendDstAlpha])); + cacheTarget.blendSrc = target.blendSrc; + cacheTarget.blendDst = target.blendDst; + cacheTarget.blendSrcAlpha = target.blendSrcAlpha; + cacheTarget.blendDstAlpha = target.blendDstAlpha; + } + if (cacheTarget.blendColorMask != target.blendColorMask) { + GL_CHECK(glColorMask((GLboolean)(target.blendColorMask & ColorMask::R), + (GLboolean)(target.blendColorMask & ColorMask::G), + (GLboolean)(target.blendColorMask & ColorMask::B), + (GLboolean)(target.blendColorMask & ColorMask::A))); + cacheTarget.blendColorMask = target.blendColorMask; } - cacheTarget.blend = target.blend; - } - if (cacheTarget.blendEq != target.blendEq || - cacheTarget.blendAlphaEq != target.blendAlphaEq) { - GL_CHECK(glBlendEquationSeparate(GLES2_BLEND_OPS[(int)target.blendEq], - GLES2_BLEND_OPS[(int)target.blendAlphaEq])); - cacheTarget.blendEq = target.blendEq; - cacheTarget.blendAlphaEq = target.blendAlphaEq; - } - if (cacheTarget.blendSrc != target.blendSrc || - cacheTarget.blendDst != target.blendDst || - cacheTarget.blendSrcAlpha != target.blendSrcAlpha || - cacheTarget.blendDstAlpha != target.blendDstAlpha) { - GL_CHECK(glBlendFuncSeparate(GLES2_BLEND_FACTORS[(int)target.blendSrc], - GLES2_BLEND_FACTORS[(int)target.blendDst], - GLES2_BLEND_FACTORS[(int)target.blendSrcAlpha], - GLES2_BLEND_FACTORS[(int)target.blendDstAlpha])); - cacheTarget.blendSrc = target.blendSrc; - cacheTarget.blendDst = target.blendDst; - cacheTarget.blendSrcAlpha = target.blendSrcAlpha; - cacheTarget.blendDstAlpha = target.blendDstAlpha; - } - if (cacheTarget.blendColorMask != target.blendColorMask) { - GL_CHECK(glColorMask((GLboolean)(target.blendColorMask & ColorMask::R), - (GLboolean)(target.blendColorMask & ColorMask::G), - (GLboolean)(target.blendColorMask & ColorMask::B), - (GLboolean)(target.blendColorMask & ColorMask::A))); - cacheTarget.blendColorMask = target.blendColorMask; } } // if @@ -2005,6 +2074,8 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli GLES2GPUTexture *gpuTexture = gpuDescriptor->gpuTexture; GLuint glTexture = gpuTexture->glTexture; + CCASSERT(!gpuTexture->glRenderbuffer, "Can not sample renderbuffers!"); + if (cache->glTextures[unit] != glTexture) { if (cache->texUint != unit) { GL_CHECK(glActiveTexture(GL_TEXTURE0 + unit)); @@ -2083,8 +2154,8 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli if (gpuInputAssembler && gpuPipelineState && gpuPipelineState->gpuShader && (isShaderChanged || gpuInputAssembler != gfxStateCache.gpuInputAssembler)) { gfxStateCache.gpuInputAssembler = gpuInputAssembler; - if (device->extensionRegistry()->useVAO) { - size_t hash = gpuPipelineState->gpuShader->glProgram ^ device->getThreadID(); + if (device->constantRegistry()->useVAO) { + size_t hash = gpuPipelineState->gpuShader->glProgram ^ device->constantRegistry()->currentBoundThreadID; GLuint glVAO = gpuInputAssembler->glVAOs[hash]; if (!glVAO) { GL_CHECK(glGenVertexArraysOES(1, &glVAO)); @@ -2111,7 +2182,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli gpuAttribute.stride, BUFFER_OFFSET(attribOffset))); - if (device->extensionRegistry()->useInstancedArrays) { + if (device->constantRegistry()->useInstancedArrays) { GL_CHECK(glVertexAttribDivisorEXT(glLoc, gpuAttribute.isInstanced ? 1 : 0)); } } @@ -2162,7 +2233,7 @@ void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipeli gpuAttribute.stride, BUFFER_OFFSET(attribOffset))); - if (device->extensionRegistry()->useInstancedArrays) { + if (device->constantRegistry()->useInstancedArrays) { GL_CHECK(glVertexAttribDivisorEXT(glLoc, gpuAttribute.isInstanced ? 1 : 0)); } } @@ -2288,7 +2359,7 @@ void cmdFuncGLES2Draw(GLES2Device *device, const DrawInfo &drawInfo) { if (drawInfo.instanceCount == 0) { GL_CHECK(glDrawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler->glIndexType, offset)); } else { - if (device->extensionRegistry()->useDrawInstanced) { + if (device->constantRegistry()->useDrawInstanced) { GL_CHECK(glDrawElementsInstancedEXT(glPrimitive, drawInfo.indexCount, gpuInputAssembler->glIndexType, offset, drawInfo.instanceCount)); } } @@ -2297,7 +2368,7 @@ void cmdFuncGLES2Draw(GLES2Device *device, const DrawInfo &drawInfo) { if (drawInfo.instanceCount == 0) { GL_CHECK(glDrawArrays(glPrimitive, drawInfo.firstIndex, drawInfo.vertexCount)); } else { - if (device->extensionRegistry()->useDrawInstanced) { + if (device->constantRegistry()->useDrawInstanced) { GL_CHECK(glDrawArraysInstancedEXT(glPrimitive, drawInfo.firstIndex, drawInfo.vertexCount, drawInfo.instanceCount)); } } @@ -2312,7 +2383,7 @@ void cmdFuncGLES2Draw(GLES2Device *device, const DrawInfo &drawInfo) { if (drawInfo.instanceCount == 0) { GL_CHECK(glDrawElements(glPrimitive, draw.indexCount, gpuInputAssembler->glIndexType, offset)); } else { - if (device->extensionRegistry()->useDrawInstanced) { + if (device->constantRegistry()->useDrawInstanced) { GL_CHECK(glDrawElementsInstancedEXT(glPrimitive, draw.indexCount, gpuInputAssembler->glIndexType, offset, draw.instanceCount)); } } @@ -2321,7 +2392,7 @@ void cmdFuncGLES2Draw(GLES2Device *device, const DrawInfo &drawInfo) { if (draw.instanceCount == 0) { GL_CHECK(glDrawArrays(glPrimitive, draw.firstIndex, draw.vertexCount)); } else { - if (device->extensionRegistry()->useDrawInstanced) { + if (device->constantRegistry()->useDrawInstanced) { GL_CHECK(glDrawArraysInstancedEXT(glPrimitive, draw.firstIndex, draw.vertexCount, draw.instanceCount)); } } @@ -2342,7 +2413,7 @@ void cmdFuncGLES2UpdateBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer, co } else { switch (gpuBuffer->glTarget) { case GL_ARRAY_BUFFER: { - if (device->extensionRegistry()->useVAO) { + if (device->constantRegistry()->useVAO) { if (device->stateCache()->glVAO) { GL_CHECK(glBindVertexArrayOES(0)); device->stateCache()->glVAO = 0; @@ -2357,7 +2428,7 @@ void cmdFuncGLES2UpdateBuffer(GLES2Device *device, GLES2GPUBuffer *gpuBuffer, co break; } case GL_ELEMENT_ARRAY_BUFFER: { - if (device->extensionRegistry()->useVAO) { + if (device->constantRegistry()->useVAO) { if (device->stateCache()->glVAO) { GL_CHECK(glBindVertexArrayOES(0)); device->stateCache()->glVAO = 0; @@ -2542,11 +2613,11 @@ void cmdFuncGLES2BlitTexture(GLES2Device *device, GLES2GPUTexture *gpuTextureSrc GLES2GPUStateCache *cache = device->stateCache(); GLuint dstFramebuffer = 0U; - if (gpuTextureDst) dstFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureDst); -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - else - dstFramebuffer = device->getDefaultFramebuffer();; -#endif + if (gpuTextureDst) { + dstFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureDst); + } else { + dstFramebuffer = device->constantRegistry()->defaultFramebuffer; + } if (cache->glFramebuffer != dstFramebuffer) { GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, dstFramebuffer)); cache->glFramebuffer = dstFramebuffer; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Context.h b/native/cocos/renderer/gfx-gles2/GLES2Context.h index ae0ec85854..a9dc666e50 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Context.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Context.h @@ -46,7 +46,6 @@ public: #if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) inline intptr_t eagl_context() const { return _eaglContext; } inline intptr_t eagl_shared_ctx() const { return _eaglSharedContext; } - inline uint getDefaultFramebuffer() const { return _defaultFBO; } #else inline NativeDisplayType nativeDisplay() const { return _nativeDisplay; } inline EGLDisplay eglDisplay() const { return _eglDisplay; } @@ -59,6 +58,7 @@ public: inline int majorVer() const { return _majorVersion; } inline int minorVer() const { return _minorVersion; } inline uint8_t multiSampleCount() const { return _sampleCount; } + inline uint getDefaultFramebuffer() const { return _defaultFBO; } bool makeCurrentImpl(bool bound); @@ -78,21 +78,21 @@ protected: bool _isInitialized = false; uint8_t _sampleBuffers = 0; uint8_t _sampleCount = 0; + uint _defaultFBO = 0; #if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) intptr_t _eaglContext = 0; intptr_t _eaglSharedContext = 0; // iOS needs to created frame buffer and attach color/depth/stencil buffer. - uint _defaultFBO = 0; uint _defaultColorBuffer = 0; uint _defaultDepthStencilBuffer = 0; #else - NativeDisplayType _nativeDisplay = 0; // NOLINT(modernize-use-nullptr) portability issues - EGLDisplay _eglDisplay = EGL_NO_DISPLAY; - EGLConfig _eglConfig = EGL_NO_CONFIG_KHR; - EGLSurface _eglSurface = EGL_NO_SURFACE; - EGLContext _eglContext = EGL_NO_CONTEXT; - EGLContext _eglSharedContext = EGL_NO_CONTEXT; - std::vector _vecEGLConfig; + NativeDisplayType _nativeDisplay = 0; // NOLINT(modernize-use-nullptr) portability issues + EGLDisplay _eglDisplay = EGL_NO_DISPLAY; + EGLConfig _eglConfig = EGL_NO_CONFIG_KHR; + EGLSurface _eglSurface = EGL_NO_SURFACE; + EGLContext _eglContext = EGL_NO_CONTEXT; + EGLContext _eglSharedContext = EGL_NO_CONTEXT; + std::vector _vecEGLConfig; #endif int _majorVersion = 0; int _minorVersion = 0; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp index 7d7b7bb5eb..a11fb6f905 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.cpp @@ -42,6 +42,10 @@ #include "GLES2Shader.h" #include "GLES2Texture.h" +// when capturing GLES commands (RENDERDOC_HOOK_EGL=1, default value) +// renderdoc doesn't support this extension during replay +#define ALLOW_MULTISAMPLED_RENDER_TO_TEXTURE_ON_DESKTOP 0 + namespace cc { namespace gfx { @@ -86,7 +90,7 @@ bool GLES2Device::doInit(const DeviceInfo &info) { _gpuStateCache = CC_NEW(GLES2GPUStateCache); _gpuBlitManager = CC_NEW(GLES2GPUBlitManager); _gpuStagingBufferPool = CC_NEW(GLES2GPUStagingBufferPool); - _gpuExtensionRegistry = CC_NEW(GLES2GPUExtensionRegistry); + _gpuConstantRegistry = CC_NEW(GLES2GPUConstantRegistry); _gpuFramebufferCacheMap = CC_NEW(GLES2GPUFramebufferCacheMap(_gpuStateCache)); bindRenderContext(true); @@ -94,6 +98,8 @@ bool GLES2Device::doInit(const DeviceInfo &info) { String extStr = reinterpret_cast(glGetString(GL_EXTENSIONS)); _extensions = StringUtil::split(extStr, " "); + _multithreadedSubmission = false; + if (checkExtension("EXT_sRGB")) { _features[static_cast(Feature::FORMAT_SRGB)] = true; } @@ -108,8 +114,6 @@ bool GLES2Device::doInit(const DeviceInfo &info) { _features[static_cast(Feature::FORMAT_R11G11B10F)] = true; - _features[static_cast(Feature::MSAA)] = _renderContext->multiSampleCount() > 0; - if (checkExtension("GL_OES_element_index_uint")) { _features[static_cast(Feature::ELEMENT_INDEX_UINT)] = true; } @@ -139,12 +143,22 @@ bool GLES2Device::doInit(const DeviceInfo &info) { _features[static_cast(Feature::BLEND_MINMAX)] = true; } - _gpuExtensionRegistry->useVAO = checkExtension("vertex_array_object"); - _gpuExtensionRegistry->useDrawInstanced = checkExtension("draw_instanced"); - _gpuExtensionRegistry->useInstancedArrays = checkExtension("instanced_arrays"); - _gpuExtensionRegistry->useDiscardFramebuffer = checkExtension("discard_framebuffer"); + _gpuConstantRegistry->useVAO = checkExtension("vertex_array_object"); + _gpuConstantRegistry->useDrawInstanced = checkExtension("draw_instanced"); + _gpuConstantRegistry->useInstancedArrays = checkExtension("instanced_arrays"); + _gpuConstantRegistry->useDiscardFramebuffer = checkExtension("discard_framebuffer"); - _features[static_cast(Feature::INSTANCED_ARRAYS)] = _gpuExtensionRegistry->useInstancedArrays; + _features[static_cast(Feature::INSTANCED_ARRAYS)] = _gpuConstantRegistry->useInstancedArrays; + +#if CC_PLATFORM != CC_PLATFORM_WINDOWS && CC_PLATFORM != CC_PLATFORM_MAC_OSX || ALLOW_MULTISAMPLED_RENDER_TO_TEXTURE_ON_DESKTOP + if (checkExtension("multisampled_render_to_texture")) { + if (checkExtension("multisampled_render_to_texture2")) { + _gpuConstantRegistry->mMSRT = MSRTSupportLevel::LEVEL2; + } else { + _gpuConstantRegistry->mMSRT = MSRTSupportLevel::LEVEL1; + } + } +#endif String fbfLevelStr = "NONE"; if (checkExtension("framebuffer_fetch")) { @@ -156,17 +170,17 @@ bool GLES2Device::doInit(const DeviceInfo &info) { if (it != _extensions.end()) { if (*it == CC_TOSTR(GL_EXT_shader_framebuffer_fetch_non_coherent)) { - _gpuExtensionRegistry->mFBF = FBFSupportLevel::NON_COHERENT_EXT; - fbfLevelStr = "NON_COHERENT_EXT"; + _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_EXT; + fbfLevelStr = "NON_COHERENT_EXT"; } else if (*it == CC_TOSTR(GL_QCOM_shader_framebuffer_fetch_noncoherent)) { - _gpuExtensionRegistry->mFBF = FBFSupportLevel::NON_COHERENT_QCOM; - fbfLevelStr = "NON_COHERENT_QCOM"; + _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_QCOM; + fbfLevelStr = "NON_COHERENT_QCOM"; GL_CHECK(glEnable(GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM)); } } else if (checkExtension(CC_TOSTR(GL_EXT_shader_framebuffer_fetch))) { // we only care about EXT_shader_framebuffer_fetch, the ARM version does not support MRT - _gpuExtensionRegistry->mFBF = FBFSupportLevel::COHERENT; - fbfLevelStr = "COHERENT"; + _gpuConstantRegistry->mFBF = FBFSupportLevel::COHERENT; + fbfLevelStr = "COHERENT"; } } @@ -191,11 +205,7 @@ bool GLES2Device::doInit(const DeviceInfo &info) { _features[static_cast(Feature::FORMAT_ASTC)] = true; compressedFmts += "astc "; } - _features[static_cast(Feature::DEPTH_BOUNDS)] = true; - _features[static_cast(Feature::LINE_WIDTH)] = true; - _features[static_cast(Feature::STENCIL_COMPARE_MASK)] = true; - _features[static_cast(Feature::STENCIL_WRITE_MASK)] = true; - _features[static_cast(Feature::FORMAT_RGB8)] = true; + _features[static_cast(Feature::FORMAT_RGB8)] = true; _renderer = reinterpret_cast(glGetString(GL_RENDERER)); _vendor = reinterpret_cast(glGetString(GL_VENDOR)); @@ -207,8 +217,9 @@ bool GLES2Device::doInit(const DeviceInfo &info) { CC_LOG_INFO("VERSION: %s", _version.c_str()); CC_LOG_INFO("SCREEN_SIZE: %d x %d", _width, _height); CC_LOG_INFO("COMPRESSED_FORMATS: %s", compressedFmts.c_str()); - CC_LOG_INFO("USE_VAO: %s", _gpuExtensionRegistry->useVAO ? "true" : "false"); + CC_LOG_INFO("USE_VAO: %s", _gpuConstantRegistry->useVAO ? "true" : "false"); CC_LOG_INFO("FRAMEBUFFER_FETCH: %s", fbfLevelStr.c_str()); + CC_LOG_DEBUG("EXTENSIONS: %s", extStr.c_str()); glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, reinterpret_cast(&_caps.maxVertexAttributes)); glGetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, reinterpret_cast(&_caps.maxVertexUniformVectors)); @@ -230,7 +241,7 @@ void GLES2Device::doDestroy() { _gpuBlitManager->destroy(); CC_SAFE_DELETE(_gpuFramebufferCacheMap) - CC_SAFE_DELETE(_gpuExtensionRegistry) + CC_SAFE_DELETE(_gpuConstantRegistry) CC_SAFE_DELETE(_gpuStagingBufferPool) CC_SAFE_DELETE(_gpuBlitManager) CC_SAFE_DELETE(_gpuStateCache) @@ -280,7 +291,7 @@ void GLES2Device::bindRenderContext(bool bound) { _context = bound ? _renderContext : nullptr; if (bound) { - _threadID = std::hash{}(std::this_thread::get_id()); + _gpuConstantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); _gpuStateCache->reset(); } } @@ -298,15 +309,11 @@ void GLES2Device::bindDeviceContext(bool bound) { _context = bound ? _deviceContext : nullptr; if (bound) { - _threadID = std::hash{}(std::this_thread::get_id()); + _gpuConstantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); _gpuStateCache->reset(); } } -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) -uint GLES2Device::getDefaultFramebuffer() const { return static_cast(_context)->getDefaultFramebuffer(); } -#endif - CommandBuffer *GLES2Device::createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) { if (hasAgent || info.type == CommandBufferType::PRIMARY) return CC_NEW(GLES2PrimaryCommandBuffer); return CC_NEW(GLES2CommandBuffer); diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.h b/native/cocos/renderer/gfx-gles2/GLES2Device.h index bc4030025b..348ebcfdfd 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.h @@ -44,7 +44,7 @@ class GLES2Context; class GLES2GPUStateCache; class GLES2GPUBlitManager; class GLES2GPUStagingBufferPool; -class GLES2GPUExtensionRegistry; +class GLES2GPUConstantRegistry; class GLES2GPUFramebufferCacheMap; class CC_GLES2_API GLES2Device final : public Device { @@ -77,7 +77,7 @@ public: inline GLES2GPUStateCache * stateCache() const { return _gpuStateCache; } inline GLES2GPUBlitManager * blitManager() const { return _gpuBlitManager; } inline GLES2GPUStagingBufferPool * stagingBufferPool() const { return _gpuStagingBufferPool; } - inline GLES2GPUExtensionRegistry * extensionRegistry() const { return _gpuExtensionRegistry; } + inline GLES2GPUConstantRegistry * constantRegistry() const { return _gpuConstantRegistry; } inline GLES2GPUFramebufferCacheMap *framebufferCacheMap() const { return _gpuFramebufferCacheMap; } inline bool checkExtension(const String &extension) const { @@ -86,12 +86,6 @@ public: }); } - inline size_t getThreadID() const { return _threadID; } - -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - uint getDefaultFramebuffer() const; -#endif - protected: static GLES2Device *instance; @@ -132,12 +126,10 @@ protected: GLES2GPUStateCache * _gpuStateCache = nullptr; GLES2GPUBlitManager * _gpuBlitManager = nullptr; GLES2GPUStagingBufferPool * _gpuStagingBufferPool = nullptr; - GLES2GPUExtensionRegistry * _gpuExtensionRegistry = nullptr; + GLES2GPUConstantRegistry * _gpuConstantRegistry = nullptr; GLES2GPUFramebufferCacheMap *_gpuFramebufferCacheMap = nullptr; StringArray _extensions; - - size_t _threadID = 0U; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.cpp b/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.cpp index 0443f9f17d..80df26cf2d 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Framebuffer.cpp @@ -42,20 +42,7 @@ GLES2Framebuffer::~GLES2Framebuffer() { destroy(); } -void GLES2Framebuffer::doInit(const FramebufferInfo &info) { - if (info.depthStencilMipmapLevel != 0) { - CC_LOG_WARNING("Mipmap level of depth stencil attachment should be 0 in GLES2. Convert to 0."); - } - if (!info.colorMipmapLevels.empty()) { - int i = 0; - for (const auto mipmapLevel : info.colorMipmapLevels) { - if (mipmapLevel != 0) { - CC_LOG_WARNING("Mipmap level of color attachment %d should be 0 in GLES2. Convert to 0.", i); - } - ++i; - } - } - +void GLES2Framebuffer::doInit(const FramebufferInfo & /*info*/) { _gpuFBO = CC_NEW(GLES2GPUFramebuffer); _gpuFBO->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h index 545324f862..b8080a3f34 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h @@ -36,9 +36,13 @@ namespace cc { namespace gfx { -class GLES2GPUExtensionRegistry { +class GLES2GPUConstantRegistry { public: - FBFSupportLevel mFBF = FBFSupportLevel::NONE; + uint currentBoundThreadID{0U}; + uint defaultFramebuffer{0U}; + + MSRTSupportLevel mMSRT{MSRTSupportLevel::NONE}; + FBFSupportLevel mFBF{FBFSupportLevel::NONE}; bool useVAO = false; bool useDrawInstanced = false; @@ -69,28 +73,31 @@ public: class GLES2GPUTexture final : public Object { public: - TextureType type = TextureType::TEX2D; - Format format = Format::UNKNOWN; - TextureUsage usage = TextureUsageBit::NONE; - uint width = 0; - uint height = 0; - uint depth = 1; - uint size = 0; - uint arrayLayer = 1; - uint mipLevel = 1; - SampleCount samples = SampleCount::X1; - TextureFlags flags = TextureFlagBit::NONE; - bool isPowerOf2 = false; - GLenum glTarget = 0; - GLenum glInternelFmt = 0; - GLenum glFormat = 0; - GLenum glType = 0; - GLenum glUsage = 0; - GLuint glTexture = 0; - GLenum glWrapS = 0; - GLenum glWrapT = 0; - GLenum glMinFilter = 0; - GLenum glMagFilter = 0; + TextureType type = TextureType::TEX2D; + Format format = Format::UNKNOWN; + TextureUsage usage = TextureUsageBit::NONE; + uint width = 0; + uint height = 0; + uint depth = 1; + uint size = 0; + uint arrayLayer = 1; + uint mipLevel = 1; + SampleCount samples = SampleCount::X1; + TextureFlags flags = TextureFlagBit::NONE; + bool isPowerOf2 = false; + bool memoryless = false; + GLenum glTarget = 0; + GLenum glInternalFmt = 0; + GLenum glFormat = 0; + GLenum glType = 0; + GLenum glUsage = 0; + GLint glSamples = 0; + GLuint glTexture = 0; + GLuint glRenderbuffer = 0; + GLenum glWrapS = 0; + GLenum glWrapT = 0; + GLenum glMinFilter = 0; + GLenum glMagFilter = 0; }; using GLES2GPUTextureList = vector; @@ -253,7 +260,10 @@ public: struct GLFramebuffer { GLuint glFramebuffer = 0U; - bool isOffscreen = false; + + // for blit-based manual resolving + GLbitfield resolveMask = 0U; + GLuint glResolveFramebuffer = 0U; }; // one per subpass, if not using FBF vector instances; @@ -323,7 +333,6 @@ struct GLES2ObjectCache final { GLES2GPUPipelineState * gpuPipelineState = nullptr; GLES2GPUInputAssembler *gpuInputAssembler = nullptr; GLenum glPrimitive = 0; - GLenum invalidAttachments[MAX_ATTACHMENTS]; Rect renderArea; ColorList clearColors; float clearDepth = 1.F; @@ -341,8 +350,9 @@ public: GLuint glProgram = 0; vector glEnabledAttribLocs; vector glCurrentAttribLocs; - GLuint glFramebuffer = 0; - GLuint glReadFBO = 0; + GLuint glFramebuffer = 0; + GLuint glRenderbuffer = 0; + GLuint glReadFBO = 0; Viewport viewport; Rect scissor; RasterizerState rs; @@ -416,7 +426,11 @@ public: explicit GLES2GPUFramebufferCacheMap(GLES2GPUStateCache *cache) : _cache(cache) {} GLuint getFramebufferFromTexture(const GLES2GPUTexture *gpuTexture) { - if (!_map.count(gpuTexture->glTexture)) { + bool isTexture = gpuTexture->glTexture; + GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; + auto & cacheMap = isTexture ? _textureMap : _renderbufferMap; + + if (!cacheMap.count(glResource)) { GLuint glFramebuffer = 0U; GL_CHECK(glGenFramebuffers(1, &glFramebuffer)); if (_cache->glFramebuffer != glFramebuffer) { @@ -425,41 +439,56 @@ public: } const FormatInfo &info = GFX_FORMAT_INFOS[static_cast(gpuTexture->format)]; - if (info.hasDepth) { - GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, gpuTexture->glTarget, gpuTexture->glTexture, 0)); - if (info.hasStencil) { - GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, gpuTexture->glTarget, gpuTexture->glTexture, 0)); + if (isTexture) { + if (info.hasDepth) { + GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, gpuTexture->glTarget, glResource, 0)); + if (info.hasStencil) GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, gpuTexture->glTarget, glResource, 0)); + } else { + GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, gpuTexture->glTarget, glResource, 0)); } } else { - GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, gpuTexture->glTarget, gpuTexture->glTexture, 0)); + if (info.hasDepth) { + GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, gpuTexture->glTarget, glResource)); + if (info.hasStencil) GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, gpuTexture->glTarget, glResource)); + } else { + GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, gpuTexture->glTarget, glResource)); + } } GLenum status; GL_CHECK(status = glCheckFramebufferStatus(GL_FRAMEBUFFER)); CCASSERT(status == GL_FRAMEBUFFER_COMPLETE, "frambuffer incomplete"); - _map[gpuTexture->glTexture] = glFramebuffer; + cacheMap[glResource] = glFramebuffer; } - return _map[gpuTexture->glTexture]; + return cacheMap[glResource]; } void onTextureDestroy(const GLES2GPUTexture *gpuTexture) { - if (_map.count(gpuTexture->glTexture)) { - GLuint glFramebuffer = _map[gpuTexture->glTexture]; + bool isTexture = gpuTexture->glTexture; + GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; + auto & cacheMap = isTexture ? _textureMap : _renderbufferMap; + + if (cacheMap.count(glResource)) { + GLuint glFramebuffer = cacheMap[glResource]; + if (!glFramebuffer) return; if (_cache->glFramebuffer == glFramebuffer) { GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); _cache->glFramebuffer = 0; } GL_CHECK(glDeleteFramebuffers(1, &glFramebuffer)); + cacheMap.erase(glResource); } - _map.erase(gpuTexture->glTexture); } private: - GLES2GPUStateCache * _cache = nullptr; - unordered_map _map; // texture -> framebuffer + GLES2GPUStateCache *_cache = nullptr; + + using CacheMap = unordered_map; + CacheMap _renderbufferMap; // renderbuffer -> framebuffer + CacheMap _textureMap; // texture -> framebuffer }; constexpr size_t CHUNK_SIZE = 16 * 1024 * 1024; // 16M per block by default diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index cf19ec4239..c5de838309 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -23,13 +23,11 @@ THE SOFTWARE. ****************************************************************************/ -#include #include "GLES3Std.h" #include "GLES3Commands.h" -#include "GLES3Context.h" #include "GLES3Device.h" -#include "gfx-base/GFXDef.h" +#include "gfx-gles-common/GLESCommandPool.h" #define BUFFER_OFFSET(idx) (static_cast(0) + (idx)) @@ -93,7 +91,7 @@ GLenum mapGLInternalFormat(Format format) { case Format::RGB10A2UI: return GL_RGB10_A2UI; case Format::R11G11B10F: return GL_R11F_G11F_B10F; case Format::D16: return GL_DEPTH_COMPONENT16; - case Format::D16S8: return GL_DEPTH_STENCIL; + case Format::D16S8: return GL_DEPTH24_STENCIL8; case Format::D24: return GL_DEPTH_COMPONENT24; case Format::D24S8: return GL_DEPTH24_STENCIL8; case Format::D32F: return GL_DEPTH_COMPONENT32F; @@ -840,178 +838,247 @@ void cmdFuncGLES3ResizeBuffer(GLES3Device *device, GLES3GPUBuffer *gpuBuffer) { void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) { static const TextureUsage MEMORYLESS = TextureUsageBit::INPUT_ATTACHMENT | TextureUsageBit::COLOR_ATTACHMENT; - // always prefer FBF - if (device->extensionRegistry()->mFBF == FBFSupportLevel::NONE && - device->extensionRegistry()->mPLS != PLSSupportLevel::NONE && + static vector supportedSampleCounts; + + gpuTexture->glInternalFmt = mapGLInternalFormat(gpuTexture->format); + gpuTexture->glFormat = mapGLFormat(gpuTexture->format); + gpuTexture->glType = formatToGLType(gpuTexture->format); + + if (gpuTexture->samples > SampleCount::X1) { + GLint supportedSampleCountCount = 0; + GL_CHECK(glGetInternalformativ(GL_RENDERBUFFER, gpuTexture->glInternalFmt, GL_SAMPLES, 1, &supportedSampleCountCount)); + supportedSampleCounts.resize(supportedSampleCountCount); + GL_CHECK(glGetInternalformativ(GL_RENDERBUFFER, gpuTexture->glInternalFmt, GL_SAMPLES, supportedSampleCountCount, supportedSampleCounts.data())); + + auto requestedSampleCount = static_cast(gpuTexture->samples); + for (GLint sampleCount : supportedSampleCounts) { + if (sampleCount <= requestedSampleCount) { + gpuTexture->glSamples = sampleCount; + break; + } + } + + // skip multi-sampled attachment resources if we can use auto resolve + if (device->constantRegistry()->mMSRT != MSRTSupportLevel::NONE && + gpuTexture->usage == TextureUsageBit::COLOR_ATTACHMENT) { + gpuTexture->memoryless = true; + return; + } + } + + // memoryless resources for PLS-based input attachments + // enabled only if FBF is not available + if (device->constantRegistry()->mFBF == FBFSupportLevel::NONE && + device->constantRegistry()->mPLS != PLSSupportLevel::NONE && + hasFlag(gpuTexture->usage, TextureUsageBit::INPUT_ATTACHMENT) && hasAllFlags(MEMORYLESS, gpuTexture->usage)) { gpuTexture->memoryless = true; return; } - gpuTexture->glInternelFmt = mapGLInternalFormat(gpuTexture->format); - gpuTexture->glFormat = mapGLFormat(gpuTexture->format); - gpuTexture->glType = formatToGLType(gpuTexture->format); - - switch (gpuTexture->type) { - case TextureType::TEX2D: { - gpuTexture->glTarget = GL_TEXTURE_2D; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_2D, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint w = gpuTexture->width; - uint h = gpuTexture->height; - if (hasFlag(gpuTexture->flags, TextureFlagBit::IMMUTABLE)) { - GL_CHECK(glTexStorage2D(GL_TEXTURE_2D, gpuTexture->mipLevel, gpuTexture->glInternelFmt, w, h)); - } else { - if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { - for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - GL_CHECK(glTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternelFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); - w = std::max(1U, w >> 1); - h = std::max(1U, h >> 1); - } + if (gpuTexture->glSamples <= 1) { + switch (gpuTexture->type) { + case TextureType::TEX2D: { + gpuTexture->glTarget = GL_TEXTURE_2D; + GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); + if (gpuTexture->size > 0) { + GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; + if (gpuTexture->glTexture != glTexture) { + GL_CHECK(glBindTexture(GL_TEXTURE_2D, gpuTexture->glTexture)); + glTexture = gpuTexture->glTexture; + } + uint w = gpuTexture->width; + uint h = gpuTexture->height; + if (hasFlag(gpuTexture->flags, TextureFlagBit::IMMUTABLE)) { + GL_CHECK(glTexStorage2D(GL_TEXTURE_2D, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); } else { - for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - uint imgSize = formatSize(gpuTexture->format, w, h, 1); - GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternelFmt, w, h, 0, imgSize, nullptr)); - w = std::max(1U, w >> 1); - h = std::max(1U, h >> 1); + if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { + for (uint i = 0; i < gpuTexture->mipLevel; ++i) { + GL_CHECK(glTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternalFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); + w = std::max(1U, w >> 1); + h = std::max(1U, h >> 1); + } + } else { + for (uint i = 0; i < gpuTexture->mipLevel; ++i) { + uint imgSize = formatSize(gpuTexture->format, w, h, 1); + GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternalFmt, w, h, 0, imgSize, nullptr)); + w = std::max(1U, w >> 1); + h = std::max(1U, h >> 1); + } } } } + break; } - break; - } - case TextureType::CUBE: { - gpuTexture->glTarget = GL_TEXTURE_CUBE_MAP; - GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint w = gpuTexture->width; - uint h = gpuTexture->height; - if (hasFlag(gpuTexture->flags, TextureFlagBit::IMMUTABLE)) { - GL_CHECK(glTexStorage2D(GL_TEXTURE_CUBE_MAP, gpuTexture->mipLevel, gpuTexture->glInternelFmt, w, h)); - } else { - if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { - for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - for (uint f = 0; f < 6; ++f) { - GL_CHECK(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternelFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); - } - w = std::max(1U, w >> 1); - h = std::max(1U, h >> 1); - } + case TextureType::CUBE: { + gpuTexture->glTarget = GL_TEXTURE_CUBE_MAP; + GL_CHECK(glGenTextures(1, &gpuTexture->glTexture)); + if (gpuTexture->size > 0) { + GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; + if (gpuTexture->glTexture != glTexture) { + GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); + glTexture = gpuTexture->glTexture; + } + uint w = gpuTexture->width; + uint h = gpuTexture->height; + if (hasFlag(gpuTexture->flags, TextureFlagBit::IMMUTABLE)) { + GL_CHECK(glTexStorage2D(GL_TEXTURE_CUBE_MAP, gpuTexture->mipLevel, gpuTexture->glInternalFmt, w, h)); } else { - for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - uint imgSize = formatSize(gpuTexture->format, w, h, 1); - for (uint f = 0; f < 6; ++f) { - GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternelFmt, w, h, 0, imgSize, nullptr)); + if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { + for (uint i = 0; i < gpuTexture->mipLevel; ++i) { + for (uint f = 0; f < 6; ++f) { + GL_CHECK(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternalFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); + } + w = std::max(1U, w >> 1); + h = std::max(1U, h >> 1); + } + } else { + for (uint i = 0; i < gpuTexture->mipLevel; ++i) { + uint imgSize = formatSize(gpuTexture->format, w, h, 1); + for (uint f = 0; f < 6; ++f) { + GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternalFmt, w, h, 0, imgSize, nullptr)); + } + w = std::max(1U, w >> 1); + h = std::max(1U, h >> 1); } - w = std::max(1U, w >> 1); - h = std::max(1U, h >> 1); } } } + break; } - break; + default: + CCASSERT(false, "Unsupported TextureType, create texture failed."); + break; + } + } else { + switch (gpuTexture->type) { + case TextureType::TEX2D: { + gpuTexture->glTarget = GL_RENDERBUFFER; + GL_CHECK(glGenRenderbuffers(1, &gpuTexture->glRenderbuffer)); + if (gpuTexture->size > 0) { + GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; + if (gpuTexture->glRenderbuffer != glRenderbuffer) { + GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, gpuTexture->glRenderbuffer)); + glRenderbuffer = gpuTexture->glRenderbuffer; + } + GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, gpuTexture->glSamples, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); + } + break; + } + default: + CCASSERT(false, "Unsupported TextureType, create texture failed."); + break; } - default: - CCASSERT(false, "Unsupported TextureType, create texture failed."); - break; } } void cmdFuncGLES3DestroyTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) { + device->framebufferCacheMap()->onTextureDestroy(gpuTexture); + if (gpuTexture->glTexture) { for (GLuint &glTexture : device->stateCache()->glTextures) { if (glTexture == gpuTexture->glTexture) { glTexture = 0; } } - device->framebufferCacheMap()->onTextureDestroy(gpuTexture); - GL_CHECK(glDeleteTextures(1, &gpuTexture->glTexture)); gpuTexture->glTexture = 0; + + } else if (gpuTexture->glRenderbuffer) { + GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; + if (gpuTexture->glRenderbuffer == glRenderbuffer) { + GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0)); + glRenderbuffer = 0; + } + GL_CHECK(glDeleteRenderbuffers(1, &gpuTexture->glRenderbuffer)); + gpuTexture->glRenderbuffer = 0; } } void cmdFuncGLES3ResizeTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) { if (gpuTexture->memoryless) return; - gpuTexture->glInternelFmt = mapGLInternalFormat(gpuTexture->format); - gpuTexture->glFormat = mapGLFormat(gpuTexture->format); - gpuTexture->glType = formatToGLType(gpuTexture->format); - - switch (gpuTexture->type) { - case TextureType::TEX2D: { - gpuTexture->glTarget = GL_TEXTURE_2D; - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_2D, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - uint w = gpuTexture->width; - uint h = gpuTexture->height; - if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { - for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - GL_CHECK(glTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternelFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); - w = std::max(1U, w >> 1); - h = std::max(1U, h >> 1); + if (gpuTexture->glSamples <= 1) { + switch (gpuTexture->type) { + case TextureType::TEX2D: { + if (gpuTexture->size > 0) { + GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; + if (gpuTexture->glTexture != glTexture) { + GL_CHECK(glBindTexture(GL_TEXTURE_2D, gpuTexture->glTexture)); + glTexture = gpuTexture->glTexture; } - } else { - for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - uint imgSize = formatSize(gpuTexture->format, w, h, 1); - GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternelFmt, w, h, 0, imgSize, nullptr)); - w = std::max(1U, w >> 1); - h = std::max(1U, h >> 1); - } - } - } - break; - } - case TextureType::CUBE: { - gpuTexture->glTarget = GL_TEXTURE_CUBE_MAP; - if (gpuTexture->size > 0) { - GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; - if (gpuTexture->glTexture != glTexture) { - GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); - glTexture = gpuTexture->glTexture; - } - if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { - for (uint f = 0; f < 6; ++f) { - uint w = gpuTexture->width; - uint h = gpuTexture->height; + uint w = gpuTexture->width; + uint h = gpuTexture->height; + if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { for (uint i = 0; i < gpuTexture->mipLevel; ++i) { - GL_CHECK(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternelFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); + GL_CHECK(glTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternalFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); w = std::max(1U, w >> 1); h = std::max(1U, h >> 1); } - } - } else { - for (uint f = 0; f < 6; ++f) { - uint w = gpuTexture->width; - uint h = gpuTexture->height; + } else { for (uint i = 0; i < gpuTexture->mipLevel; ++i) { uint imgSize = formatSize(gpuTexture->format, w, h, 1); - GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternelFmt, w, h, 0, imgSize, nullptr)); + GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_2D, i, gpuTexture->glInternalFmt, w, h, 0, imgSize, nullptr)); w = std::max(1U, w >> 1); h = std::max(1U, h >> 1); } } } + break; } - break; + case TextureType::CUBE: { + if (gpuTexture->size > 0) { + GLuint &glTexture = device->stateCache()->glTextures[device->stateCache()->texUint]; + if (gpuTexture->glTexture != glTexture) { + GL_CHECK(glBindTexture(GL_TEXTURE_CUBE_MAP, gpuTexture->glTexture)); + glTexture = gpuTexture->glTexture; + } + if (!GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].isCompressed) { + for (uint f = 0; f < 6; ++f) { + uint w = gpuTexture->width; + uint h = gpuTexture->height; + for (uint i = 0; i < gpuTexture->mipLevel; ++i) { + GL_CHECK(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternalFmt, w, h, 0, gpuTexture->glFormat, gpuTexture->glType, nullptr)); + w = std::max(1U, w >> 1); + h = std::max(1U, h >> 1); + } + } + } else { + for (uint f = 0; f < 6; ++f) { + uint w = gpuTexture->width; + uint h = gpuTexture->height; + for (uint i = 0; i < gpuTexture->mipLevel; ++i) { + uint imgSize = formatSize(gpuTexture->format, w, h, 1); + GL_CHECK(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, gpuTexture->glInternalFmt, w, h, 0, imgSize, nullptr)); + w = std::max(1U, w >> 1); + h = std::max(1U, h >> 1); + } + } + } + } + break; + } + default: + CCASSERT(false, "Unsupported TextureType, resize texture failed."); + break; + } + } else { + switch (gpuTexture->type) { + case TextureType::TEX2D: { + if (gpuTexture->size > 0) { + GLuint &glRenderbuffer = device->stateCache()->glRenderbuffer; + if (gpuTexture->glRenderbuffer != glRenderbuffer) { + GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, gpuTexture->glRenderbuffer)); + glRenderbuffer = gpuTexture->glRenderbuffer; + } + GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, gpuTexture->glSamples, gpuTexture->glInternalFmt, gpuTexture->width, gpuTexture->height)); + } + break; + } + default: + CCASSERT(false, "Unsupported TextureType, resize texture failed."); + break; } - default: - CCASSERT(false, "Unsupported TextureType, resize texture failed."); - break; } } @@ -1194,7 +1261,7 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { GL_CHECK(glGetProgramiv(gpuShader->glProgram, GL_ACTIVE_UNIFORM_BLOCKS, &blockCount)); GLint bufferCount = 0; - if (device->getMinorVersion() > 0) { + if (device->constantRegistry()->glMinorVersion > 0) { GL_CHECK(glGetProgramInterfaceiv(gpuShader->glProgram, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &bufferCount)); } @@ -1254,8 +1321,8 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { } // fallback subpassInputs into samplerTextures if not using FBF or PLS - if (device->extensionRegistry()->mFBF == FBFSupportLevel::NONE && - device->extensionRegistry()->mPLS == PLSSupportLevel::NONE) { + if (device->constantRegistry()->mFBF == FBFSupportLevel::NONE && + device->constantRegistry()->mPLS == PLSSupportLevel::NONE) { for (const auto &subpassInput : gpuShader->subpassInputs) { auto &samplerTexture = gpuShader->samplerTextures.emplace_back(); samplerTexture.name = subpassInput.name; @@ -1456,129 +1523,188 @@ void cmdFuncGLES3DestroyInputAssembler(GLES3Device *device, GLES3GPUInputAssembl gpuInputAssembler->glVAOs.clear(); } -void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO) { - size_t colorAttachmentCount = gpuFBO->gpuColorTextures.size(); - static vector attachments; +static GLuint doCreateFramebuffer(GLES3Device * device, + const vector &attachments, const uint *colors, uint colorCount, + const GLES3GPUTexture *depthStencil, + const uint * resolves = nullptr, + const GLES3GPUTexture *depthStencilResolve = nullptr, + GLbitfield * resolveMask = nullptr) { + static vector drawBuffers; + GLuint glFramebuffer{0U}; + GLES3GPUStateCache * cache = device->stateCache(); - auto createFBO = [&](const vector &colorIndices, uint depthStencilIndex, GLES3GPUFramebuffer::GLFramebuffer *outFBO) { - uint offscreenCount{0U}; - for (uint idx : colorIndices) { - const auto *colorTex = gpuFBO->gpuColorTextures[idx]; - if (colorTex) ++offscreenCount; + GL_CHECK(glGenFramebuffers(1, &glFramebuffer)); + if (cache->glDrawFramebuffer != glFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, glFramebuffer)); + cache->glDrawFramebuffer = glFramebuffer; + } + + drawBuffers.clear(); + + auto supportLevel = device->constantRegistry()->mMSRT; + bool autoResolve = supportLevel > MSRTSupportLevel::LEVEL1 || (supportLevel != MSRTSupportLevel::NONE && colorCount <= 1); + + for (size_t j = 0; j < colorCount; ++j) { + GLES3GPUTexture *gpuColorTexture = attachments[colors[j]]; + GLES3GPUTexture *gpuResolveTexture = resolves ? attachments[resolves[j]] : nullptr; + drawBuffers.push_back(static_cast(GL_COLOR_ATTACHMENT0 + j)); + + if (gpuResolveTexture) { + if (autoResolve) { + GL_CHECK(glFramebufferTexture2DMultisampleEXT(GL_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), + gpuResolveTexture->glTarget, gpuResolveTexture->glTexture, 0, + gpuColorTexture->glSamples)); + continue; + } + *resolveMask |= GL_COLOR_BUFFER_BIT; // fallback to blit-based manual resolve } - CCASSERT(!offscreenCount || offscreenCount == colorIndices.size(), - "Partially offscreen FBO is not supported"); - - outFBO->isOffscreen = offscreenCount; - - if (outFBO->isOffscreen) { - GL_CHECK(glGenFramebuffers(1, &outFBO->glFramebuffer)); - if (device->stateCache()->glDrawFramebuffer != outFBO->glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, outFBO->glFramebuffer)); - device->stateCache()->glDrawFramebuffer = outFBO->glFramebuffer; - } - - attachments.clear(); - - size_t colorMipmapLevelCount = gpuFBO->colorMipmapLevels.size(); - for (size_t j = 0; j < colorIndices.size(); ++j) { - GLES3GPUTexture *gpuColorTexture = gpuFBO->gpuColorTextures[colorIndices[j]]; - if (gpuColorTexture) { - GLint mipmapLevel = 0; - if (j < colorMipmapLevelCount) { - mipmapLevel = gpuFBO->colorMipmapLevels[j]; - } - GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), gpuColorTexture->glTarget, gpuColorTexture->glTexture, mipmapLevel)); - - attachments.push_back(static_cast(GL_COLOR_ATTACHMENT0 + j)); - } - } - const auto *depthStencilTexture = depthStencilIndex < colorAttachmentCount - ? gpuFBO->gpuColorTextures[depthStencilIndex] - : gpuFBO->gpuDepthStencilTexture; - if (depthStencilTexture) { - const GLenum glAttachment = GFX_FORMAT_INFOS[static_cast(depthStencilTexture->format)].hasStencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT; - GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, glAttachment, depthStencilTexture->glTarget, depthStencilTexture->glTexture, gpuFBO->depthStencilMipmapLevel)); - } - - GL_CHECK(glDrawBuffers(attachments.size(), attachments.data())); - - GLenum status; - GL_CHECK(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); - if (status != GL_FRAMEBUFFER_COMPLETE) { - switch (status) { - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); - break; - case GL_FRAMEBUFFER_UNSUPPORTED: - CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED"); - break; - } - } + if (gpuColorTexture->glTexture) { + GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), + gpuColorTexture->glTarget, gpuColorTexture->glTexture, 0)); } else { -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - outFBO->glFramebuffer = device->getDefaultFramebuffer(); -#endif + GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0 + j), + gpuColorTexture->glTarget, gpuColorTexture->glRenderbuffer)); + } + } + if (depthStencil) { + bool hasStencil = GFX_FORMAT_INFOS[static_cast(depthStencil->format)].hasStencil; + GLenum glAttachment = hasStencil ? GL_DEPTH_STENCIL_ATTACHMENT : GL_DEPTH_ATTACHMENT; + if (depthStencil->glTexture) { + GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, glAttachment, depthStencil->glTarget, depthStencil->glTexture, 0)); + } else { + GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, glAttachment, depthStencil->glTarget, depthStencil->glRenderbuffer)); } - }; - if (gpuFBO->gpuRenderPass->subpasses.size() > 1) { - gpuFBO->usesFBF = device->extensionRegistry()->mFBF != FBFSupportLevel::NONE; - gpuFBO->usesPLS = std::any_of(gpuFBO->gpuColorTextures.begin(), gpuFBO->gpuColorTextures.end(), [](const auto *gpuTexture) { - return gpuTexture && gpuTexture->memoryless; - }); + // fallback to blit-based manual resolve + if (depthStencilResolve) *resolveMask |= hasStencil ? GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT : GL_DEPTH_BUFFER_BIT; + } - if (gpuFBO->usesFBF || gpuFBO->usesPLS) { - gpuFBO->uberColorAttachmentIndices.clear(); - for (uint i = 0U; i < gpuFBO->gpuColorTextures.size(); ++i) { - const auto *gpuTexture = gpuFBO->gpuColorTextures[i]; - if (!gpuTexture || gpuTexture->memoryless) continue; - if (GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].hasDepth) continue; - gpuFBO->uberColorAttachmentIndices.push_back(i); - } - createFBO(gpuFBO->uberColorAttachmentIndices, gpuFBO->gpuColorTextures.size(), &gpuFBO->uberInstance); - return; + GL_CHECK(glDrawBuffers(drawBuffers.size(), drawBuffers.data())); + + GLenum status; + GL_CHECK(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); + if (status != GL_FRAMEBUFFER_COMPLETE) { + switch (status) { + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); + break; + case GL_FRAMEBUFFER_UNSUPPORTED: + CC_LOG_ERROR("checkFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED"); + break; + default: + CC_LOG_ERROR("checkFramebufferStatus() - %x", status); + break; } } - for (const auto &subpass : gpuFBO->gpuRenderPass->subpasses) { - createFBO(subpass.colors, subpass.depthStencil, &gpuFBO->instances.emplace_back()); + return glFramebuffer; +} + +static void doCreateFramebufferInstance(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO, const vector &colors, + uint depthStencil, GLES3GPUFramebuffer::GLFramebuffer *outFBO, + const uint *resolves = nullptr, uint depthStencilResolve = INVALID_BINDING) { + uint offscreenCount{0U}; + for (uint idx : colors) { + const auto *colorTex = gpuFBO->gpuColorTextures[idx]; + if (colorTex) ++offscreenCount; + } + CCASSERT(!offscreenCount || offscreenCount == colors.size(), "Partially offscreen FBO is not supported"); + + const GLES3GPUTexture *depthStencilTexture = nullptr; + if (depthStencil != INVALID_BINDING) { + depthStencilTexture = depthStencil < gpuFBO->gpuColorTextures.size() + ? gpuFBO->gpuColorTextures[depthStencil] + : gpuFBO->gpuDepthStencilTexture; + } + const GLES3GPUTexture *depthStencilResolveTexture = nullptr; + if (depthStencilResolve != INVALID_BINDING) { + depthStencilResolveTexture = depthStencilResolve < gpuFBO->gpuColorTextures.size() + ? gpuFBO->gpuColorTextures[depthStencilResolve] + : gpuFBO->gpuDepthStencilTexture; + } + + if (offscreenCount || depthStencilTexture) { + outFBO->glFramebuffer = doCreateFramebuffer(device, gpuFBO->gpuColorTextures, colors.data(), colors.size(), + depthStencilTexture, resolves, depthStencilResolveTexture, &outFBO->resolveMask); + if (outFBO->resolveMask) { + uint resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? colors.size() : 0U; + outFBO->glResolveFramebuffer = doCreateFramebuffer(device, gpuFBO->gpuColorTextures, resolves, resolveCount, depthStencilResolveTexture); + } + } else { + outFBO->glFramebuffer = device->constantRegistry()->defaultFramebuffer; } } +void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO) { + if (gpuFBO->gpuRenderPass->subpasses.size() > 1) { + gpuFBO->usesFBF = device->constantRegistry()->mFBF != FBFSupportLevel::NONE; + gpuFBO->usesPLS = std::any_of(gpuFBO->gpuColorTextures.begin(), gpuFBO->gpuColorTextures.end(), [](const auto *gpuTexture) { + return gpuTexture && gpuTexture->memoryless; + }); + } + + if (gpuFBO->usesFBF || gpuFBO->usesPLS) { + gpuFBO->uberColorAttachmentIndices.clear(); + for (uint i = 0U; i < gpuFBO->gpuColorTextures.size(); ++i) { + const auto *gpuTexture = gpuFBO->gpuColorTextures[i]; + if (!gpuTexture || gpuTexture->memoryless) continue; + if (GFX_FORMAT_INFOS[static_cast(gpuTexture->format)].hasDepth) continue; + gpuFBO->uberColorAttachmentIndices.push_back(i); + } + doCreateFramebufferInstance(device, gpuFBO, gpuFBO->uberColorAttachmentIndices, gpuFBO->gpuColorTextures.size(), &gpuFBO->uberInstance); + } else { + for (const auto &subpass : gpuFBO->gpuRenderPass->subpasses) { + doCreateFramebufferInstance(device, gpuFBO, subpass.colors, subpass.depthStencil, &gpuFBO->instances.emplace_back(), + subpass.resolves.empty() ? nullptr : subpass.resolves.data(), subpass.depthStencilResolve); + } + } +} + +static void doDestroyFramebuffer(GLES3GPUStateCache *cache, GLuint *pFBO) { + if (cache->glDrawFramebuffer == *pFBO) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); + cache->glDrawFramebuffer = 0; + } + GL_CHECK(glDeleteFramebuffers(1, pFBO)); + *pFBO = 0U; +} + void cmdFuncGLES3DestroyFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpuFBO) { + auto *cache = device->stateCache(); + uint defaultFBO = device->constantRegistry()->defaultFramebuffer; + for (auto &instance : gpuFBO->instances) { - if (instance.isOffscreen && instance.glFramebuffer) { - if (device->stateCache()->glDrawFramebuffer == instance.glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); - device->stateCache()->glDrawFramebuffer = 0; - } - GL_CHECK(glDeleteFramebuffers(1, &instance.glFramebuffer)); - instance.glFramebuffer = 0U; + if (instance.glFramebuffer != defaultFBO) { + doDestroyFramebuffer(cache, &instance.glFramebuffer); + } + if (instance.glResolveFramebuffer != defaultFBO) { + doDestroyFramebuffer(cache, &instance.glResolveFramebuffer); } } gpuFBO->instances.clear(); - if (gpuFBO->uberInstance.isOffscreen && gpuFBO->uberInstance.glFramebuffer) { - if (device->stateCache()->glDrawFramebuffer == gpuFBO->uberInstance.glFramebuffer) { - GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); - device->stateCache()->glDrawFramebuffer = 0; - } - GL_CHECK(glDeleteFramebuffers(1, &gpuFBO->uberInstance.glFramebuffer)); - gpuFBO->uberInstance.glFramebuffer = 0U; + if (gpuFBO->uberInstance.glFramebuffer != defaultFBO) { + doDestroyFramebuffer(cache, &gpuFBO->uberInstance.glFramebuffer); + } + if (gpuFBO->uberInstance.glResolveFramebuffer != defaultFBO) { + doDestroyFramebuffer(cache, &gpuFBO->uberInstance.glResolveFramebuffer); } } void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPURenderPass *gpuRenderPass, GLES3GPUFramebuffer *gpuFramebuffer, const Rect *renderArea, const Color *clearColors, float clearDepth, uint clearStencil) { - static uint attachmentLoadOpRecord = 0U; + static uint attachmentLoadOpRecord = 0U; + static vector invalidAttachments; GLES3GPUStateCache *cache = device->stateCache(); GLES3ObjectCache & gfxStateCache = cache->gfxStateCache; @@ -1600,8 +1726,6 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR attachmentLoadOpRecord = 0U; } - GLenum *invalidAttachments = gfxStateCache.invalidAttachments; - if (gpuFramebuffer && gpuRenderPass) { const auto &instance = gpuFramebuffer->usesPLS || gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[subpassIdx]; if (cache->glDrawFramebuffer != instance.glFramebuffer) { @@ -1631,12 +1755,9 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR cache->scissor.height = renderArea->height; } - GLbitfield glClears = 0; - uint numAttachments = 0; - bool hasBoundFBO = instance.isOffscreen; -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - hasBoundFBO = true; -#endif + GLbitfield glClears = 0; + bool hasBoundFBO = instance.glFramebuffer; + invalidAttachments.clear(); static const Color ZERO; float fColors[4]{}; @@ -1667,7 +1788,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR } break; case LoadOp::DISCARD: // invalidate fbo - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); + invalidAttachments.push_back(hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); break; } } @@ -1688,7 +1809,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR glClears |= GL_DEPTH_BUFFER_BIT; break; case LoadOp::DISCARD: - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH); + invalidAttachments.push_back(hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH); break; } } @@ -1707,13 +1828,13 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR glClears |= GL_STENCIL_BUFFER_BIT; } break; case LoadOp::DISCARD: - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL); + invalidAttachments.push_back(hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL); break; } } - if (numAttachments) { - GL_CHECK(glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, numAttachments, invalidAttachments)); + if (!invalidAttachments.empty()) { + GL_CHECK(glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, invalidAttachments.size(), invalidAttachments.data())); } if (glClears) { @@ -1768,20 +1889,20 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR } void cmdFuncGLES3EndRenderPass(GLES3Device *device) { - GLES3GPUStateCache * cache = device->stateCache(); - GLES3ObjectCache & gfxStateCache = cache->gfxStateCache; - GLES3GPURenderPass * gpuRenderPass = gfxStateCache.gpuRenderPass; - GLES3GPUFramebuffer *gpuFramebuffer = gfxStateCache.gpuFramebuffer; - GLenum * invalidAttachments = gfxStateCache.invalidAttachments; - const auto & instance = gpuFramebuffer->usesPLS || gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[gfxStateCache.subpassIdx]; - const SubpassInfo & subpass = gpuRenderPass->subpasses[gfxStateCache.subpassIdx]; - bool isTheLastSubpass = gfxStateCache.subpassIdx == gpuRenderPass->subpasses.size() - 1; - bool hasBoundFBO = instance.isOffscreen; -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - hasBoundFBO = true; -#endif + static vector drawBuffers; + static vector invalidAttachments; - uint numAttachments = 0; + GLES3GPUStateCache * cache = device->stateCache(); + GLES3ObjectCache & gfxStateCache = cache->gfxStateCache; + GLES3GPURenderPass * gpuRenderPass = gfxStateCache.gpuRenderPass; + GLES3GPUFramebuffer *gpuFramebuffer = gfxStateCache.gpuFramebuffer; + const auto & instance = gpuFramebuffer->usesPLS || gpuFramebuffer->usesFBF ? gpuFramebuffer->uberInstance : gpuFramebuffer->instances[gfxStateCache.subpassIdx]; + const SubpassInfo & subpass = gpuRenderPass->subpasses[gfxStateCache.subpassIdx]; + bool isTheLastSubpass = gfxStateCache.subpassIdx == gpuRenderPass->subpasses.size() - 1; + bool hasBoundFBO = instance.glFramebuffer; + GLenum invalidateTarget = GL_DRAW_FRAMEBUFFER; + + invalidAttachments.clear(); auto performStoreOp = [&](uint attachmentIndex, uint glAttachmentIndex) { const ColorAttachment &colorAttachment = gpuRenderPass->colorAttachments[attachmentIndex]; @@ -1790,7 +1911,7 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { case StoreOp::STORE: break; case StoreOp::DISCARD: // invalidate fbo - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); + invalidAttachments.push_back(hasBoundFBO ? GL_COLOR_ATTACHMENT0 + glAttachmentIndex : GL_COLOR); break; } } @@ -1804,7 +1925,7 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { switch (gpuRenderPass->depthStencilAttachment.depthStoreOp) { case StoreOp::STORE: break; case StoreOp::DISCARD: - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH); + invalidAttachments.push_back(hasBoundFBO ? GL_DEPTH_ATTACHMENT : GL_DEPTH); break; } } @@ -1812,15 +1933,62 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { switch (gpuRenderPass->depthStencilAttachment.stencilStoreOp) { case StoreOp::STORE: break; case StoreOp::DISCARD: - invalidAttachments[numAttachments++] = (hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL); + invalidAttachments.push_back(hasBoundFBO ? GL_STENCIL_ATTACHMENT : GL_STENCIL); break; } } - if (numAttachments) { - GL_CHECK(glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, numAttachments, invalidAttachments)); //NOLINT(bugprone-lambda-function-name) + if (!invalidAttachments.empty()) { + GL_CHECK(glInvalidateFramebuffer(invalidateTarget, invalidAttachments.size(), invalidAttachments.data())); } }; + if (instance.resolveMask) { + drawBuffers.clear(); + + if (cache->glReadFramebuffer != instance.glFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, instance.glFramebuffer)); + cache->glReadFramebuffer = instance.glFramebuffer; + } + if (cache->glDrawFramebuffer != instance.glResolveFramebuffer) { + GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, instance.glResolveFramebuffer)); + cache->glDrawFramebuffer = instance.glResolveFramebuffer; + } + + if (instance.resolveMask & GL_COLOR_BUFFER_BIT) { + for (uint i = 0; i < subpass.colors.size(); ++i) { + auto attachment = static_cast(GL_COLOR_ATTACHMENT0 + i); + GL_CHECK(glReadBuffer(attachment)); + GL_CHECK(glDrawBuffers(1, &attachment)); + + GLES3GPUTexture *srcTex = gpuFramebuffer->gpuColorTextures[subpass.colors[i]]; + GLES3GPUTexture *dstTex = gpuFramebuffer->gpuColorTextures[subpass.resolves[i]]; + + GL_CHECK(glBlitFramebuffer( + 0, 0, srcTex->width, srcTex->height, + 0, 0, dstTex->width, dstTex->height, + GL_COLOR_BUFFER_BIT, GL_NEAREST)); + + drawBuffers.push_back(attachment); + } + } + + if (instance.resolveMask & GL_DEPTH_BUFFER_BIT) { + GLES3GPUTexture *srcTex = subpass.depthStencil < gpuFramebuffer->gpuColorTextures.size() + ? gpuFramebuffer->gpuColorTextures[subpass.depthStencil] + : gpuFramebuffer->gpuDepthStencilTexture; + GLES3GPUTexture *dstTex = subpass.depthStencilResolve < gpuFramebuffer->gpuColorTextures.size() + ? gpuFramebuffer->gpuColorTextures[subpass.depthStencilResolve] + : gpuFramebuffer->gpuDepthStencilTexture; + + GL_CHECK(glBlitFramebuffer( + 0, 0, srcTex->width, srcTex->height, + 0, 0, dstTex->width, dstTex->height, + instance.resolveMask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT), GL_NEAREST)); + } + + invalidateTarget = GL_READ_FRAMEBUFFER; + } + uint glAttachmentIndex = 0U; if (gpuFramebuffer->usesPLS || gpuFramebuffer->usesFBF) { if (isTheLastSubpass) { @@ -1833,15 +2001,16 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { cache->isPLSEnabled = false; } } else if (gpuFramebuffer->usesFBF) { - if (device->extensionRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_EXT) { + if (device->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_EXT) { GL_CHECK(glFramebufferFetchBarrierEXT()); - } else if (device->extensionRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { + } else if (device->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { GL_CHECK(glFramebufferFetchBarrierQCOM()); } } } else { if (isTheLastSubpass) { - for (const auto attachmentIndex : subpass.colors) { + const auto &indices = subpass.resolves.empty() ? subpass.colors : subpass.resolves; + for (const auto attachmentIndex : indices) { performStoreOp(attachmentIndex, glAttachmentIndex++); } performDepthStencilStoreOp(); @@ -1849,7 +2018,6 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { } } -//NOLINTNEXTLINE void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipelineState, GLES3GPUInputAssembler *gpuInputAssembler, const GLES3GPUDescriptorSet *const *gpuDescriptorSets, const uint *dynamicOffsets, const DynamicStates *dynamicStates) { GLES3ObjectCache &gfxStateCache = device->stateCache()->gfxStateCache; @@ -2016,42 +2184,44 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli cache->bs.blendColor = gpuPipelineState->bs.blendColor; } - BlendTarget & cacheTarget = cache->bs.targets[0]; - const BlendTarget &target = gpuPipelineState->bs.targets[0]; - if (cacheTarget.blend != target.blend) { - if (!cacheTarget.blend) { - GL_CHECK(glEnable(GL_BLEND)); - } else { - GL_CHECK(glDisable(GL_BLEND)); + if (!gpuPipelineState->bs.targets.empty()) { + BlendTarget & cacheTarget = cache->bs.targets[0]; + const BlendTarget &target = gpuPipelineState->bs.targets[0]; + if (cacheTarget.blend != target.blend) { + if (!cacheTarget.blend) { + GL_CHECK(glEnable(GL_BLEND)); + } else { + GL_CHECK(glDisable(GL_BLEND)); + } + cacheTarget.blend = target.blend; + } + if (cacheTarget.blendEq != target.blendEq || + cacheTarget.blendAlphaEq != target.blendAlphaEq) { + GL_CHECK(glBlendEquationSeparate(GLES3_BLEND_OPS[(int)target.blendEq], + GLES3_BLEND_OPS[(int)target.blendAlphaEq])); + cacheTarget.blendEq = target.blendEq; + cacheTarget.blendAlphaEq = target.blendAlphaEq; + } + if (cacheTarget.blendSrc != target.blendSrc || + cacheTarget.blendDst != target.blendDst || + cacheTarget.blendSrcAlpha != target.blendSrcAlpha || + cacheTarget.blendDstAlpha != target.blendDstAlpha) { + GL_CHECK(glBlendFuncSeparate(GLES3_BLEND_FACTORS[(int)target.blendSrc], + GLES3_BLEND_FACTORS[(int)target.blendDst], + GLES3_BLEND_FACTORS[(int)target.blendSrcAlpha], + GLES3_BLEND_FACTORS[(int)target.blendDstAlpha])); + cacheTarget.blendSrc = target.blendSrc; + cacheTarget.blendDst = target.blendDst; + cacheTarget.blendSrcAlpha = target.blendSrcAlpha; + cacheTarget.blendDstAlpha = target.blendDstAlpha; + } + if (cacheTarget.blendColorMask != target.blendColorMask) { + GL_CHECK(glColorMask((GLboolean)(target.blendColorMask & ColorMask::R), + (GLboolean)(target.blendColorMask & ColorMask::G), + (GLboolean)(target.blendColorMask & ColorMask::B), + (GLboolean)(target.blendColorMask & ColorMask::A))); + cacheTarget.blendColorMask = target.blendColorMask; } - cacheTarget.blend = target.blend; - } - if (cacheTarget.blendEq != target.blendEq || - cacheTarget.blendAlphaEq != target.blendAlphaEq) { - GL_CHECK(glBlendEquationSeparate(GLES3_BLEND_OPS[(int)target.blendEq], - GLES3_BLEND_OPS[(int)target.blendAlphaEq])); - cacheTarget.blendEq = target.blendEq; - cacheTarget.blendAlphaEq = target.blendAlphaEq; - } - if (cacheTarget.blendSrc != target.blendSrc || - cacheTarget.blendDst != target.blendDst || - cacheTarget.blendSrcAlpha != target.blendSrcAlpha || - cacheTarget.blendDstAlpha != target.blendDstAlpha) { - GL_CHECK(glBlendFuncSeparate(GLES3_BLEND_FACTORS[(int)target.blendSrc], - GLES3_BLEND_FACTORS[(int)target.blendDst], - GLES3_BLEND_FACTORS[(int)target.blendSrcAlpha], - GLES3_BLEND_FACTORS[(int)target.blendDstAlpha])); - cacheTarget.blendSrc = target.blendSrc; - cacheTarget.blendDst = target.blendDst; - cacheTarget.blendSrcAlpha = target.blendSrcAlpha; - cacheTarget.blendDstAlpha = target.blendDstAlpha; - } - if (cacheTarget.blendColorMask != target.blendColorMask) { - GL_CHECK(glColorMask((GLboolean)(target.blendColorMask & ColorMask::R), - (GLboolean)(target.blendColorMask & ColorMask::G), - (GLboolean)(target.blendColorMask & ColorMask::B), - (GLboolean)(target.blendColorMask & ColorMask::A))); - cacheTarget.blendColorMask = target.blendColorMask; } } // if @@ -2164,7 +2334,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli GLuint glTexture = gpuDescriptor->gpuTexture->glTexture; if (cache->glImages[unit] != glTexture) { - GL_CHECK(glBindImageTexture(unit, glTexture, 0, GL_TRUE, 0, glImage.glMemoryAccess, gpuDescriptor->gpuTexture->glInternelFmt)); + GL_CHECK(glBindImageTexture(unit, glTexture, 0, GL_TRUE, 0, glImage.glMemoryAccess, gpuDescriptor->gpuTexture->glInternalFmt)); } } } @@ -2176,7 +2346,7 @@ void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipeli (isShaderChanged || gpuInputAssembler != gfxStateCache.gpuInputAssembler)) { gfxStateCache.gpuInputAssembler = gpuInputAssembler; if (USE_VAO) { - size_t hash = gpuPipelineState->gpuShader->glProgram ^ device->getThreadID(); + size_t hash = gpuPipelineState->gpuShader->glProgram ^ device->constantRegistry()->currentBoundThreadID; GLuint glVAO = gpuInputAssembler->glVAOs[hash]; if (!glVAO) { GL_CHECK(glGenVertexArrays(1, &glVAO)); @@ -2655,27 +2825,15 @@ void cmdFuncGLES3BlitTexture(GLES3Device *device, GLES3GPUTexture *gpuTextureSrc for (uint i = 0U; i < count; ++i) { const TextureBlit ®ion = regions[i]; - GLuint srcFramebuffer = 0U; - if (gpuTextureSrc) { - srcFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureSrc, region.srcSubres); - } -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - else - srcFramebuffer = device->getDefaultFramebuffer(); -#endif + GLuint srcFramebuffer = gpuTextureSrc ? device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureSrc, region.srcSubres) + : device->constantRegistry()->defaultFramebuffer; if (cache->glReadFramebuffer != srcFramebuffer) { GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, srcFramebuffer)); cache->glReadFramebuffer = srcFramebuffer; } - GLuint dstFramebuffer = 0U; - if (gpuTextureDst) { - dstFramebuffer = device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureDst, region.srcSubres); - } -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - else - dstFramebuffer = device->getDefaultFramebuffer(); -#endif + GLuint dstFramebuffer = gpuTextureDst ? device->framebufferCacheMap()->getFramebufferFromTexture(gpuTextureDst, region.dstSubres) + : device->constantRegistry()->defaultFramebuffer; if (cache->glDrawFramebuffer != dstFramebuffer) { GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, dstFramebuffer)); cache->glDrawFramebuffer = dstFramebuffer; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Context.cpp b/native/cocos/renderer/gfx-gles3/GLES3Context.cpp index dc3e676ba7..6ede21cf36 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Context.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Context.cpp @@ -600,7 +600,7 @@ bool GLES3Context::makeCurrent(bool bound) { GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0)); GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0)); - if (GLES3Device::getInstance()->extensionRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { + if (GLES3Device::getInstance()->constantRegistry()->mFBF == FBFSupportLevel::NON_COHERENT_QCOM) { GL_CHECK(glEnable(GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM)); } diff --git a/native/cocos/renderer/gfx-gles3/GLES3Context.h b/native/cocos/renderer/gfx-gles3/GLES3Context.h index 1b23bbce7b..b48c860861 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Context.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Context.h @@ -46,7 +46,6 @@ public: #if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) inline intptr_t eagl_context() const { return _eaglContext; } inline intptr_t eagl_shared_ctx() const { return _eaglSharedContext; } - inline uint getDefaultFramebuffer() const { return _defaultFBO; } #else inline NativeDisplayType nativeDisplay() const { return _nativeDisplay; } inline EGLDisplay eglDisplay() const { return _eglDisplay; } @@ -59,6 +58,7 @@ public: inline int majorVer() const { return _majorVersion; } inline int minorVer() const { return _minorVersion; } inline uint8_t multiSampleCount() const { return _sampleCount; } + inline uint getDefaultFramebuffer() const { return _defaultFBO; } void releaseSurface(uintptr_t windowHandle); void acquireSurface(uintptr_t windowHandle); @@ -77,21 +77,21 @@ protected: bool _isInitialized = false; uint8_t _sampleBuffers = 0; uint8_t _sampleCount = 0; + uint _defaultFBO = 0; #if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) intptr_t _eaglContext = 0; intptr_t _eaglSharedContext = 0; // iOS needs to created frame buffer and attach color/depth/stencil buffer. - uint _defaultFBO = 0; uint _defaultColorBuffer = 0; uint _defaultDepthStencilBuffer = 0; #else - NativeDisplayType _nativeDisplay = 0; // NOLINT(modernize-use-nullptr) portability issues - EGLDisplay _eglDisplay = EGL_NO_DISPLAY; - EGLConfig _eglConfig = EGL_NO_CONFIG_KHR; - EGLSurface _eglSurface = EGL_NO_SURFACE; - EGLContext _eglContext = EGL_NO_CONTEXT; - EGLContext _eglSharedContext = EGL_NO_CONTEXT; - std::vector _vecEGLConfig; + NativeDisplayType _nativeDisplay = 0; // NOLINT(modernize-use-nullptr) portability issues + EGLDisplay _eglDisplay = EGL_NO_DISPLAY; + EGLConfig _eglConfig = EGL_NO_CONFIG_KHR; + EGLSurface _eglSurface = EGL_NO_SURFACE; + EGLContext _eglContext = EGL_NO_CONTEXT; + EGLContext _eglSharedContext = EGL_NO_CONTEXT; + std::vector _vecEGLConfig; #endif int _majorVersion = 0; int _minorVersion = 0; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index c1854fd138..da63b268ee 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -42,6 +42,11 @@ #include "GLES3Sampler.h" #include "GLES3Shader.h" #include "GLES3Texture.h" +#include "gfx-gles-common/GLESCommandPool.h" + +// when capturing GLES commands (RENDERDOC_HOOK_EGL=1, default value) +// renderdoc doesn't support this extension during replay +#define ALLOW_MULTISAMPLED_RENDER_TO_TEXTURE_ON_DESKTOP 0 namespace cc { namespace gfx { @@ -86,7 +91,7 @@ bool GLES3Device::doInit(const DeviceInfo &info) { _gpuStateCache = CC_NEW(GLES3GPUStateCache); _gpuStagingBufferPool = CC_NEW(GLES3GPUStagingBufferPool); - _gpuExtensionRegistry = CC_NEW(GLES3GPUExtensionRegistry); + _gpuConstantRegistry = CC_NEW(GLES3GPUConstantRegistry); _gpuFramebufferCacheMap = CC_NEW(GLES3GPUFramebufferCacheMap(_gpuStateCache)); bindRenderContext(true); @@ -94,7 +99,8 @@ bool GLES3Device::doInit(const DeviceInfo &info) { String extStr = reinterpret_cast(glGetString(GL_EXTENSIONS)); _extensions = StringUtil::split(extStr, " "); - _features[static_cast(Feature::MSAA)] = _renderContext->multiSampleCount() > 0; + _multithreadedSubmission = false; + _features[static_cast(Feature::TEXTURE_FLOAT)] = true; _features[static_cast(Feature::TEXTURE_HALF_FLOAT)] = true; _features[static_cast(Feature::FORMAT_R11G11B10F)] = true; @@ -128,6 +134,16 @@ bool GLES3Device::doInit(const DeviceInfo &info) { _features[static_cast(Feature::TEXTURE_HALF_FLOAT_LINEAR)] = true; } +#if CC_PLATFORM != CC_PLATFORM_WINDOWS && CC_PLATFORM != CC_PLATFORM_MAC_OSX || ALLOW_MULTISAMPLED_RENDER_TO_TEXTURE_ON_DESKTOP + if (checkExtension("multisampled_render_to_texture")) { + if (checkExtension("multisampled_render_to_texture2")) { + _gpuConstantRegistry->mMSRT = MSRTSupportLevel::LEVEL2; + } else { + _gpuConstantRegistry->mMSRT = MSRTSupportLevel::LEVEL1; + } + } +#endif + String fbfLevelStr = "NONE"; if (checkExtension("framebuffer_fetch")) { String nonCoherent = "framebuffer_fetch_non"; @@ -138,17 +154,17 @@ bool GLES3Device::doInit(const DeviceInfo &info) { if (it != _extensions.end()) { if (*it == CC_TOSTR(GL_EXT_shader_framebuffer_fetch_non_coherent)) { - _gpuExtensionRegistry->mFBF = FBFSupportLevel::NON_COHERENT_EXT; - fbfLevelStr = "NON_COHERENT_EXT"; + _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_EXT; + fbfLevelStr = "NON_COHERENT_EXT"; } else if (*it == CC_TOSTR(GL_QCOM_shader_framebuffer_fetch_noncoherent)) { - _gpuExtensionRegistry->mFBF = FBFSupportLevel::NON_COHERENT_QCOM; - fbfLevelStr = "NON_COHERENT_QCOM"; + _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_QCOM; + fbfLevelStr = "NON_COHERENT_QCOM"; GL_CHECK(glEnable(GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM)); } } else if (checkExtension(CC_TOSTR(GL_EXT_shader_framebuffer_fetch))) { // we only care about EXT_shader_framebuffer_fetch, the ARM version does not support MRT - _gpuExtensionRegistry->mFBF = FBFSupportLevel::COHERENT; - fbfLevelStr = "COHERENT"; + _gpuConstantRegistry->mFBF = FBFSupportLevel::COHERENT; + fbfLevelStr = "COHERENT"; } } @@ -156,14 +172,17 @@ bool GLES3Device::doInit(const DeviceInfo &info) { #if CC_PLATFORM != CC_PLATFORM_WINDOWS && CC_PLATFORM != CC_PLATFORM_MAC_OSX if (checkExtension("pixel_local_storage")) { if (checkExtension("pixel_local_storage2")) { - _gpuExtensionRegistry->mPLS = PLSSupportLevel::LEVEL2; + _gpuConstantRegistry->mPLS = PLSSupportLevel::LEVEL2; } else { - _gpuExtensionRegistry->mPLS = PLSSupportLevel::LEVEL1; + _gpuConstantRegistry->mPLS = PLSSupportLevel::LEVEL1; } - glGetIntegerv(GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_SIZE_EXT, reinterpret_cast(&_gpuExtensionRegistry->mPLSsize)); + glGetIntegerv(GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_SIZE_EXT, reinterpret_cast(&_gpuConstantRegistry->mPLSsize)); } #endif + _gpuConstantRegistry->glMinorVersion = _renderContext->minorVer(); + _gpuConstantRegistry->defaultFramebuffer = _renderContext->getDefaultFramebuffer(); + String compressedFmts; if (checkExtension("compressed_ETC1")) { @@ -183,11 +202,7 @@ bool GLES3Device::doInit(const DeviceInfo &info) { _features[static_cast(Feature::FORMAT_ASTC)] = true; compressedFmts += "astc "; } - _features[static_cast(Feature::DEPTH_BOUNDS)] = true; - _features[static_cast(Feature::LINE_WIDTH)] = true; - _features[static_cast(Feature::STENCIL_COMPARE_MASK)] = true; - _features[static_cast(Feature::STENCIL_WRITE_MASK)] = true; - _features[static_cast(Feature::FORMAT_RGB8)] = true; + _features[static_cast(Feature::FORMAT_RGB8)] = true; _renderer = reinterpret_cast(glGetString(GL_RENDERER)); _vendor = reinterpret_cast(glGetString(GL_VENDOR)); @@ -199,7 +214,7 @@ bool GLES3Device::doInit(const DeviceInfo &info) { CC_LOG_INFO("VERSION: %s", _version.c_str()); CC_LOG_INFO("SCREEN_SIZE: %d x %d", _width, _height); CC_LOG_INFO("COMPRESSED_FORMATS: %s", compressedFmts.c_str()); - CC_LOG_INFO("PIXEL_LOCAL_STORAGE: level %d, size %d", _gpuExtensionRegistry->mPLS, _gpuExtensionRegistry->mPLSsize); + CC_LOG_INFO("PIXEL_LOCAL_STORAGE: level %d, size %d", _gpuConstantRegistry->mPLS, _gpuConstantRegistry->mPLSsize); CC_LOG_INFO("FRAMEBUFFER_FETCH: %s", fbfLevelStr.c_str()); glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, reinterpret_cast(&_caps.maxVertexAttributes)); @@ -237,7 +252,7 @@ bool GLES3Device::doInit(const DeviceInfo &info) { void GLES3Device::doDestroy() { CC_SAFE_DELETE(_gpuFramebufferCacheMap) - CC_SAFE_DELETE(_gpuExtensionRegistry) + CC_SAFE_DELETE(_gpuConstantRegistry) CC_SAFE_DELETE(_gpuStagingBufferPool) CC_SAFE_DELETE(_gpuStateCache) @@ -286,7 +301,7 @@ void GLES3Device::bindRenderContext(bool bound) { _context = bound ? _renderContext : nullptr; if (bound) { - _threadID = std::hash{}(std::this_thread::get_id()); + _gpuConstantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); _gpuStateCache->reset(); } } @@ -304,16 +319,11 @@ void GLES3Device::bindDeviceContext(bool bound) { _context = bound ? _deviceContext : nullptr; if (bound) { - _threadID = std::hash{}(std::this_thread::get_id()); + _gpuConstantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); _gpuStateCache->reset(); } } -uint GLES3Device::getMinorVersion() const { return static_cast(_context)->minorVer(); } -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) -uint GLES3Device::getDefaultFramebuffer() const { return static_cast(_context)->getDefaultFramebuffer(); } -#endif - CommandBuffer *GLES3Device::createCommandBuffer(const CommandBufferInfo &info, bool hasAgent) { if (hasAgent || info.type == CommandBufferType::PRIMARY) return CC_NEW(GLES3PrimaryCommandBuffer); return CC_NEW(GLES3CommandBuffer); diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.h b/native/cocos/renderer/gfx-gles3/GLES3Device.h index cdebbdc4e8..198a162a93 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.h @@ -35,7 +35,7 @@ class GLES3Context; class GLES3GPUStateCache; class GLES3GPUStagingBufferPool; class GLES3GPUFramebufferCacheMap; -class GLES3GPUExtensionRegistry; +class GLES3GPUConstantRegistry; class CC_GLES3_API GLES3Device final : public Device { public: @@ -66,7 +66,7 @@ public: inline GLES3GPUStateCache * stateCache() const { return _gpuStateCache; } inline GLES3GPUStagingBufferPool * stagingBufferPool() const { return _gpuStagingBufferPool; } - inline GLES3GPUExtensionRegistry * extensionRegistry() const { return _gpuExtensionRegistry; } + inline GLES3GPUConstantRegistry * constantRegistry() const { return _gpuConstantRegistry; } inline GLES3GPUFramebufferCacheMap *framebufferCacheMap() const { return _gpuFramebufferCacheMap; } inline bool checkExtension(const String &extension) const { @@ -75,13 +75,6 @@ public: }); } - inline size_t getThreadID() const { return _threadID; } - - uint getMinorVersion() const; -#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) - uint getDefaultFramebuffer() const; -#endif - protected: static GLES3Device *instance; @@ -119,12 +112,10 @@ protected: GLES3Context * _deviceContext = nullptr; GLES3GPUStateCache * _gpuStateCache = nullptr; GLES3GPUStagingBufferPool * _gpuStagingBufferPool = nullptr; - GLES3GPUExtensionRegistry * _gpuExtensionRegistry = nullptr; + GLES3GPUConstantRegistry * _gpuConstantRegistry = nullptr; GLES3GPUFramebufferCacheMap *_gpuFramebufferCacheMap = nullptr; StringArray _extensions; - - size_t _threadID = 0U; }; } // namespace gfx diff --git a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp index e1decba77b..6282b68233 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Framebuffer.cpp @@ -42,13 +42,9 @@ GLES3Framebuffer::~GLES3Framebuffer() { destroy(); } -void GLES3Framebuffer::doInit(const FramebufferInfo &info) { - _gpuFBO = CC_NEW(GLES3GPUFramebuffer); - _gpuFBO->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); - _gpuFBO->depthStencilMipmapLevel = info.depthStencilMipmapLevel; - for (uint mipLevel : info.colorMipmapLevels) { - _gpuFBO->colorMipmapLevels.push_back(mipLevel); - } +void GLES3Framebuffer::doInit(const FramebufferInfo & /*info*/) { + _gpuFBO = CC_NEW(GLES3GPUFramebuffer); + _gpuFBO->gpuRenderPass = static_cast(_renderPass)->gpuRenderPass(); _gpuFBO->gpuColorTextures.resize(_colorTextures.size()); for (size_t i = 0; i < _colorTextures.size(); ++i) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 0346fc749a..f480d4c23d 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -36,18 +36,16 @@ namespace cc { namespace gfx { -enum class PLSSupportLevel { - NONE, - LEVEL1, - LEVEL2, -}; - -class GLES3GPUExtensionRegistry { +class GLES3GPUConstantRegistry { public: - FBFSupportLevel mFBF = FBFSupportLevel::NONE; + uint currentBoundThreadID{0U}; + uint glMinorVersion{0U}; + uint defaultFramebuffer{0U}; - PLSSupportLevel mPLS = PLSSupportLevel::NONE; - uint mPLSsize = 0U; + MSRTSupportLevel mMSRT{MSRTSupportLevel::NONE}; + FBFSupportLevel mFBF{FBFSupportLevel::NONE}; + PLSSupportLevel mPLS{PLSSupportLevel::NONE}; + uint mPLSsize{0U}; }; class GLES3GPUBuffer final : public Object { @@ -67,29 +65,31 @@ using GLES3GPUBufferList = vector; class GLES3GPUTexture final : public Object { public: - TextureType type = TextureType::TEX2D; - Format format = Format::UNKNOWN; - TextureUsage usage = TextureUsageBit::NONE; - uint width = 0; - uint height = 0; - uint depth = 1; - uint size = 0; - uint arrayLayer = 1; - uint mipLevel = 1; - SampleCount samples = SampleCount::X1; - TextureFlags flags = TextureFlagBit::NONE; - bool isPowerOf2 = false; - bool memoryless = false; - GLenum glTarget = 0; - GLenum glInternelFmt = 0; - GLenum glFormat = 0; - GLenum glType = 0; - GLenum glUsage = 0; - GLuint glTexture = 0; - GLenum glWrapS = 0; - GLenum glWrapT = 0; - GLenum glMinFilter = 0; - GLenum glMagFilter = 0; + TextureType type = TextureType::TEX2D; + Format format = Format::UNKNOWN; + TextureUsage usage = TextureUsageBit::NONE; + uint width = 0; + uint height = 0; + uint depth = 1; + uint size = 0; + uint arrayLayer = 1; + uint mipLevel = 1; + SampleCount samples = SampleCount::X1; + TextureFlags flags = TextureFlagBit::NONE; + bool isPowerOf2 = false; + bool memoryless = false; + GLenum glTarget = 0; + GLenum glInternalFmt = 0; + GLenum glFormat = 0; + GLenum glType = 0; + GLenum glUsage = 0; + GLint glSamples = 0; + GLuint glTexture = 0; + GLuint glRenderbuffer = 0; + GLenum glWrapS = 0; + GLenum glWrapT = 0; + GLenum glMinFilter = 0; + GLenum glMagFilter = 0; }; using GLES3GPUTextureList = vector; @@ -153,8 +153,8 @@ struct GLES3GPUUniformSamplerTexture final { uint count = 0U; vector units; - GLenum glType = 0; - GLint glLoc = -1; + GLenum glType = 0; + GLint glLoc = -1; }; using GLES3GPUUniformSamplerTextureList = vector; @@ -237,16 +237,18 @@ class GLES3GPUFramebuffer final : public Object { public: GLES3GPURenderPass *gpuRenderPass = nullptr; GLES3GPUTextureList gpuColorTextures; - vector colorMipmapLevels; - GLES3GPUTexture * gpuDepthStencilTexture = nullptr; - GLint depthStencilMipmapLevel = 0; - bool usesPLS = false; - bool usesFBF = false; + GLES3GPUTexture * gpuDepthStencilTexture = nullptr; + bool usesPLS = false; + bool usesFBF = false; struct GLFramebuffer { GLuint glFramebuffer = 0U; - bool isOffscreen = false; + + // for blit-based manual resolving + GLbitfield resolveMask = 0U; + GLuint glResolveFramebuffer = 0U; }; + // one per subpass, if not using FBF or PLS vector instances; @@ -325,7 +327,6 @@ struct GLES3ObjectCache final { GLES3GPUPipelineState * gpuPipelineState = nullptr; GLES3GPUInputAssembler *gpuInputAssembler = nullptr; GLenum glPrimitive = 0; - GLenum invalidAttachments[MAX_ATTACHMENTS]; Rect renderArea; ColorList clearColors; float clearDepth = 1.F; @@ -353,6 +354,7 @@ public: vector glCurrentAttribLocs; GLuint glReadFramebuffer = 0; GLuint glDrawFramebuffer = 0; + GLuint glRenderbuffer = 0; Viewport viewport; Rect scissor; RasterizerState rs; @@ -396,6 +398,7 @@ public: glCurrentAttribLocs.assign(glCurrentAttribLocs.size(), false); glReadFramebuffer = 0; glDrawFramebuffer = 0; + glRenderbuffer = 0; isCullFaceEnabled = true; isStencilTestEnabled = false; isPLSEnabled = false; @@ -422,11 +425,14 @@ public: ~GLES3GPUFramebufferCacheMap() override = default; GLuint getFramebufferFromTexture(const GLES3GPUTexture *gpuTexture, const TextureSubresLayers &subres) { - // TODO(YunHsiao): single layer support using glFramebufferTextureLayer + bool isTexture = gpuTexture->glTexture; + GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; + auto & cacheMap = isTexture ? _textureMap : _renderbufferMap; + uint mipLevel = isTexture ? subres.mipLevel : 0; - if (_map[gpuTexture->glTexture].empty()) _map[gpuTexture->glTexture].resize(gpuTexture->mipLevel, 0U); + if (cacheMap[glResource].empty()) cacheMap[glResource].resize(gpuTexture->mipLevel, 0U); - if (!_map[gpuTexture->glTexture][subres.mipLevel]) { + if (!cacheMap[glResource][mipLevel]) { GLuint glFramebuffer = 0U; GL_CHECK(glGenFramebuffers(1, &glFramebuffer)); if (_cache->glDrawFramebuffer != glFramebuffer) { @@ -441,21 +447,29 @@ public: } else if (info.hasDepth) { attachment = GL_DEPTH_ATTACHMENT; } - GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attachment, gpuTexture->glTarget, gpuTexture->glTexture, subres.mipLevel)); + if (isTexture) { + GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, attachment, gpuTexture->glTarget, glResource, mipLevel)); + } else { + GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, attachment, gpuTexture->glTarget, glResource)); + } GLenum status; GL_CHECK(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); CCASSERT(status == GL_FRAMEBUFFER_COMPLETE, "frambuffer incomplete"); - _map[gpuTexture->glTexture][subres.mipLevel] = glFramebuffer; + cacheMap[glResource][mipLevel] = glFramebuffer; } - return _map[gpuTexture->glTexture][subres.mipLevel]; + return cacheMap[glResource][mipLevel]; } void onTextureDestroy(const GLES3GPUTexture *gpuTexture) { - if (_map.count(gpuTexture->glTexture)) { - for (GLuint glFramebuffer : _map[gpuTexture->glTexture]) { + bool isTexture = gpuTexture->glTexture; + GLuint glResource = isTexture ? gpuTexture->glTexture : gpuTexture->glRenderbuffer; + auto & cacheMap = isTexture ? _textureMap : _renderbufferMap; + + if (cacheMap.count(glResource)) { + for (GLuint glFramebuffer : cacheMap[glResource]) { if (!glFramebuffer) continue; if (_cache->glDrawFramebuffer == glFramebuffer || _cache->glReadFramebuffer == glFramebuffer) { @@ -464,13 +478,16 @@ public: } GL_CHECK(glDeleteFramebuffers(1, &glFramebuffer)); } - _map.erase(gpuTexture->glTexture); + cacheMap.erase(glResource); } } private: - GLES3GPUStateCache * _cache = nullptr; - unordered_map> _map; // texture -> mip level -> framebuffer + GLES3GPUStateCache *_cache = nullptr; + + using CacheMap = unordered_map>; + CacheMap _renderbufferMap; // renderbuffer -> mip level -> framebuffer + CacheMap _textureMap; // texture -> mip level -> framebuffer }; constexpr size_t CHUNK_SIZE = 16 * 1024 * 1024; // 16M per block by default diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index a29574b254..d3dabf1fe2 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -168,16 +168,10 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { _features[static_cast(Feature::TEXTURE_HALF_FLOAT)] = true; _features[static_cast(Feature::FORMAT_R11G11B10F)] = true; _features[static_cast(Feature::FORMAT_SRGB)] = true; - _features[static_cast(Feature::MSAA)] = true; _features[static_cast(Feature::INSTANCED_ARRAYS)] = true; _features[static_cast(Feature::MULTIPLE_RENDER_TARGETS)] = true; _features[static_cast(Feature::BLEND_MINMAX)] = true; _features[static_cast(Feature::ELEMENT_INDEX_UINT)] = true; - _features[static_cast(Feature::DEPTH_BOUNDS)] = false; - _features[static_cast(Feature::LINE_WIDTH)] = false; - _features[static_cast(Feature::STENCIL_COMPARE_MASK)] = false; - _features[static_cast(Feature::STENCIL_WRITE_MASK)] = false; - _features[static_cast(Feature::MULTITHREADED_SUBMISSION)] = true; _features[static_cast(Feature::COMPUTE_SHADER)] = true; _features[static_cast(Feature::FORMAT_RGB8)] = false; diff --git a/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm b/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm index 313f99d37b..8008731efe 100644 --- a/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLFramebuffer.mm @@ -39,14 +39,10 @@ CCMTLFramebuffer::CCMTLFramebuffer() : Framebuffer() { void CCMTLFramebuffer::doInit(const FramebufferInfo &info) { auto *mtlRenderPass = static_cast(_renderPass); size_t slot = 0; - size_t levelCount = info.colorMipmapLevels.size(); size_t i = 0; size_t attachmentIndices = 0; for (const auto *colorTexture : info.colorTextures) { int level = 0; - if (levelCount > i) { - level = info.colorMipmapLevels[i]; - } const auto *texture = static_cast(colorTexture); if (texture) { attachmentIndices |= (1 << i); @@ -57,7 +53,7 @@ void CCMTLFramebuffer::doInit(const FramebufferInfo &info) { if (_depthStencilTexture) { id texture = static_cast(_depthStencilTexture)->getMTLTexture(); - mtlRenderPass->setDepthStencilAttachment(texture, info.depthStencilMipmapLevel); + mtlRenderPass->setDepthStencilAttachment(texture, 0); attachmentIndices |= (1 << i); } diff --git a/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp b/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp index e0729f68d1..20de0a04bb 100644 --- a/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp +++ b/native/cocos/renderer/gfx-validator/PipelineStateValidator.cpp @@ -50,7 +50,15 @@ void PipelineStateValidator::doInit(const PipelineStateInfo &info) { PipelineStateInfo actorInfo = info; actorInfo.shader = static_cast(info.shader)->getActor(); actorInfo.pipelineLayout = static_cast(info.pipelineLayout)->getActor(); - if (info.renderPass) actorInfo.renderPass = static_cast(info.renderPass)->getActor(); + if (info.renderPass) { + actorInfo.renderPass = static_cast(info.renderPass)->getActor(); + + const auto &subpasses = info.renderPass->getSubpasses(); + size_t colorAttachmentCount = info.subpass >= subpasses.size() + ? info.renderPass->getColorAttachments().size() + : subpasses[info.subpass].colors.size(); + //CCASSERT(colorAttachmentCount == info.blendState.targets.size(), "Wrong number of blend targets"); // be more lenient on this + } _actor->initialize(actorInfo); } diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp index 882362f502..af926adda7 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp @@ -150,11 +150,11 @@ void CCVKCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fbo } clearValues[attachmentCount - 1].depthStencil = {depth, static_cast(stencil)}; } - auto* device = CCVKDevice::getInstance(); + auto * device = CCVKDevice::getInstance(); VkRenderPassBeginInfo passBeginInfo{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; passBeginInfo.renderPass = gpuRenderPass->vkRenderPass; passBeginInfo.framebuffer = framebuffer; - passBeginInfo.clearValueCount = clearValues.size(); + passBeginInfo.clearValueCount = utils::toUint(clearValues.size()); passBeginInfo.pClearValues = clearValues.data(); passBeginInfo.renderArea = {{0, 0}, {device->getWidth(), device->getHeight()}}; vkCmdBeginRenderPass(_gpuCommandBuffer->vkCommandBuffer, &passBeginInfo, @@ -229,13 +229,13 @@ void CCVKCommandBuffer::bindInputAssembler(InputAssembler *ia) { if (_curGPUInputAssember != gpuInputAssembler) { // buffers may be rebuilt(e.g. resize event) without IA's acknowledge - size_t vbCount = gpuInputAssembler->gpuVertexBuffers.size(); + uint vbCount = utils::toUint(gpuInputAssembler->gpuVertexBuffers.size()); if (gpuInputAssembler->vertexBuffers.size() < vbCount) { gpuInputAssembler->vertexBuffers.resize(vbCount); gpuInputAssembler->vertexBufferOffsets.resize(vbCount); } - for (size_t i = 0U; i < vbCount; ++i) { + for (uint i = 0U; i < vbCount; ++i) { gpuInputAssembler->vertexBuffers[i] = gpuInputAssembler->gpuVertexBuffers[i]->vkBuffer; gpuInputAssembler->vertexBufferOffsets[i] = gpuInputAssembler->gpuVertexBuffers[i]->startOffset; } @@ -498,9 +498,9 @@ void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, co _blitRegions[i].srcOffsets[0].x = region.srcOffset.x; _blitRegions[i].srcOffsets[0].y = region.srcOffset.y; _blitRegions[i].srcOffsets[0].z = region.srcOffset.z; - _blitRegions[i].srcOffsets[1].x = region.srcOffset.x + region.srcExtent.width; - _blitRegions[i].srcOffsets[1].y = region.srcOffset.y + region.srcExtent.height; - _blitRegions[i].srcOffsets[1].z = region.srcOffset.z + region.srcExtent.depth; + _blitRegions[i].srcOffsets[1].x = static_cast(region.srcOffset.x + region.srcExtent.width); + _blitRegions[i].srcOffsets[1].y = static_cast(region.srcOffset.y + region.srcExtent.height); + _blitRegions[i].srcOffsets[1].z = static_cast(region.srcOffset.z + region.srcExtent.depth); _blitRegions[i].dstSubresource.aspectMask = dstAspectMask; _blitRegions[i].dstSubresource.mipLevel = region.dstSubres.mipLevel; @@ -509,9 +509,9 @@ void CCVKCommandBuffer::blitTexture(Texture *srcTexture, Texture *dstTexture, co _blitRegions[i].dstOffsets[0].x = region.dstOffset.x; _blitRegions[i].dstOffsets[0].y = region.dstOffset.y; _blitRegions[i].dstOffsets[0].z = region.dstOffset.z; - _blitRegions[i].dstOffsets[1].x = region.dstOffset.x + region.dstExtent.width; - _blitRegions[i].dstOffsets[1].y = region.dstOffset.y + region.dstExtent.height; - _blitRegions[i].dstOffsets[1].z = region.dstOffset.z + region.dstExtent.depth; + _blitRegions[i].dstOffsets[1].x = static_cast(region.dstOffset.x + region.dstExtent.width); + _blitRegions[i].dstOffsets[1].y = static_cast(region.dstOffset.y + region.dstExtent.height); + _blitRegions[i].dstOffsets[1].z = static_cast(region.dstOffset.z + region.dstExtent.depth); } vkCmdBlitImage(_gpuCommandBuffer->vkCommandBuffer, @@ -525,7 +525,7 @@ void CCVKCommandBuffer::bindDescriptorSets(VkPipelineBindPoint bindPoint) { CCVKGPUDevice * gpuDevice = device->gpuDevice(); CCVKGPUPipelineLayout *pipelineLayout = _curGPUPipelineState->gpuPipelineLayout; vector & dynamicOffsetOffsets = pipelineLayout->dynamicOffsetOffsets; - uint descriptorSetCount = pipelineLayout->setLayouts.size(); + uint descriptorSetCount = utils::toUint(pipelineLayout->setLayouts.size()); _curDynamicOffsets.resize(pipelineLayout->dynamicOffsetCount); uint dirtyDescriptorSetCount = descriptorSetCount - _firstDirtyDescriptorSet; diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index d5e59331b0..cb1dbf2a1a 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -31,6 +31,8 @@ #include "VKDevice.h" #include "VKQueue.h" #include "VKSPIRV.h" +#include "gfx-base/GFXSampler.h" +#include "vulkan/vulkan_core.h" #include @@ -89,8 +91,8 @@ void cmdFuncCCVKGetDeviceQueue(CCVKDevice *device, CCVKGPUQueue *gpuQueue) { const CCVKGPUContext *context = device->gpuContext(); - size_t queueCount = context->queueFamilyProperties.size(); - for (size_t i = 0U; i < queueCount; ++i) { + uint queueCount = utils::toUint(context->queueFamilyProperties.size()); + for (uint i = 0U; i < queueCount; ++i) { const VkQueueFamilyProperties &properties = context->queueFamilyProperties[i]; const VkBool32 isPresentable = context->queueFamilyPresentables[i]; if (properties.queueCount > 0 && (properties.queueFlags & queueType) && (!needPresentable || isPresentable)) { @@ -128,7 +130,7 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { createInfo.extent = {gpuTexture->width, gpuTexture->height, gpuTexture->depth}; createInfo.mipLevels = gpuTexture->mipLevels; createInfo.arrayLayers = gpuTexture->arrayLayers; - createInfo.samples = mapVkSampleCount(gpuTexture->samples); + createInfo.samples = device->gpuContext()->getSampleCountForAttachments(gpuTexture->format, gpuTexture->samples); createInfo.tiling = VK_IMAGE_TILING_OPTIMAL; createInfo.usage = usageFlags; createInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; @@ -141,7 +143,8 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { if (ENABLE_LAZY_ALLOCATION && hasAllFlags(TEXTURE_USAGE_TRANSIENT, gpuTexture->usage)) { createInfo.usage = usageFlags | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; allocInfo.usage = VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED; - VkResult result = vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, &gpuTexture->vkImage, &gpuTexture->vmaAllocation, &res); + VkResult result = vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, + &gpuTexture->vkImage, &gpuTexture->vmaAllocation, &res); if (!result) { gpuTexture->memoryless = true; return; @@ -153,18 +156,23 @@ void cmdFuncCCVKCreateTexture(CCVKDevice *device, CCVKGPUTexture *gpuTexture) { } gpuTexture->memoryless = false; - VK_CHECK(vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, &gpuTexture->vkImage, &gpuTexture->vmaAllocation, &res)); - //CC_LOG_DEBUG("Allocated texture: %llu %llx %llx %llu %x", res.size, gpuTexture->vkImage, res.deviceMemory, res.offset, res.pMappedData); + VK_CHECK(vmaCreateImage(device->gpuDevice()->memoryAllocator, &createInfo, &allocInfo, + &gpuTexture->vkImage, &gpuTexture->vmaAllocation, &res)); } void cmdFuncCCVKCreateTextureView(CCVKDevice *device, CCVKGPUTextureView *gpuTextureView) { if (!gpuTextureView->gpuTexture || !gpuTextureView->gpuTexture->vkImage) return; + auto formatInfo = GFX_FORMAT_INFOS[static_cast(gpuTextureView->format)]; + + VkImageAspectFlags aspect = VK_IMAGE_ASPECT_COLOR_BIT; + if (formatInfo.hasDepth) aspect = VK_IMAGE_ASPECT_DEPTH_BIT; + VkImageViewCreateInfo createInfo{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; createInfo.image = gpuTextureView->gpuTexture->vkImage; createInfo.viewType = mapVkImageViewType(gpuTextureView->type); createInfo.format = mapVkFormat(gpuTextureView->format); - createInfo.subresourceRange.aspectMask = GFX_FORMAT_INFOS[static_cast(gpuTextureView->format)].hasDepth ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT; + createInfo.subresourceRange.aspectMask = aspect; createInfo.subresourceRange.baseMipLevel = gpuTextureView->baseLevel; createInfo.subresourceRange.levelCount = gpuTextureView->levelCount; createInfo.subresourceRange.baseArrayLayer = gpuTextureView->baseLayer; @@ -177,7 +185,8 @@ void cmdFuncCCVKCreateTextureView(CCVKDevice *device, CCVKGPUTextureView *gpuTex void cmdFuncCCVKCreateSampler(CCVKDevice *device, CCVKGPUSampler *gpuSampler) { VkSamplerCreateInfo createInfo{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - CCVKGPUContext * context = device->gpuContext(); + CCVKGPUContext * context = device->gpuContext(); + float maxAnisotropy = context->physicalDeviceProperties.limits.maxSamplerAnisotropy; createInfo.magFilter = VK_FILTERS[static_cast(gpuSampler->magFilter)]; createInfo.minFilter = VK_FILTERS[static_cast(gpuSampler->minFilter)]; @@ -187,7 +196,7 @@ void cmdFuncCCVKCreateSampler(CCVKDevice *device, CCVKGPUSampler *gpuSampler) { createInfo.addressModeW = VK_SAMPLER_ADDRESS_MODES[static_cast(gpuSampler->addressW)]; createInfo.mipLodBias = gpuSampler->mipLODBias; createInfo.anisotropyEnable = gpuSampler->maxAnisotropy && context->physicalDeviceFeatures.samplerAnisotropy; - createInfo.maxAnisotropy = std::min(context->physicalDeviceProperties.limits.maxSamplerAnisotropy, static_cast(gpuSampler->maxAnisotropy)); + createInfo.maxAnisotropy = std::min(maxAnisotropy, static_cast(gpuSampler->maxAnisotropy)); createInfo.compareEnable = gpuSampler->cmpFunc != ComparisonFunc::ALWAYS; createInfo.compareOp = VK_CMP_FUNCS[static_cast(gpuSampler->cmpFunc)]; createInfo.minLod = 0.0; // UNASSIGNED-BestPractices-vkCreateSampler-lod-clamping @@ -226,8 +235,8 @@ void cmdFuncCCVKCreateBuffer(CCVKDevice *device, CCVKGPUBuffer *gpuBuffer) { } VmaAllocationInfo res; - VK_CHECK(vmaCreateBuffer(device->gpuDevice()->memoryAllocator, &bufferInfo, &allocInfo, &gpuBuffer->vkBuffer, &gpuBuffer->vmaAllocation, &res)); - //CC_LOG_DEBUG("Allocated buffer: %llu, %llx %llx %llu %x", res.size, gpuBuffer->vkBuffer, res.deviceMemory, res.offset, res.pMappedData); + VK_CHECK(vmaCreateBuffer(device->gpuDevice()->memoryAllocator, &bufferInfo, &allocInfo, + &gpuBuffer->vkBuffer, &gpuBuffer->vmaAllocation, &res)); gpuBuffer->mappedData = reinterpret_cast(res.pMappedData); gpuBuffer->startOffset = 0; // we are creating one VkBuffer each for now @@ -239,17 +248,18 @@ void cmdFuncCCVKCreateBuffer(CCVKDevice *device, CCVKGPUBuffer *gpuBuffer) { } void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRenderPass) { - static vector attachmentDescriptions; - static vector subpassDescriptions; - static vector attachmentReferences; - static vector subpassDependencies; - static vector accessTypeCaches; - static vector beginAccessInfos; - static vector endAccessInfos; + static vector depthStencilResolves; + static vector attachmentDescriptions; + static vector attachmentReferences; + static vector subpassDescriptions; + static vector subpassDependencies; + static vector accessTypeCaches; + static vector beginAccessInfos; + static vector endAccessInfos; const size_t colorAttachmentCount = gpuRenderPass->colorAttachments.size(); const size_t hasDepth = gpuRenderPass->depthStencilAttachment.format != Format::UNKNOWN ? 1 : 0; - attachmentDescriptions.resize(colorAttachmentCount + hasDepth); + attachmentDescriptions.assign(colorAttachmentCount + hasDepth, {VK_STRUCTURE_TYPE_ATTACHMENT_DESCRIPTION_2}); gpuRenderPass->clearValues.resize(colorAttachmentCount + hasDepth); gpuRenderPass->beginAccesses.resize(colorAttachmentCount + hasDepth); gpuRenderPass->endAccesses.resize(colorAttachmentCount + hasDepth); @@ -270,11 +280,15 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende for (AccessType type : attachment.endAccesses) { endAccesses.push_back(THSVS_ACCESS_TYPES[static_cast(type)]); } - thsvsGetAccessInfo(beginAccesses.size(), beginAccesses.data(), &beginAccessInfo.stageMask, &beginAccessInfo.accessMask, &beginAccessInfo.imageLayout, &beginAccessInfo.hasWriteAccess); - thsvsGetAccessInfo(endAccesses.size(), endAccesses.data(), &endAccessInfo.stageMask, &endAccessInfo.accessMask, &endAccessInfo.imageLayout, &endAccessInfo.hasWriteAccess); + thsvsGetAccessInfo(utils::toUint(beginAccesses.size()), beginAccesses.data(), &beginAccessInfo.stageMask, + &beginAccessInfo.accessMask, &beginAccessInfo.imageLayout, &beginAccessInfo.hasWriteAccess); + thsvsGetAccessInfo(utils::toUint(endAccesses.size()), endAccesses.data(), &endAccessInfo.stageMask, + &endAccessInfo.accessMask, &endAccessInfo.imageLayout, &endAccessInfo.hasWriteAccess); + + VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(attachment.format, attachment.sampleCount); attachmentDescriptions[i].format = mapVkFormat(attachment.format); - attachmentDescriptions[i].samples = mapVkSampleCount(attachment.sampleCount); + attachmentDescriptions[i].samples = samples; attachmentDescriptions[i].loadOp = mapVkLoadOp(attachment.loadOp); attachmentDescriptions[i].storeOp = mapVkStoreOp(attachment.storeOp); attachmentDescriptions[i].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; @@ -296,11 +310,15 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende for (AccessType type : depthStencilAttachment.endAccesses) { endAccesses.push_back(THSVS_ACCESS_TYPES[static_cast(type)]); } - thsvsGetAccessInfo(beginAccesses.size(), beginAccesses.data(), &beginAccessInfo.stageMask, &beginAccessInfo.accessMask, &beginAccessInfo.imageLayout, &beginAccessInfo.hasWriteAccess); - thsvsGetAccessInfo(endAccesses.size(), endAccesses.data(), &endAccessInfo.stageMask, &endAccessInfo.accessMask, &endAccessInfo.imageLayout, &endAccessInfo.hasWriteAccess); + thsvsGetAccessInfo(utils::toUint(beginAccesses.size()), beginAccesses.data(), &beginAccessInfo.stageMask, + &beginAccessInfo.accessMask, &beginAccessInfo.imageLayout, &beginAccessInfo.hasWriteAccess); + thsvsGetAccessInfo(utils::toUint(endAccesses.size()), endAccesses.data(), &endAccessInfo.stageMask, + &endAccessInfo.accessMask, &endAccessInfo.imageLayout, &endAccessInfo.hasWriteAccess); + + VkSampleCountFlagBits samples = device->gpuContext()->getSampleCountForAttachments(depthStencilAttachment.format, depthStencilAttachment.sampleCount); attachmentDescriptions[colorAttachmentCount].format = mapVkFormat(depthStencilAttachment.format); - attachmentDescriptions[colorAttachmentCount].samples = mapVkSampleCount(depthStencilAttachment.sampleCount); + attachmentDescriptions[colorAttachmentCount].samples = samples; attachmentDescriptions[colorAttachmentCount].loadOp = mapVkLoadOp(depthStencilAttachment.depthLoadOp); attachmentDescriptions[colorAttachmentCount].storeOp = mapVkStoreOp(depthStencilAttachment.depthStoreOp); attachmentDescriptions[colorAttachmentCount].stencilLoadOp = mapVkLoadOp(depthStencilAttachment.stencilLoadOp); @@ -311,45 +329,81 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende size_t subpassCount = gpuRenderPass->subpasses.size(); attachmentReferences.clear(); + gpuRenderPass->sampleCounts.clear(); for (const auto &subpassInfo : gpuRenderPass->subpasses) { + VkSampleCountFlagBits sampleCount = VK_SAMPLE_COUNT_1_BIT; + for (uint input : subpassInfo.inputs) { VkImageLayout layout = gpuRenderPass->colorAttachments[input].isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - attachmentReferences.push_back({input, layout}); + attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, input, layout, VK_IMAGE_ASPECT_COLOR_BIT}); } for (uint color : subpassInfo.colors) { - VkImageLayout layout = gpuRenderPass->colorAttachments[color].isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - attachmentReferences.push_back({color, layout}); + const ColorAttachment & desc = gpuRenderPass->colorAttachments[color]; + const VkAttachmentDescription2 &attachment = attachmentDescriptions[color]; + VkImageLayout layout = desc.isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, color, layout, VK_IMAGE_ASPECT_COLOR_BIT}); + sampleCount = std::max(sampleCount, attachment.samples); } for (uint resolve : subpassInfo.resolves) { VkImageLayout layout = gpuRenderPass->colorAttachments[resolve].isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - attachmentReferences.push_back({resolve, layout}); + attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, resolve, layout, VK_IMAGE_ASPECT_COLOR_BIT}); } - bool isGeneralLayout = subpassInfo.depthStencil >= gpuRenderPass->colorAttachments.size() - ? gpuRenderPass->depthStencilAttachment.isGeneralLayout - : gpuRenderPass->colorAttachments[subpassInfo.depthStencil].isGeneralLayout; + bool isGeneralLayout{false}; + Format dsFormat{Format::UNKNOWN}; + if (subpassInfo.depthStencil != INVALID_BINDING) { + if (subpassInfo.depthStencil >= gpuRenderPass->colorAttachments.size()) { + const DepthStencilAttachment & desc = gpuRenderPass->depthStencilAttachment; + const VkAttachmentDescription2 &attachment = attachmentDescriptions.back(); + isGeneralLayout = desc.isGeneralLayout; + dsFormat = desc.format; + sampleCount = std::max(sampleCount, attachment.samples); + } else { + const ColorAttachment & desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencil]; + const VkAttachmentDescription2 &attachment = attachmentDescriptions[subpassInfo.depthStencil]; + isGeneralLayout = desc.isGeneralLayout; + dsFormat = desc.format; + sampleCount = std::max(sampleCount, attachment.samples); + } - VkImageLayout layout = isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - attachmentReferences.push_back({subpassInfo.depthStencil, layout}); + VkImageAspectFlags aspect = GFX_FORMAT_INFOS[static_cast(dsFormat)].hasStencil + ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT + : VK_IMAGE_ASPECT_DEPTH_BIT; + VkImageLayout layout = isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, subpassInfo.depthStencil, layout, aspect}); + gpuRenderPass->sampleCounts.push_back(sampleCount); + } + + if (subpassInfo.depthStencilResolve != INVALID_BINDING) { + const ColorAttachment &desc = gpuRenderPass->colorAttachments[subpassInfo.depthStencilResolve]; + + VkImageAspectFlags aspect = GFX_FORMAT_INFOS[static_cast(desc.format)].hasStencil + ? VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT + : VK_IMAGE_ASPECT_DEPTH_BIT; + VkImageLayout layout = desc.isGeneralLayout ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + attachmentReferences.push_back({VK_STRUCTURE_TYPE_ATTACHMENT_REFERENCE_2, nullptr, subpassInfo.depthStencilResolve, layout, aspect}); + } } - uint offset{0U}; - subpassDescriptions.assign(subpassCount, {}); // init to zeros first + size_t offset{0U}; + subpassDescriptions.assign(subpassCount, {VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_2}); // init to zeros first + depthStencilResolves.resize(subpassCount, {VK_STRUCTURE_TYPE_SUBPASS_DESCRIPTION_DEPTH_STENCIL_RESOLVE}); + const VkPhysicalDeviceDepthStencilResolveProperties &prop{device->gpuContext()->physicalDeviceDepthStencilResolveProperties}; for (uint i = 0U; i < gpuRenderPass->subpasses.size(); ++i) { const SubpassInfo subpassInfo = gpuRenderPass->subpasses[i]; - VkSubpassDescription &desc = subpassDescriptions[i]; - desc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + VkSubpassDescription2 &desc = subpassDescriptions[i]; + desc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; if (!subpassInfo.inputs.empty()) { - desc.inputAttachmentCount = subpassInfo.inputs.size(); + desc.inputAttachmentCount = utils::toUint(subpassInfo.inputs.size()); desc.pInputAttachments = attachmentReferences.data() + offset; offset += subpassInfo.inputs.size(); } if (!subpassInfo.colors.empty()) { - desc.colorAttachmentCount = subpassInfo.colors.size(); + desc.colorAttachmentCount = utils::toUint(subpassInfo.colors.size()); desc.pColorAttachments = attachmentReferences.data() + offset; offset += subpassInfo.colors.size(); if (!subpassInfo.resolves.empty()) { @@ -359,7 +413,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende } if (!subpassInfo.preserves.empty()) { - desc.preserveAttachmentCount = subpassInfo.preserves.size(); + desc.preserveAttachmentCount = utils::toUint(subpassInfo.preserves.size()); desc.pPreserveAttachments = subpassInfo.preserves.data(); } @@ -368,6 +422,28 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende } else { desc.pDepthStencilAttachment = nullptr; } + + if (subpassInfo.depthStencilResolve != INVALID_BINDING) { + VkSubpassDescriptionDepthStencilResolve &resolveDesc{depthStencilResolves[i]}; + + VkResolveModeFlagBits depthResolveMode = VK_RESOLVE_MODES[static_cast(subpassInfo.depthResolveMode)]; + VkResolveModeFlagBits stencilResolveMode = VK_RESOLVE_MODES[static_cast(subpassInfo.stencilResolveMode)]; + + if ((depthResolveMode & prop.supportedDepthResolveModes) == 0) depthResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; + if ((stencilResolveMode & prop.supportedStencilResolveModes) == 0) stencilResolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; + + if (!prop.independentResolveNone && stencilResolveMode != depthResolveMode) { + stencilResolveMode = depthResolveMode; + } else if (prop.independentResolveNone && !prop.independentResolve && stencilResolveMode && + depthResolveMode && stencilResolveMode != depthResolveMode) { + stencilResolveMode = VK_RESOLVE_MODE_NONE; + } + + resolveDesc.depthResolveMode = depthResolveMode; + resolveDesc.stencilResolveMode = stencilResolveMode; + resolveDesc.pDepthStencilResolveAttachment = attachmentReferences.data() + offset++; + desc.pNext = &resolveDesc; + } } size_t dependencyCount = gpuRenderPass->dependencies.size(); @@ -389,14 +465,15 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende bool hasWriteAccess{false}; for (uint i = 0U; i < dependencyCount; ++i) { - const SubpassDependency &dependency = gpuRenderPass->dependencies[i]; - VkSubpassDependency & vkDependency = subpassDependencies.emplace_back(); - vkDependency.srcSubpass = dependency.srcSubpass; - vkDependency.dstSubpass = dependency.dstSubpass; - vkDependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; + const SubpassDependency &dependency = gpuRenderPass->dependencies[i]; + subpassDependencies.push_back({VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2}); + VkSubpassDependency2 &vkDependency = subpassDependencies.back(); + vkDependency.srcSubpass = dependency.srcSubpass; + vkDependency.dstSubpass = dependency.dstSubpass; + vkDependency.dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; thsvsGetAccessInfo( - dependency.srcAccesses.size(), + utils::toUint(dependency.srcAccesses.size()), accessTypeCaches.data() + offset, &vkDependency.srcStageMask, &vkDependency.srcAccessMask, @@ -405,7 +482,7 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende offset += dependency.srcAccesses.size(); thsvsGetAccessInfo( - dependency.dstAccesses.size(), + utils::toUint(dependency.dstAccesses.size()), accessTypeCaches.data() + offset, &vkDependency.dstStageMask, &vkDependency.dstAccessMask, @@ -417,11 +494,14 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende // explicitly declare external dependencies if not specified // wait for resources to become available by the specified access types - VkSubpassDependency beginDependency{VK_SUBPASS_EXTERNAL, 0, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT}; - auto beginDependencyCheck = [&beginDependency](const VkAttachmentReference &ref, VkPipelineStageFlags dstStage, + VkSubpassDependency2 beginDependency{VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, nullptr, + VK_SUBPASS_EXTERNAL, 0, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT}; + + auto beginDependencyCheck = [&beginDependency](const VkAttachmentReference2 &ref, VkPipelineStageFlags dstStage, VkPipelineStageFlags dstAccessRead, VkAccessFlags dstAccessWrite) { - const VkAttachmentDescription &desc = attachmentDescriptions[ref.attachment]; - const CCVKAccessInfo & info = beginAccessInfos[ref.attachment]; + const VkAttachmentDescription2 &desc = attachmentDescriptions[ref.attachment]; + const CCVKAccessInfo & info = beginAccessInfos[ref.attachment]; if (desc.loadOp == VK_ATTACHMENT_LOAD_OP_DONT_CARE) return; if (desc.initialLayout != ref.layout || info.hasWriteAccess || desc.loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) { beginDependency.srcStageMask |= info.stageMask; @@ -432,23 +512,34 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende } } }; - VkSubpassDescription &firstSubpass = subpassDescriptions[0]; + VkSubpassDescription2 &firstSubpass = subpassDescriptions[0]; for (size_t j = 0U; j < firstSubpass.colorAttachmentCount; ++j) { beginDependencyCheck(firstSubpass.pColorAttachments[j], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_COLOR_ATTACHMENT_READ_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT); + if (firstSubpass.pResolveAttachments) { + beginDependencyCheck(firstSubpass.pResolveAttachments[j], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_ACCESS_COLOR_ATTACHMENT_READ_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT); + } } if (firstSubpass.pDepthStencilAttachment) { beginDependencyCheck(*firstSubpass.pDepthStencilAttachment, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT); } + if (gpuRenderPass->subpasses[0].depthStencilResolve != INVALID_BINDING) { + beginDependencyCheck(*depthStencilResolves[0].pDepthStencilResolveAttachment, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, + VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT); + } if (beginDependency.srcStageMask != VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT) { subpassDependencies.push_back(beginDependency); } // make rendering result visible for the specified access types - VkSubpassDependency endDependency{static_cast(subpassCount) - 1, VK_SUBPASS_EXTERNAL, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT}; - auto endDependencyCheck = [&endDependency](const VkAttachmentReference &ref, VkPipelineStageFlags srcStage, VkAccessFlags srcAccess) { - const VkAttachmentDescription &desc = attachmentDescriptions[ref.attachment]; + VkSubpassDependency2 endDependency{VK_STRUCTURE_TYPE_SUBPASS_DEPENDENCY_2, nullptr, + static_cast(subpassCount) - 1, VK_SUBPASS_EXTERNAL, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT}; + + auto endDependencyCheck = [&endDependency](const VkAttachmentReference2 &ref, VkPipelineStageFlags srcStage, VkAccessFlags srcAccess) { + const VkAttachmentDescription2 &desc = attachmentDescriptions[ref.attachment]; if (desc.storeOp == VK_ATTACHMENT_STORE_OP_STORE) { const CCVKAccessInfo &info = endAccessInfos[ref.attachment]; endDependency.srcStageMask |= srcStage; @@ -457,27 +548,38 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende endDependency.dstAccessMask |= info.accessMask; } }; - VkSubpassDescription &lastSubpass = subpassDescriptions[subpassCount - 1]; + VkSubpassDescription2 &lastSubpass = subpassDescriptions[subpassCount - 1]; for (size_t j = 0U; j < lastSubpass.colorAttachmentCount; ++j) { - endDependencyCheck(lastSubpass.pColorAttachments[j], VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT); + endDependencyCheck(lastSubpass.pColorAttachments[j], + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT); + if (lastSubpass.pResolveAttachments) { + endDependencyCheck(lastSubpass.pResolveAttachments[j], + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT); + } } if (lastSubpass.pDepthStencilAttachment) { - endDependencyCheck(*lastSubpass.pDepthStencilAttachment, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT); + endDependencyCheck(*lastSubpass.pDepthStencilAttachment, + VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT); + } + if (gpuRenderPass->subpasses[subpassCount - 1].depthStencilResolve != INVALID_BINDING) { + endDependencyCheck(*depthStencilResolves[subpassCount - 1].pDepthStencilResolveAttachment, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT); } if (endDependency.dstAccessMask) { subpassDependencies.push_back(endDependency); } } - VkRenderPassCreateInfo renderPassCreateInfo{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; - renderPassCreateInfo.attachmentCount = attachmentDescriptions.size(); + VkRenderPassCreateInfo2 renderPassCreateInfo{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO_2}; + renderPassCreateInfo.attachmentCount = utils::toUint(attachmentDescriptions.size()); renderPassCreateInfo.pAttachments = attachmentDescriptions.data(); - renderPassCreateInfo.subpassCount = subpassDescriptions.size(); + renderPassCreateInfo.subpassCount = utils::toUint(subpassDescriptions.size()); renderPassCreateInfo.pSubpasses = subpassDescriptions.data(); - renderPassCreateInfo.dependencyCount = subpassDependencies.size(); + renderPassCreateInfo.dependencyCount = utils::toUint(subpassDependencies.size()); renderPassCreateInfo.pDependencies = subpassDependencies.data(); - VK_CHECK(vkCreateRenderPass(device->gpuDevice()->vkDevice, &renderPassCreateInfo, nullptr, &gpuRenderPass->vkRenderPass)); + VK_CHECK(device->gpuDevice()->createRenderPass2(device->gpuDevice()->vkDevice, &renderPassCreateInfo, + nullptr, &gpuRenderPass->vkRenderPass)); } void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFramebuffer) { @@ -507,7 +609,7 @@ void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFra if (gpuFramebuffer->isOffscreen) { VkFramebufferCreateInfo createInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; createInfo.renderPass = gpuFramebuffer->gpuRenderPass->vkRenderPass; - createInfo.attachmentCount = attachments.size(); + createInfo.attachmentCount = utils::toUint(attachments.size()); createInfo.pAttachments = attachments.data(); createInfo.width = gpuTexture ? gpuTexture->width : 1; createInfo.height = gpuTexture ? gpuTexture->height : 1; @@ -531,7 +633,7 @@ void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFra } VkFramebufferCreateInfo createInfo{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; createInfo.renderPass = gpuFramebuffer->gpuRenderPass->vkRenderPass; - createInfo.attachmentCount = attachments.size(); + createInfo.attachmentCount = utils::toUint(attachments.size()); createInfo.pAttachments = attachments.data(); createInfo.width = device->getWidth(); createInfo.height = device->getHeight(); @@ -539,7 +641,9 @@ void cmdFuncCCVKCreateFramebuffer(CCVKDevice *device, CCVKGPUFramebuffer *gpuFra for (size_t i = 0U; i < swapchainImageCount; ++i) { for (size_t j = 0U; j < colorViewCount; ++j) { if (swapchainImageIndices & (1 << j)) { - attachments[j] = gpuFramebuffer->swapchain->vkSwapchainImageViews[i]; + attachments[j] = GFX_FORMAT_INFOS[static_cast(gpuFramebuffer->gpuRenderPass->colorAttachments[j].format)].hasDepth + ? gpuFramebuffer->swapchain->depthStencilImageViews[i] + : gpuFramebuffer->swapchain->vkSwapchainImageViews[i]; } } if (swapchainImageIndices & (1 << colorViewCount)) { @@ -576,7 +680,7 @@ void cmdFuncCCVKCreateDescriptorSetLayout(CCVKDevice *device, CCVKGPUDescriptorS } VkDescriptorSetLayoutCreateInfo setCreateInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - setCreateInfo.bindingCount = bindingCount; + setCreateInfo.bindingCount = utils::toUint(bindingCount); setCreateInfo.pBindings = gpuDescriptorSetLayout->vkBindings.data(); VK_CHECK(vkCreateDescriptorSetLayout(gpuDevice->vkDevice, &setCreateInfo, nullptr, &gpuDescriptorSetLayout->vkDescriptorSetLayout)); @@ -603,7 +707,7 @@ void cmdFuncCCVKCreateDescriptorSetLayout(CCVKDevice *device, CCVKGPUDescriptorS } VkDescriptorUpdateTemplateCreateInfo createInfo = {VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO}; - createInfo.descriptorUpdateEntryCount = bindingCount; + createInfo.descriptorUpdateEntryCount = utils::toUint(bindingCount); createInfo.pDescriptorUpdateEntries = entries.data(); createInfo.templateType = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET; createInfo.descriptorSetLayout = gpuDescriptorSetLayout->vkDescriptorSetLayout; @@ -625,7 +729,7 @@ void cmdFuncCCVKCreatePipelineLayout(CCVKDevice *device, CCVKGPUPipelineLayout * } VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; - pipelineLayoutCreateInfo.setLayoutCount = layoutCount; + pipelineLayoutCreateInfo.setLayoutCount = utils::toUint(layoutCount); pipelineLayoutCreateInfo.pSetLayouts = descriptorSetLayouts.data(); VK_CHECK(vkCreatePipelineLayout(gpuDevice->vkDevice, &pipelineLayoutCreateInfo, nullptr, &gpuPipelineLayout->vkPipelineLayout)); } @@ -651,33 +755,41 @@ void cmdFuncCCVKCreateComputePipelineState(CCVKDevice *device, CCVKGPUPipelineSt } void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineState *gpuPipelineState) { + static vector stageInfos; + static vector bindingDescriptions; + static vector attributeDescriptions; + static vector offsets; + static vector dynamicStates; + static vector blendTargets; + VkGraphicsPipelineCreateInfo createInfo{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; ///////////////////// Shader Stage ///////////////////// - const CCVKGPUShaderStageList & stages = gpuPipelineState->gpuShader->gpuStages; - const size_t stageCount = stages.size(); - vector stageInfos(stageCount, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}); + const CCVKGPUShaderStageList &stages = gpuPipelineState->gpuShader->gpuStages; + const size_t stageCount = stages.size(); + + stageInfos.resize(stageCount, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}); for (size_t i = 0U; i < stageCount; ++i) { stageInfos[i].stage = mapVkShaderStageFlagBits(stages[i].type); stageInfos[i].module = stages[i].vkShader; stageInfos[i].pName = "main"; } - createInfo.stageCount = stageCount; + createInfo.stageCount = utils::toUint(stageCount); createInfo.pStages = stageInfos.data(); ///////////////////// Input State ///////////////////// const AttributeList &attributes = gpuPipelineState->inputState.attributes; const size_t attributeCount = attributes.size(); - size_t bindingCount = 1U; + uint bindingCount = 1U; for (size_t i = 0U; i < attributeCount; ++i) { const Attribute &attr = attributes[i]; - bindingCount = std::max(bindingCount, static_cast(attr.stream + 1)); + bindingCount = std::max(bindingCount, attr.stream + 1); } - vector bindingDescriptions(bindingCount); - for (size_t i = 0U; i < bindingCount; ++i) { + bindingDescriptions.resize(bindingCount); + for (uint i = 0U; i < bindingCount; ++i) { bindingDescriptions[i].binding = i; bindingDescriptions[i].stride = 0; bindingDescriptions[i].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; @@ -690,11 +802,10 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS } } - const AttributeList & shaderAttrs = gpuPipelineState->gpuShader->attributes; - const size_t shaderAttrCount = shaderAttrs.size(); - vector attributeDescriptions(shaderAttrCount); - vector offsets(bindingCount, 0); + const AttributeList &shaderAttrs = gpuPipelineState->gpuShader->attributes; + const size_t shaderAttrCount = shaderAttrs.size(); + attributeDescriptions.resize(shaderAttrCount); for (size_t i = 0; i < shaderAttrCount; ++i) { bool attributeFound = false; offsets.assign(bindingCount, 0); @@ -720,7 +831,7 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS VkPipelineVertexInputStateCreateInfo vertexInput{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; vertexInput.vertexBindingDescriptionCount = bindingCount; vertexInput.pVertexBindingDescriptions = bindingDescriptions.data(); - vertexInput.vertexAttributeDescriptionCount = shaderAttrCount; + vertexInput.vertexAttributeDescriptionCount = utils::toUint(shaderAttrCount); vertexInput.pVertexAttributeDescriptions = attributeDescriptions.data(); createInfo.pVertexInputState = &vertexInput; @@ -732,11 +843,11 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS ///////////////////// Dynamic State ///////////////////// - vector dynamicStates{VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}; + dynamicStates.assign({VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR}); insertVkDynamicStates(&dynamicStates, gpuPipelineState->dynamicStates); VkPipelineDynamicStateCreateInfo dynamicState{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO}; - dynamicState.dynamicStateCount = dynamicStates.size(); + dynamicState.dynamicStateCount = utils::toUint(dynamicStates.size()); dynamicState.pDynamicStates = dynamicStates.data(); createInfo.pDynamicState = &dynamicState; @@ -766,7 +877,7 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS ///////////////////// Multisample State ///////////////////// VkPipelineMultisampleStateCreateInfo multisampleState{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; - multisampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + multisampleState.rasterizationSamples = gpuPipelineState->gpuRenderPass->sampleCounts[gpuPipelineState->subpass]; multisampleState.alphaToCoverageEnable = gpuPipelineState->bs.isA2C; //multisampleState.sampleShadingEnable; //multisampleState.minSampleShading; @@ -807,10 +918,14 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS ///////////////////// Blend State ///////////////////// - size_t blendTargetCount = gpuPipelineState->bs.targets.size(); - vector blendTargets(blendTargetCount); + size_t blendTargetCount = gpuPipelineState->gpuRenderPass->subpasses[gpuPipelineState->subpass].colors.size(); + blendTargets.resize(blendTargetCount, {}); + for (size_t i = 0U; i < blendTargetCount; ++i) { - BlendTarget &target = gpuPipelineState->bs.targets[i]; + BlendTarget &target = i >= gpuPipelineState->bs.targets.size() + ? gpuPipelineState->bs.targets[0] + : gpuPipelineState->bs.targets[i]; + blendTargets[i].blendEnable = target.blend; blendTargets[i].srcColorBlendFactor = VK_BLEND_FACTORS[static_cast(target.blendSrc)]; blendTargets[i].dstColorBlendFactor = VK_BLEND_FACTORS[static_cast(target.blendDst)]; @@ -825,7 +940,7 @@ void cmdFuncCCVKCreateGraphicsPipelineState(CCVKDevice *device, CCVKGPUPipelineS VkPipelineColorBlendStateCreateInfo colorBlendState{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; //colorBlendState.logicOpEnable; //colorBlendState.logicOp; - colorBlendState.attachmentCount = blendTargetCount; + colorBlendState.attachmentCount = utils::toUint(blendTargetCount); colorBlendState.pAttachments = blendTargets.data(); colorBlendState.blendConstants[0] = blendColor.x; colorBlendState.blendConstants[1] = blendColor.y; @@ -944,7 +1059,7 @@ void cmdFuncCCVKCopyBuffersToTexture(CCVKDevice *device, const uint8_t *const *b barrier.subresourceRange.levelCount = VK_REMAINING_MIP_LEVELS; barrier.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; barrier.subresourceRange.aspectMask = gpuTexture->aspectMask; - barrier.prevAccessCount = curTypes.size(); + barrier.prevAccessCount = utils::toUint(curTypes.size()); barrier.pPrevAccesses = curTypes.data(); barrier.nextAccessCount = 1; barrier.pNextAccesses = &THSVS_ACCESS_TYPES[static_cast(AccessType::TRANSFER_WRITE)]; @@ -993,7 +1108,7 @@ void cmdFuncCCVKCopyBuffersToTexture(CCVKDevice *device, const uint8_t *const *b } vkCmdCopyBufferToImage(gpuCommandBuffer->vkCommandBuffer, stagingBuffer.vkBuffer, gpuTexture->vkImage, - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, stagingRegions.size(), stagingRegions.data()); + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, utils::toUint(stagingRegions.size()), stagingRegions.data()); if (hasFlag(gpuTexture->flags, TextureFlags::GEN_MIPMAP)) { VkFormatProperties formatProperties; @@ -1215,6 +1330,33 @@ void CCVKGPURecycleBin::clear() { _count = 0; } +VkSampleCountFlagBits CCVKGPUContext::getSampleCountForAttachments(Format format, SampleCount sampleCount) const { + if (sampleCount <= SampleCount::X1) return VK_SAMPLE_COUNT_1_BIT; + + static unordered_map cacheMap; + if (!cacheMap.count(format)) { + bool hasDepth = GFX_FORMAT_INFOS[static_cast(format)].hasDepth; + VkImageUsageFlags usages = hasDepth ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + + VkImageFormatProperties properties; + vkGetPhysicalDeviceImageFormatProperties(physicalDevice, mapVkFormat(format), VK_IMAGE_TYPE_2D, + VK_IMAGE_TILING_OPTIMAL, usages, 0, &properties); + cacheMap[format] = properties.sampleCounts; + } + + VkSampleCountFlags availableSampleCounts = cacheMap[format]; + + auto requestedSampleCount = static_cast(sampleCount); + if (requestedSampleCount >= 64 && (availableSampleCounts & VK_SAMPLE_COUNT_64_BIT)) return VK_SAMPLE_COUNT_64_BIT; + if (requestedSampleCount >= 32 && (availableSampleCounts & VK_SAMPLE_COUNT_32_BIT)) return VK_SAMPLE_COUNT_32_BIT; + if (requestedSampleCount >= 16 && (availableSampleCounts & VK_SAMPLE_COUNT_16_BIT)) return VK_SAMPLE_COUNT_16_BIT; + if (requestedSampleCount >= 8 && (availableSampleCounts & VK_SAMPLE_COUNT_8_BIT)) return VK_SAMPLE_COUNT_8_BIT; + if (requestedSampleCount >= 4 && (availableSampleCounts & VK_SAMPLE_COUNT_4_BIT)) return VK_SAMPLE_COUNT_4_BIT; + if (requestedSampleCount >= 2 && (availableSampleCounts & VK_SAMPLE_COUNT_2_BIT)) return VK_SAMPLE_COUNT_2_BIT; + + return VK_SAMPLE_COUNT_1_BIT; +} + void CCVKGPUBarrierManager::update(CCVKGPUTransportHub *transportHub) { if (_buffersToBeChecked.empty() && _texturesToBeChecked.empty()) return; @@ -1241,9 +1383,9 @@ void CCVKGPUBarrierManager::update(CCVKGPUTransportHub *transportHub) { VkMemoryBarrier *pVkBarrier = nullptr; if (!prevAccesses.empty()) { ThsvsGlobalBarrier globalBarrier{}; - globalBarrier.prevAccessCount = prevAccesses.size(); + globalBarrier.prevAccessCount = utils::toUint(prevAccesses.size()); globalBarrier.pPrevAccesses = prevAccesses.data(); - globalBarrier.nextAccessCount = nextAccesses.size(); + globalBarrier.nextAccessCount = utils::toUint(nextAccesses.size()); globalBarrier.pNextAccesses = nextAccesses.data(); VkPipelineStageFlags tempSrcStageMask = 0; VkPipelineStageFlags tempDstStageMask = 0; @@ -1268,7 +1410,7 @@ void CCVKGPUBarrierManager::update(CCVKGPUTransportHub *transportHub) { if (gpuTexture->transferAccess == THSVS_ACCESS_NONE || render.empty()) continue; vector ¤t = gpuTexture->currentAccessTypes; imageBarrier.pPrevAccesses = &gpuTexture->transferAccess; - imageBarrier.nextAccessCount = render.size(); + imageBarrier.nextAccessCount = utils::toUint(render.size()); imageBarrier.pNextAccesses = render.data(); imageBarrier.image = gpuTexture->vkImage; imageBarrier.subresourceRange.aspectMask = gpuTexture->aspectMask; @@ -1289,7 +1431,7 @@ void CCVKGPUBarrierManager::update(CCVKGPUTransportHub *transportHub) { if (pVkBarrier || !vkImageBarriers.empty()) { transportHub->checkIn([&](CCVKGPUCommandBuffer *gpuCommandBuffer) { vkCmdPipelineBarrier(gpuCommandBuffer->vkCommandBuffer, srcStageMask, dstStageMask, 0, - pVkBarrier ? 1 : 0, pVkBarrier, 0, nullptr, vkImageBarriers.size(), vkImageBarriers.data()); + pVkBarrier ? 1 : 0, pVkBarrier, 0, nullptr, utils::toUint(vkImageBarriers.size()), vkImageBarriers.data()); }); } diff --git a/native/cocos/renderer/gfx-vulkan/VKContext.cpp b/native/cocos/renderer/gfx-vulkan/VKContext.cpp index 80b6e12e57..41238b763c 100644 --- a/native/cocos/renderer/gfx-vulkan/VKContext.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKContext.cpp @@ -334,6 +334,7 @@ bool CCVKContext::doInit(const ContextInfo &info) { if (_minorVersion >= 1 || checkExtension(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME)) { _gpuContext->physicalDeviceFeatures2.pNext = &_gpuContext->physicalDeviceVulkan11Features; _gpuContext->physicalDeviceVulkan11Features.pNext = &_gpuContext->physicalDeviceVulkan12Features; + _gpuContext->physicalDeviceProperties2.pNext = &_gpuContext->physicalDeviceDepthStencilResolveProperties; if (_minorVersion >= 1) { vkGetPhysicalDeviceProperties2(_gpuContext->physicalDevice, &_gpuContext->physicalDeviceProperties2); vkGetPhysicalDeviceFeatures2(_gpuContext->physicalDevice, &_gpuContext->physicalDeviceFeatures2); diff --git a/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp b/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp index c9bd7f74f5..f37bcac7b0 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDescriptorSet.cpp @@ -46,8 +46,8 @@ CCVKDescriptorSet::~CCVKDescriptorSet() { void CCVKDescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { CCVKGPUDescriptorSetLayout *gpuDescriptorSetLayout = static_cast(_layout)->gpuDescriptorSetLayout(); - const uint bindingCount = gpuDescriptorSetLayout->bindings.size(); - const uint descriptorCount = gpuDescriptorSetLayout->descriptorCount; + uint bindingCount = utils::toUint(gpuDescriptorSetLayout->bindings.size()); + uint descriptorCount = gpuDescriptorSetLayout->descriptorCount; _gpuDescriptorSet = CC_NEW(CCVKGPUDescriptorSet); _gpuDescriptorSet->gpuDescriptors.resize(descriptorCount, {}); @@ -93,12 +93,12 @@ void CCVKDescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { _gpuDescriptorSet->gpuLayout = gpuDescriptorSetLayout; _gpuDescriptorSet->instances.resize(gpuDevice->backBufferCount); - for (size_t t = 0U; t < gpuDevice->backBufferCount; ++t) { + for (uint t = 0U; t < gpuDevice->backBufferCount; ++t) { CCVKGPUDescriptorSet::Instance &instance = _gpuDescriptorSet->instances[t]; instance.vkDescriptorSet = gpuDevice->getDescriptorSetPool(_gpuDescriptorSet->layoutID)->request(t); instance.descriptorInfos.resize(descriptorCount, {}); - for (size_t i = 0U, k = 0U; i < bindingCount; ++i) { + for (uint i = 0U, k = 0U; i < bindingCount; ++i) { const DescriptorSetLayoutBinding &binding = gpuDescriptorSetLayout->bindings[i]; for (uint j = 0; j < binding.count; ++j, ++k) { if (hasFlag(DESCRIPTOR_BUFFER_TYPE, binding.descriptorType)) { @@ -117,9 +117,9 @@ void CCVKDescriptorSet::doInit(const DescriptorSetInfo & /*info*/) { vector &entries = instance.descriptorUpdateEntries; entries.resize(descriptorCount, {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}); - for (size_t i = 0U, j = 0U; i < bindingCount; i++) { + for (uint i = 0U, j = 0U; i < bindingCount; i++) { const VkDescriptorSetLayoutBinding &descriptor = gpuDescriptorSetLayout->vkBindings[i]; - for (size_t k = 0U; k < descriptor.descriptorCount; k++, j++) { + for (uint k = 0U; k < descriptor.descriptorCount; k++, j++) { entries[j].dstSet = instance.vkDescriptorSet; entries[j].dstBinding = descriptor.binding; entries[j].dstArrayElement = k; @@ -155,8 +155,9 @@ void CCVKDescriptorSet::doDestroy() { if (_gpuDescriptorSet) { CCVKGPUDevice * gpuDevice = CCVKDevice::getInstance()->gpuDevice(); CCVKGPUDescriptorHub *descriptorHub = CCVKDevice::getInstance()->gpuDescriptorHub(); + uint instanceCount = utils::toUint(_gpuDescriptorSet->instances.size()); - for (size_t t = 0U; t < _gpuDescriptorSet->instances.size(); ++t) { + for (uint t = 0U; t < instanceCount; ++t) { CCVKGPUDescriptorSet::Instance &instance = _gpuDescriptorSet->instances[t]; for (uint i = 0U; i < _gpuDescriptorSet->gpuDescriptors.size(); i++) { @@ -190,7 +191,8 @@ void CCVKDescriptorSet::update() { if (_isDirty && _gpuDescriptorSet) { CCVKGPUDescriptorHub * descriptorHub = CCVKDevice::getInstance()->gpuDescriptorHub(); CCVKGPUBarrierManager *layoutMgr = CCVKDevice::getInstance()->gpuBarrierManager(); - uint descriptorCount = _gpuDescriptorSet->gpuDescriptors.size(); + uint descriptorCount = utils::toUint(_gpuDescriptorSet->gpuDescriptors.size()); + uint instanceCount = utils::toUint(_gpuDescriptorSet->instances.size()); for (size_t i = 0U; i < descriptorCount; i++) { CCVKGPUDescriptor &binding = _gpuDescriptorSet->gpuDescriptors[i]; @@ -199,7 +201,7 @@ void CCVKDescriptorSet::update() { if (_buffers[i]) { CCVKGPUBufferView *bufferView = static_cast(_buffers[i])->gpuBufferView(); if (binding.gpuBufferView != bufferView) { - for (size_t t = 0U; t < _gpuDescriptorSet->instances.size(); ++t) { + for (uint t = 0U; t < instanceCount; ++t) { CCVKDescriptorInfo &descriptorInfo = _gpuDescriptorSet->instances[t].descriptorInfos[i]; if (binding.gpuBufferView) { @@ -225,7 +227,7 @@ void CCVKDescriptorSet::update() { if (textureView) { descriptorHub->connect(_gpuDescriptorSet, textureView, &descriptorInfo.image); descriptorHub->update(textureView, &descriptorInfo.image); - layoutMgr->checkIn(textureView->gpuTexture, binding.accessTypes.data(), binding.accessTypes.size()); + layoutMgr->checkIn(textureView->gpuTexture, binding.accessTypes.data(), utils::toUint(binding.accessTypes.size())); } } binding.gpuTextureView = textureView; diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index 216dfcdf24..7fc6f67e2f 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -59,6 +59,12 @@ namespace gfx { //#define DISABLE_PRE_TRANSFORM +static VkResult VKAPI_PTR vkCreateRenderPass2KHRFallback( + VkDevice device, + const VkRenderPassCreateInfo2 *pCreateInfo, + const VkAllocationCallbacks * pAllocator, + VkRenderPass * pRenderPass); + CCVKDevice *CCVKDevice::instance = nullptr; CCVKDevice *CCVKDevice::getInstance() { @@ -112,6 +118,9 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { vector requestedExtensions{ VK_KHR_SWAPCHAIN_EXTENSION_NAME, }; + if (_gpuDevice->minorVersion < 2) { + requestedExtensions.push_back(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME); + } if (_gpuDevice->minorVersion < 1) { requestedExtensions.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME); requestedExtensions.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME); @@ -211,21 +220,23 @@ bool CCVKDevice::doInit(const DeviceInfo &info) { _features[static_cast(Feature::TEXTURE_HALF_FLOAT_LINEAR)] = true; _features[static_cast(Feature::FORMAT_R11G11B10F)] = true; _features[static_cast(Feature::FORMAT_SRGB)] = true; - _features[static_cast(Feature::MSAA)] = true; _features[static_cast(Feature::ELEMENT_INDEX_UINT)] = true; _features[static_cast(Feature::INSTANCED_ARRAYS)] = true; _features[static_cast(Feature::MULTIPLE_RENDER_TARGETS)] = true; _features[static_cast(Feature::BLEND_MINMAX)] = true; - _features[static_cast(Feature::DEPTH_BOUNDS)] = deviceFeatures.depthBounds; - _features[static_cast(Feature::LINE_WIDTH)] = true; - _features[static_cast(Feature::STENCIL_COMPARE_MASK)] = true; - _features[static_cast(Feature::STENCIL_WRITE_MASK)] = true; - _features[static_cast(Feature::MULTITHREADED_SUBMISSION)] = true; _features[static_cast(Feature::COMPUTE_SHADER)] = true; _gpuDevice->useMultiDrawIndirect = deviceFeatures.multiDrawIndirect; _gpuDevice->useDescriptorUpdateTemplate = _gpuDevice->minorVersion > 0 || checkExtension(VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME); + if (_gpuDevice->minorVersion > 1) { + _gpuDevice->createRenderPass2 = vkCreateRenderPass2; + } else if (checkExtension(VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME)) { + _gpuDevice->createRenderPass2 = vkCreateRenderPass2KHR; + } else { + _gpuDevice->createRenderPass2 = vkCreateRenderPass2KHRFallback; + } + VkFormatFeatureFlags requiredFeatures = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT; VkFormatProperties formatProperties; vkGetPhysicalDeviceFormatProperties(gpuContext->physicalDevice, VK_FORMAT_R8G8B8_UNORM, &formatProperties); @@ -816,5 +827,102 @@ void CCVKDevice::acquireSurface(uintptr_t windowHandle) { static_cast(_context)->acquireSurface(windowHandle); } +//////////////////////////// Function Fallbacks ///////////////////////////////////////// + +static VkResult VKAPI_PTR vkCreateRenderPass2KHRFallback( + VkDevice device, + const VkRenderPassCreateInfo2 *pCreateInfo, + const VkAllocationCallbacks * pAllocator, + VkRenderPass * pRenderPass) { + static vector attachmentDescriptions; + static vector subpassDescriptions; + static vector attachmentReferences; + static vector subpassDependencies; + + attachmentDescriptions.resize(pCreateInfo->attachmentCount); + for (uint i = 0; i < pCreateInfo->attachmentCount; ++i) { + VkAttachmentDescription & desc{attachmentDescriptions[i]}; + const VkAttachmentDescription2 &desc2{pCreateInfo->pAttachments[i]}; + desc.flags = desc2.flags; + desc.format = desc2.format; + desc.samples = desc2.samples; + desc.loadOp = desc2.loadOp; + desc.storeOp = desc2.storeOp; + desc.stencilLoadOp = desc2.stencilLoadOp; + desc.stencilStoreOp = desc2.stencilStoreOp; + desc.initialLayout = desc2.initialLayout; + desc.finalLayout = desc2.finalLayout; + } + + subpassDescriptions.resize(pCreateInfo->subpassCount); + attachmentReferences.clear(); + size_t input{std::numeric_limits::max()}; + size_t color{std::numeric_limits::max()}; + size_t resolve{std::numeric_limits::max()}; + size_t depth{std::numeric_limits::max()}; + for (uint i = 0; i < pCreateInfo->subpassCount; ++i) { + const VkSubpassDescription2 &desc2{pCreateInfo->pSubpasses[i]}; + if (desc2.inputAttachmentCount) { + input = attachmentReferences.size(); + for (uint j = 0; j < desc2.inputAttachmentCount; ++j) { + attachmentReferences.push_back({desc2.pInputAttachments[j].attachment, desc2.pInputAttachments[j].layout}); + } + } + if (desc2.colorAttachmentCount) { + input = attachmentReferences.size(); + for (uint j = 0; j < desc2.colorAttachmentCount; ++j) { + attachmentReferences.push_back({desc2.pColorAttachments[j].attachment, desc2.pColorAttachments[j].layout}); + } + if (desc2.pResolveAttachments) { + resolve = attachmentReferences.size(); + for (uint j = 0; j < desc2.colorAttachmentCount; ++j) { + attachmentReferences.push_back({desc2.pResolveAttachments[j].attachment, desc2.pResolveAttachments[j].layout}); + } + } + } + if (desc2.pDepthStencilAttachment) { + depth = attachmentReferences.size(); + attachmentReferences.push_back({desc2.pDepthStencilAttachment->attachment, desc2.pDepthStencilAttachment->layout}); + } + } + for (uint i = 0; i < pCreateInfo->subpassCount; ++i) { + VkSubpassDescription & desc{subpassDescriptions[i]}; + const VkSubpassDescription2 &desc2{pCreateInfo->pSubpasses[i]}; + desc.flags = desc2.flags; + desc.pipelineBindPoint = desc2.pipelineBindPoint; + desc.inputAttachmentCount = desc2.inputAttachmentCount; + desc.pInputAttachments = input > attachmentReferences.size() ? nullptr : &attachmentReferences[input]; + desc.colorAttachmentCount = desc2.colorAttachmentCount; + desc.pColorAttachments = color > attachmentReferences.size() ? nullptr : &attachmentReferences[color]; + desc.pResolveAttachments = resolve > attachmentReferences.size() ? nullptr : &attachmentReferences[resolve]; + desc.pDepthStencilAttachment = depth > attachmentReferences.size() ? nullptr : &attachmentReferences[depth]; + desc.preserveAttachmentCount = desc2.preserveAttachmentCount; + desc.pPreserveAttachments = desc2.pPreserveAttachments; + } + + subpassDependencies.resize(pCreateInfo->dependencyCount); + for (uint i = 0; i < pCreateInfo->dependencyCount; ++i) { + VkSubpassDependency & desc{subpassDependencies[i]}; + const VkSubpassDependency2 &desc2{pCreateInfo->pDependencies[i]}; + desc.srcSubpass = desc2.srcSubpass; + desc.dstSubpass = desc2.dstSubpass; + desc.srcStageMask = desc2.srcStageMask; + desc.dstStageMask = desc2.dstStageMask; + desc.srcAccessMask = desc2.srcAccessMask; + desc.dstAccessMask = desc2.dstAccessMask; + desc.dependencyFlags = desc2.dependencyFlags; + } + + VkRenderPassCreateInfo renderPassCreateInfo{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; + renderPassCreateInfo.attachmentCount = attachmentDescriptions.size(); + renderPassCreateInfo.pAttachments = attachmentDescriptions.data(); + renderPassCreateInfo.subpassCount = subpassDescriptions.size(); + renderPassCreateInfo.pSubpasses = subpassDescriptions.data(); + renderPassCreateInfo.dependencyCount = subpassDependencies.size(); + renderPassCreateInfo.pDependencies = subpassDependencies.data(); + + return vkCreateRenderPass(device, &renderPassCreateInfo, pAllocator, pRenderPass); +} + } // namespace gfx } // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index 87c1b50579..36dd0dfbc7 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -45,20 +45,23 @@ public: VkDebugUtilsMessengerEXT vkDebugUtilsMessenger = VK_NULL_HANDLE; VkDebugReportCallbackEXT vkDebugReport = VK_NULL_HANDLE; - VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; - VkPhysicalDeviceFeatures physicalDeviceFeatures{}; - VkPhysicalDeviceFeatures2 physicalDeviceFeatures2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; - VkPhysicalDeviceVulkan11Features physicalDeviceVulkan11Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; - VkPhysicalDeviceVulkan12Features physicalDeviceVulkan12Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; - VkPhysicalDeviceProperties physicalDeviceProperties{}; - VkPhysicalDeviceProperties2 physicalDeviceProperties2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; - VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties{}; - vector queueFamilyProperties; - vector queueFamilyPresentables; + VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; + VkPhysicalDeviceFeatures physicalDeviceFeatures{}; + VkPhysicalDeviceFeatures2 physicalDeviceFeatures2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; + VkPhysicalDeviceVulkan11Features physicalDeviceVulkan11Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES}; + VkPhysicalDeviceVulkan12Features physicalDeviceVulkan12Features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + VkPhysicalDeviceDepthStencilResolveProperties physicalDeviceDepthStencilResolveProperties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES}; + VkPhysicalDeviceProperties physicalDeviceProperties{}; + VkPhysicalDeviceProperties2 physicalDeviceProperties2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; + VkPhysicalDeviceMemoryProperties physicalDeviceMemoryProperties{}; + vector queueFamilyProperties; + vector queueFamilyPresentables; VkSurfaceKHR vkSurface = VK_NULL_HANDLE; VkSwapchainCreateInfoKHR swapchainCreateInfo{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; + + VkSampleCountFlagBits getSampleCountForAttachments(Format format, SampleCount sampleCount) const; }; struct CCVKAccessInfo { @@ -82,7 +85,8 @@ public: VkRenderPass vkRenderPass; // helper storage - vector clearValues; + vector clearValues; + vector sampleCounts; // per subpass }; class CCVKGPUTexture final : public Object { @@ -355,6 +359,8 @@ public: bool useDescriptorUpdateTemplate = false; bool useMultiDrawIndirect = false; + PFN_vkCreateRenderPass2 createRenderPass2 = nullptr; + // for default backup usages CCVKGPUSampler defaultSampler; CCVKGPUTexture defaultTexture; @@ -490,7 +496,7 @@ public: } } - uint leakedSetCount = 0U; + size_t leakedSetCount = 0U; for (DescriptorSetPool &pool : _pools) { leakedSetCount += pool.activeSets.size(); vkDestroyDescriptorPool(_device->vkDevice, pool.vkPool, nullptr); @@ -1225,8 +1231,8 @@ public: private: struct BufferUpdate { - uint srcIndex = 0U; - size_t size = 0U; + uint srcIndex = 0U; + size_t size = 0U; bool canMemcpy = false; }; diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp index 32fd90fcb2..951fcd4511 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.cpp @@ -210,21 +210,6 @@ VkImageType mapVkImageType(TextureType type) { } } -VkSampleCountFlagBits mapVkSampleCount(SampleCount count) { - switch (count) { - case SampleCount::X1: return VK_SAMPLE_COUNT_1_BIT; - case SampleCount::X2: return VK_SAMPLE_COUNT_2_BIT; - case SampleCount::X4: return VK_SAMPLE_COUNT_4_BIT; - case SampleCount::X8: return VK_SAMPLE_COUNT_8_BIT; - case SampleCount::X16: return VK_SAMPLE_COUNT_16_BIT; - case SampleCount::X32: return VK_SAMPLE_COUNT_32_BIT; - default: { - CCASSERT(false, "Unsupported TextureType, convert to VkImageType failed."); - return VK_SAMPLE_COUNT_1_BIT; - } - } -} - VkFormatFeatureFlags mapVkFormatFeatureFlags(TextureUsage usage) { uint flags = 0U; if (hasFlag(usage, TextureUsage::TRANSFER_SRC)) flags |= VK_FORMAT_FEATURE_TRANSFER_SRC_BIT; @@ -233,7 +218,6 @@ VkFormatFeatureFlags mapVkFormatFeatureFlags(TextureUsage usage) { if (hasFlag(usage, TextureUsage::STORAGE)) flags |= VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT; if (hasFlag(usage, TextureUsage::COLOR_ATTACHMENT)) flags |= VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT; if (hasFlag(usage, TextureUsage::DEPTH_STENCIL_ATTACHMENT)) flags |= VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT; - if (hasFlag(usage, TextureUsage::INPUT_ATTACHMENT)) flags |= VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT; return static_cast(flags); } @@ -535,6 +519,14 @@ const ThsvsAccessType THSVS_ACCESS_TYPES[] = { THSVS_ACCESS_HOST_WRITE, // HOST_WRITE }; +const VkResolveModeFlagBits VK_RESOLVE_MODES[] = { + VK_RESOLVE_MODE_NONE, + VK_RESOLVE_MODE_SAMPLE_ZERO_BIT, + VK_RESOLVE_MODE_AVERAGE_BIT, + VK_RESOLVE_MODE_MIN_BIT, + VK_RESOLVE_MODE_MAX_BIT, +}; + const VkImageLayout VK_IMAGE_LAYOUTS[] = { VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, diff --git a/native/cocos/renderer/gfx-vulkan/VKUtils.h b/native/cocos/renderer/gfx-vulkan/VKUtils.h index 5b66728163..4b6bc4f252 100644 --- a/native/cocos/renderer/gfx-vulkan/VKUtils.h +++ b/native/cocos/renderer/gfx-vulkan/VKUtils.h @@ -55,7 +55,6 @@ extern VkAttachmentLoadOp mapVkLoadOp(LoadOp loadOp); extern VkAttachmentStoreOp mapVkStoreOp(StoreOp storeOp); extern VkBufferUsageFlagBits mapVkBufferUsageFlagBits(BufferUsage usage); extern VkImageType mapVkImageType(TextureType type); -extern VkSampleCountFlagBits mapVkSampleCount(SampleCount count); extern VkFormatFeatureFlags mapVkFormatFeatureFlags(TextureUsage usage); extern VkImageUsageFlagBits mapVkImageUsageFlagBits(TextureUsage usage); extern VkImageAspectFlags mapVkImageAspectFlags(Format format); @@ -88,6 +87,7 @@ extern const VkSamplerMipmapMode VK_SAMPLER_MIPMAP_MODES[]; extern const VkSamplerAddressMode VK_SAMPLER_ADDRESS_MODES[]; extern const VkPipelineBindPoint VK_PIPELINE_BIND_POINTS[]; extern const ThsvsAccessType THSVS_ACCESS_TYPES[]; +extern const VkResolveModeFlagBits VK_RESOLVE_MODES[]; extern const VkImageLayout VK_IMAGE_LAYOUTS[]; extern const VkStencilFaceFlags VK_STENCIL_FACE_FLAGS[]; extern const VkAccessFlags FULL_ACCESS_FLAGS; diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index f0f6630935..782230b208 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp @@ -35,7 +35,7 @@ #include "gfx-base/GFXTexture.h" namespace cc::pipeline { -std::unordered_map ShadowFlow::renderPassHashMap; +std::unordered_map ShadowFlow::renderPassHashMap; RenderFlowInfo ShadowFlow::initInfo = { "ShadowFlow", @@ -161,7 +161,6 @@ void ShadowFlow::resizeShadowMap(const scene::Light *light, scene::Shadow **shad _renderPass, renderTargets, depth, - {}, }); } @@ -176,9 +175,9 @@ void ShadowFlow::initShadowFrameBuffer(RenderPipeline *pipeline, const scene::Li const auto width = static_cast(shadowMapSize.x); const auto height = static_cast(shadowMapSize.y); const auto format = supportsHalfFloatTexture(device) - ? (shadowInfo->packing ? gfx::Format::RGBA8 : gfx::Format::RGBA16F) - : gfx::Format::RGBA8; - + ? (shadowInfo->packing ? gfx::Format::RGBA8 : gfx::Format::RGBA16F) + : gfx::Format::RGBA8; + const gfx::ColorAttachment colorAttachment = { format, gfx::SampleCount::X1, @@ -202,10 +201,10 @@ void ShadowFlow::initShadowFrameBuffer(RenderPipeline *pipeline, const scene::Li gfx::RenderPassInfo rpInfo; rpInfo.colorAttachments.emplace_back(colorAttachment); rpInfo.depthStencilAttachment = depthStencilAttachment; - + uint rpHash = cc::gfx::RenderPass::computeHash(rpInfo); - auto iter = renderPassHashMap.find(rpHash); - if(iter != renderPassHashMap.end()) { + auto iter = renderPassHashMap.find(rpHash); + if (iter != renderPassHashMap.end()) { _renderPass = iter->second; } else { _renderPass = device->createRenderPass(rpInfo); @@ -237,15 +236,13 @@ void ShadowFlow::initShadowFrameBuffer(RenderPipeline *pipeline, const scene::Li _renderPass, renderTargets, depth, - {}, //colorMipmapLevels }); pipeline->getPipelineSceneData()->setShadowFramebuffer(light, framebuffer); } void ShadowFlow::destroy() { - - for (auto rpPair: renderPassHashMap) { + for (auto rpPair : renderPassHashMap) { rpPair.second->destroy(); } renderPassHashMap.clear();